-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathserver.R
1587 lines (1420 loc) · 54.6 KB
/
server.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Server logic for a surveydown survey
#'
#' @description
#' This function defines the server-side logic for a 'shiny' application used in
#' surveydown. It handles various operations such as conditional display,
#' progress tracking, page navigation, database updates for survey responses,
#' and exit survey functionality.
#'
#' @param db A list containing database connection information created using
#' `sd_database()` function. Defaults to `NULL`.
#' @param required_questions Vector of character strings. The IDs of questions
#' that must be answered. Defaults to `NULL`.
#' @param all_questions_required Logical. If `TRUE`, all questions in the
#' survey will be required. Defaults to `FALSE`.
#' @param start_page Character string. The ID of the page to start on.
#' Defaults to `NULL`.
#' @param auto_scroll Logical. Whether to enable auto-scrolling to the next
#' question after answering. Defaults to `FALSE`.
#' @param rate_survey Logical. If `TRUE`, shows a rating question when exiting
#' the survey. If `FALSE`, shows a simple confirmation dialog.
#' Defaults to `FALSE`.
#' @param language Set the language for the survey system messages. Include
#' your own in a `translations.yml` file, or choose a built in one from
#' the following list: English (`"en"`), German (`"de"`), Spanish (`"es"`),
#' French (`"fr"`), Italian (`"it"`), Simplified Chinese (`"zh-CN"`).
#' Defaults to `"en"`.
#' @param use_cookies Logical. If `TRUE`, enables cookie-based session management
#' for storing and restoring survey progress. Defaults to `TRUE`.
#'
#' @details
#' The function performs the following tasks:
#' \itemize{
#' \item Initializes variables and reactive values.
#' \item Implements conditional display logic for questions.
#' \item Tracks answered questions and updates the progress bar.
#' \item Handles page navigation and skip logic.
#' \item Manages required questions.
#' \item Performs database operation.
#' \item Controls auto-scrolling behavior based on the `auto_scroll` argument.
#' \item Uses sweetalert for warning messages when required questions are not
#' answered.
#' \item Handles the exit survey process based on the `rate_survey` argument.
#' }
#'
#' @section Progress Bar:
#' The progress bar is updated based on the last answered question. It will jump
#' to the percentage corresponding to the last answered question and will never
#' decrease, even if earlier questions are answered later. The progress is
#' calculated as the ratio of the last answered question's index to the total
#' number of questions.
#'
#' @section Database Operations:
#' If `db` is provided, the function will update the database with survey
#' responses. If `db` is `NULL` (ignore mode), responses will be saved to a local
#' CSV file.
#'
#' @section Auto-Scrolling:
#' When `auto_scroll` is `TRUE`, the survey will automatically scroll to the
#' next question after the current question is answered. This behavior can be
#' disabled by setting `auto_scroll = FALSE`.
#'
#' @section Exit Survey:
#' When `rate_survey = TRUE`, the function will show a rating question when
#' the user attempts to exit the survey. When `FALSE`, it will show a simple
#' confirmation dialog. The rating, if provided, is saved with the survey data.
#'
#' @return
#' This function does not return a value; it sets up the server-side logic for
#' the 'shiny' application.
#'
#' @examples
#' if (interactive()) {
#' library(surveydown)
#'
#' # Get path to example survey file
#' survey_path <- system.file("examples", "basic_survey.qmd",
#' package = "surveydown")
#'
#' # Copy to a temporary directory
#' temp_dir <- tempdir()
#' file.copy(survey_path, file.path(temp_dir, "survey.qmd"))
#' orig_dir <- getwd()
#' setwd(temp_dir)
#'
#' # Define a minimal server
#' server <- function(input, output, session) {
#'
#' # sd_server() accepts these following parameters
#' sd_server(
#' db = NULL,
#' required_questions = NULL,
#' all_questions_required = FALSE,
#' start_page = NULL,
#' auto_scroll = FALSE,
#' rate_survey = FALSE,
#' language = "en",
#' use_cookies = TRUE
#' )
#' }
#'
#' # Run the app
#' shiny::shinyApp(ui = sd_ui(), server = server)
#'
#' # Clean up
#' setwd(orig_dir)
#' }
#'
#' @seealso
#' `sd_database()`, `sd_ui()`
#'
#' @export
sd_server <- function(
db = NULL,
required_questions = NULL,
all_questions_required = FALSE,
start_page = NULL,
auto_scroll = FALSE,
rate_survey = FALSE,
language = "en",
use_cookies = TRUE
) {
# 1. Initialize local variables ----
# Get input, output, and session from the parent environment
parent_env <- parent.frame()
input <- get("input", envir = parent_env)
output <- get("output", envir = parent_env)
session <- get("session", envir = parent_env)
session$userData$db <- db
# Tag start time
time_start <- get_utc_timestamp()
# Get any skip or show conditions
show_if <- shiny::getDefaultReactiveDomain()$userData$show_if
skip_forward <- shiny::getDefaultReactiveDomain()$userData$skip_forward
# Run the configuration settings
config <- run_config(
required_questions,
all_questions_required,
start_page,
skip_forward,
show_if,
rate_survey,
language
)
# Create local objects from config file
pages <- config$pages
page_ids <- config$page_ids
question_ids <- config$question_ids
question_structure <- config$question_structure
start_page <- config$start_page
question_required <- config$question_required
page_id_to_index <- stats::setNames(seq_along(page_ids), page_ids)
# Pre-compute timestamp IDs
page_ts_ids <- paste0("time_p_", page_ids)
question_ts_ids <- paste0("time_q_", question_ids)
start_page_ts_id <- page_ts_ids[which(page_ids == start_page)]
all_ids <- c('time_end', question_ids, question_ts_ids, page_ts_ids)
# Create current_page_id reactive value
current_page_id <- shiny::reactiveVal(start_page)
# Progress bar
max_progress <- shiny::reactiveVal(0)
last_answered_question <- shiny::reactiveVal(0)
update_progress_bar <- function(index) {
if (index > last_answered_question()) {
last_answered_question(index)
current_progress <- index / length(question_ids)
max_progress(max(max_progress(), current_progress))
session$sendCustomMessage("updateProgressBar", max_progress() * 100)
}
}
# Initialize session handling and session_id
session_id <- session$token
session_id <- handle_sessions(session_id, db, session, input, time_start, start_page,
current_page_id, question_ids, question_ts_ids,
update_progress_bar, use_cookies)
# Auto scroll
session$sendCustomMessage("updateSurveydownConfig", list(autoScrollEnabled = auto_scroll))
# Check if db is NULL (either blank or specified with ignore = TRUE)
ignore_mode <- is.null(db)
# Initialize translations list (from '_survey/translations.yml' file)
translations <- get_translations()$translations
# Keep-alive observer - this will be triggered every 60 seconds
shiny::observeEvent(input$keepAlive, {
cat("Session keep-alive at", format(Sys.time(), "%m/%d/%Y %H:%M:%S"), "\n")
})
# 2. show_if conditions ----
# Reactive to store visibility status of all questions
question_visibility <- shiny::reactiveVal(
stats::setNames(rep(TRUE, length(question_ids)), question_ids)
)
# Observer to apply show_if conditions and update question_visibility
shiny::observe({
shiny::reactiveValuesToList(input)
show_if_results <- set_show_if_conditions(show_if)()
current_visibility <- question_visibility()
for (target in names(show_if_results)) {
current_visibility[target] <- show_if_results[[target]]
if (show_if_results[[target]]) {
shinyjs::show(paste0('container-', target))
} else {
shinyjs::hide(paste0('container-', target))
}
}
question_visibility(current_visibility)
})
# 3. Update data ----
update_data <- function(time_last = FALSE) {
data_list <- latest_data()
fields <- changed_fields()
# Only update fields that have actually changed and have values
if (length(fields) > 0) {
# Filter out fields with empty values unless explicitly changed
valid_fields <- character(0)
for (field in fields) {
if (!is.null(data_list[[field]]) && data_list[[field]] != "") {
valid_fields <- c(valid_fields, field)
}
}
fields <- valid_fields
} else {
# On initial load or restoration, use all non-empty fields
fields <- names(data_list)[sapply(data_list, function(x) !is.null(x) && x != "")]
}
if (time_last) {
data_list[['time_end']] <- get_utc_timestamp()
fields <- unique(c(fields, 'time_end'))
}
# Local data handling
if (ignore_mode) {
if (file.access('.', 2) == 0) {
tryCatch({
# Read existing data
existing_data <- if (file.exists("preview_data.csv")) {
utils::read.csv("preview_data.csv", stringsAsFactors = FALSE)
} else {
data.frame()
}
# Convert current data_list to data frame
new_data <- as.data.frame(data_list, stringsAsFactors = FALSE)
# If there is existing data, update or append based on session_id
if (nrow(existing_data) > 0) {
# Find if this session_id already exists
session_idx <- which(existing_data$session_id == data_list$session_id)
if (length(session_idx) > 0) {
# Update existing session data
for (field in fields) {
if (field %in% names(existing_data)) {
existing_data[session_idx, field] <- data_list[[field]]
} else {
# Add new column with NAs, then update the specific row
existing_data[[field]] <- NA
existing_data[session_idx, field] <- data_list[[field]]
}
}
updated_data <- existing_data
} else {
# Ensure all columns from existing_data are in new_data
missing_cols <- setdiff(names(existing_data), names(new_data))
for (col in missing_cols) {
new_data[[col]] <- NA
}
# Ensure all columns from new_data are in existing_data
missing_cols <- setdiff(names(new_data), names(existing_data))
for (col in missing_cols) {
existing_data[[col]] <- NA
}
# Now both data frames should have the same columns
updated_data <- rbind(existing_data, new_data[names(existing_data)])
}
} else {
# If no existing data, use new data
updated_data <- new_data
}
# Write updated data back to file
utils::write.csv(
updated_data,
"preview_data.csv",
row.names = FALSE,
na = ""
)
}, error = function(e) {
warning("Unable to write to preview_data.csv: ", e$message)
message("Error details: ", e$message)
})
} else {
message("Running in a non-writable environment.")
}
} else {
database_uploading(data_list, db$db, db$table, fields)
}
# Only reset changed fields that were actually processed
changed_fields(setdiff(changed_fields(), fields))
}
# 4. Data tracking ----
# First check and initialize table if needed
if (!ignore_mode) {
# Create a minimal initial data just for table creation
min_initial_data <- list(
session_id = character(0),
time_start = character(0),
time_end = character(0)
)
table_exists <- pool::poolWithTransaction(db$db, function(conn) {
DBI::dbExistsTable(conn, db$table)
})
if (!table_exists) {
create_table(min_initial_data, db$db, db$table)
}
}
# Now handle session and get proper initial data
initial_data <- get_initial_data(
session, session_id, time_start, all_ids, start_page_ts_id
)
all_data <- do.call(shiny::reactiveValues, initial_data)
# Reactive expression that returns a list of the latest data
latest_data <- shiny::reactive({
# Convert reactiveValues to a regular list
data <- shiny::reactiveValuesToList(all_data)
# Ensure all elements are of length 1, use "" for empty or NULL values
data <- lapply(data, function(x) {
if (length(x) == 0 || is.null(x) || (is.na(x) && !is.character(x))) "" else as.character(x)[1]
})
data[names(data) != ""]
})
# Reactive value to track which fields have changed
changed_fields <- shiny::reactiveVal(names(initial_data))
# Expose all_data and changed_fields to session's userData for use by sd_store_value
session$userData$all_data <- all_data
session$userData$changed_fields <- changed_fields
# Update checkpoint 1 - when session starts
shiny::isolate({
update_data()
})
# 5. Main question observers ----
lapply(seq_along(question_ids), function(index) {
local({
local_id <- question_ids[index]
local_ts_id <- question_ts_ids[index]
shiny::observeEvent(input[[local_id]], {
# Tag event time and update value
timestamp <- get_utc_timestamp()
value <- input[[local_id]]
formatted_value <- format_question_value(value)
all_data[[local_id]] <- formatted_value
# Update timestamp and progress if interacted
changed <- local_id
if (!is.null(input[[paste0(local_id, "_interacted")]])) {
all_data[[local_ts_id]] <- timestamp
changed <- c(changed, local_ts_id)
update_progress_bar(index)
}
# Update tracker of which fields changed
changed_fields(c(changed_fields(), changed))
# Get question labels and values from question structure
question_info <- question_structure[[local_id]]
label_question <- question_info$label
options <- question_info$options
label_options <- names(options)
# For the selected value(s), get the corresponding label(s)
if (length(options) == length(label_options)) {
names(options) <- label_options
}
label_option <- if (is.null(value) || length(value) == 0) {
""
} else {
options[options %in% value] |>
names() |>
paste(collapse = ", ")
}
# Store the values and labels in output
output[[paste0(local_id, "_value")]] <- shiny::renderText({
formatted_value
})
output[[paste0(local_id, "_label_option")]] <- shiny::renderText({
label_option
})
output[[paste0(local_id, "_label_question")]] <- shiny::renderText({
label_question
})
},
ignoreNULL = FALSE,
ignoreInit = TRUE)
})
})
# Observer to update cookies with answers
shiny::observe({
# Get current page ID
page_id <- current_page_id()
# Get all questions for current page
page_questions <- names(input)[names(input) %in% question_ids]
# Create answers list
answers <- list()
last_timestamp <- NULL
max_index <- 0
for (q_id in page_questions) {
# Get question value
val <- input[[q_id]]
if (!is.null(val)) {
answers[[q_id]] <- val
# If question was interacted with, check its position
if (!is.null(input[[paste0(q_id, "_interacted")]])) {
# Find this question's index in the overall sequence
current_index <- match(q_id, question_ids)
if (!is.na(current_index) && current_index > max_index) {
max_index <- current_index
last_timestamp <- list(
id = paste0("time_q_", q_id),
time = get_utc_timestamp()
)
}
}
}
}
# Send to client to update cookie
if (length(answers) > 0 && !is.null(db)) { # Only update cookies in db mode
page_data <- list(
answers = answers,
last_timestamp = last_timestamp
)
session$sendCustomMessage("setAnswerData",
list(pageId = page_id,
pageData = page_data))
}
})
# 6. Page rendering ----
# Create reactive values for the start page ID
get_current_page <- shiny::reactive({
pages[[which(sapply(pages, function(p) p$id == current_page_id()))]]
})
# Render main page content when current page changes
output$main <- shiny::renderUI({
current_page <- get_current_page()
shiny::tagList(
shiny::tags$div(
class = "content",
shiny::tags$div(
class = "page-columns page-rows-contents page-layout-article",
shiny::tags$div(
id = "quarto-content",
role = "main",
shiny::HTML(current_page$content)
)
)
)
)
})
# 7. Page navigation ----
check_required <- function(page) {
required_questions <- page$required_questions
is_visible <- question_visibility()[required_questions]
all(vapply(required_questions, function(q) {
if (!is_visible[q]) return(TRUE)
if (question_structure[[q]]$is_matrix) {
all(sapply(question_structure[[q]]$row, function(r) check_answer(paste0(q, "_", r), input)))
} else {
check_answer(q, input)
}
}, logical(1)))
}
# Determine which page is next, then update current_page_id() to it
shiny::observe({
lapply(pages, function(page) {
shiny::observeEvent(input[[page$next_button_id]], {
shiny::isolate({
# Grab the time stamp of the page turn
timestamp <- get_utc_timestamp()
# Figure out page ids
current_page_id <- page$id
next_page_id <- get_default_next_page(
page, page_ids, page_id_to_index
)
next_page_id <- handle_skip_logic(
input, skip_forward,
current_page_id, next_page_id,
page_id_to_index
)
if (!is.null(next_page_id) && check_required(page)) {
# Set the current page as the next page
current_page_id(next_page_id)
# Update the page time stamp
next_ts_id <- page_ts_ids[which(page_ids == next_page_id)]
all_data[[next_ts_id]] <- timestamp
# Save the current page to all_data
all_data[["current_page"]] <- next_page_id
# Update tracker of which fields changed
changed_fields(c(changed_fields(), next_ts_id, "current_page"))
# Update checkpoint 2 - upon going to the next page
update_data()
} else if (!is.null(next_page_id)) {
shinyWidgets::sendSweetAlert(
session = session,
title = translations[["warning"]],
text = translations[["required"]],
type = "warning"
)
}
})
})
})
})
# Observer to max out the progress bar when we reach the last page
shiny::observe({
page <- get_current_page()
if (is.null(page$next_page_id)) {
update_progress_bar(length(question_ids))
}
})
# 8. Survey rating and exit ----
# Observer for the exit survey modal
shiny::observeEvent(input$show_exit_modal, {
if (rate_survey) {
shiny::showModal(shiny::modalDialog(
title = translations[["rating_title"]],
sd_question(
type = 'mc_buttons',
id = 'survey_rating',
label = glue::glue("{translations[['rating_text']]}:<br><small>({translations[['rating_scale']]})</small>"),
option = c(
"1" = "1",
"2" = "2",
"3" = "3",
"4" = "4",
"5" = "5"
)
),
footer = shiny::tagList(
shiny::modalButton(translations[["cancel"]]),
shiny::actionButton("submit_rating", translations[["submit_exit"]])
)
))
} else {
shiny::showModal(shiny::modalDialog(
title = translations[["confirm_exit"]],
translations[["sure_exit"]],
footer = shiny::tagList(
shiny::modalButton(translations[["cancel"]]),
shiny::actionButton("confirm_exit", translations[["exit"]])
)
))
}
})
# Observer to handle the rating submission or exit confirmation
shiny::observeEvent(input$submit_rating, {
# Save the rating
rating <- input$survey_rating
all_data[['exit_survey_rating']] <- rating
changed_fields(c(changed_fields(), 'exit_survey_rating'))
# Update checkpoint 3 - when submitting rating
shiny::isolate({
update_data(time_last = TRUE)
})
# Close the modal and the window
shiny::removeModal()
session$sendCustomMessage("closeWindow", list())
})
shiny::observeEvent(input$confirm_exit, {
# Update checkpoint 4 - when exiting survey
shiny::isolate({
update_data(time_last = TRUE)
})
# Close the modal and the window
shiny::removeModal()
session$sendCustomMessage("closeWindow", list())
})
# Update checkpoint 5 - when session ends
shiny::onSessionEnded(function() {
shiny::isolate({
update_data(time_last = TRUE)
})
})
}
#' Define forward skip conditions for survey pages
#'
#' @description
#' This function is used to define conditions under which certain pages in the
#' survey should be skipped ahead to (forward only). It takes one or more formulas
#' where the left-hand side is the condition and the right-hand side is the target page ID.
#'
#' @param ... One or more formulas defining skip conditions.
#' The left-hand side of each formula should be a condition based on input
#' values, and the right-hand side should be the ID of the page to skip to if
#' the condition is met. Only forward skipping (to pages later in the sequence) is allowed.
#'
#' @return A list of parsed conditions, where each element contains the
#' condition and the target page ID.
#'
#' @examples
#' if (interactive()) {
#' library(surveydown)
#'
#' # Get path to example survey file
#' survey_path <- system.file("examples", "sd_skip_forward.qmd",
#' package = "surveydown")
#'
#' # Copy to a temporary directory
#' temp_dir <- tempdir()
#' file.copy(survey_path, file.path(temp_dir, "survey.qmd"))
#' orig_dir <- getwd()
#' setwd(temp_dir)
#'
#' # Define a minimal server
#' server <- function(input, output, session) {
#'
#' # Skip forward to specific pages based on fruit selection
#' sd_skip_forward(
#' input$fav_fruit == "apple" ~ "apple_page",
#' input$fav_fruit == "orange" ~ "orange_page",
#' input$fav_fruit == "other" ~ "other_page"
#' )
#'
#' sd_server()
#' }
#'
#' # Run the app
#' shiny::shinyApp(ui = sd_ui(), server = server)
#'
#' # Clean up
#' setwd(orig_dir)
#' }
#'
#' @seealso `sd_show_if()`
#'
#' @export
sd_skip_forward <- function(...) {
conditions <- parse_conditions(...)
calling_env <- parent.frame()
# Process each condition
processed_conditions <- lapply(conditions, function(rule) {
tryCatch({
# Store the original condition for use with function calls
rule$original_condition <- rule$condition
# Extract any reactive expressions that might be called
# We're storing the environment for potential evaluation later
rule$calling_env <- calling_env
# # For debugging
# cat("Captured condition: ", deparse(rule$condition), "\n")
return(rule)
}, error = function(e) {
warning("Error processing condition: ", e$message)
return(rule)
})
})
# Store in userData
shiny::isolate({
session <- shiny::getDefaultReactiveDomain()
if (is.null(session)) {
stop("sd_skip_forward must be called within a Shiny reactive context")
}
if (is.null(session$userData$skip_forward)) {
session$userData$skip_forward <- list()
}
session$userData$skip_forward$conditions <- processed_conditions
session$userData$skip_forward$targets <- get_unique_targets(processed_conditions)
})
}
#' Define skip conditions for survey pages (Deprecated)
#'
#' @description
#' This function is deprecated. Please use `sd_skip_forward()` instead.
#'
#' This function is used to define conditions under which certain pages in the
#' survey should be skipped. It now behaves like `sd_skip_forward()` where only forward
#' skipping is allowed to prevent navigation loops.
#'
#' @param ... One or more formulas defining skip conditions.
#' The left-hand side of each formula should be a condition based on input
#' values, and the right-hand side should be the ID of the page to skip to if
#' the condition is met.
#'
#' @return A list of parsed conditions, where each element contains the
#' condition and the target page ID.
#'
#' @export
sd_skip_if <- function(...) {
# v0.9.0
.Deprecated("sd_skip_forward()")
sd_skip_forward(...)
}
#' Define show conditions for survey questions
#'
#' @description
#' This function is used to define conditions under which certain questions in the survey should be shown.
#' It takes one or more formulas where the left-hand side is the condition and the right-hand side is the target question ID.
#' If called with no arguments, it will return `NULL` and set no conditions.
#'
#' @param ... One or more formulas defining show conditions.
#' The left-hand side of each formula should be a condition based on input values,
#' and the right-hand side should be the ID of the question to show if the condition is met.
#'
#' @return A list of parsed conditions, where each element contains the condition and the target question ID.
#' Returns `NULL` if no conditions are provided.
#'
#' @examples
#' if (interactive()) {
#' library(surveydown)
#'
#' # Get path to example survey file
#' survey_path <- system.file("examples", "sd_show_if.qmd",
#' package = "surveydown")
#'
#' # Copy to a temporary directory
#' temp_dir <- tempdir()
#' file.copy(survey_path, file.path(temp_dir, "survey.qmd"))
#' orig_dir <- getwd()
#' setwd(temp_dir)
#'
#' # Define a minimal server
#' server <- function(input, output, session) {
#'
#' sd_show_if(
#' # If "Other" is chosen, show the conditional question
#' input$fav_fruit == "other" ~ "fav_fruit_other"
#' )
#'
#' sd_server()
#' }
#'
#' # Run the app
#' shiny::shinyApp(ui = sd_ui(), server = server)
#'
#' # Clean up
#' setwd(orig_dir)
#' }
#'
#' @seealso `sd_skip_forward()`
#'
#' @export
sd_show_if <- function(...) {
conditions <- parse_conditions(...)
calling_env <- parent.frame()
# Process each condition
processed_conditions <- lapply(conditions, function(rule) {
tryCatch({
# Store the original condition for use with function calls
rule$original_condition <- rule$condition
# Store the calling environment for later evaluation
rule$calling_env <- calling_env
# # For debugging
# cat("Captured show_if condition: ", deparse(rule$condition), "\n")
return(rule)
}, error = function(e) {
warning("Error processing show_if condition: ", e$message)
return(rule)
})
})
# Create a list in userData to store the show_if targets
shiny::isolate({
session <- shiny::getDefaultReactiveDomain()
if (is.null(session)) {
stop("sd_show_if must be called within a Shiny reactive context")
}
if (is.null(session$userData$show_if)) {
session$userData$show_if <- list()
}
session$userData$show_if$conditions <- processed_conditions
session$userData$show_if$targets <- get_unique_targets(processed_conditions)
})
}
#' Set password for surveydown survey
#'
#' This function sets your surveydown password, which is used to access
#' the 'PostgreSQL' data (e.g. Supabase). The password is saved in a `.Renviron`
#' file and adds `.Renviron` to `.gitignore`.
#'
#' @param password Character string. The password to be set for the database
#' connection.
#'
#' @details The function performs the following actions:
#' 1. Creates a `.Renviron` file in the root directory if it doesn't exist.
#' 2. Adds or updates the `SURVEYDOWN_PASSWORD` entry in the `.Renviron` file.
#' 3. Adds `.Renviron` to `.gitignore` if it's not already there.
#'
#' @return None. The function is called for its side effects.
#'
#' @examples
#' \dontrun{
#' # Set a temporary password for demonstration
#' temp_password <- paste0(sample(letters, 10, replace = TRUE), collapse = "")
#'
#' # Set the password
#' sd_set_password(temp_password)
#'
#' # After restarting R, verify the password was set
#' cat("Password is :", Sys.getenv('SURVEYDOWN_PASSWORD'))
#' }
#'
#' @export
sd_set_password <- function(password) {
# v0.8.0
.Deprecated("sd_db_config")
# Define the path to .Renviron file
renviron_path <- file.path(getwd(), ".Renviron")
# Check if .Renviron file exists, if not create it
if (!file.exists(renviron_path)) {
file.create(renviron_path)
}
# Read existing content
existing_content <- readLines(renviron_path)
# Check if SURVEYDOWN_PASSWORD is already defined
password_line_index <- grep("^SURVEYDOWN_PASSWORD=", existing_content)
# Prepare the new password line
new_password_line <- paste0("SURVEYDOWN_PASSWORD=", password)
# If SURVEYDOWN_PASSWORD is already defined, replace it; otherwise, append it
if (length(password_line_index) > 0) {
existing_content[password_line_index] <- new_password_line
} else {
existing_content <- c(existing_content, new_password_line)
}
# Write the updated content back to .Renviron
writeLines(existing_content, renviron_path)
# Add .Renviron to .gitignore if not already there
gitignore_path <- file.path(getwd(), ".gitignore")
if (file.exists(gitignore_path)) {
gitignore_content <- readLines(gitignore_path)
if (!".Renviron" %in% gitignore_content) {
# Remove any trailing empty lines
while (length(gitignore_content) > 0 && gitignore_content[length(gitignore_content)] == "") {
gitignore_content <- gitignore_content[-length(gitignore_content)]
}
# Add .Renviron to the end without an extra newline
gitignore_content <- c(gitignore_content, ".Renviron")
writeLines(gitignore_content, gitignore_path)
}
} else {
writeLines(".Renviron", gitignore_path)
}
message("Password set successfully and .Renviron added to .gitignore.")
}
#' Store a value in the survey data
#'
#' This function allows storing additional values to be included in the survey
#' data, such as respondent IDs or other metadata.
#'
#' @param value The value to be stored. This can be any R object that can be
#' coerced to a character string.
#' @param id (Optional) Character string. The id (name) of the value in the
#' data. If not provided, the name of the `value` variable will be used.
#'
#' @return `NULL` (invisibly)
#'
#' @examples
#' if (interactive()) {
#' library(surveydown)
#'
#' # Get path to example survey file
#' survey_path <- system.file("examples", "sd_ui.qmd",
#' package = "surveydown")
#'
#' # Copy to a temporary directory
#' temp_dir <- tempdir()
#' file.copy(survey_path, file.path(temp_dir, "basic_survey.qmd"))
#' orig_dir <- getwd()
#' setwd(temp_dir)
#'
#' # Define a minimal server
#' server <- function(input, output, session) {
#'
#' # Create a respondent ID to store
#' respondentID <- 42
#'
#' # Store the respondentID
#' sd_store_value(respondentID)
#'
#' # Store the respondentID as the variable "respID"
#' sd_store_value(respondentID, "respID")
#'
#' sd_server()
#' }
#'
#' # Run the app
#' shiny::shinyApp(ui = sd_ui(), server = server)
#'
#' # Clean up
#' setwd(orig_dir)
#' }
#'
#' @export
sd_store_value <- function(value, id = NULL) {
if (is.null(id)) {
id <- deparse(substitute(value))
}
shiny::isolate({
session <- shiny::getDefaultReactiveDomain()
if (is.null(session)) {
stop("sd_store_value must be called from within a Shiny reactive context")
}
# Initialize stored_values if it doesn't exist
if (is.null(session$userData$stored_values)) {
session$userData$stored_values <- list()
}
formatted_value <- format_question_value(value)
session$userData$stored_values[[id]] <- formatted_value
# Make value accessible in the UI
output <- shiny::getDefaultReactiveDomain()$output
output[[paste0(id, "_value")]] <- shiny::renderText({ formatted_value })
# Get access to all_data and update it if available
# This allows the stored value to be accessible through sd_output
if (!is.null(session$userData$all_data)) {
session$userData$all_data[[id]] <- formatted_value
# Add to changed fields to trigger database update
if (!is.null(session$userData$changed_fields)) {
current_fields <- session$userData$changed_fields()