How to add/inject arbitrary Javascript to code that tmap_leaflet() generates? - leaflet

Using the R's tmap package in "view" mode, here I have R pseudocode that generates an interactive world map, and adds an info-button that shows an alert using javascript.
# this is pseudocode - providing real data would be too much work
lf <- tmap_leaflet(tm_world) %>%
setView(2.2945, 0, zoom=2) %>%
addEasyButton(
button = easyButton(
icon = 'fa-warning',
onClick = JS('function(btn, map){ alert("At very high zoom levels,\\nsite locations are approximate\\ndue to various issues."); }')
)
)
print(lf)
Now when print.tmap() and save_tmap() are called, they generate a complex HTML page with lots of javascript base64-encoded inside the page.
I want to include some of my javascript snippets (onLoad handlers, AMD modules) that end up as script tags in the <head> or <footer> elements, unlike the onClick handler of the easyButton).
How can I do that without editing the generated file manually after saving? I want to do this from within R.

Related

How can you change the colour of the R background for `exams2moodle` questions?

I'm writing some quizzes for Moodle using R/exams' exams2moodle. The XML file is created fine and I can import the quiz to Moodle ok, however, any question that has R code as part of either the question or the solution has the R code on a dark background making it almost impossible to read. Is there an option somewhere that controls this?
I am using this code to create the XML:
exams2moodle(c("q1.Rmd", "q2b.Rmd", "q3.Rmd", "q4.Rmd", "q5.Rmd", "q6.Rmd"),
name = "GLM_prac1",
iname = FALSE,
converter = "pandoc-mathjax",
cloze = list(cloze_schoice_display = "MULTICHOICE_V"))
And this is an example of the issue:
The color of the R code displayed is not controlled through exams2moodle(), at least not explicitly. What exams2moodle() does, is to put verbatim code input and output into standard HTML tags for this <pre><code> ... </code></pre>. This stands for pre-formatted text with markup for typewriter code. (Actually, this is not even produced by exams2moodle() directly but by pandoc.)
The rendering of these standard HTML tags is then controlled through the CSS styles employed in your Moodle installation. In a vanilla Moodle installation you currently simply get a black font on the same light blueish background as for regular text. In previous versions the background was light gray. Given that you have light orange background for text and dark background for code, I guess that this is a setting in your Moodle installation. Hence I would recommend to reach out to the Moodle team at your university and ask them about this. This seems to be a poor setting that would likely affect others as well.
If you cannot get in touch with the Moodle team or they are unwilling to change their CSS, you can insert your own custom CSS code into your exercises. The advantage is that you have full control over the color then. The disadvantage is that you yourself have to include that style code into every exercise where it is needed. It is not hard but tedious. For example, you can include the following R code chunk in the exercise directly at the beginning of the question section:
Question
========
```{r, echo = FALSE, results = "asis"}
writeLines("<style>
pre {
background: #FFFFFF00
}
</style>")
```
This simply inserts a short HTML snippet with CSS into your Rmd exercise:
<style>
pre {
background: #FFFFFF00
}
</style>
This will instruct the browser to use the background color #FFFFFF00 (fully transparent white) for all <pre>-formatted chunks. Of course, you can also play around with this and use a different color, say #EEEEEE (light gray) or similar.

embedding multiple RunKit REPL instances on a single web page

I am creating a web-based presentation using RemarkJS, my preferred tool for presentations. Since I want to demo small bits of nodejs code, I want to use RunKit's REPL embedding capability. I couldn't quite figure out how to embed multiple instances on a single web page, but I managed to kludge something up by running the following code multiple times
var nb1 = RunKit.createNotebook({
// the parent element for the new notebook
element: document.getElementById("div1"),
// specify the source of the notebook
source: source1
})
var nb2 = RunKit.createNotebook({
// the parent element for the new notebook
element: document.getElementById("div2"),
// specify the source of the notebook
source: source2
})
and so on. This actually works, but is super-inefficient. When I launch my presentation, multiple calls to RunKit are made even though the entire page is loaded only once. Not only that, multiple calls to RunKit are made every time I change the slides, which, in RemarkJS, simple hides and displays different parts of the same, single web page. Since the web page itself is being loaded only once, RunKit should be called only once. At least, that is what I think (obviously, it seems I am wrong).
Finally, the actual RunKit REPL frame takes a while before it is rendered. In the beginning, only a few lines of truncated code shows up, but after a while of waiting, the entire frame gets rendered.
What am I doing wrong? Is there a better way of doing this?
I had the same problem and figured it out. So for future users here is how you do it.
<script src="https://embed.runkit.com"></script>
<style>.embed { overflow: visible; }</style>
<pre class="embed" data-gutter="inside">console.log("hello inside");
1 + 1</pre>
<pre class="embed" data-gutter="outside">console.log("hello outside");
1 + 1</pre>
<pre class="embed" data-gutter="none">console.log("hello none");
1 + 1</pre>
<script>
const elements = [...document.getElementsByClassName('embed')]
const notebooks = elements.reduce((notebooks, element) => {
const innerText = element.firstChild
const currentCell = window.RunKit.createNotebook({
element,
gutterStyle: element.getAttribute("data-gutter"),
source: innerText.textContent,
// Remove the text content of the pre tag after the embed has loaded
onLoad: () => innerText.remove()
})
return notebooks
}, [])
</script>
The sample is taken from here: https://runkit.com/docs/embed
Scroll down and you will find it.

