26 Design widgets

Framework7 brings dozen of different widgets like a photo browser, virtual lists (high performance lists), messages, notifications, toasts. Figure ?? shows from left to right the chat widget, the floating action buttons and the gauges.

Looking at the documentation, the API is most of the time always the same that is, we create the widget:

app.widget.create(parameters);

and we update, open or close it later:

app.widget.update(newParameters);
app.widget.open();
app.widget.close();

I must admit, there are few deviations like the navbar (app.navbar.show()) or the modal dialog but we have enough common points to design a main wrapper that creates any widget and update/open/close it.

What we do below significantly simplifies the R/JS API by providing a general method to initialize and update some of those widgets.

As a reminder, the code examples shown throughout this chapter are gathered in the {OSUICode} package accessible here, specifically here for widgets.

26.1 Build the UI

We know that JavaScript must receive a configuration object to create the widget instance. As shown earlier in this book, there is a simple way to achieve this. Let’s consider the gauge example:

On the UI side, we expect to have:

<div class="gauge"></div>

Upon instantiating, Framework7 populates this container with the relevant tags. The f7_gauge() function creates a div tag with the gauge class as well as a configuration tag:

f7_gauge <- function(id, value, options = NULL) {

  if (is.null(options[["valueText"]])) {
    options[["valueText"]] <- paste(value * 100, "%")
  }

  gaugeProps <- c(list(value = value), options)

  gaugeConfig <- shiny::tags$script(
    type = "application/json",
    `data-for` = id,
    jsonlite::toJSON(
      x = gaugeProps,
      auto_unbox = TRUE,
      json_verbatim = TRUE
    )
  )

  shiny::tags$div(
    class = "gauge",
    id = id,
    gaugeConfig
  )
}

