-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathdash.R
2012 lines (1766 loc) · 91 KB
/
dash.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
#' R6 class representing a Dash application
#'
#' @export
#' @docType class
#' @format An [R6::R6Class] generator object
#' @description
#' A framework for building analytical web applications, Dash offers a pleasant and productive development experience. No JavaScript required.
Dash <- R6::R6Class(
'Dash',
public = list(
#' @field server
#' A cloned (and modified) version of the [fiery::Fire] object
#' provided to the `server` argument (various routes will be added which enable
#' Dash functionality).
server = NULL,
#' @field config
#' A list of configuration options passed along to dash-renderer.
#' Users shouldn't need to alter any of these options unless they are
#' constructing their own authorization front-end or otherwise need to know
#' where the application is making API calls.
config = list(),
#' @description
#' Create and configure a Dash application.
#' @param server [fiery::Fire] object. The web server used to power the application.
#' @param assets_folder Character. A path, relative to the current working directory,
#' for extra files to be used in the browser. All .js and
#' .css files will be loaded immediately unless excluded by `assets_ignore`,
#' and other files such as images will be served if requested. Default is `assets`.
#' @param assets_url_path Character. Specify the URL path for asset serving. Default is `assets`.
#' @param eager_loading Logical. Controls whether asynchronous resources are prefetched (if `TRUE`) or loaded on-demand (if `FALSE`).
#' @param assets_ignore Character. A regular expression, to match assets to omit from
#' immediate loading. Ignored files will still be served if specifically requested. You
#' cannot use this to prevent access to sensitive files.
#' @param serve_locally Logical. Whether to serve HTML dependencies locally or
#' remotely (via URL).
#' @param meta_tags List of lists. HTML `<meta>` tags to be added to the index page.
#' Each list element should have the attributes and values for one tag, eg:
#' `list(name = 'description', content = 'My App')`.
#' @param url_base_pathname Character. A local URL prefix to use app-wide. Default is
#' `/`. Both `requests_pathname_prefix` and `routes_pathname_prefix` default to `url_base_pathname`.
#' Environment variable is `DASH_URL_BASE_PATHNAME`.
#' @param routes_pathname_prefix Character. A prefix applied to the backend routes.
#' Environment variable is `DASH_ROUTES_PATHNAME_PREFIX`.
#' @param requests_pathname_prefix Character. A prefix applied to request endpoints
#' made by Dash's front-end. Environment variable is `DASH_REQUESTS_PATHNAME_PREFIX`.
#' @param external_scripts List. An optional list of valid URLs from which
#' to serve JavaScript source for rendered pages. Each entry can be a string (the URL)
#' or a named list with `src` (the URL) and optionally other `<script>` tag attributes such
#' as `integrity` and `crossorigin`.
#' @param external_stylesheets List. An optional list of valid URLs from which
#' to serve CSS for rendered pages. Each entry can be a string (the URL) or a list
#' with `href` (the URL) and optionally other `<link>` tag attributes such as
#' `rel`, `integrity` and `crossorigin`.
#' @param compress Logical. Whether to try to compress files and data served by Fiery.
#' By default, `brotli` is attempted first, then `gzip`, then the `deflate` algorithm,
#' before falling back to `identity`.
#' @param suppress_callback_exceptions Logical. Whether to relay warnings about
#' possible layout mis-specifications when registering a callback.
#' @param show_undo_redo Logical. Set to `TRUE` to enable undo and redo buttons for
#' stepping through the history of the app state.
#' @param update_title Character. Defaults to `Updating...`; configures the document.title
#' (the text that appears in a browser tab) text when a callback is being run.
#' Set to NULL or '' if you don't want the document.title to change or if you
#' want to control the document.title through a separate component or
#' clientside callback.
initialize = function(server = fiery::Fire$new(),
assets_folder = "assets",
assets_url_path = "/assets",
eager_loading = FALSE,
assets_ignore = "",
serve_locally = TRUE,
meta_tags = NULL,
url_base_pathname = "/",
routes_pathname_prefix = NULL,
requests_pathname_prefix = NULL,
external_scripts = NULL,
external_stylesheets = NULL,
compress = TRUE,
suppress_callback_exceptions = FALSE,
show_undo_redo = FALSE,
update_title="Updating...") {
# argument type checking
assertthat::assert_that(inherits(server, "Fire"))
assertthat::assert_that(is.logical(serve_locally))
assertthat::assert_that(is.logical(suppress_callback_exceptions))
private$serve_locally <- serve_locally
private$eager_loading <- eager_loading
# remove leading and trailing slash(es) if present
private$assets_folder <- gsub("^/+|/+$", "", assets_folder)
# remove trailing slash in assets_url_path, if present
private$assets_url_path <- sub("/$", "", assets_url_path)
private$assets_ignore <- assets_ignore
private$suppress_callback_exceptions <- suppress_callback_exceptions
private$compress <- compress
private$app_root_path <- getAppPath()
private$app_launchtime <- as.integer(Sys.time())
private$meta_tags <- meta_tags
private$in_viewer <- FALSE
# config options
self$config$routes_pathname_prefix <- resolvePrefix(routes_pathname_prefix, "DASH_ROUTES_PATHNAME_PREFIX", url_base_pathname)
self$config$requests_pathname_prefix <- resolvePrefix(requests_pathname_prefix, "DASH_REQUESTS_PATHNAME_PREFIX", url_base_pathname)
self$config$external_scripts <- external_scripts
self$config$external_stylesheets <- external_stylesheets
self$config$show_undo_redo <- show_undo_redo
self$config$update_title <- update_title
# ensure attributes are valid, if using a list within a list, elements are all named
assertValidExternals(scripts = external_scripts, stylesheets = external_stylesheets)
# ------------------------------------------------------------
# Initialize a route stack and register a static resource route
# ------------------------------------------------------------
router <- routr::RouteStack$new()
server$set_data("user-routes", list()) # placeholder for custom routes
# ensure that assets_folder is neither NULL nor character(0)
if (!(is.null(private$assets_folder)) & length(private$assets_folder) != 0) {
if (!(dir.exists(private$assets_folder)) && gsub("/+", "", assets_folder) != "assets") {
warning(sprintf(
"The supplied assets folder, '%s', could not be found in the project directory.",
private$assets_folder),
call. = FALSE
)
} else if (dir.exists(private$assets_folder)) {
if (length(countEnclosingFrames("dash_nested_fiery_server")) == 0) {
private$refreshAssetMap()
private$last_refresh <- as.integer(Sys.time())
}
# fiery is attempting to launch a server within a server, do not refresh assets
}
}
# ------------------------------------------------------------------------
# Set a sensible default logger
# ------------------------------------------------------------------------
server$set_logger(dashLogger)
server$access_log_format <- fiery::combined_log_format
# ------------------------------------------------------------------------
# define & register routes on the server
# https://github.com/plotly/dash/blob/d2ebc837/dash/dash.py#L88-L124
# http://www.data-imaginist.com/2017/Introducing-routr/
# ------------------------------------------------------------------------
route <- routr::Route$new()
dash_layout <- paste0(self$config$routes_pathname_prefix, "_dash-layout")
route$add_handler("get", dash_layout, function(request, response, keys, ...) {
rendered_layout <- private$layout_render()
# pass the layout on to encode_plotly in case there are dccGraph
# components which include Plotly.js figures for which we'll need to
# run plotly_build from the plotly package
lay <- encode_plotly(rendered_layout)
response$body <- to_JSON(lay, pretty = TRUE)
response$status <- 200L
response$type <- 'json'
TRUE
})
dash_deps <- paste0(self$config$routes_pathname_prefix, "_dash-dependencies")
route$add_handler("get", dash_deps, function(request, response, keys, ...) {
# dash-renderer wants an empty array when no dependencies exist (see python/01.py)
if (!length(private$callback_map)) {
response$body <- to_JSON(list())
response$status <- 200L
response$type <- 'json'
return(FALSE)
}
payload <- Map(function(callback_signature) {
list(
inputs=callback_signature$inputs,
output=createCallbackId(callback_signature$output),
state=callback_signature$state,
clientside_function=callback_signature$clientside_function
)
}, private$callback_map)
response$body <- to_JSON(setNames(payload, NULL))
response$status <- 200L
response$type <- 'json'
if (private$compress)
response <- tryCompress(request, response)
TRUE
})
dash_update <- paste0(self$config$routes_pathname_prefix, "_dash-update-component")
route$add_handler("post", dash_update, function(request, response, keys, ...) {
request <- request_parse_json(request)
if (!"output" %in% names(request$body)) {
response$body <- "Couldn't find output component in request body"
response$status <- 500L
response$type <- 'json'
return(FALSE)
}
# get the callback associated with this particular output
callback <- private$callback_map[[request$body$output]][['func']]
if (!length(callback)) stop_report("Couldn't find output component.")
if (!is.function(callback)) {
stop(sprintf("Couldn't find a callback function associated with '%s'", thisOutput))
}
# the following callback_args code handles inputs which may contain
# NULL values; we wish to retain the NULL elements, since these can
# be passed into the callback handler, rather than dropping the list
# elements when they are encountered (which also compromises the
# sequencing of passed arguments). the R FAQ notes that list(NULL)
# can be used to append NULL elements into a constructed list, but
# that assigning NULL into list elements omits them from the object.
#
# we want the NULL elements to be wrapped in a list when they're
# passed, so they're nested in the code below.
#
# https://cran.r-project.org/doc/FAQ/R-FAQ.html#Others:
callback_args <- list()
for (input_element in request$body$inputs) {
if (any(grepl("id.", names(unlist(input_element))))) {
if (!is.null(input_element$id)) input_element <- list(input_element)
values <- character(0)
for (wildcard_input in input_element) {
values <- c(values, wildcard_input$value)
}
callback_args <- c(callback_args, ifelse(length(values), list(values), list(NULL)))
}
else if(is.null(input_element$value)) {
callback_args <- c(callback_args, list(list(NULL)))
}
else {
callback_args <- c(callback_args, list(input_element$value))
}
}
if (length(request$body$state)) {
for (state_element in request$body$state) {
if (any(grepl("id.", names(unlist(state_element))))) {
if (!is.null(state_element$id)) state_element <- list(state_element)
values <- character(0)
for (wildcard_state in state_element) {
values <- c(values, wildcard_state$value)
}
callback_args <- c(callback_args, ifelse(length(values), list(values), list(NULL)))
}
else if(is.null(state_element$value)) {
callback_args <- c(callback_args, list(list(NULL)))
}
else {
callback_args <- c(callback_args, list(state_element$value))
}
}
}
# set the callback context associated with this invocation of the callback
private$callback_context_ <- setCallbackContext(request$body)
output_value <- getStackTrace(do.call(callback, callback_args),
debug = private$debug,
prune_errors = private$prune_errors)
# reset callback context
private$callback_context_ <- NULL
# inspect the output_value to determine whether any outputs have no_update
# objects within them; these should not be updated
if (length(output_value) == 1 && class(output_value) == "no_update") {
response$body <- character(1) # return empty string
response$status <- 204L
}
else if (is.null(private$stack_message)) {
# pass on output_value to encode_plotly in case there are dccGraph
# components which include Plotly.js figures for which we'll need to
# run plotly_build from the plotly package
output_value <- encode_plotly(output_value)
# for multiple outputs, have to format the response body like this, including 'multi' key:
# https://github.com/plotly/dash/blob/d9ddc877d6b15d9354bcef4141acca5d5fe6c07b/dash/dash.py#L1174-L1209
# for single outputs, the response body is formatted slightly differently:
# https://github.com/plotly/dash/blob/d9ddc877d6b15d9354bcef4141acca5d5fe6c07b/dash/dash.py#L1210-L1220
if (substr(request$body$output, 1, 2) == '..') {
# omit return objects of class "no_update" from output_value
updatable_outputs <- vapply(output_value, function(x) !("no_update" %in% class(x)), logical(1))
output_value <- output_value[updatable_outputs]
# if multi-output callback, isolate the output IDs and properties
ids <- getIdProps(request$body$output)$ids[updatable_outputs]
props <- getIdProps(request$body$output)$props[updatable_outputs]
# prepare a response object which has list elements corresponding to ids
# which themselves contain named list elements corresponding to props
# then fill in nested list elements based on output_value
allprops <- setNames(vector("list", length(unique(ids))), unique(ids))
idmap <- setNames(ids, props)
for (id in unique(ids)) {
allprops[[id]] <- output_value[grep(id, ids)]
names(allprops[[id]]) <- names(idmap[which(idmap==id)])
}
resp <- list(
response = allprops,
multi = TRUE
)
} else if (is.list(request$body$outputs$id)) {
props = setNames(list(output_value), gsub( "(^.+)(\\.)", "", request$body$output))
resp <- list(
response = setNames(list(props), to_JSON(request$body$outputs$id)),
multi = TRUE
)
} else {
resp <- list(
response = list(
props = setNames(list(output_value), gsub( "(^.+)(\\.)", "", request$body$output))
)
)
}
response$body <- to_JSON(resp)
response$status <- 200L
response$type <- 'json'
} else if (private$debug==TRUE) {
# if there is an error, send it back to dash-renderer
response$body <- private$stack_message
response$status <- 500L
response$type <- 'html'
private$stack_message <- NULL
} else {
# if not in debug mode, do not return stack
response$body <- NULL
response$status <- 500L
private$stack_message <- NULL
}
if (private$compress)
response <- tryCompress(request, response)
TRUE
})
# This endpoint supports dynamic dependency loading
# during `_dash-update-component` -- for reference:
# https://docs.python.org/3/library/pkgutil.html#pkgutil.get_data
#
# analogous to
# https://github.com/plotly/dash/blob/2d735aa250fc67b14dc8f6a337d15a16b7cbd6f8/dash/dash.py#L543-L551
dash_suite <- paste0(self$config$routes_pathname_prefix, "_dash-component-suites/:package_name/:filename")
route$add_handler("get", dash_suite, function(request, response, keys, ...) {
filename <- basename(file.path(keys$filename))
# checkFingerprint returns a list of length 2, the first element is
# the un-fingerprinted path, if a fingerprint is present (otherwise
# the original path is returned), while the second element indicates
# whether the original filename included a valid fingerprint (by
# Dash convention)
fingerprinting_metadata <- checkFingerprint(filename)
filename <- fingerprinting_metadata[[1]]
has_fingerprint <- fingerprinting_metadata[[2]] == TRUE
dep_list <- c(private$dependencies_internal,
private$dependencies,
private$dependencies_user)
dep_pkg <- get_package_mapping(filename,
keys$package_name,
clean_dependencies(dep_list)
)
# return warning if a dependency goes unmatched, since the page
# will probably fail to render properly anyway without it
if (length(dep_pkg$rpkg_path) == 0) {
warning(sprintf("The dependency '%s' could not be loaded; the file was not found.",
filename),
call. = FALSE)
response$body <- NULL
response$status <- 404L
} else {
# need to check for debug mode, don't cache, don't etag
# if debug mode is not active
dep_path <- system.file(dep_pkg$rpkg_path,
package = dep_pkg$rpkg_name)
response$type <- get_mimetype(filename)
if (grepl("text|javascript", response$type)) {
response$body <- readLines(dep_path,
warn = FALSE,
encoding = "UTF-8")
if (private$compress && length(response$body) > 0) {
response <- tryCompress(request, response)
}
} else {
file_handle <- file(dep_path, "rb")
file_size <- file.size(dep_path)
response$body <- readBin(dep_path,
raw(),
file_size)
close(file_handle)
}
if (!private$debug && has_fingerprint) {
response$status <- 200L
response$append_header('Cache-Control',
sprintf('public, max-age=%s',
'31536000') # 1 year
)
} else if (!private$debug && !has_fingerprint) {
modified <- as.character(as.integer(file.mtime(dep_path)))
response$append_header('ETag',
modified)
request_etag <- request$get_header('If-None-Match')
if (!is.null(request_etag) && modified == request_etag) {
response$body <- NULL
response$status <- 304L
} else {
response$status <- 200L
}
} else {
response$status <- 200L
}
}
TRUE
})
dash_assets <- paste0(self$config$routes_pathname_prefix, private$assets_url_path, "/*")
# ensure slashes are not doubled
dash_assets <- sub("//", "/", dash_assets)
route$add_handler("get", dash_assets, function(request, response, keys, ...) {
# unfortunately, keys do not exist for wildcard headers in routr -- URL must be parsed
# e.g. for "http://127.0.0.1:8050/assets/stylesheet.css?m=1552591104"
#
# the following regex pattern will return "/stylesheet.css":
assets_pattern <- paste0("(?<=",
gsub("/",
"\\\\/",
private$assets_url_path),
")([^?])+"
)
# now, identify vector positions for asset string matching pattern above
asset_match <- gregexpr(pattern = assets_pattern, request$url, perl=TRUE)
# use regmatches to retrieve only the substring following assets_url_path
asset_to_match <- unlist(regmatches(request$url, asset_match))
# now that we've parsed the URL, attempt to match the subpath in the map,
# then return the local absolute path to the asset
asset_path <- get_asset_path(private$asset_map,
asset_to_match)
# the following codeblock attempts to determine whether the requested
# content exists, if the data should be encoded as plain text or binary,
# and opens/closes a file handle if the type is assumed to be binary
if (!(is.null(asset_path)) && file.exists(asset_path)) {
response$type <- request$headers[["Content-Type"]] %||%
get_mimetype(asset_to_match)
if (grepl("text|javascript", response$type)) {
response$body <- readLines(asset_path,
warn = FALSE,
encoding = "UTF-8")
if (private$compress && length(response$body) > 0) {
response <- tryCompress(request, response)
}
} else {
file_handle <- file(asset_path, "rb")
file_size <- file.size(asset_path)
response$body <- readBin(file_handle,
raw(),
file_size)
close(file_handle)
}
response$status <- 200L
}
TRUE
})
dash_favicon <- paste0(self$config$routes_pathname_prefix, "_favicon.ico")
route$add_handler("get", dash_favicon, function(request, response, keys, ...) {
asset_path <- get_asset_path(private$asset_map,
"/favicon.ico")
file_handle <- file(asset_path, "rb")
response$body <- readBin(file_handle,
raw(),
file.size(asset_path))
close(file_handle)
response$append_header('Cache-Control',
sprintf('public, max-age=%s',
'31536000')
)
response$type <- 'image/x-icon'
response$status <- 200L
TRUE
})
# Add a 'catchall' handler to redirect other requests to the index
dash_catchall <- paste0(self$config$routes_pathname_prefix, "*")
route$add_handler('get', dash_catchall, function(request, response, keys, ...) {
response$body <- private$.index
response$status <- 200L
response$type <- 'html'
if (private$compress)
response <- tryCompress(request, response)
TRUE
})
dash_reload_hash <- paste0(self$config$routes_pathname_prefix, "_reload-hash")
route$add_handler("get", dash_reload_hash, function(request, response, keys, ...) {
modified_files <- private$modified_since_reload
hard <- TRUE
if (is.null(modified_files)) {
# dash-renderer requires that this element not be NULL
modified_files <- list()
}
resp <- list(files = modified_files,
hard = hard,
packages = c("dash_renderer",
unique(
vapply(
private$dependencies,
function(x) x[["name"]],
FUN.VALUE=character(1),
USE.NAMES = FALSE)
)
),
reloadHash = self$config$reload_hash)
response$body <- to_JSON(resp)
response$status <- 200L
response$type <- 'json'
# reset the field for the next reloading operation
private$modified_since_reload <- list()
TRUE
})
router$add_route(route, "dashR-endpoints")
server$attach(router)
server$on("start", function(server, ...) {
private$generateReloadHash()
private$index()
viewer <- !(is.null(getOption("viewer"))) && (dynGet("use_viewer") == TRUE)
app_url <- paste0("http://", self$server$host, ":", self$server$port)
if (viewer && self$server$host %in% c("localhost", "127.0.0.1")) {
rstudioapi::viewer(app_url)
private$in_viewer <- TRUE
}
else if (viewer) {
warning("\U{26A0} RStudio viewer not supported; ensure that host is 'localhost' or '127.0.0.1' and that you are using RStudio to run your app. Opening default browser...")
utils::browseURL(app_url)
}
})
# user-facing fields
self$server <- server
},
# ------------------------------------------------------------------------
# methods to add custom server routes
# ------------------------------------------------------------------------
#' @description
#' Connect a URL to a custom server route
#' @details
#' `fiery`, the underlying web service framework upon which Dash for R is based,
#' supports custom routing through plugins. While convenient, the plugin API
#' providing this functionality is different from that provided by Flask, as
#' used by Dash for Python. This method wraps the pluggable routing of `routr`
#' routes in a manner that should feel slightly more idiomatic to Dash users.
#' ## Querying User-Defined Routes:
#' It is possible to retrieve the list of user-defined routes by invoking the
#' `get_data` method. For example, if your Dash application object is `app`, use
#' `app$server$get_data("user-routes")`.
#'
#' If you wish to erase all user-defined routes without instantiating a new Dash
#' application object, one option is to clear the routes manually:
#' `app$server$set_data("user-routes", list())`.
#' @param path Character. Represents a URL path comprised of strings, parameters
#' (strings prefixed with :), and wildcards (*), separated by /. Wildcards can
#' be used to match any path element, rather than restricting (as by default) to
#' a single path element. For example, it is possible to catch requests to multiple
#' subpaths using a wildcard. For more information, see \link{Route}.
#' @param handler Function. Adds a handler function to the specified method and path.
#' For more information, see \link{Route}.
#' @param methods Character. A string indicating the request method (in lower case,
#' e.g. 'get', 'put', etc.), as used by `reqres`. The default is `get`.
#' For more information, see \link{Route}.
#' @examples
#' library(dash)
#' app <- Dash$new()
#'
#' # A handler to redirect requests with `307` status code (temporary redirects);
#' # for permanent redirects (`301`), see the `redirect` method described below
#' #
#' # A simple single path-to-path redirect
#' app$server_route('/getting-started', function(request, response, keys, ...) {
#' response$status <- 307L
#' response$set_header('Location', '/layout')
#' TRUE
#' })
#'
#' # Example of a redirect with a wildcard for subpaths
#' app$server_route('/getting-started/*', function(request, response, keys, ...) {
#' response$status <- 307L
#' response$set_header('Location', '/layout')
#' TRUE
#' })
#'
#' # Example of a parameterized redirect with wildcard for subpaths
#' app$server_route('/accounts/:user_id/*', function(request, response, keys, ...) {
#' response$status <- 307L
#' response$set_header('Location', paste0('/users/', keys$user_id))
#' TRUE
#' })
server_route = function(path = NULL, handler = NULL, methods = "get") {
if (is.null(path) || is.null(handler)) {
stop("The server_route method requires that a path and handler function are specified. Please ensure these arguments are non-missing.", call.=FALSE)
}
user_routes <- self$server$get_data("user-routes")
user_routes[[path]] <- list("path" = path,
"handler" = handler,
"methods" = methods)
self$server$set_data("user-routes", user_routes)
},
#' @description
#' Redirect a Dash application URL path
#' @details
#' This is a convenience method to simplify adding redirects
#' for your Dash application which automatically return a `301`
#' HTTP status code and direct the client to load an alternate URL.
#' @param old_path Character. Represents the URL path to redirect,
#' comprised of strings, parameters (strings prefixed with :), and
#' wildcards (*), separated by /. Wildcards can be used to match any
#' path element, rather than restricting (as by default) to a single
#' path element. For example, it is possible to catch requests to multiple
#' subpaths using a wildcard. For more information, see \link{Route}.
#' @param new_path Character or function. Same as `old_path`, but represents the
#' new path which the client should load instead. If a function is
#' provided instead of a string, it should have `keys` within its formals.
#' @param methods Character. A string indicating the request method
#' (in lower case, e.g. 'get', 'put', etc.), as used by `reqres`. The
#' default is `get`. For more information, see \link{Route}.
#' @examples
#' library(dash)
#' app <- Dash$new()
#'
#' # example of a simple single path-to-path redirect
#' app$redirect("/getting-started", "/layout")
#'
#' # example of a redirect using wildcards
#' app$redirect("/getting-started/*", "/layout/*")
#'
#' # example of a parameterized redirect using a function for new_path,
#' # which requires passing in keys to take advantage of subpaths within
#' # old_path that are preceded by a colon (e.g. :user_id):
#' app$redirect("/accounts/:user_id/*", function(keys) paste0("/users/", keys$user_id))
redirect = function(old_path = NULL, new_path = NULL, methods = "get") {
if (is.null(old_path) || is.null(new_path)) {
stop("The redirect method requires that both an old path and a new path are specified. Please ensure these arguments are non-missing.", call.=FALSE)
}
if (is.function(new_path)) {
handler <- function(request, response, keys, ...) {
response$status <- 301L
response$set_header('Location', new_path(keys))
TRUE
}
} else {
handler <- function(request, response, keys, ...) {
response$status <- 301L
response$set_header('Location', new_path)
TRUE
}
}
self$server_route(old_path, handler)
},
# ------------------------------------------------------------------------
# dash layout methods
# ------------------------------------------------------------------------
#' @description
#' Retrieves the Dash application layout.
#' @details
#' If render is `TRUE`, and the layout is a function,
#' the result of the function (rather than the function itself) is returned.
#' @param render Logical. If the layout is a function, should the function be
#' executed to return the layout? If `FALSE`, the function is returned as-is.
#' @return List or function, depending on the value of `render` (see above).
#' When returning an object of class `dash_component`, the default `print`
#' method for this class will display the corresponding pretty-printed JSON
#' representation of the object to the console.
layout_get = function(render = TRUE) {
if (render) private$layout_render() else private$layout_
},
#' @description
#' Set the Dash application layout (i.e., specify its user interface).
#' @details
#' `value` should be either a
#' collection of Dash components (e.g., [dccSlider], [htmlDiv], etc) or
#' a function which returns a collection of components. The collection
#' of components must be nested, such that any additional components
#' contained within `value` are passed solely as `children` of the top-level
#' component. In all cases, `value` must be a member of the `dash_component`
#' class.
#' @param value An object of the `dash_component` class, which provides
#' a component or collection of components, specified either as a Dash
#' component or a function that returns a Dash component.
layout = function(value) {
# private$layout_ <- if (is.function(..1)) ..1 else list(...)
private$layout_ <- value
# render the layout, and then return the rendered layout without printing
invisible(private$layout_render())
},
#' @description
#' Update the version of React in the list of dependencies served by dash-renderer to the client.
#' @param version Character. The version number of React to use.
react_version_set = function(version) {
versions <- private$react_versions()
idx <- versions %in% version
# needs to match one react & one react-dom version
if (sum(idx) != 2) {
stop(sprintf(
"React version '%s' is not supported. Supported versions include: '%s'",
version, paste(unique(versions), collapse = "', '")
), call. = FALSE)
}
private$react_version_enabled <- version
},
# ------------------------------------------------------------------------
# callback registration
# ------------------------------------------------------------------------
#' @description
#' Define a Dash callback.
#' @details
#' Describes a server or clientside callback relating the values of one or more
#' `output` items to one or more `input` items which will trigger the callback
#' when they change, and optionally `state` items which provide additional
#' information but do not trigger the callback directly.
#'
#' For detailed examples of how to use pattern-matching callbacks, see the
#' entry for \link{selectors} or visit our interactive online
#' documentation at \url{https://dashr.plotly.com}.
#'
#' The `output` argument defines which layout component property should
#' receive the results (via the [output] object). The events that
#' trigger the callback are then described by the [input] (and/or [state])
#' object(s) (which should reference layout components), which become
#' argument values for R callback handlers defined in `func`.
#'
#' Here `func` may either be an anonymous R function, a JavaScript function
#' provided as a character string, or a call to `clientsideFunction()`, which
#' describes a locally served JavaScript function instead. The latter
#' two methods define a "clientside callback", which updates components
#' without passing data to and from the Dash backend. The latter may offer
#' improved performance relative to callbacks written purely in R.
#' @param output Named list. The `output` argument provides the component `id`
#' and `property` which will be updated by the callback; a callback can
#' target one or more outputs (i.e. multiple outputs).
#' @param params Unnamed list; provides [input] and [state] statements, each
#' with its own defined `id` and `property`. For pattern-matching callbacks,
#' the `id` field of a component is written in JSON-like syntax and provides
#' fields that are arbitrary keys which describe the targets of the callback.
#' See \link{selectors} for more details.
#' @param func Function; must return [output] provided [input] or [state]
#' arguments. `func` may be any valid R function, or a character string
#' containing valid JavaScript, or a call to [clientsideFunction],
#' including `namespace` and `function_name` arguments for a locally served
#' JavaScript function.
callback = function(output, params, func) {
assert_valid_callbacks(output, params, func)
inputs <- params[vapply(params, function(x) 'input' %in% attr(x, "class"), FUN.VALUE=logical(1))]
state <- params[vapply(params, function(x) 'state' %in% attr(x, "class"), FUN.VALUE=logical(1))]
if (is.function(func)) {
clientside_function <- NULL
} else if (is.character(func)) {
# update the scripts before generating tags, and remove exact
# duplicates from inline_scripts
fn_name <- paste0("_dashprivate_", output$id)
func <- paste0('<script>\n',
'var clientside = window.dash_clientside = window.dash_clientside || {};\n',
'var ns = clientside["', fn_name, '"] = clientside["', fn_name, '"] || {};\n',
'ns["', output$property, '"] = \n',
func,
'\n;',
'</script>')
private$inline_scripts <- unique(c(private$inline_scripts, func))
clientside_function <- clientsideFunction(namespace = fn_name,
function_name = output$property)
func <- NULL
} else {
clientside_function <- func
func <- NULL
}
# register the callback_map
private$callback_map <- insertIntoCallbackMap(private$callback_map,
inputs,
output,
state,
func,
clientside_function)
},
# ------------------------------------------------------------------------
# request and return callback context
# ------------------------------------------------------------------------
#' @description
#' Request and return the calling context of a Dash callback.
#' @details
#' The `callback_context` method permits retrieving the inputs which triggered
#' the firing of a given callback, and allows introspection of the input/state
#' values given their names. It is only available from within a callback;
#' attempting to use this method outside of a callback will result in a warning.
#'
#' The `callback_context` method returns a list containing three elements:
#' `states`, `triggered`, `inputs`. The first and last of these correspond to
#' the values of `states` and `inputs` for the current invocation of the
#' callback, and `triggered` provides a list of changed properties.
#'
#' @return List comprising elements `states`, `triggered`, `inputs`.
callback_context = function() {
if (is.null(private$callback_context_)) {
warning("callback_context is undefined; callback_context may only be accessed within a callback.")
}
private$callback_context_
},
# ------------------------------------------------------------------------
# request and return callback timing data
# ------------------------------------------------------------------------
#' @description
#' Records timing information for a server resource.
#' @details
#' The `callback_context.record_timing` method permits retrieving the
#' duration required to execute a given callback. It may only be called
#' from within a callback; a warning will be thrown and the method will
#' otherwise return `NULL` if invoked outside of a callback.
#'
#' @param name Character. The name of the resource.
#' @param duration Numeric. The time in seconds to report. Internally, this is
#' rounded to the nearest millisecond.
#' @param description Character. A description of the resource.
#'
callback_context.record_timing = function(name,
duration=NULL,
description=NULL) {
if (is.null(private$callback_context_)) {
warning("callback_context is undefined; callback_context.record_timing may only be accessed within a callback.")
return(NULL)
}
timing_information <- self$server$get_data("timing-information")
if (name %in% timing_information) {
stop(paste0("Duplicate resource name ", name, " found."), call.=FALSE)
}
timing_information[[name]] <- list("dur" = round(duration * 1000),
"desc" = description)
self$server$set_data("timing-information", timing_information)
},
# ------------------------------------------------------------------------
# return asset URLs
# ------------------------------------------------------------------------
#' @description
#' Return a URL for a Dash asset.
#' @details
#' The `get_asset_url` method permits retrieval of an asset's URL given its filename.
#' For example, `app$get_asset_url('style.css')` should return `/assets/style.css` when
#' `assets_folder = 'assets'`. By default, the prefix is the value of `requests_pathname_prefix`,
#' but this is configurable via the `prefix` parameter. Note: this method will
#' present a warning and return `NULL` if the Dash app was not loaded via `source()`
#' if the `DASH_APP_PATH` environment variable is undefined.
#' @param asset_path Character. Specifies asset filename whose URL should be returned.
#' @param prefix Character. Specifies pathname prefix; default is to use `requests_pathname_prefix`.
#' @return Character. A string representing the URL to the asset.
get_asset_url = function(asset_path, prefix = self$config$requests_pathname_prefix) {
app_root_path <- Sys.getenv("DASH_APP_PATH")
if (app_root_path == "" && getAppPath() != FALSE) {
# app loaded via source(), root path is known
app_root_path <- dirname(private$app_root_path)
} else if (getAppPath() == FALSE) {
# app not loaded via source(), env var not set, no reliable way to ascertain root path
warning("application not started via source(), and DASH_APP_PATH environment variable is undefined. get_asset_url returns NULL since root path cannot be reliably identified.")
return(NULL)
}
asset <- lapply(private$asset_map,
function(x) {
# asset_path should be prepended with the full app root & assets path
# if leading slash(es) present in asset_path, remove them before
# assembling full asset path
asset_path <- file.path(app_root_path,
private$assets_folder,
sub(pattern="^/+",
replacement="",
asset_path))
return(names(x[x == asset_path]))
}
)
asset <- unlist(asset, use.names = FALSE)
if (length(asset) == 0)
stop(sprintf("the asset path '%s' is not valid; please verify that this path exists within the '%s' directory.",
asset_path,
private$assets_folder))
# strip multiple slashes if present, since we'll
# introduce one when we concatenate the prefix and
# asset path & prepend the asset name with route prefix
return(gsub(pattern="/+",
replacement="/",
paste(prefix,
private$assets_url_path,
asset,
sep="/")))
},
# ------------------------------------------------------------------------
# return relative asset URLs
# ------------------------------------------------------------------------
#' @description
#' Return relative asset paths for Dash assets.
#' @details
#' The `get_relative_path` method simplifies the handling of URLs and pathnames for apps
#' running locally and on a deployment server such as Dash Enterprise. It handles the prefix
#' for requesting assets similar to the `get_asset_url` method, but can also be used for URL handling
#' in components such as `dccLink` or `dccLocation`. For example, `app$get_relative_url("/page/")`
#' would return `/app/page/` for an app running on a deployment server. The path must be prefixed with
#' a `/`.
#' @param path Character. A path string prefixed with a leading `/` which directs
#' at a path or asset directory.
#' @param requests_pathname_prefix Character. The pathname prefix for the application when
#' deployed. Defaults to the environment variable set by the server,
#' or `""` if run locally.
#' @return Character. A string describing a relative path to a Dash app's asset
#' given a `path` and `requests_pathname_prefix`.
get_relative_path = function(path, requests_pathname_prefix = self$config$requests_pathname_prefix) {
asset = get_relative_path(requests_pathname = requests_pathname_prefix, path = path)
return(asset)
},
# ------------------------------------------------------------------------
# return relative asset URLs
# ------------------------------------------------------------------------
#' @description
#' Return a Dash asset path without its prefix.
#' @details
#' The `strip_relative_path` method simplifies the handling of URLs and pathnames for apps
#' running locally and on a deployment server such as Dash Enterprise. It acts almost opposite to the `get_relative_path`
#' method, by taking a `relative path` as an input, and returning the `path` stripped of the `requests_pathname_prefix`,
#' and any leading or trailing `/`. For example, a path string `/app/homepage/`, would be returned as
#' `homepage`. This is particularly useful for `dccLocation` URL routing.