Skip to content

Commit

Permalink
feat: Make auto-reload work with default entrypoint
Browse files Browse the repository at this point in the history
  • Loading branch information
kamilzyla committed Jan 30, 2024
1 parent d1f3499 commit 6634af1
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
17 changes: 9 additions & 8 deletions R/app.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,16 @@ load_main_module <- function() {
main
}

as_top_level <- function(shiny_module) {
as_top_level <- function(app_env) {
# Necessary to avoid infinite recursion / bugs due to lazy evaluation:
# https://adv-r.hadley.nz/function-factories.html?q=force#forcing-evaluation
force(shiny_module)
force(app_env)

# The actual function must be sourced with `keep.source = TRUE` for reloading to work:
# https://github.com/Appsilon/rhino/issues/157
wrap <- source(fs::path_package("rhino", "as_top_level.R"), keep.source = TRUE)$value

wrap(shiny_module)
wrap(app_env)
}

load_app <- function() {
Expand All @@ -72,14 +72,15 @@ load_app <- function() {
app_env
}

clear_reload_callback <- function() NULL
reload_callback <- new.env(parent = emptyenv())
reload_callback$clear <- function() NULL

register_reload_callback <- function(callback) {
message("@ Clearing reload callback")
clear_reload_callback()
reload_callback$clear()

message("@ Registering reload callback")
clear_reload_callback <<- shiny:::autoReloadCallbacks$register(
reload_callback$clear <- shiny:::autoReloadCallbacks$register(
function() {
message("@ Reload callback")
tryCatch(
Expand Down Expand Up @@ -176,8 +177,8 @@ app <- function() {
server = main$server
)
} else if (is.null(entrypoint)) {
main <- load_main_module()
main <- as_top_level(main)
app_env <- load_app()
main <- as_top_level(app_env)
shiny::shinyApp(
ui = with_head_tags(main$ui),
server = main$server
Expand Down
6 changes: 3 additions & 3 deletions inst/as_top_level.R
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# This function is defined in the `inst` directory, as it must be sourced with `keep.source = TRUE`
# for reloading to work: https://github.com/Appsilon/rhino/issues/157
function(shiny_module) {
function(app_env) {
list(
# Wrap the UI in a function to support Shiny bookmarking.
ui = function(request) shiny_module$ui("app"),
ui = function(request) app_env$main$ui("app"),
# The curly braces below are essential: https://github.com/Appsilon/rhino/issues/157
server = function(input, output) {
shiny_module$server("app")
app_env$main$server("app")
}
)
}

0 comments on commit 6634af1

Please sign in to comment.