Making Modules

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

Introduction

This vignette will provide an overview of the formods framework for creating reproducable modules that interact with each other. Each module has its own namespace that is mantained by using a module short name as a prefix for functions. For example the figure generation module uses FG. If you want to create a module, please submit an issue at the formods github repository with the following information:

Current modules

The following modules are currently available:

Other short names in use:

Currently in development:

formods framework

To get started you need to create some template files. The example below assumes you are creating this module for a package called mypackage and that you are running this command in a git repository. Say that this module is used to produce widgets, the short name is MM which stands for My Module:

use_formods(SN          = "MM",
            Module_Name = "My Module",
            element     = "widgets", 
            package     = "mypackage")

This command will create the following files:

Expected functions

The module template will create a standard set of functions for you. The MM below will be replaced with whatever short name you choose above when you create the templates. These functions can be customized for your specific module. Some are optional and can be deleted. For example the MM_fetch_ds function is only needed if your module creates datasets and provides them for other modules to use (like the DW module exports data views to be used by other modules). The modules are designed to create elements. For example the DW module creates data view elements, the FG module is used to create figure elements, etc.

Expected UI components

Module interaction

Say you are using the UD module to feed data into the DW module and the user goes back to the upload form and uploads a different data set. This will need to trigger a reset of the Data Wrangling module as well as tell your larger app that something has changed.

Module state and reacting to changes

Changes in module states are detected with the react_state object. For a given module of type "MM" with a module id of "ID" you would detect changes by reacting to react_state[["ID"]] and looking for changes in the checksum element below:

react_state[["ID"]][["MM"]][["checksum"]]

Helper functions in formods

The examples below require a Shiny session variable and a formods state object. Here we create some examples and other objects needed to demonstrate the functions below.

library(formods)
# This creates the state and session objects
sess_res = UD_test_mksession(session=list())
state    = sess_res$state
session  = sess_res$session

# Here we load an example dataset into the df object.
data_file_local =  system.file(package="formods", "test_data", "TEST_DATA.xlsx")
sheet           = "DATA"

df = readxl::read_excel(path=data_file_local, sheet=sheet)

Setting holds on UI elements

The mechanics of the fetch state functions mean that each time a fetch state is called, all of the UI elements in the App are pulled and placed in the app state. This generally works well with some exceptions. The main exception is when you want to have a UI element that changes another UI element. Say for example you have a selection box with a UI id of my_selection. You want that selection to alter a text input with an id of my_text. However if you just poll the ui elements you may update my_text based on changes to my_selection then have those overwritten by the current value of my_text. To prevent this, you need to do two things:

Lastly you need to remove the hold. This is done after the UI has refreshed with the new text value populated in to my_text (with the appropriate reactions set). This is done with an observeEvent that is triggered after everything else (with a priority of -100 below):

remove_hold_listen  <- reactive({
  list(input$my_selection)
})
observeEvent(remove_hold_listen(), {
  # Once the UI has been regenerated we
  # remove any holds for this module
  state = MM_fetch_state(id              = id,
                         input           = input,
                         session         = session,
                         FM_yaml_file    = FM_yaml_file,
                         MOD_yaml_file   = MOD_yaml_file,
                         react_state     = react_state)

  FM_le(state, "removing holds")
  # Removing all holds
  for(hname in names(state[["MM"]][["ui_hold"]])){
    remove_hold(state, session, hname)
  }
}, priority = -100)

The remove_hold_listen object should contain all of the inputs that create holds.

Dataframe formatting information

If you want to tables and pulldown menues based on the types of data in each column you can use the FM_fetch_data_format() function.

hfmt = FM_fetch_data_format(df, state)

# Descriptive headers 
head(as.vector(unlist( hfmt[["col_heads"]])))

# Subtext
head(as.vector(unlist( hfmt[["col_subtext"]])))

The custom headers can be used with the {rhandsontable} package.

