-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathformods.R
More file actions
3508 lines (3052 loc) · 117 KB
/
formods.R
File metadata and controls
3508 lines (3052 loc) · 117 KB
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
#' formods: Shiny modules for common tasks.
#'
#' Shiny apps can often make use of the same key elements, this package
#' provides modules for common tasks (data upload, wrangling data, figure
#' generation and saving the app state). These modules can react and interact
#' as well as generate code to create reproducible analyses.
#'
#' @seealso \url{https://formods.ubiquity.tools/}
#' @docType package
#' @name formods
"_PACKAGE"
#'@import cli
#'@importFrom digest digest
#'@importFrom rio export
.onAttach <- function(libname, pkgname){
#------------------------------------
# If all the suggested packages are found this will be true:
suggested_found = TRUE
packageStartupMessage("Loading formods")
fcres = formods_check(verbose = FALSE)
if(!fcres[["all_found"]]){
packageStartupMessage("Missing suggested packages")
for(pkg in fcres[["missing_pkgs"]]){
packageStartupMessage(paste0(" - ",pkg))
}
packageStartupMessage("")
packageStartupMessage("Install with the following:")
packageStartupMessage(paste0('install.packages(c("', paste0(fcres[["missing_pkgs"]], collapse='", "'), '"))'))
}
}
#'@export
#'@title Checks `formods` Dependencies
#'@description Looks at the suggested dependencies and checks to make sure
#'@param verbose Logical indicating if messages should be displayed
#'@return List with the following elements:
#' \itemize{
#' \item{all_found:} Boolean indicating if all packages were found
#' \item{found_pkgs:} Character vector of found packages
#' \item{missing_pkgs:} Character vector of missing packages
#'}
#'@examples
#' fcres = formods_check()
formods_check <- function(verbose=TRUE){
#------------------------------------
# Checking for rxpackages
# If all the suggested packages are found this will be true:
suggested_found = TRUE
if(verbose){
mr = FM_message("Checking formods for suggested packages", entry_type="h1")
}
pkgs = c(
"clipr",
"covr",
"devtools",
"DT",
"flextable",
"ggpubr",
"gtools",
"here",
"janitor",
"knitr",
"plotly",
"prompter",
"rmarkdown",
"shinybusy",
"shinydashboard",
"testthat",
"zoo",
"utils")
pkg_found = c()
pkg_missing = c()
for(pkg in pkgs){
if(!requireNamespace(pkg, quietly=TRUE)){
if(verbose){
mr = FM_message(paste0("missing ", pkg), entry_type="danger")
}
pkg_missing = c(pkg_missing, pkg)
suggested_found = FALSE
} else {
if(verbose){
mr = FM_message(paste0("found ", pkg), entry_type="success")
}
pkg_found = c(pkg_found , pkg)
}
}
res = list(
all_found = suggested_found,
found_pkgs = pkg_found,
missing_pkgs = pkg_missing
)
res}
#'@export
#'@title Fetches Datasets from Modules in the App
#'@description Loops through each specified module ID or all modules if no ID
#'was specified. For each ID, an attempt will be made to extract any datasets
#'available.
#'@param state Current module state after yaml file has been read
#'@param session Shiny session variable
#'@param ids Vector of ID strings for the modules containing the datasets or
#'@param meta_only Include only metadata and not the dataset (default \code{FALSE})
#'NULL for all datasets available.
#'@return list containing the current dataset with the following format:
#' \itemize{
#' \item{isgood:} Boolean indicating the whether a dataset was found
#' (\code{FALSE})
#' \item{ds:} List of datasets with element names corresponding to the
#' R object name for that dataset. This has the following format
#' \itemize{
#' \item{label:} Text label for the dataset (used to display to the user)
#' \item{DS:} Data frame with the dataset
#' \item{DSMETA:} Optional data frame with metadata about the colunns of the
#' dataset in \code{DS}.
#' \item{code:} Code to generate the dataset.
#' \item{checksum:} Module checksum when the dataset was pulled
#' \item{DSchecksum:} Checksum of the dataframe in DS
#' }
#' \item{choices:} List of values to use with selectInput()/pickerInput()
#' \itemize{
#' \item{plain:} Raw vector of choices
#' \item{labeled:} Named vector of choices
#' \item{grouped:} Choices grouped by module
#' }
#' \item{catalog:} Dataframe containing the a tabular catalog of the
#' datasets found.
#' \itemize{
#' \item{label:} Text label
#' \item{object:} Name of the R Object containing the data frame
#' \item{MOD_TYPE:} Short name of the type of module
#' \item{id:} Module ID
#' \item{idx:} Numerical identifier within the module
#' \item{res_label: optional label that can be defined by a user and used in
#' workflows. Must be unique to the module.}
#' \item{checksum:} Module checksum
#' \item{DSchecksum:} Checksum of the dataset
#' \item{code:} Code to generate the dataset
#' }
#' \item{modules:} List with an entry for each module. The element name is
#' the short name. Each of these is a list with an entry that is the shiny module
#' ID. For each of these there is a checksum. For example to access the
#' checksum of a DW module with a module ID of 'my_id', you would use the
#' following: \code{res$modules$DW$my_id}.
#' \item{module_ids:} List with an entry for each module_id. The element name is
#' the module id. For each of these there is a checksum. For example to access the
#' checksum of a module with id of 'my_id', you would use the
#' following: \code{res$module_ids$my_id}.
#' }
#'@examples
#' # We need a module state and a Shiny session variable
#' # to use this function:
#' sess_res = UD_test_mksession()
#' session = sess_res$session
#' state = sess_res$state
#' ds = FM_fetch_ds(state, session)
#' ds$catalog
FM_fetch_ds = function(state, session, ids=NULL, meta_only = FALSE){
isgood = TRUE
hasds = FALSE
catalog = NULL
ds = list()
modules = list()
module_ids = list()
choices = list()
# Pulling out the app state:
app_state = FM_fetch_app_state(session)
# If we're null then we walk through the session variable and pull out all
# the IDs to be used below
if(is.null(ids)){
for(mod_state in names(app_state)){
ids = c(ids, app_state[[mod_state]]$id)
}
}
# Walking through each module id and attempting to extract a dataset
MOD_DESC_list = list()
for(tmp_id in ids){
# pulling out the current module state and creating the
# name of the ds fetching function for that module
tmp_state = FM_fetch_mod_state(session, tmp_id)
tmp_MOD_TYPE = tmp_state[["MOD_TYPE"]]
MOD_FUNC = paste0(tmp_MOD_TYPE, "_fetch_ds")
MOD_DESC = tmp_state[["MC"]][["module"]][["description"]]
if(is.null(tmp_state[["MC"]][["module"]][["description"]])){
MOD_DESC = tmp_id
}
# If that module has a ds fetching function then we try to fetch it:
if(exists(MOD_FUNC, mode="function")){
# Function call used to fetch a dataset
fetch_ds_res = NULL
FUNC_CALL = paste0("fetch_ds_res = ", MOD_FUNC,"(state = tmp_state, meta_only = ", toString(meta_only), ")")
eval(parse(text=FUNC_CALL))
if(fetch_ds_res[["hasds"]]){
# We've found at least one dataset
hasds = TRUE
MOD_DESC_list[names(fetch_ds_res[["ds"]])] = MOD_DESC
ds = c(ds, fetch_ds_res[["ds"]])
}
}
}
if(hasds){
# Creating catalog and modules elements:
tmp_choices_group = list()
tmp_choices_group_labels = list()
for(dsname in names(ds)){
catalog = rbind(
catalog,
data.frame(
label = ds[[dsname]][["label"]],
object = dsname,
MOD_TYPE = ds[[dsname]][["MOD_TYPE"]],
MOD_DESC = MOD_DESC_list[[dsname]],
id = ds[[dsname]][["id"]],
idx = ds[[dsname]][["idx"]],
res_label = ds[[dsname]][["res_label"]],
checksum = ds[[dsname]][["checksum"]],
DSchecksum = ds[[dsname]][["DSchecksum"]],
code = ds[[dsname]][["code"]])
)
# Stores the values for the selector
tmp_choices_group[[ MOD_DESC_list[[dsname]] ]] = c(
tmp_choices_group[[ MOD_DESC_list[[dsname]] ]],
dsname)
# corresponding list storing the lables
tmp_choices_group_labels[[ MOD_DESC_list[[dsname]] ]] = c(
tmp_choices_group_labels[[ MOD_DESC_list[[dsname]] ]],
ds[[dsname]][["label"]])
modules[[ ds[[dsname]][["MOD_TYPE"]]] ][[ ds[[dsname]][["id"]] ]] = ds[[dsname]][["checksum"]]
module_ids[[ ds[[dsname]][["id"]] ]] = ds[[dsname]][["checksum"]]
}
# This creates choices for selectInput()
choices[["plain"]] = catalog[["object"]]
choices[["labeled"]] = catalog[["object"]]
names(choices[["labeled"]]) = catalog[["label"]]
if(length(tmp_choices_group) > 0){
for(gname in names(tmp_choices_group)){
choices[["grouped"]][[gname]] = tmp_choices_group[[gname]]
names(choices[["grouped"]][[gname]]) = tmp_choices_group_labels[[gname]]
}
}
} else {
isgood = FALSE
}
# Packing everything up to be returned to the user
res = list(isgood = isgood,
hasds = hasds,
catalog = catalog,
modules = modules,
module_ids = module_ids,
choices = choices,
ds = ds)
res}
#'@export
#'@title Automatically Cast UI Input Variable
#'@description Takes UI input and tries to figure out if it's numeric or text
#'@param ui_input UI input from a shiny form
#'@param quote_char TRUE will include double quotes in the character string
#'@return Best guess of type casting applied to the ui_input
#'@examples
#' number = autocast('10')
#' text = autocast('ten')
autocast = function(ui_input, quote_char=TRUE){
ui_input_num = suppressWarnings(as.numeric(as.character(ui_input)))
# NULL returns numeric length zero
# Taken from here:
# https://stackoverflow.com/a/36239701
# as.num = function(x, na.strings = "NA") {
# stopifnot(is.character(x))
# na = x %in% na.strings
# x[na] = "0"
# x = as.numeric(x)
# x[na] = NA_real_
# x
#}
if(any(is.na(ui_input_num)) | (length(ui_input_num) == 0)){
res = as.character(ui_input)
if(quote_char){
res = paste0('"', res, '"')
}
} else {
res = ui_input_num
}
res}
#'@export
#'@title Remove Factor From Object
#'@description Takes an object that is a factor and returns an unfactored
#'vector with the same type by the value removed
#'@param fctobj Factorized object
#'@return Object with factors removed
#'@examples
#'
#' df = data.frame(
#' text = c("a", "b", "c"),
#' float = c( 1 , 2 , 3 ))
#'
#' df$float = as.factor(df$float)
#' # This is a factor
#' df$float
#' # This is not a factor
#' unfactor(df$float)
unfactor = function(fctobj){
res = fctobj
if(is.factor(fctobj)){
objtype = typeof(fctobj)
cmd = paste0("res = as.", objtype,"(as.character(fctobj))");
eval(parse(text=cmd))
}
res}
#'@export
#'@title Depreciated: Detect if a UI element has changed
#'@description Depreciated please use has_updated instead: Takes a UI element value and an older value and determines if
#'it has been modified
#'@param ui_val Current value from the UI.
#'@param old_val Last value of of the element.
#'@param init_value Default value for reading in UI data when it has not been
#'defined.
#'@return Boolean result of the comparison
#'@examples
#' changed_true = has_changed(ui_val = "a", old_val = "")
#' changed_true
#' changed_false = has_changed(ui_val = "a", old_val = "a")
#' changed_false
has_changed = function(ui_val = NULL,
old_val = NULL,
init_value = c("")){
res = FALSE
# Detecting length differences
if(length(ui_val) != length(old_val)){
res = TRUE
} else if((length(ui_val) == length(old_val)) &
length(ui_val) > 1){
# here we're comparing vectors
if(!all(ui_val %in% old_val)){
res = TRUE
}
}
# here we're comparing scalers
if((length(ui_val) == 1) &
(length(old_val) == 1) &
!res
){
if(!is.null(ui_val)){
if(ui_val != 0 & ui_val !=init_value){
if(ui_val != old_val){
res = TRUE
}
}
}
}
res}
#'@export
#'@title Detect if a UI element has updated
#'@description Takes a UI element value and an older value and determines if
#'it has been modified
#'@param ui_val Current value from the UI.
#'@param old_val Last value of of the element.
#'defined.
#'@param init_val List of values to skip. These are values expected to be
#'assigned on initialization. For buttons it may be 0. For others it may be
#'"".
#'@return Boolean result of the comparison
#'@examples
#' changed_true = has_updated(ui_val = "a", old_val = "")
#' changed_true
#' changed_false = has_updated(ui_val = "a", old_val = "a")
#' changed_false
has_updated = function(ui_val = NULL,
old_val = NULL,
init_val = NULL){
res = FALSE
# Detecting length differences
if(length(ui_val) != length(old_val)){
res = TRUE
} else if((length(ui_val) == length(old_val)) &
length(ui_val) > 1){
# here we're comparing vectors
if(!all(ui_val %in% old_val)){
res = TRUE
}
} else {
# Here were checking the value against the init values
init_pass = TRUE
if(!is.null(init_val)){
if(ui_val %in% init_val){
init_pass = FALSE
}
}
# Here we continue checking if we pass the init
if(init_pass){
# here we're comparing scalers
if((length(ui_val) == 1) &
(length(old_val) == 1)){
if(ui_val != old_val){
res = TRUE
#message(paste0("old_val: ", old_val))
#message(paste0("ui_val: ", ui_val))
}
} else {
message("Unknown scenario has_updated:")
message(paste0("old_val: ", old_val))
message(paste0("ui_val: ", ui_val ))
}
}
}
res}
#'@export
#'@title Removes Hold on UI Element
#'@description When some buttons are clicked they will change the state of the
#'system, but other UI components will not detect that change correctly. So those
#'triggers are put on hold. This will remove the hold after those UI
#'components have updated.
#'@param state module state with all of the current ui elements populated
#'@param session Shiny session variable
#'@param inputId The input ID of the UI element that was put on hold
#'@return No return value, called to remove holds.
#'@example inst/test_apps/FM_holds.R
remove_hold = function(state, session, inputId){
FM_ID = paste0("FM_", state[["id"]])
MOD_TYPE = state[["MOD_TYPE"]]
# pulling out the state
state = session$userData[["FM"]][[FM_ID]]
# removing hold on inputId
state[[MOD_TYPE]][["ui_hold"]][[inputId]] = FALSE
# Saving the state
session$userData[["FM"]][[FM_ID]] = state
NULL}
#'@export
#'@title Sets Hold on One or All UI Elements
#'@description When some buttons are clicked they will change the state of the
#'system, but other UI components will not detect that change correctly. So those
#'triggers are put on hold. This will set the hold for a specified inputId or
#'all ids if that value is set to NULL
#'@param state module state with all of the current ui elements populated
#'@param inputId The input ID of the UI element that was put on hold or
#'\code{NULL} to hold all IDs in the module
#'@return state with hold or holds set
#'@example inst/test_apps/FM_holds.R
set_hold = function(state, inputId=NULL){
isgood = TRUE
MOD_TYPE = state[["MOD_TYPE"]]
if(is.null(inputId)){
# here we set the hold for all inputIds in the module
for(tmpinputId in names(state[[MOD_TYPE]][["ui_hold"]])){
state[[MOD_TYPE]][["ui_hold"]][[tmpinputId]] = TRUE
}
} else {
if(inputId %in% names(state[[MOD_TYPE]][["ui_hold"]])){
state[[MOD_TYPE]][["ui_hold"]][[inputId]] = TRUE
}else{
# here we set the hold for a single inputId
FM_le(state = state,
entry = paste0("Unable to set hold for unknown inputId: ", inputId),
entry_type="danger")
#cli::cli_alert_danger(paste0("Unable to set hold for unknown inputId: ", inputId))
isgood = FALSE
}
}
if(!isgood){
stop("Hold not set") }
state}
#'@export
#'@title Fetches the Hold Status UI Element Supplied
#'@description When some buttons are clicked they will change the state of the
#'system, but other UI components will not detect that change correctly. So those
#'triggers are put on hold. This will fetch hold status for a specified inputId
#'@param state module state with all of the current ui elements populated
#'@param inputId The input ID of the UI element that was put on hold
#'@return Boolean value with the hold status
#'@example inst/test_apps/FM_holds.R
fetch_hold = function(state, inputId=NULL){
hold_status = NULL
isgood = TRUE
MOD_TYPE = state[["MOD_TYPE"]]
if(is.null(inputId)){
isgood = FALSE
} else {
if(inputId %in% names(state[[MOD_TYPE]][["ui_hold"]])){
hold_status = state[[MOD_TYPE]][["ui_hold"]][[inputId]]
}else{
# here we set the hold for a single inputId
stop(paste0("Unable to fetch hold for unknown inputId: ", inputId))
isgood = FALSE
}
}
if(!isgood){
stop("Hold status not found") }
hold_status}
#'@export
#'@title Fetches the Code to Reproduce Analysis
#'@description Takes the current state of the app and builds a script to
#'reproduce the analysis within the app.
#'@param session Shiny session variable
#'@param state module state after yaml read
#'@param mod_ids Vector of module IDs and order they are needed (used for code generation).
#'@return list with the following elements:
#' \itemize{
#' \item{isgood:} Boolean indicating the whether code generation was
#' successful
#' (\code{TRUE})
#' \item{msgs:} Any messages generated
#' \item{code:} Code to regenerate the app
#' }
#'@examples
#' # We need a Shiny session object to use this function:
#' sess_res = DW_test_mksession()
#' session = sess_res$session
#' state = sess_res$state
#' app_code = FM_fetch_app_code(session = session,
#' state = state,
#' mod_ids = c("UD", "DW"))
#' cat(app_code$code)
FM_fetch_app_code = function(session, state, mod_ids){
isgood = TRUE
msgs = c()
code = ""
code_chunks = c()
#preamble_chunks = c()
app_state = FM_fetch_app_state(session)
if(length(names(app_state))>0){
mods_found = list()
# We start with the preamble
code_chunks = c(state[["yaml"]][["FM"]][["code"]][["gen_preamble"]])
# Finding the packages used by each module and creating
app_packages = c()
for(tmp_mod_key in names(app_state)){
app_packages = c(app_packages,
app_state[[tmp_mod_key]][["MC"]][["code"]][["packages"]])
}
app_packages = sort(unique(app_packages))
app_packages = paste0('library("',app_packages,'")')
code_chunks = c(code_chunks, app_packages, "\n")
# Creating a word reporting object to use generate elements
code_chunks = c(code_chunks,
"# This reporting object has the formatting ",
"# information for table generation",
state[["yaml"]][["FM"]][["reporting"]][["content_init"]][["docx"]],
"")
# Now we walk through each module type
for(gen_mod in mod_ids){
# Then we walk through each state key and pull the code
# if it matchs the value in gen_mod
for(state_key in names(app_state)){
tmp_state = app_state[[state_key]]
# This can be null if we're processing something other than a module
# (e.g. notifications).
MOD_TYPE = tmp_state[["MOD_TYPE"]]
if(!is.null(MOD_TYPE)){
if(MOD_TYPE == gen_mod){
## Getting the preamble code. This just collects it in
## preamble_chunks and will be appended to the top down below.
#mod_deps = FM_fetch_deps(state=tmp_state, session = session)
#if("package_code" %in% names(mod_deps)){
# preamble_chunks = c(preamble_chunks, mod_deps$package_code)
#}
MOD_FUNC = paste0(MOD_TYPE, "_fetch_code")
# We make sure the code generation function exists
# and if it does we generate the code for that module
if(exists(MOD_FUNC, mode="function")){
tmp_code = NULL
FUNC_CALL = paste0("tmp_code = ", MOD_FUNC,"(tmp_state)")
eval(parse(text=FUNC_CALL))
if(!is.null(tmp_code)){
# This adds a header the first time a module type is encountered
if(!(MOD_TYPE %in% names(mods_found))){
code_chunks = c(code_chunks, tmp_state[["MC"]][["code"]][["preamble"]])
mods_found[[MOD_TYPE]] = TRUE
}
code_chunks = c(code_chunks, tmp_code, "")
}
} else {
msgs = c(msgs, paste0("Unable to find code fetching function: ", MOD_FUNC, "() for module type: ", MOD_TYPE))
}
}
}
}
}
} else {
isgood = FALSE
msgs = "No modules found"
}
## If there are preamble elements we prepend
## those to the code_chunks
#if(!is.null(preamble_chunks)){
# preamble_chunks = sort(unique(preamble_chunks))
# code_chunks = c(preamble_chunks, "", code_chunks)
#}
code = paste(code_chunks, collapse="\n")
res = list(isgood = isgood,
msgs = msgs,
code = code)
res}
#'@export
#'@title Compares DS Summary with Current State for Changes
#'@description Takes the result of \code{FM_fetch_ds()} and compares that to the
#'current react_state to determine if any datasets have changed for the given
#'module IDs.
#'@param state module state after yaml read
#'@param fdres Output of \code{FM_fetch_ds()}.
#'@param ids IDs the current module is
#'@param react_state Reactive shiny object (in app) or a list (outside of app) used to trigger reactions
#'@return Logical indicating if a change has been
#' detected (\code{TRUE}) or not '(\code{FALSE})
#'@examples
#' session = shiny::MockShinySession$new()
#' sess_res = FG_test_mksession(session=session)
#' state = sess_res$state
#' FM_has_ds_changed(state = state, fdres = NULL, ids = ("DW"), react_state=list())
FM_has_ds_changed = function(state, fdres, ids, react_state){
ds_has_changed = FALSE
# Flags used to determine if any of the modules have datasets
anyds = FALSE
# Finding the IDs that are present in react_state
rs = list()
for(tmpid in ids){
# This will skip modules that have not yet been initialized
if(length(isolate(react_state[[tmpid]])) > 0){
rs[[tmpid]] = isolate(react_state[[tmpid]][[1]])
# Determining if there are any datasets present
if(is.logical(rs[[tmpid]][["hasds"]])){
if(rs[[tmpid]][["hasds"]]){
anyds = TRUE
}
}
}
}
# We only proceed if there are ids found in react_state
if(!is.null(rs)){
# If fdres$catalog is NULL but there are ids where rs hasds == TRUE
# - fdres is not initialized but there are datasets so this should force it
# to be initialized
if(is.null(fdres[["catalog"]]) & anyds){
ds_has_changed = TRUE
FM_le(state, "Data source change detected: fdres$catalog is NULL")
}
if(is.data.frame(fdres[["catalog"]])){
for(tmpid in names(rs)){
# Any of the ids in rs where hasds==TRUE but _are not_ present in fdres
# - this means that there were no datasets when fdres was
# generated but there are now
if(rs[[tmpid]][["hasds"]]){
if(!any(fdres[["catalog"]][["id"]] == tmpid)){
#browser()
ds_has_changed = TRUE
FM_le(state, paste0("Data source change detected: fdres is is missing ", tmpid))
}
}
# Any of the ids in rs where hasds==FALSE but _are_ present in fdres
# - this means that there were datasets when fdres was
# generated but have since been deleted
if(!rs[[tmpid]][["hasds"]]){
if(any((fdres[["catalog"]][["id"]] == tmpid))){
ds_has_changed = TRUE
FM_le(state, paste0("Data source change detected: source dataset from ", tmpid, " is missing"))
}
}
# Any of the ids in fdres have checksums different
# from the ids in rs
if(!is.null(fdres[["module_ids"]][[tmpid]]) &
!is.null(rs[[tmpid]][["checksum"]])){
if(rs[[tmpid]][["checksum"]] != fdres[["module_ids"]][[tmpid]]){
ds_has_changed = TRUE
FM_le(state, paste0("Data source change detected: source dataset from ", tmpid, " checksums different."))
FM_le(state, paste0("fdres (old): ", fdres[["module_ids"]][[tmpid]]))
FM_le(state, paste0("react_state (new): ", rs[[tmpid]][["checksum"]]))
}
} else {
# JMH we may need to add some logic here. It gets triggered when
# either fdres or rs has been initialized but the other has not.
#if(is.logical(rs[[tmpid]][["hasds"]])){
# if(rs[[tmpid]][["hasds"]]){
# FM_le(state, paste0("One or more checksum not found"), entry_type="danger")
# FM_le(state, paste0("fdres: ", fdres[["module_ids"]][[tmpid]]), entry_type="danger")
# FM_le(state, paste0("react_state: ", rs[[tmpid]][["checksum"]]), entry_type="danger")
# }
#}
}
}
}
}
ds_has_changed}
#'@export
#'@title Fetches the Path to the Log File
#'@description Use this to get the path to the formods log file
#'@param state module state after yaml read
#'@return Character string with the path to the log file.
#'@examples
#' # Within shiny a session variable will exist,
#' # this creates one here for testing purposes:
#' sess_res = UD_test_mksession()
#' session = sess_res$session
#' state = sess_res$state
#' FM_fetch_log_path(state)
FM_fetch_log_path = function(state){
res = state[["yaml"]][["FM"]][["logging"]][["log_file"]]
res = file.path(FM_fetch_user_files_path(state), res)
res}
#'@export
#'@title Fetches the Path to the User Files
#'@description Use this to get the path to the temporary directory where formods stores user files.
#'@param state module state after yaml read
#'@return Character string with the path to the log file.
#'@examples
#' # We need a state object to use this function:
#' sess_res = UD_test_mksession()
#' state = sess_res$state
#' user_dir = FM_fetch_user_files_path(state)
#' user_dir
FM_fetch_user_files_path = function(state){
# Finding the path to the user directory:
use_tmpdir = TRUE
if(!is.null(state[["yaml"]][["FM"]][["user_"]][["use_tmpdir"]])){
use_tmpdir = state[["yaml"]][["FM"]][["logging"]][["use_tmpdir"]]
}
if(use_tmpdir){
user_dir = file.path(tempdir(), state[["shiny_token"]], "FM")
} else{
user_dir = file.path(getwd(), state[["shiny_token"]], "FM")
}
# Making sure the directory exits
if(!dir.exists(user_dir)){
dir.create(user_dir, recursive = TRUE)
}
user_dir}
#'@export
#'@title Adds Message to Log File and Displays it to the Console
#'@description Add the supplied txt and the module type to the log file and
#'display it to the console.
#'@param state Module state after yaml read
#'@param entry Text to add
#'@param escape_braces Set to \code{TRUE} (default) to escape curly braces in the entry, set to \code{FALSE} to have the values interpreted.
#'@param entry_type Set to either "alert"(default), "danger", "info", "success", or "warning"
#'@return Boolean value indicating success (\code{TRUE}) or failure (\code{FALSE}).
#'@examples
#' # We need a module state to use this function:
#' sess_res = UD_test_mksession()
#' state = sess_res$state
#' FM_le(state, "This is a normal message")
#' FM_le(state, "This is a danger message", entry_type="danger")
#' FM_le(state, "This is a info message", entry_type="info")
#' FM_le(state, "This is a success message", entry_type="success")
#' FM_le(state, "This is a warning message", entry_type="warning")
FM_le = function(state, entry, escape_braces=TRUE, entry_type="alert"){
# pulling out the log file
log_file = FM_fetch_log_path(state)
isgood = NULL
# If the log file does not exist we initalize it
if(!file.exists(log_file)){
file.create(log_file)
write("formods log init", file=log_file, append=TRUE)
}
# module type
if(is.null(state[["MOD_TYPE"]])){
mod_type = "UK"
}else {
mod_type = state[["MOD_TYPE"]]
}
# Appending the module type:
entry = paste0(mod_type, ": ", entry)
# Writing messages to the console
if(state[["yaml"]][["FM"]][["logging"]][["console"]]){
for(line in entry){
FM_message(line=line,
escape_braces=escape_braces,
entry_type=entry_type)
# This will conditionally show the entry if the cli packages is present:
#if(system.file(package="cli") != ""){
# if(escape_braces){
# if(entry_type=="alert"){
# cli::cli_alert("{line}") }
# if(entry_type=="danger"){
# cli::cli_alert_danger("{line}") }
# if(entry_type=="warning"){
# cli::cli_alert_warning("{line}") }
# if(entry_type=="info"){
# cli::cli_alert_info("{line}") }
# if(entry_type=="success"){
# cli::cli_alert_success("{line}") }
# } else {
# if(entry_type=="alert"){
# cli::cli_alert(line)}
# if(entry_type=="danger"){
# cli::cli_alert_danger(line)}
# if(entry_type=="warning"){
# cli::cli_alert_warning(line)}
# if(entry_type=="info"){
# cli::cli_alert_info(line)}
# if(entry_type=="success"){
# cli::cli_alert_success(line)}
# }
#} else {
# message(line)
#}
}
}
# Appending the optional time stamp
if(state[["yaml"]][["FM"]][["logging"]][["timestamp"]]){
entry = paste0(format(Sys.time(),
state[["yaml"]][["FM"]][["logging"]][["timestamp_fmt"]]),
" ", entry)
}
# Appending the log entry to the log file
isgood = write(entry, file=log_file, append=TRUE)
isgood}
#'@export
#'@title Show Message to User
#'@description Writes a message to the console depending on whether cli is
#'installed or not.
#'@param line Text to display
#'@param escape_braces Set to \code{TRUE} (default) to escape curly braces in the entry, set to \code{FALSE} to have the values interpreted.
#'@param entry_type Set to either "alert"(default), "danger", "info", "success", "warning", "h1", "h2", or "h3"
#'@return Returns NULL
#'@examples
#' mr = FM_message("This is a normal message")
#' mr = FM_message("This is a danger message", entry_type="danger")
#' mr = FM_message("This is a info message", entry_type="info")
#' mr = FM_message("This is a success message", entry_type="success")
#' mr = FM_message("This is a warning message", entry_type="warning")
#' mr = FM_message("This is an H1 header", entry_type="h1")
#' mr = FM_message("This is an H2 header", entry_type="h2")
#' mr = FM_message("This is an H3 header", entry_type="h3")
FM_message = function(line, escape_braces=TRUE, entry_type="alert"){
if(is_installed("cli") != ""){
if(escape_braces){
if(entry_type=="alert"){
cli::cli_alert("{line}") }
if(entry_type=="danger"){
cli::cli_alert_danger("{line}") }
if(entry_type=="warning"){
cli::cli_alert_warning("{line}") }
if(entry_type=="info"){
cli::cli_alert_info("{line}") }
if(entry_type=="success"){
cli::cli_alert_success("{line}") }
if(entry_type=="h1"){
cli::cli_h1("{line}") }
if(entry_type=="h2"){
cli::cli_h2("{line}") }
if(entry_type=="h3"){
cli::cli_h3("{line}") }
} else {
if(entry_type=="alert"){
cli::cli_alert(line)}
if(entry_type=="danger"){
cli::cli_alert_danger(line)}
if(entry_type=="warning"){
cli::cli_alert_warning(line)}
if(entry_type=="info"){
cli::cli_alert_info(line)}
if(entry_type=="success"){
cli::cli_alert_success(line)}
if(entry_type=="h1"){
cli::cli_h1(line)}
if(entry_type=="h2"){
cli::cli_h2(line)}
if(entry_type=="h3"){
cli::cli_h3(line)}
}
} else {
message(line)
}
NULL}
#'@export
#'@title Run Try/Catch and Process Results
#'@description Attempts to execute the text in cmd. This is done in a
#' try/catch environment to capture any errors.
#'@param cmd Character object containing the R command to evaluate in the try/catch block
#'@param tc_env list of with names corresponding to object names and
#' corresponding Values to define in the try/catch environment
#'@param capture Character vector of values to capture after the command is
#' successfully captured. If capture is \code{NULL} (e.g., \code{c()}), then all
#' objects generated by cmd will be captured.
#'@return list with the following fields:
#' \itemize{
#' \item{isgood:} Boolean indicating the whether the evaluation was
#' successful.
#' \item{error:} If the evaluation failed this contains the error object.
#' \item{msgs:} Character vector of messages and/or errors.
#' \item{capture:} List with names of objects to be captured and values
#' corresponding to those captured objects.
#' }
#'@examples
#' # Successful command
#' res_good = FM_tc("good_cmd=ls()", list(), c("good_cmd"))
#' res_good
#'
#' # Failed command
#' res_bad = FM_tc("bad_cmd =not_a_command()", list(), c("bad_cmd"))
#' res_bad
FM_tc = function(cmd, tc_env, capture){
# Defining the environment
for(name in names(tc_env)){
assign(name, tc_env[[name]])
}