Shiny module trees
Two functions, two entry points
call_stack() starts from a function that R can already find by name. A Shiny app usually isn’t in that position. Its functions live in a directory of .R files that hasn’t been installed, or inside the environment of an app object that was built but never launched.
stackcallr covers both cases with two functions:
-
call_tree_dir()reads a directory of.Rfiles from disk and builds the call graph among the functions defined there, without evaluating any of it. -
call_tree_app()inspects ashiny.appobjat runtime and builds the call graph among the functions visible to its server function.
Both return an object of class call_stack, the same class call_stack() returns, so both print as the same block-character tree. There’s no separate renderer to learn.
Scanning a directory with call_tree_dir()
call_tree_dir(path, root, ...) parses every .R file in path, extracts each top-level function definition (name <- function(...) ...), and builds the call graph among those locally-defined functions. It returns the tree of calls reachable from root.
Nothing in the scanned files is loaded, sourced, or run. That’s what makes it usable on a package’s R/ directory, or on a Shiny app’s source, without installing it first.
The code below writes a throwaway app into a temporary directory: a launch() function that assembles the app, an app_ui()/app_server() pair, and one module, mod_a_ui()/mod_a_server().
app_dir <- tempfile("app")
dir.create(app_dir)
writeLines(
'launch <- function() { shinyApp(ui = app_ui(), server = app_server) }',
file.path(app_dir, "launch.R")
)
writeLines(
'app_ui <- function() { mod_a_ui("a") }',
file.path(app_dir, "app_ui.R")
)
writeLines(
'app_server <- function(input, output, session) { mod_a_server("a") }',
file.path(app_dir, "app_server.R")
)
writeLines(
'mod_a_ui <- function(id) { ns <- NS(id) }',
file.path(app_dir, "mod_a_ui.R")
)
writeLines(
c(
'mod_a_server <- function(id) {',
' moduleServer(id, function(input, output, session) { helper() })',
'}'
),
file.path(app_dir, "mod_a_server.R")
)
writeLines(
'helper <- function() 1',
file.path(app_dir, "helper.R")
)Rooting the tree at launch gives every locally-defined function reachable from it:
call_tree_dir(app_dir, root = "launch")
#> █─launch
#> ├─█─app_ui
#> │ └─mod_a_ui
#> └─█─app_server
#> └─█─mod_a_server
#> └─helperNote that helper() shows up under mod_a_server(), and that shinyApp() does not show up at all. Only functions defined in the scanned files become nodes; calls out to shiny or any other package are ignored, since there’s no local definition to expand.
Showing only modules with modules_only
Both functions take modules_only. When TRUE, the tree is pruned to root plus the functions that call shiny::NS() or shiny::moduleServer(). That pair of names is the static test for “this function is a Shiny module”: it’s a pattern match on the parsed expression, not a call into shiny.
call_tree_dir(app_dir, root = "launch", modules_only = TRUE)
#> █─launch
#> ├─█─app_ui
#> │ └─mod_a_ui
#> └─█─app_server
#> └─mod_a_serverapp_ui() and app_server() don’t call NS() or moduleServer(), but they stay in the tree because root calls them directly. modules_only always keeps the functions root calls, so UI modules stay grouped under the UI function and server modules under the server function.
Below that level, a function that isn’t a module is dropped, and its children are spliced up into its parent’s position rather than dropped with it. Without that, a real module reached only through a plain wrapper (a tabs_ui() that assembles several module UIs, say) would vanish from the pruned tree.
helper() is gone, because it isn’t a module and has no module descendants to promote.
Dropping noise with exclude
Most apps have a helper that nearly every function calls, such as a logging function. In a call tree, that helper shows up under almost every node and buries the structure you came to see. The example below adds a logr_msg() helper to each function in a new app directory:
log_dir <- tempfile("app")
dir.create(log_dir)
writeLines(
c(
'launch <- function() { logr_msg("start"); app_ui() }',
'app_ui <- function() { logr_msg("ui"); mod_a_ui("a") }',
'mod_a_ui <- function(id) { logr_msg("mod"); NS(id) }',
'logr_msg <- function(msg) message(msg)'
),
file.path(log_dir, "app.R")
)
call_tree_dir(log_dir, root = "launch")
#> █─launch
#> ├─logr_msg
#> └─█─app_ui
#> ├─logr_msg
#> └─█─mod_a_ui
#> └─logr_msgexclude takes a character vector of function names to drop. Each dropped function’s children are spliced up into its place, the same way modules_only handles wrapper functions:
call_tree_dir(log_dir, root = "launch", exclude = "logr_msg")
#> █─launch
#> └─█─app_ui
#> └─mod_a_uiexclude runs after modules_only, so the two combine. It never drops root. call_tree_app() and call_stack() take the same argument.
Trimming a tree with prune, keep, and max_depth
Three more arguments trim a tree. prune drops a function together with everything below it, where exclude splices the children up. keep takes regular expressions and keeps only the matching functions (with their subtrees) and the path from root down to them. max_depth sets how many levels below root are shown:
call_tree_dir(app_dir, root = "launch", prune = "app_server")
#> █─launch
#> └─█─app_ui
#> └─mod_a_ui
call_tree_dir(app_dir, root = "launch", keep = "_server$")
#> █─launch
#> └─█─app_server
#> └─█─mod_a_server
#> └─helper
call_tree_dir(app_dir, root = "launch", max_depth = 1)
#> █─launch
#> ├─app_ui
#> └─app_serverThey run in this order: prune, modules_only, exclude, keep, then max_depth. call_tree_app() takes all three.
External and default argument calls
include_ns names packages whose exported functions should show up as nodes. They are nested the way the calls are written, so shinyApp(ui = app_ui(), server = app_server) puts both functions under shinyApp:
call_tree_dir(app_dir, root = "launch", include_ns = "shiny")
#> █─launch
#> └─█─shinyApp
#> ├─█─app_ui
#> │ └─█─mod_a_ui
#> │ └─NS
#> └─█─app_server
#> └─█─mod_a_server
#> └─█─moduleServer
#> └─helperExternal functions are never followed into their own source. include_defaults = TRUE also reads calls in default argument values, such as function(dir = util_dir()), which are skipped otherwise.
If a function is defined in more than one file, call_tree_dir() warns and names the files. The definition parsed last is used.
R6 classes
Methods of R6 classes are nodes too, named Class$method. initialize is shown as Class$new, since that’s how it gets called. A variable assigned Class$new() inside a function resolves its method calls, so inputs$ui() below becomes ModInputs$ui:
r6_dir <- tempfile("r6app")
dir.create(r6_dir)
writeLines(c(
"ModInputs <- R6::R6Class('ModInputs',",
" public = list(",
" initialize = function(id) private$ns <- shiny::NS(id),",
" ui = function() private$picker(),",
" server = function() shiny::moduleServer('inputs', function(input, output, session) NULL)",
" ),",
" private = list(ns = NULL, picker = function() util_picker())",
")"
), file.path(r6_dir, "ModInputs.R"))
writeLines(c(
"app_ui <- function() { inputs <- ModInputs$new('inputs'); inputs$ui() }",
"app_server <- function() { inputs <- ModInputs$new('inputs'); inputs$server() }",
"launch <- function() { app_ui(); app_server() }",
"util_picker <- function() 1"
), file.path(r6_dir, "app.R"))
call_tree_dir(r6_dir, root = "launch")
#> █─launch
#> ├─█─app_ui
#> │ ├─ModInputs$new
#> │ └─█─ModInputs$ui
#> │ └─█─ModInputs$picker
#> │ └─util_picker
#> └─█─app_server
#> ├─ModInputs$new
#> └─ModInputs$serverself$m(), private$m(), and super$m() resolve within the class and follow inherit. A class counts as a module for modules_only when any of its methods calls NS() or moduleServer(). Its $new and public methods are then kept, and private helpers are spliced out:
call_tree_dir(r6_dir, root = "launch", modules_only = TRUE)
#> █─launch
#> ├─█─app_ui
#> │ ├─ModInputs$new
#> │ └─ModInputs$ui
#> └─█─app_server
#> ├─ModInputs$new
#> └─ModInputs$serverA method can be the root, too: call_tree_dir(r6_dir, root = "ModInputs$ui"). See vignette("r6") for inheritance, the full set of rules, and what call_tree_dir() can’t follow.
Inspecting a live app with call_tree_app()
call_tree_app(app, app_fun, ui_fun, server_fun, modules_only) works on a shiny.appobj, the object returned by shiny::shinyApp() or shiny::shinyAppDir(). Instead of reading files, it extracts the app’s server function, walks the server’s enclosing environment chain to collect every visible function, and builds the call graph among those.
Constructing a shiny.appobj does not start a server, so the app below is safe to build in a knitted document. It defines a module and a UI/server pair, then passes both to shiny::shinyApp().
library(shiny)
app <- local({
mod_a_ui <- function(id) {
ns <- NS(id)
tagList(textOutput(ns("out")))
}
mod_a_server <- function(id) {
moduleServer(id, function(input, output, session) {
output$out <- renderText("hello")
})
}
app_ui <- function() fluidPage(mod_a_ui("a"))
app_server <- function(input, output, session) mod_a_server("a")
shinyApp(ui = app_ui, server = app_server)
})
call_tree_app(app)
#> █─app
#> ├─█─app_ui
#> │ └─mod_a_ui
#> └─█─app_server
#> └─mod_a_serverThe root node is labelled "app" by default. The app object doesn’t store the name of the function that built it, so app_fun is display text only:
call_tree_app(app, app_fun = "launch", modules_only = TRUE)
#> █─launch
#> ├─█─app_ui
#> │ └─mod_a_ui
#> └─█─app_server
#> └─mod_a_serverNaming the UI function
ui_fun and server_fun default to NULL, which means call_tree_app() recovers the names itself by comparing function bodies against the functions it collected from the environment.
For the server function this is reliable. For the UI it depends on how ui was passed to shinyApp(). Passing a bare function reference (shinyApp(ui = app_ui, ...)) stores the function, and the name can be recovered. Passing a pre-evaluated call (shinyApp(ui = app_ui(), ...)) stores the resulting tag list, and there’s no function left to match, so the UI branch is dropped.
That second form is common. When you’re using it, name the UI function explicitly:
app2 <- local({
mod_a_ui <- function(id) tagList(textOutput(NS(id)("out")))
mod_a_server <- function(id) {
moduleServer(id, function(input, output, session) {})
}
app_ui <- function() fluidPage(mod_a_ui("a"))
app_server <- function(input, output, session) mod_a_server("a")
shinyApp(ui = app_ui(), server = app_server)
})
call_tree_app(app2, ui_fun = "app_ui")
#> █─app
#> ├─█─app_ui
#> │ └─mod_a_ui
#> └─█─app_server
#> └─mod_a_serverHow resolution works
Neither function runs the app. call_tree_dir() works entirely from parsed source:
- Every
.Rfile inpathis parsed withparse(). Files that fail to parse are skipped rather than raising an error. - Each top-level expression is checked for a function assignment (
name <- function(...),name = function(...), orassign("name", function(...))), and the name and unevaluated body are kept. An R6 class (Name <- R6Class(...)) adds one node per method, namedName$method. - Each body is walked recursively for references to the other collected names. Both direct calls (
fun()) and bare references (fun) count, so a function passed as an argument still registers as an edge. A bare name that the function binds itself (a parameter, a variable assigned with<-or=, or aforloop variable) is skipped, because it refers to that value and not the function. The name after$(as inobj$g()) is never read as a call tog(); it only counts when it resolves to an R6 method. - The tree is built depth-first from
root, skipping any name already on the current path, so recursive or mutually recursive functions don’t loop forever. - When
modules_only = TRUE, each body is tested forNS()ormoduleServer()(bare or namespaced), and non-matching nodes are spliced out.
call_tree_app() follows the same steps 3 through 5. It differs only in where the functions come from. app$serverFuncSource() gives the server function and environment() gives its enclosure. The environment chain is then walked upward, collecting functions until it reaches globalenv(), baseenv(), or a loaded package namespace.
What it can’t inspect
call_tree_app() requires a shiny.appobj. It cannot inspect the ShinyAppHandle returned by shiny::startApp() (added in shiny 1.14.0). That handle is a runtime control object for an app that may be running in a separate process; it exposes stop(), status(), url(), and result(). It holds no reference back to the app’s UI, server, or environment. Passing one raises an error that says so, and tells you to pass the shiny.appobj itself, before calling startApp() on it.
Two other limits are worth knowing:
-
call_tree_dir()only sees top-level function definitions and R6 methods. A function defined inside another function, or built by a factory, isn’t a node. An R6 object stored in a field (self$data <- Class$new()) or passed in as an argument isn’t tracked, so its method calls aren’t edges. -
call_tree_app()only sees what’s visible from the server’s environment chain. Functions that live in an unrelated environment, or in a package namespace, stop the walk rather than being expanded.
Shiny isn’t a dependency
Neither function requires shiny to be installed for stackcallr to work. call_tree_dir() matches on the names NS and moduleServer in parsed code, which is text, not a call. call_tree_app() identifies the object it’s handed with inherits() and reaches into it with $; there is no shiny:: call anywhere in its body.
Shiny is in Suggests, and you need it only if you’re building a shiny.appobj to pass in.
Recap
call_tree_dir() maps a directory of source files and call_tree_app() maps a shiny.appobj; neither runs the app. Both return a call_stack tree, and modules_only = TRUE prunes it to the modules while keeping modules reached through wrapper functions. exclude drops named functions, such as a logging helper, from any of the three trees.
Learning more
See ?call_tree_dir and ?call_tree_app for the full argument reference, and vignette("stackcallr") for call_stack(), which covers the case these two complement: a single function R can already resolve by name.