hot = rhandsontable::rhandsontable(
  head(df),
  width      = "100%",
  height     = "100%",
  colHeaders = as.vector(unlist(hfmt[["col_heads"]])),
  rowHeaders = NULL
  )
hot

To add subtext to a selection widget in Shiny you need to use the {shinyWidgets} package.

sel_subtext = as.vector(unlist( hfmt[["col_subtext"]]))
library(shinyWidgets)
shinyWidgets::pickerInput(
    inputId    = "select_example",
    choices    = names(df),
    label      = "Select with subtext",
    choicesOpt = list(subtext = sel_subtext))

To alter the formats shown here you need to edit the formods.yaml configuration file and look at the FM$\rightarrow$data_meta section.

Notifications

Notifications are created using the {shinybusy} package and are produced with two different functions: FM_set_notification() and FM_notify(). This is done in a centralized fashion where notifications are added to the state object as user information is processed. This will set a notification called Example Notification. Along with that a timestamp is set:

   state = FM_set_notification(state, "Something happened", "Example Notification")

That timestamp is used to track and prevent the notification from being shown multiple times. Next you need to setup the reactions to display the notifications. Here you can create a reactive expression of the inputs that will lead to a notification:

    toNotify <- reactive({
      list(input$input1,
           input$input2)
    })

Next you use observeEvent() with that reactive expression to trigger notifications. You need to use the fetch state function for that module to get the state object with the notifications. Then FM_notify() will be called an any unprocessed notifications will be displayed:

    observeEvent(toNotify(), {
      state = MM_fetch_state(id              = id,
                             input           = input,
                             session         = session,
                             FM_yaml_file    = FM_yaml_file,
                             MOD_yaml_file   = MOD_yaml_file,
                             react_state     = react_state)

      # Triggering optional notifications
      notify_res =
      FM_notify(state    = state,
                session  = session)
    })

Adding tooltips

Tooltips are created internally using the suggested {prompter} package. To add a tool tip to a ui element you would use the FM_add_ui_tooltip() function. For example to add the tool tip, You need to type harder! to a text input you would do the following:

uiele = shiny::textInput(
          inputId = "some_text", 
          label   = "You need to type harder!")
uiele = FM_add_ui_tooltip(state, uiele, 
      tooltip  = "This is a tooltip",
      position = "left")

Pausing the screen

To pause the screen the {shinybusy} package is also used. This is controlled with two functions: FM_pause_screen() is used to pause the screen and/or update the pause message, and FM_resume_screen() is used end the pause and resume interaction with the user.

FM_pause_screen(state, session)
FM_resume_screen(state, session)

formods state objects

When you create a formods state object it can have the following fields:

App information in MM

This field state$MM is relatively free form but there are some reserved elements. These reserved keyword are:

Other than those fields you can store whatever else you need for your module.

Checklist

The following is a suggested checkist to go over when making a module:

Configuration file

```{css, echo=FALSE} .scroll-100 { max-height: 100px; overflow-y: auto; background-color: inherit; }

# YAML configuration files {.tabset}

```r
yaml= file.path(system.file(package="formods"), "templates", "formods.yaml")
cat(readLines(file.path(system.file(package="formods"), "templates", "formods.yaml")), sep="\n")

#library(shiny)
#library(shinyAce)
# renderUI({
# aceEditor("formods", value=readLines(file.path(system.file(package="formods"), "templates", "formods.yaml")))
# })

# yamls = list(
#   formods.yaml= file.path(system.file(package="formods"), "templates", "formods.yaml"),
#   ASM.yaml    = file.path(system.file(package="formods"), "templates", "ASM.yaml"),
#   DS.yaml     = file.path(system.file(package="formods"), "templates", "DW.yaml") 
#   
# )
# 
# for(yaml in names(yamls)){
# # cat("``` yaml")
#   cat(paste(readLines(file.path(system.file(package="formods"), "templates", "formods.yaml"))), collapse="\n")
# }


Try the formods package in your browser

Any scripts or data that you put into this service are public.

formods documentation built on April 12, 2025, 1:57 a.m.