surveydown-dev / surveydown

Markdown-Based Surveys Using R, Quarto, and Shiny
https://pkg.surveydown.org/
Other
70 stars 10 forks source link

Shiny actionButton #84

Closed CyuHat closed 2 months ago

CyuHat commented 3 months ago

Hi! First of all, thank you for this amazing project.

I have a question regarding the integration of shiny functionalities. I tried to integrate an actionButton from a chunck in one of the pages:

actionButton("do", "button")

So far, no problems since the button appear. Then in the server chunck I add the following code as I would do in a shiny app but it does not work:

#| context: server

...

observeEvent(input$do, {
    session$sendCustomMessage(type = 'testmessage',
      message = 'Thank you for clicking')
  })

Is it possible?

Thanks in advance

jhelvy commented 3 months ago

Hey, thanks for trying out surveydown! I thought just putting that observe code in the server chunk should work, but I believe it may need to ultimately be inside the sd_server() function that gets called, which wouldn't be possible without manually modifying sd_server(). I'll try and look into this to see if I can set up a way to pass some custom code like this into sd_server. I'm sure it can be done, just have had time to try it and won't have time for a little bit. I'm thinking we just need to add a ... argument to sd_server() to allow things like this to be passed in and it might work. You can try and modify that yourself if you'd like to try it yourself.

jhelvy commented 2 months ago

Okay I finally got a chance to look at this more closely, and I am able to insert an action button and have it trigger things by just putting the server code directly in the server chunk. Here is an example below. Note that you'll want to install the latest package version from GH because I found a bug where it throws an error if the survey has no questions (previously you had to have at least one question defined with sd_question(). You can update the package with:

remotes::install_github("surveydown-dev/surveydown", force = TRUE)

Example survey with button:

---
server: shiny
filters: [surveydown]
---

```{r}
#| context: setup
#| echo: false
#| warning: false
#| message: false

library(surveydown)
sd_setup()

::: {#welcome .sd-page}

Here's a button. Each time you press it, the button press count is incremented.

actionButton("pressme", "Press me")
textOutput("counter")

:::

#| context: server

count <- reactiveVal(0)

observeEvent(input$pressme, {
  count(count() + 1)
})

output$counter <- renderText({
  paste("Button pressed", count(), "times")
})

db <- sd_database(pause  = TRUE)

config <- sd_config()

sd_server(
  input   = input,
  output  = output,
  session = session,
  config  = config,
  db      = db
)
CyuHat commented 2 months ago

Hi! Thank you so much for your time, it works! Thank you again for this amazing project and I wish it keeps growing.