JohnCoene / echarts4r

🐳 ECharts 5 for R
http://echarts4r.john-coene.com/
Other
601 stars 81 forks source link

Feature request: reset 'clicked_data' callback #351

Open u9090 opened 3 years ago

u9090 commented 3 years ago

Hello,

Using the example shiny app below and the example here, it does not seem possible to reset the input$chart_clicked_data$value[1] to NULL when the user clicks a second time the same bar or clicks outside of the bar area. This feature would be great to implement, mainly to avoid to create a reset button.

Example app:

library(shiny)
library(echarts4r)
library(dplyr)

# toy data
data <- mtcars %>%
    tibble::rownames_to_column("model") %>% 
    tail()

# UI
ui <- fluidPage(
    column(8, echarts4rOutput('chart')),
    column(4, verbatimTextOutput('selected_bar'))
)

# SERVER
server <- function(input, output, session) {
    # Barplot
    output$chart <- renderEcharts4r({
        data %>%
            e_charts(model) %>%
            e_bar(cyl)
    })

    # Proxy
    observeEvent(input$chart_clicked_data, {
        echarts4rProxy("chart") %>%
            e_highlight_p(series_name = "model")
    })

    # Output
    output$selected_bar <- renderPrint({
        print(input$chart_clicked_data$value[1])
    })
}

shinyApp(ui, server)
JohnCoene commented 3 years ago

In shiny inputs are never reset as far as I know, since an input is fired when its value changes.

Do you have an example use case where this would be necessary?

u9090 commented 3 years ago

Sorry @JohnCoene , I might not have explained the problem properly. You are right about shiny inputs that cannot be reset. I could probably save input$chart_clicked_data$value[1] in a reactive variable for that (or use shinyjs::reset function maybe).

The tricky part I am facing is how to translate the 'click the same bar again' or 'click outside of the selected bar' into shiny (or javascript maybe).

JohnCoene commented 3 years ago

I think something similar came to light before but it was resolved by making sure the data for that input is treated as an event: it's always sent to the server regardless of whether it's value has changed, e.g.: clicking the same bar twice fires the event.

https://github.com/JohnCoene/echarts4r/blob/ec03e95fe0a4e37c552c41146c2ff1059249245a/inst/htmlwidgets/echarts4r.js#L93

Therefore this "works" as in it increments the count at every click even if it is the same bar as previously clicked.

count <- 0
observeEvent(input$chart_clicked_data, {
  count <<- count + 1
  print(count)
})

If there is an event that is not supported you can use e_capture to do so. The list of events is here.

Happy to help with the implementation if you find something you need in there.