Hide an html element with coffeescript

I would hide an html element when a condition occurs.
I try to implement this code in coffeescript:
if byName == username
document.#prv-btn.style.display = 'none'
I have already tried this code but don't run.
The element #prv-btn is my html element. In my page i have some users and for each of them i have this #prv-btn. For example if i have ten users, i have ten #prv-btn, but only one i want that i see, each user see the button near his name.
How can I do?
There are a couple of issues:
You need to indent the body of if clauses in CoffeeScript.
You need to use getElementById() to actually select the button by its ID.
Also, I recommend using jQuery for DOM work such as this. It works just fine with the compiled CoffeeScript.
Code:
if byName == username
document.getElementById("prv-btn").style.display = 'none'
Here is a link to a jsFiddle that I made for this: http://jsfiddle.net/jonathanporta/tw3nn/1/

getBoundingClientRect() is returning zero in XUL

I have a problem with my firefox extension
I have a XUL popup panel with a hbox for the tag cloud, and a JS code to add divs to this hbox:
<hbox id="tag_base" ondblclick="alert('done')"/>
JS:
var root = document.getElementById('tag_base');
var tag = document.createElement('div');
tag.textContent = 'test';
root.appendChild(tag);
var rect = tag.getBoundingClientRect()
alert(rect.top)
I need to get the dimensions of each added div, however, getBoundingClientRect simply refuses to work.
If I remove alerts, it's always zero.
With alerts the story is different:
The first time the alert is called it returns zero, although the div appears on the screen.
Any subsequent alerts return the correct coordinates.
If I set a breakpoint in Chromebug, everything is reported correctly.
If I do not interupt the execution in any way, and run a loop, only zeroes got returned.
This has got me quite confused.
Calling "boxObject" produces the same results, while "getClientRects[0]" is undefined on the first call.
Any hints on what might be causing this will be greatly appreciated.
Note :
Caution, if you use getBoundingClientRect with an element which has display:none then it will return 0, anywhere in the dom.
Although I can't find any documentation on this seemingly fundamental issue, the problem you noticed is most likely because the layout (aka "reflow") process has not yet run by the moment you ask for the coordinates.
The layout/reflow process takes the page's DOM with any styles the page has and determines the positions and dimensions of the elements and other portions of the page (you could try to read Notes on HTML reflow, although it's not targeted at web developers and probably is a bit outdated).
This reflow process doesn't run synchronously after any change to the DOM, otherwise code like
elt.style.top = "5px";
elt.style.left = "15px";
would update the layout twice, which is inefficient.
On the other hand, asking for elements position/dimension (at least via .offsetTop) is supposed to force layout to return the correct information. This doesn't happen in your case for some reason and I'm not sure why.
Please create a simple testcase demonstrating the problem and file a bug in bugzilla.mozilla.org (CC me - ***********#gmail.com).
My guess is that this is related to XUL layout, which is less robust than HTML; you could try creating the cloud in an HTML doc in an iframe or at least in a <description> using createElementNS to create real HTML elements instead of xul:div you're creating with your current code.
Be sure the DOM is ready. In my case, even when using the getBoundingClientRect function on click events. The binding of the events needed to happen when the DOM is ready.

How do I keep focus on a textbox using Lift (the Scala framework)?

Pardon my excruciatingly simple question, but I'm quite new to the world of Lift (and Scala, for that matter).
I'm following the "Getting Started" tutorial on the Lift website: http://liftweb.net/getting_started
I've got it up and running but I'd like to make a quick modification to the app so that every time I press enter in the textbox, it maintains focus. I've managed to get it to focus on page load using FocusOnLoad but I can't quite figure out how to get it to keep focus (using only Lift's classes, no custom JavaScript).
Here's what my def render method (the bind part) code looks like:
def render =
bind("chat", // the namespace for binding
"line" -> lines _, // bind the function lines
"input" -> FocusOnLoad(SHtml.text("", s => ChatServer ! s)) )
So that works for getting it to focus upon page load. But since this is a Comet app, the page only loads once.
All my other code looks exactly like the tutorial FWIW.
The render method in a CometActor only gets called when the CometActor is first initialized, which happens when the user first goes to the Chat page. Afterwards, the page updates usually happen inside of the lowPriority or highPriority methods. So if you want the text box to become focused after the user sends an AJAX update to the CometActor, you should add it to one of those methods. An example which uses JQuery would be this:
override def lowPriority = {
case m: List[ChatCmd] => {
val delta = m diff msgs
msgs = m
updateDeltas(delta)
partialUpdate((JqJE.Jq(JE.Str("input[type=text]")) ~> (new JsRaw("focus()") with JsMember)).toJsCmd)
}
}
I haven't tried compiling this, so it might need some slight tweaking. Essentially, it's just sending another JavaScript command to the browser that uses JQuery to find a text input on the page and then sets the focus on that control. If there are multiple text inputs, you'll need to modify the class on the HTML template for the control you want to set focus on, then make sure that you change your render method to be:
def render =
bind("chat",
"line" -> lines _,
"input" -%> FocusOnLoad(SHtml.text("", s => ChatServer ! s)) )
The -%> method instructs Lift to not ignore any attributes in the template during the bind phase. Then you can modify the JQuery selector to use that class to find the right control to focus on. Part of the form security in Lift obscures the ID assigned to forms and their controls to prevent XSS attacks, so it's generally better to use class selectors to find form controls using JQuery or some other Javascript framework.