How do I add css style element to Rmd shiny renderImage? - css

I am struggling to add css style element to my shiny renderImage code.
I have tried various options with css source file via tag$link as well as with straight css code via tag$style.
I have tried both the tag$link as well as the tag$style options (in my sample code)
(1) outside of the renderImage code
(2) inside the renderImage code, outside of the list wrapper
(3) inside the renderImage code, inside of the list wrapper
I get one of two errors:
Error 1: Object of type 'closure' is not subsettable
Error 2: Object 'centerImage' not found
With my logo5.png image on my local machine, with no additional css - it works.
With my logo5.png image on my local machine, with additional css - it DOES NOT work.
Note that I left the '1', dir() and '2' in my code prior to renderImage to track execution.
Can someone please help?
(To run in Rstudio, change the rrr`` to the 3 back quotes in 4 places)
(My online image URL is http://www.richpat.com/wp-content/uploads/2019/04/logov5.png)
---
title: 'Shiny Dev with Logo'
output:
flexdashboard::flex_dashboard:
theme: united
orientation: columns
source_code: embed
runtime: shiny
---
rrr``{r setup, include=FALSE} #CORRECT THIS WHEN RUNNING
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE)
library(flexdashboard,quietly=TRUE, verbose=FALSE)
library(shiny,quietly=TRUE, verbose=FALSE)
library(plotly,quietly=TRUE, verbose=FALSE)
rrr`` #CORRECT THIS WHEN RUNNING
Corporate
=======================================================================
Column
-----------------------------------------------------------------------
### Logo
rrr``{r} #CORRECT THIS WHEN RUNNING
(1)
dir()
#tag$head(tags$link(rel = "stylesheet", type = "text/css", href = "BRstyle.css"))
#tag$head(tag$style("centerImage {text-align:center;}"))
(2)
renderImage({
rfilename=normalizePath("logov5.png")
list(src=rfilename, contentType = "image/png", alt = "logo5", class=centerImage)
}, deleteFile = FALSE)
rrr`` #CORRECT THIS WHEN RUNNING
Background
=======================================================================
Column
-----------------------------------------------------------------------
### Purpose
ad valorem libram

OK - so I found the answer. And simplicity is the route...
Instead of doing this in shiny renderImage, I learned a lot about how shiny and flexdashboard and markdown work together !!!
I used img html tag as part of the markdown section with direct display tags
<img src="http://www.richpat.com/wp-content/uploads/2019/04/logov5.png"
alt="Markdown Monster icon"
style="ftext-align:center; display: center;" />
And I removed the complete shiny renderImage r-code section
As a bonus - and just to show a bit more of what I learned, here is my revised yaml
title: 'Br F A'
output:
flexdashboard::flex_dashboard:
logo: logov5s.png
theme: readable
css: BRstyle.css
navbar:
- { title: "About", href: "http://www.richpat.com", align: left }
source_code: embed
orientation: columns
runtime: shiny

Related

Highlight text inline. R-markdown with reference .docx

