---
title: "Portal UI and Code Customization"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Portal UI and Code Customization}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

This article describes how to customize certain visual aspects using the configuration file and how to extend the portal with custom modules.

## Customizing the portal UI

There are two ways to customize the interface of a deployed portal: global settings and module-specific settings.

### Global customizations

In the current version, you can add an acronym or logo, change the title of the tab in the browser, add an icon-based shortcut menu to the landing page and modify the [Bootswatch](https://bootswatch.com) theme.

The configuration file should look like the following:

```yaml
name: PROJ
logo: logo.png
windowtitle: MyProject analysis portal
iconMenu:
- moduleName
- moduleName2
bootswatch:
 theme: theme_name
 version: 3, 4 or 5
```

For the logo and the icon menu, you should create a folder named **www** in your project's folder and place the corresponding images inside, so the resulting file tree looks like this:

```
project/
├─about.md
├─app.R
├─config.yaml
├─...
└─www/
  ├─logo.png
  └─...
```

The icon menu enables using a screenshot of a module to highlight results and provide a shortcut to it. A PNG file named for each module should be created and placed inside the www folder and the names of the modules should be listed under iconMenu in the configuration file, as shown above.

Regarding the themes, the current version of the package will work well with most light-based themes. Not every theme was tested so it's recommended that you test different themes until you find one that works well for your project.

### Module customization

Every module included in the package supports `title` and `description` fields. The title is the entry on the menu, whereas the description field is the text that appears between the menu and the content of the module. The description should be used to instruct visitors about how to use the module and also describe some aspects of that module if needed. For example, it could include a link to an external resource or references.

Besides these two fields, most modules include some degree of customization of colors:

**compareTrajGroups**: a list of HTML-compatible colors for the points for each different value of trajectory_category (e.g. time points).

```yaml
compareTrajGroups:
  custom_traj_colors: ["#ff0000", "#ff00ff", "#0000ff"]
```
**degDetails**: a list of HTML-compatible colors for non-significant, logFC-only significant, p-value-only significant and logFC and p-value significant genes in the volcano plot

```yaml
degDetails:
  custom_point_colors: ["black", "yellow", "red", "blue"]
```

**geneModulesHeatmap**: colors (discrete or for interpolation) or RColorBrewer palettes for the variables that can be used in annotations for the heatmaps and a RColorBrewer palette for the heatmap colors.
  
```yaml
geneModulesHeatmap:
  custom_annotation_colors:
    NumericVar1: ["red", "blue"]
    NumericVar2: "RdBu"
    DiscreteVar1: ["yellow", "green", "blue"]
  custom_heatmap_palette: "BrBG"
```

**multiMeasureCorr**: RColorBrewer palete for heatmap colors.

```yaml
multiMeasureCorr:
  custom_heatmap_palette: "BrBG"
```
**singleGeneCorr**: list of colors for categorical variables in scatterplot.

```yaml
singleGeneCorr:
  custom_point_colors:
    SubjectVar1: ["red", "blue"]
    SubjectVar2:
      Value1: "red"
      Value2: "blue"
```

## Using custom modules

The package also supports the inclusion of new external models, without requiring any changes to the source code of the package. The feature is primarily aimed at supporting features that may have a more niche use case or experimenting with new ideas. Any new code should be implemented based on the following template, for a new `moduleName`:

```{r, eval = FALSE}
moduleName_config <- function(config, ...) { 
  message("Checking moduleName configuration")
  # Add dependency names here
  requiredPackages <- c("")
  stopIfNotInstalled(requiredPackages, "moduleName")
  if (is.null(config$required_variable)) {
    stop("moduleName: 
         'required_variable' is missing")
  }
  config
}

mod_moduleName_ui <- function(module_name, config, module_config) {
  ns <- NS(module_name)
  title <- module_config$title
  description <- module_config$description
  
  required_variable <- module_config$required_variables
  
  tabPanel(
      title = title %||% "Default title",
      value = "moduleName",
      tags$h5(description %||% "Default description"),
      splitLayout(
        verticalLayout(
          wellPanel(
           # Inputs that use the ns object above
          )
        ),
        verticalLayout(
          # Outputs
        ),
        cellWidths = c("20%", "80%"),
        cellArgs = list(style = "white-space: normal;")
      )
    )
  
}

mod_moduleName_server <- function(module_name, config, module_config) {
  moduleServer(module_name, function(input, output, session) {
    ns <- session$ns
    
    measures <- config$data$measures
    expression_matrix <- config$data$expression_matrix
    sample_lookup <- config$data$sample_lookup
    subject_var <- config$subject_variable
    sample_var <- config$sample_variable

    required_variable <- module_config$required_variable
    # Module code here
  })
}
  
```

`moduleName` can now be included in config.yaml file along with required or optional properties. Note that the config function above must be defined otherwise the new module will not be used, although the property validation step is not needed. Each new module can be placed in the main `app.R` or in its own `.R` file. If the second option is used, then each R file must be sourced in the `app.R`, e.g. `source("newCode.R")`.

> **Create the template in your code folder:** the package includes a function that will create a file with the above themplate. After loading the package, run `create_module_template("moduleName")` to create the file and edit it.

At deployment level, besides sourcing the moduleName file if required, two other changes must be made in the app.R file: setting a vector that contains the names of any new modules and passing that variable as the `extra_modules` argument to `run_app`:

```{r, eval = FALSE}
library(shinyExprPortal)

source("newModule.R")
source("anotherModule.R")

extra_modules <- c("newModule", "anotherModule")

run_app("config.yaml", extra_modules = extra_modules)
```

If you are unsure about how to implement a feature in a new module, please post an issue on the package GitHub or check the source code for the existing modules.