We provide a default for the valueText option that should display the current value followed by a % symbol. Note that the class is crucial to target the relevant tag on the JS side. All other widgets more or less follow the same scheme. Be careful about partial matching with the $ operator. This is the reason why we used [[ instead: with $, valueText could be matched with valueTextColor, leading to unexpected behavior.

26.2 Widgets without preexisting UI

There are few widgets like toasts, notifications that don’t have any predefined UI element when the app starts. In this case, we simply send the configuration to JS, through the session:

f7_notif <- function(
  id = NULL, 
  text, 
  options = NULL, 
  session = shiny::getDefaultReactiveDomain()
) {

  if (!is.null(options$icon)) {
    options$icon <- as.character(options$icon)
  }

  message <- c(dropNulls(list(id = id, text = text)), options)
  # see my-app.js function
  sendCustomMessage("notification", message, session)

}

Pay attention to the options$icon element. As we can’t convert shiny tags to JSON, it must be converted to character first. If multiple parameters should contain tags, you must treat them accordingly!

26.3 Initialize the widget

On the JS side, we create a new script, widgets.js:

We set an array containing all compatible widget names in two categories and concatenate in a widgets element:

const uiWidgets = ["gauge", "swiper", "searchbar"];
const serverWidgets = ["toast", "photoBrowser", "notification"];
const widgets = uiWidgets.concat(serverWidgets);

Notice that as we are going to use the app object, we import them from the init.js script, located in the same /srcjs folder.

We then define the activateWidget function, only considering UI widgets. Since we have two widgets categories, this function first checks whether the widget is part of the uiWidgets array with indexOf:

if (uiWidgets.indexOf(widget) > -1) {
  // Do things
}

As there may be multiple widgets of the same type, we must loop through all possible elements. This is where the class is important and must match the widget generic name. For instance, the gauge has the gauge class and the methods are always app.gauge.. How do we loop through multiple widgets? We use the jQuery each method:

if (uiWidgets.indexOf(widget) > -1) {
  $("." + widget).each(function() {
    // Do things
  }
}

We see that $("." + widget) gives $(".gauge) when the widget is a gauge, which targets all gauges one by one. Then for each gauge, we extract the configuration containing all options passed by the end user. Remember that each element has a unique id. We extract the current element $(this) in the $el variable and search for a script tag pointing to the unique tag having $el.attr("id") as id. The configuration is parsed and converted to an object. Note that most of the time, Framework7 expects to have a el attributes which simply contains the CSS selector of the current element, in other words its unique id '#' + $el.attr("id"):

if (uiWidgets.indexOf(widget) > -1) {
  $("." + widget).each(function() {
    let $el = $(this);
    let config = $(document).find(
      "script[data-for='" + $el.attr("id") + "']"
    );
    config = JSON.parse(config.html());
    // add the id
    config.el = '#' + $el.attr("id");
  }
}

The final step consists in initializing the widget, which is quite straightforward if we notice that app.gauge is the same as app["gauge"]. We obtain the general code:

app[widget].create(config);

For the server widgets, it is even simpler. We recover the message with a Shiny.addCustomMessageHandler("type", callback) and initialize it. The only possible source of problem is the custom message type that must be the same as the one specified in the R function with session$sendCustomMessage("type", message). We create an else statement following the if condition and put the below code inside:

Shiny.addCustomMessageHandler(widget, function(message) {
  if (message.id !== undefined) {
    message.on = {
      opened: function() {
        Shiny.setInputValue(message.id, true);
      },
      closed: function() {
        Shiny.setInputValue(message.id, false);
        app.data[widget][message.id].destroy();
      }
    }; 
  }

  app[widget].create(message).open();
});

As shown in the above code, we can chain methods and immediately open the widget, right after its creation. Moreover, it is always good practice to let Shiny know about the widget state, that is whether it is currently opened. This is the reason why we added an on property to the message. All widgets trigger events, for instance notifications have the notification:opened and notification:closed. For each event, we set an input value on the fly, with Shiny.setInputValue as explained in Chapter (quick-inputs). This way, our future users can know exactly when the widget is closed or opened, thereby being able to trigger any subsequent action. This obviously requires the widget to pass an optional id attribute to ensure the uniqueness!

The full JavaScript code may be found here:

// Instantiate a widget
activateWidget = function(widget) {
  // Handle ui side widgets
  if (uiWidgets.indexOf(widget) > -1) {
    $("." + widget).each(function() {
      let $el = $(this);
      let config = $(document).find(
        "script[data-for='" + $el.attr("id") + "']"
      );
      config = JSON.parse(config.html());
      // add the id
      config.el = '#' + $el.attr("id");

      // feed the create method
      app[widget].create(config);
    });
  } else {
    // This concerns toasts, notifications, photoBrowser, ...
    // that don't have any UI element in the DOM before creating
    // the widget instance.
    Shiny.addCustomMessageHandler(widget, function(message) {
      if (message.id !== undefined) {
        message.on = {
          opened: function() {
            Shiny.setInputValue(message.id, true);
          },
          closed: function() {
            Shiny.setInputValue(message.id, false);
            app.data[widget][message.id].destroy();
          }
        }; 
      }
      app[widget].create(message).open();
    });
  }
};

The final step aims at activating all widgets. We proceed with a forEach loop:

// Loop over all widgets to activate them
widgets.forEach(function(w) {
  activateWidget(w);
});

Let’s try below with a notification example, where we capture the state of the notification in an input element:

library(shiny)
ui <- f7_page(
  navbar = f7_navbar("Title"),
  toolbar = f7_toolbar(),
  title = "shinyMobile",
  options = list(
    theme = "ios",
    version = "1.0.0",
    taphold = TRUE,
    color = "#42f5a1",
    filled = TRUE,
    dark = TRUE
  )
)

server <- function(input, output, session) {
  observe({
    f7_notif(
      id = "welcome", 
      "Helloooooo", 
      options = list(closeTimeout = 2000)
    )
  })
  
  observeEvent(input$welcome, {
    shiny::showNotification(
      sprintf("Notification is %s", input$welcome)
    )
  })
}

shinyApp(ui, server)

Alternatively you may run in the R console:

shinyAppDir(system.file(
  "shinyMobile/notification", 
  package = "OSUICode"
))

26.4 Update widgets

We would like to develop a similar generalized interface to update any element in the DOM. Instead of having update_f7_gauge() or update_f7_swiper(), we want an update_f7_instance() function.

We leverage the app.data element that stores all instances by widget type. In Chapter 24.5.7, we already created a cache for tooltips, so let’s do it for gauges:

config.data = function() {
  return {
    // any other widget type to cache ...
    gauge: []
  };
};

The array name must be the same as the app method. For instance, we have app.gauge, which means that we should create config.data.gauge and not config.data.gauges, as it would lead to errors later.

Once the cache is available, we have to modify the JavaScript that creates the widget instance, to store the new instance in the cache, as shown Figure 26.1. We add the following code, where w refers to the widget instance:

// ui widgets
app.data[widget][$el.attr("id")] = w;

This manipulation does not make sense for server widgets as they are already generated by the server.

The activateWidget function should be:

// Instantiate a widget
activateWidget = function(widget) {
  // Handle ui side widgets
  if (uiWidgets.indexOf(widget) > -1) {
    $("." + widget).each(function() {
      let $el = $(this);
      let config = $(document).find(
        "script[data-for='" + $el.attr("id") + "']"
      );
      config = JSON.parse(config.html());
      // add the id
      config.el = '#' + $el.attr("id");

      // feed the create method
      let w = app[widget].create(config);
      // Store the widget instance in the app data cache
      app.data[widget][$el.attr("id")] = w;
    });
  } else {
    // This concerns toasts, notifications, photoBrowser, ...
    // that don't have any UI element in the DOM before creating
    // the widget instance.
    Shiny.addCustomMessageHandler(widget, function(message) {
      if (message.id !== undefined) {
        message.on = {
          opened: function() {
            Shiny.setInputValue(message.id, true);
          },
          closed: function() {
            Shiny.setInputValue(message.id, false);
            app.data[widget][message.id].destroy();
          }
        }; 
      }
      app[widget].create(message).open();
    });
  }
};

Once done, this is time to design update_f7_instance(). The R code sends a message to the current session containing:

  • The id of the element to update.
  • The new configuration.

Since we send a JSON, the hardest part is to correctly process shiny tags. How do we track shiny tags? As a reminder, let’s run the code below:

class(shiny::div())
## [1] "shiny.tag"
class(shiny::tagList(shiny::div(), shiny::h1()))
## [1] "shiny.tag.list" "list"

For each configuration element, we must check whether its class contains shiny.tag or shiny.tag.list and convert it to a character. Moreover, it may contain a nested list, like this:

options = list(
  buttons = list(
   list(
     text = "Some text",
     icon = f7Icon("info"),
     color = "pink"
   )
  )
)

In that case, our function must be recursive to handle any item having the list class. If the element is simple text or numeric, we return it as is.

We finally get:

update_f7_instance <- function(
  id, 
  options, 
  session = shiny::getDefaultReactiveDomain()
) {

  # Convert any shiny tag into character so that toJSON does not cry
  listRenderTags <- function(l) {
    lapply(
      X = l,
      function(x) {
        if (inherits(x, c("shiny.tag", "shiny.tag.list"))) {
          as.character(x)
        } else if (inherits(x, "list")) {
          # Recursive part
          listRenderTags(x)
        } else {
          x
        }
      }
    )
  }
  options <- listRenderTags(options)

  message <- list(id = id, options = options)
  sendCustomMessage("update-instance", message, session)
}

On the JS side, we receive the message, still in the widget.js script:

Shiny.addCustomMessageHandler(
  'update-instance', function(message) {
  // Treat message ...
});

All widgets are stored by type in the app data, for instance, the element having for unique id mygauge is located in app.data["gauge"]["mygauge"]. As there is no easy way to recover the widget type given its id, the first step of the message handler is to find where our instance is located. We design a nested for loop. The outer loop scans all app.data properties (ie widget categories), while the inner loop scans all existing instances for each category. Whenever, the message.id matches the instance name, we store the corresponding widget category in a variable:

let instanceFamily;
for (const property in app.data) {
  for (const e in app.data[property]) {
    if (e === message.id) {
      instanceFamily = property;
    }
  }
}

We then access the old instance using the newly defined variable and the message.id. We capture its parameters located in oldInstance.params. From there, multiple options are available:

  • We extend the old configuration with the new one.
  • We entirely overwrite the existing options.

In what follows, we decided to merge the old and new configurations using app.utils.extend:

let oldInstance = app.data[instanceFamily][message.id];
let oldConfig = oldInstance.params;
let newConfig = app.utils.extend(oldConfig,  message.options);

The next step consists in destroying the old instance, initializing the new instance and refreshing the app.data cache:

// Destroy old instance
oldInstance.destroy();
// Create new config
let newInstance = app[instanceFamily].create(newConfig);
// Update app data
app.data[instanceFamily][message.id] = newInstance;

The whole code is found below:

Shiny.addCustomMessageHandler(
  'update-instance', function(message) {
  // Recover in which array is stored the given instance.
  // Uniqueness is ensured since HTML id are supposed to be unique.
  let instanceFamily;
  for (const property in app.data) {
    for (const e in app.data[property]) {
      if (e === message.id) {
        instanceFamily = property;
      }
    }
  }

  let oldInstance = app.data[instanceFamily][message.id];
  let oldConfig = oldInstance.params;
  let newConfig = app.utils.extend(oldConfig,  message.options);

  // Destroy old instance
  oldInstance.destroy();
  // Create new config
  let newInstance = app[instanceFamily].create(newConfig);
  // Update app data
  app.data[instanceFamily][message.id] = newInstance;
});

The update concept is illustrated Figure 26.1.

Initializing and updating widgets in the app.data store

FIGURE 26.1: Initializing and updating widgets in the app.data store

Below is an example showing how to update a gauge from the server. As you may notice, this approach is not perfect as the user has to explicitly update the valueText field so that it reflects the new value. Similarly, you may ask why the gauge value has to be between 0 and 1, instead of 0 and 100. The reason comes from the Framework7 API. One might be tempted to convert the value inside f7_gauge (so that the user only provides number between 0 and 100), but this would also mean to manually convert the value in the update_f7_instance function later. As stated in previous chapters, there is always a compromise to do between a simple API easy to maintain (for the developer) and user experience. This issue may/should be solved by a comprehensive documentation.

ui <- f7_page(
  f7_gauge(
    "mygauge", 
    value = 0.1,
    options = list(
      type  = "semicircle",
      borderColor = "#2196f3",
      borderWidth = 10,
      valueFontSize = 41,
      valueTextColor = "#2196f3",
      labelText = "amount of something"
    )
  ),
  navbar = f7_navbar("Title"),
  toolbar = f7_toolbar(),
  title = "shinyMobile",
  options = list(
    theme = "ios",
    version = "1.0.0",
    taphold = TRUE,
    color = "#42f5a1",
    filled = TRUE,
    dark = TRUE
  )
)

server <- function(input, output, session) {
  observe({
    Sys.sleep(2)
    update_f7_instance(
      "mygauge", 
      options = list(
        value = 0.75, 
        valueText = "75 %", 
        labelText = "New label!"
      )
    )
  })
}

shinyApp(ui, server)

Alternatively you may run in the R console:

shinyAppDir(system.file("shinyMobile/pwa", package = "OSUICode"))