I need to be able to highlight all text in an r-markdown document that has been inserted using an inline code chunk. E.G r TEXT.
This is to enable editing of the automated Word document creation.
I have tried using
.highlight {
background-color: lightpink;
border: 3px solid red;
font-weight: bold;
}
r sprintf("<span class='highlight'>%s</span>",PNAME)
AND
r text_spec(TEXT, color = "red")
However, I suspect these are not working due to the reference .docx that I am using over-riding the styles.
Is there a way to still use the reference doc and have the highlighting??
Thanks in advance.
Silas
Using officedown::rdocx_document: default as the output type, we can use ftext and fp_text function from {officer} package to highlight text that were inserted using inline r code chunk.
---
title: "Inline code styling"
output:
officedown::rdocx_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officer)
ft <- officer::fp_text(shading.color = "yellow")
word_spec <- function(x, prop = ft) ftext(text = toString(x) ,prop = ft)
```
## Inline code highlighting for word document
We can highlight text in an r-markdown document that has been inserted using an inline code for output type word document too.
- `r word_spec("text in inline code is highlighted")`
- The sum of 2 + 2 is `r word_spec(2 + 2)`
- The sequence from 1 to 10 is `r word_spec(1:10)`
And the rendered word document looks like this,

CSS selector for font color in flextable with shadow host on

I'm unsuccessfully trying to set the font color for flextable generated in r markdown using a css stylesheet.
I can accomplish this when I turn off shadow host, but not with it on. (Just turning it off removes other desirable features.) Here's a short r markdown file demonstrating the difference.
---
title: "Untitled"
output: html_document
---
<style>
div.flextable-shadow-host * {
color: pink;
}
div.tabwid * {
color: pink;
}
</style>
# ignores CSS above
```{r, echo=FALSE}
library(flextable)
flextable(head(mtcars))
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
I want the css external to the r code because I have a button selector on the website the user can change the overall style (e.g., dark mode or not).
When using shadow, the table is assembled outside of HTML. Only the id connects the table to HTML. However, flextable has functions for setting the color. Why not just use one of the many built-in methods to change the color?
For example:
# ignores CSS above
```{r liberator,include=F}
library(flextable)
library(tidyverse)
```
```{r tbler, echo=FALSE}
flextable(head(mtcars)) %>%
color(color = "pink", part = "all")
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
There are many things you can do with flextable styling. You can see more customization options here.
Update: Based on your comments
Okay, this works to change the color of a flextable.
This works if there is only one flextable in the script.
I have the color of the text set to #b21E29 (a shade of red). You can change that as you see fit.
These will SKIP non-shadow flextables
Add this chunk anywhere in your RMD script. This requires no additional libraries or any other customization in your R code.
```{r js_ing,results="asis",engine="js",echo=F}
// extract the styles that are set for the flextable
letMe = document.querySelector('div.flextable-shadow-host').shadowRoot.querySelector('div>style');
// replace color style
// preceding ';' so that 'background-color' doesn't change
letMe.innerHTML = letMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
```
If you have more than one flextable with shadow on, you can use one of the two following chunks instead. In the first--all the same color; in the second--each table has a different color.
These work if there is more than one flextable in the script.
Pay attention to the comments so you can see what to use when depending on your desired output.
All the same color:
```{r moreJs_ing,results="asis",engine="js",echo=F}
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// to set all shadow flextables to the same font color:
for(i = 0, n = letMe.length; i < n; i++){
showMe = letMe[i].shadowRoot.querySelector('div>style');
showMe.innerHTML = showMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
}
```
Each with there own color:
```{r evenMoreJs_ing,results="asis",engine="js",echo=F}
//alternatively to set each to a different color
// make sure you only include one of these options!
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// first table in script
showFirst = letMe[0].shadowRoot.querySelector('div>style');
showFirst.innerHTML = showFirst.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
// second table in script
showSecond = letMe[1].shadowRoot.querySelector('div>style');
showSecond.innerHTML = showSecond.innerHTML.replace(/;(color:.+?);/g, ';color:#003b70 !important;');
// change the indices for each table, keep in mind the first table is [0], not [1]
```
If you aren't sure where you want to go with these, add all three and and include=F as a chunk option to the two you aren't using at that moment in time.

Mermaid (diagrammeR) graph not displayed in RPres

I am trying to include a graph built with the diagrammeR package in an RPres. That's the graph:
library(DiagrammeR)
mermaid("graph TD
X1(X1)-->Z1(Z2)
X2(X2)-->Z2(Z2)
X1(X1)-->Z2(Z2)
Z1(Z1)-->Y(Y)
Z2(Z2)-->Y(Y)
")
Looking at the output in RStudio's viewer pane is no problem. No I include it in an RPres:
Untitled
========================================================
author:
date:
autosize: true
First Slide
========================================================
```{r,echo=FALSE, results = "asis"}
library(DiagrammeR)
mermaid("graph TD
X1(X1)-->Z1(Z2)
X2(X2)-->Z2(Z2)
X1(X1)-->Z2(Z2)
Z1(Z1)-->Y(Y)
Z2(Z2)-->Y(Y)
")
(note that the "```" to close the code chunk aren't displayed here because of markup...)
Alas, nothing but the abyss of emptiness:
Are you committed to RPres or would you consider alternative slide formats? For example, if you create a new R Markdown document and specify output: ioslides_presentation in the YAML header, the diagram will render properly:
---
title: "Untitled"
author: "Your Name"
date: "5/2/2020"
output: ioslides_presentation
---
Untitled
===========================================================
Here is the content for the second slide in different style
## Title of Mermaid Slide
```{r,echo=FALSE, results = "asis"}
library(DiagrammeR)
mermaid("graph TD
X1(X1)-->Z1(Z2)
X2(X2)-->Z2(Z2)
X1(X1)-->Z2(Z2)
Z1(Z1)-->Y(Y)
Z2(Z2)-->Y(Y)
")
Which produces this:

DownloadButton width in R Flexdashboard

I'm having problems to change my DownloadButton width, since he's different from actionButton (which have the width parameter).
Any easy ideas to solve it?
Here's my code (Just a simple download button):
Normalidade
=======================================================================
Inputs {.sidebar}
-----------------------------------------------------------------------
<h5>
```{r}
tags$hr()
downloadButton("downloadNormal",label = "Download seu teste", class = "butt1")
downloadHandler(
filename = "Resultados_Normal.csv",
content = function(file) {
write.csv(data, file)
}
)
tags$hr()
tags$br()
actionButton("AjudaNormal", label = " Ajuda", icon("question-circle"),
width = "100%",
onclick="window.open('http://google.com', '_blank')")
```
</h5>
Actually, after playing around with this I recommend to use uiOutput with renderUI.
Without using uiOutput the downloadButton function gets ignored (only the downloadHandler gets evaluated), that's why the width parameter was not set, and also you can't modify the label of the button.
There are all solved with using uiOutput.
---
title: "Full width downloadButton"
output:
flexdashboard::flex_dashboard:
css: styles.css
runtime: shiny
---
```{r setup, include=FALSE}
library(flexdashboard)
```
Inputs {.sidebar}
-----------------------------------------------------------------------
```{r}
# Create placeholder for the downloadButton
uiOutput("downloadUI")
```
```{r}
# Create the actual downloadButton
output$downloadUI <- renderUI( {
downloadButton("downBtn", "Download Iris data", style = "width:100%;")
})
# Add download handling
output$downBtn <- downloadHandler(
filename = function() {
"iris.csv"
},
content = function(file) {
write.csv(iris, file, row.names = FALSE)
}
)
```
I set the width using inlineCSS with the style argument, but you can (and should) use an external style sheet if you have multiple CSS rules.
Using an external stylesheet (CSS file)
An external CSS file can be used in Flexdashboard by adding css: path/filename.css to the YAML header.
---
title: "Full width downloadButton"
output:
flexdashboard::flex_dashboard:
css: styles.css
runtime: shiny
---
In this case the app tries to read a file called styles.css in the same folder as the Rmd.
Create the css file in the same folder and add the rule:
#downBtn {
width: 100%;
}
You can now remove style = "width:100%;" from the downloadButton and still get full width button.
Output:

Rmarkdown: Indentation of TOC items in HTML output

I want to indent TOC according to header level.
My example document looks like this:
# Tutorial
## Start a new project
### Project structure
### Analysis code
I'm compiling Rmd document with:
rmarkdown::render("foo.Rmd",
output_options = HTMLlook,
output_file = "foo.html")
HTMLlook <- list(toc = TRUE,
toc_depth = 5,
toc_float = list(collapsed = FALSE,
smooth_scroll = TRUE))
This produces document with TOC
However, I want indented TOC (indentation equivalent to header level). Wanted result should look like this:
Is it possible to set this option in render or maybe pass css parameters to it?
I am not aware of a built-in solution. But here is a little tweak:
<script>
$(document).ready(function() {
$items = $('div#TOC li');
$items.each(function(idx) {
num_ul = $(this).parentsUntil('#TOC').length;
$(this).css({'text-indent': num_ul * 10, 'padding-left': 0});
});
});
</script>
The depth of your headers is actually mapped inside the TOC. For each level you go down, a new ul element is created. This is what we are making use of here. In detail:
When the document has finished loading ($(document).ready(....):
Select all list items inside the element with id TOC
For each list item count the number of parent elements until you reach the element with id TOC. This is the number of ul elements.
Change the style for the current list item according to the number of parents.
You can tweak the spacing by playing around with the two parameters for text-indent and padding-left.
MRE:
---
title: "Habits"
author: Martin Schmelzer
date: September 14, 2017
output:
html_document:
toc: true
toc_depth: 5
toc_float:
collapsed: false
smooth_scroll: true
---
<script>
$(document).ready(function() {
$items = $('div#TOC li');
$items.each(function(idx) {
num_ul = $(this).parentsUntil('#TOC').length;
$(this).css({'text-indent': num_ul * 10, 'padding-left': 0});
});
});
</script>
# In the morning
## Waking up
### Getting up
#### Take a shower
##### Make coffee
# In the evening
## Make dinner
This is the result:

Resources