Title: | Interactive Sketches |
---|---|
Description: | Creates static / animated / interactive visualisations embeddable in R Markdown documents. It implements an R-to-JavaScript transpiler and enables users to write JavaScript applications using the syntax of R. |
Authors: | Chun Fung Kwok [aut, cre] , Kate Saunders [ctb] |
Maintainer: | Chun Fung Kwok <[email protected]> |
License: | Apache License (>= 2.0) |
Version: | 1.1.20.3 |
Built: | 2024-11-13 04:28:31 UTC |
Source: | https://github.com/kcf-jackson/sketch |
Creates interactive visualisation embeddable in R Markdown documents. It implements an R-to-JavaScript transpiler and enables users to write JavaScript applications using the syntax of R.
Parse and annotate expressions with lines and columns tracking.
annotate_exprs(x)
annotate_exprs(x)
x |
A character string; the input to parse. |
Take a 'sketch' R file as input, extract and process the resources links as provided by the user with the '#!'/'#|' header.
assets(file, ..., trace = FALSE)
assets(file, ..., trace = FALSE)
file |
Character string; the file path. |
... |
(Optional) List of processors to pass to convert_src. |
trace |
TRUE or FALSE; if TRUE, assets are extracted, but not processed. |
file <- system.file("test_files/test_RMD.R", package = "sketch") assets(file, trace = TRUE) assets(file, trace = FALSE)
file <- system.file("test_files/test_RMD.R", package = "sketch") assets(file, trace = TRUE) assets(file, trace = FALSE)
A minimal list of deparsers for deparsing JavaScript
basic_deparsers()
basic_deparsers()
This is used as input to deparse_js, compile_r and compile_exprs.
basic_deparsers()
basic_deparsers()
Bundle a list of files into a single JavaScript file
bundle(fs)
bundle(fs)
fs |
A character vector; a list of R or JavaScript files. The R files will be transpiled to JavaScript before bundling. |
library(sketch) js <- bundle(c(src("dom"), src("io"))) cat(paste(readLines(js), collapse = "\n"))
library(sketch) js <- bundle(c(src("dom"), src("io"))) cat(paste(readLines(js), collapse = "\n"))
This function turns an n-pass transpilation into k-pass, where n is the number of rules and k is the number of precedence groups.
combine_rules(rs, group = rep(1, length(rs)))
combine_rules(rs, group = rep(1, length(rs)))
rs |
A list of rewriting rules (each of which is an output from make_rule). |
group |
A numeric vector; the precedence group. Rules with a higher precedence come before the the ones with lower precedence, and they are processed by the transpiler first. For rules with the same precedence, the natural order (in which they show up) determines which rules get processed first. |
The key insight about optimising the transpilation is that rewriting passes that do not interfere with each other can be combined, and it saves a full traversal of the parse tree.
Compile active file in 'RStudio'
compile_active(...)
compile_active(...)
... |
Optional arguments to pass to |
## Not run: # At 'RStudio', opens a 'sketch' R file in the editor, then # run the following: compile_active() ## End(Not run)
## Not run: # At 'RStudio', opens a 'sketch' R file in the editor, then # run the following: compile_active() ## End(Not run)
Compile a data file into a JavaScript file
compile_data(input, output = tempfile(), ...)
compile_data(input, output = tempfile(), ...)
input |
A character string; the path to the input file. |
output |
A character string; the path to the output file. |
... |
Extra arguments to be passed to to_json. |
file <- system.file("test_files/test_csv.csv", package = "sketch") readLines(compile_data(file))
file <- system.file("test_files/test_csv.csv", package = "sketch") readLines(compile_data(file))
Compile R code into JavaScript code
compile_exprs(x, rules = default_rules(), deparsers = default_deparsers())
compile_exprs(x, rules = default_rules(), deparsers = default_deparsers())
x |
A character string; the expression to transpile to JS. |
rules |
A list of rewriting rules. See make_rule for more detail. |
deparsers |
A list of deparsers. See make_deparser for more detail. |
A character string.
compile_exprs("R + Cpp", list(make_rule('Cpp', 'JS'))) compile_exprs("math.add(a, b)", list(make_rule('math.add', '+')))
compile_exprs("R + Cpp", list(make_rule('Cpp', 'JS'))) compile_exprs("math.add(a, b)", list(make_rule('math.add', '+')))
Compile an R file into a JavaScript file
compile_r( input, output = "", rules = default_rules(), deparsers = default_deparsers() )
compile_r( input, output = "", rules = default_rules(), deparsers = default_deparsers() )
input |
A character string; the input file. |
output |
A character string; the output file. When the output is "", the result is printed to the standard output. |
rules |
A list of rewriting rules. See make_rule for more detail. |
deparsers |
A list of deparsers. See make_deparser for more detail. |
A character string; the output file path.
file <- system.file("test_files/test_source.R", package = "sketch") readLines(file) compile_r(input = file)
file <- system.file("test_files/test_source.R", package = "sketch") readLines(file) compile_r(input = file)
Convert an asset link into a 'shiny.tag' object
convert_src(x, processors = default_processors())
convert_src(x, processors = default_processors())
x |
A character string; the header line (without the prefix '#!'/'#|'). |
processors |
A list of handlers for processing the '#!'/'#|' header. |
A 'shiny.tag' object.
Support automatic variable declaration, automatic 'return' and shorthand notation for the DOM module.
default_2_deparsers()
default_2_deparsers()
lifecycle: experimental
This is used as input to compile_r and compile_exprs.
default_2_deparsers()
default_2_deparsers()
A list of default deparsers for deparsing JavaScript
default_deparsers()
default_deparsers()
This is used as input to compile_r and compile_exprs.
default_deparsers()
default_deparsers()
A list of handlers for processing the '#!'/'#|' header
default_processors()
default_processors()
This is used as input to assets.
default_processors()
default_processors()
Deparsers (specialised)
Deparser for NULL
Deparser for NA
Deparser for NaN
Deparser for calls
Deparser for infix operators
Deparser for brackets
Deparser for the 'for' keyword
Deparser for the 'if' keyword
Deparser for the 'while' keyword
Deparser for the "function" keyword
Deparser for the "function" keyword with explicit return
Deparser for return
Deparser for assignments
Deparser for assignments (automatic variable declaration)
Deparser for the "next" keyword
Deparser for the "try" keyword
Deparser for the "tryCatch" keyword
Deparser for the "throw" keyword
Deparser for the "list" operator
Deparser for the "data.frame" operators
Deparser for the "summarise" operators
Deparser for the "mutate" operators
Deparser for the "R6Class" function
Deparser for the "new" operator
Deparser for the "typeof" operator
Deparser for the "export" operator
Deparser for the ""async" and "await" operators
Deparser for the "let" operator
Deparser for the "const" operator
Deparser for the "var" operator
Deparser for the "dataURI" operator
Deparser for the "ifelse" operator
Deparser for the "lambda" operator
Deparser for the "pipe" operator
Deparser for the "assignment pipe" operator
Deparser for the raw string operator
Deparser for formula
Deparser for the "add" operator
Deparser for the "subtract" operator
Deparser for the "extract" operator
Deparser for the "extractAssign" operator
Deparser for the "extract2" operator
Deparser for the "extract2Assign" operator
Deparser for the HTML tags
Deparser for the d3.js 'attr' function
Deparser for the d3.js 'style' function
Deparser for '.macro'
Deparser for '.data'
deparse_sym(ast, ...) deparse_NULL(ast, ...) deparse_NA(ast, ...) deparse_NaN(ast, ...) deparse_call(ast, ...) deparse_infix(ast, ...) deparse_wrap(ast, ...) deparse_for(ast, ...) deparse_if(ast, ...) deparse_while(ast, ...) deparse_function(ast, ...) deparse_function_with_return(ast, ...) deparse_return(ast, ...) deparse_assignment(ast, ...) deparse_assignment_auto(ast, ...) deparse_next(ast, ...) deparse_try(ast, ...) deparse_tryCatch(ast, ...) deparse_throw(ast, ...) deparse_list(ast, ...) deparse_df(ast, ...) deparse_df_summarise(ast, ...) deparse_df_mutate(ast, ...) deparse_R6Class(ast, ...) deparse_new(ast, ...) deparse_typeof(ast, ...) deparse_export(ast, ...) deparse_async_await(ast, ...) deparse_let(ast, ...) deparse_const(ast, ...) deparse_var(ast, ...) deparse_dataURI(ast, ...) deparse_ifelse(ast, ...) deparse_lambda(ast, ...) deparse_pipe(ast, ...) deparse_assignment_pipe(ast, ...) deparse_raw_string(ast, ...) deparse_formula(ast, ...) deparse_add(ast, ...) deparse_subtract(ast, ...) deparse_extract(ast, ...) deparse_extractAssign(ast, ...) deparse_extract2(ast, ...) deparse_extract2Assign(ast, ...) deparse_html_tags(ast, ...) deparse_d3_attr(ast, ...) deparse_d3_style(ast, ...) deparse_macro(ast, ...) deparse_data(ast, ...)
deparse_sym(ast, ...) deparse_NULL(ast, ...) deparse_NA(ast, ...) deparse_NaN(ast, ...) deparse_call(ast, ...) deparse_infix(ast, ...) deparse_wrap(ast, ...) deparse_for(ast, ...) deparse_if(ast, ...) deparse_while(ast, ...) deparse_function(ast, ...) deparse_function_with_return(ast, ...) deparse_return(ast, ...) deparse_assignment(ast, ...) deparse_assignment_auto(ast, ...) deparse_next(ast, ...) deparse_try(ast, ...) deparse_tryCatch(ast, ...) deparse_throw(ast, ...) deparse_list(ast, ...) deparse_df(ast, ...) deparse_df_summarise(ast, ...) deparse_df_mutate(ast, ...) deparse_R6Class(ast, ...) deparse_new(ast, ...) deparse_typeof(ast, ...) deparse_export(ast, ...) deparse_async_await(ast, ...) deparse_let(ast, ...) deparse_const(ast, ...) deparse_var(ast, ...) deparse_dataURI(ast, ...) deparse_ifelse(ast, ...) deparse_lambda(ast, ...) deparse_pipe(ast, ...) deparse_assignment_pipe(ast, ...) deparse_raw_string(ast, ...) deparse_formula(ast, ...) deparse_add(ast, ...) deparse_subtract(ast, ...) deparse_extract(ast, ...) deparse_extractAssign(ast, ...) deparse_extract2(ast, ...) deparse_extract2Assign(ast, ...) deparse_html_tags(ast, ...) deparse_d3_attr(ast, ...) deparse_d3_style(ast, ...) deparse_macro(ast, ...) deparse_data(ast, ...)
ast |
A language object. |
... |
The contextual information to be passed on to the next call. |
A character string.
At the moment, the '.macro' / 'deparse_macro' function must be used with the 'compile_exprs' call. This is currently an experimental feature.
At the moment, the '.data' / 'deparse_data' function must be used with the 'compile_exprs' call. This is currently an experimental feature.
This is the "master" deparser that dispatches the "worker" deparsers based on the type of the input.
deparse_js(ast, deparsers)
deparse_js(ast, deparsers)
ast |
language object. |
deparsers |
A list of "typed" deparsers. |
A character string.
expr_1 <- parse_expr("R.extract(x, 3, )") deparse_js(expr_1, basic_deparsers()) deparse_js(expr_1, default_deparsers()) expr_2 <- parse_expr("R.data_frame(x = 1, y = 2)") deparse_js(expr_2, basic_deparsers()) deparse_js(expr_2, default_deparsers()) expr_3 <- parse_expr("lambda(x, x + 1)") deparse_js(expr_3, basic_deparsers())
expr_1 <- parse_expr("R.extract(x, 3, )") deparse_js(expr_1, basic_deparsers()) deparse_js(expr_1, default_deparsers()) expr_2 <- parse_expr("R.data_frame(x = 1, y = 2)") deparse_js(expr_2, basic_deparsers()) deparse_js(expr_2, default_deparsers()) expr_3 <- parse_expr("lambda(x, x + 1)") deparse_js(expr_3, basic_deparsers())
Deparse a compiled AST
deparse_js_ast(ast)
deparse_js_ast(ast)
ast |
The compiled AST. The JavaScript AST compiled from the R AST. |
A character string. The compiled string.
This feature is experimental.
Constructor function to combine low-level deparsers
dp(...)
dp(...)
... |
character strings indicating the features needed of the deparsers. The supported features are "basic", "r", "auto" and "dom" corresponding to the basic deparsers, the R support, the automatic variable declaration and return, and the dom shorthand notation. |
lifecycle: experimental
This supports the use of 'sketch' code chunk in an R Markdown document.
eng_sketch(options)
eng_sketch(options)
options |
A list of chunk options. |
# The following line makes `sketch::eng_sketch` available to `knitr::knit_engines`. # It is usually used in the 'setup' code chunk of an R Markdown document knitr::knit_engines$set(sketch = sketch::eng_sketch)
# The following line makes `sketch::eng_sketch` available to `knitr::knit_engines`. # It is usually used in the 'setup' code chunk of an R Markdown document knitr::knit_engines$set(sketch = sketch::eng_sketch)
Flatten a list of files and directories into a list of files
flatten_filelist(fs, pattern = NULL, ...)
flatten_filelist(fs, pattern = NULL, ...)
fs |
A character vector; a list of files. |
pattern |
An optional regular expression to pass to 'list.files' for filtering files while expanding a directory into a list of files. |
... |
Additional parameters to pass to 'list.files'. |
modules_dir <- system.file("modules", package = "sketch") flatten_filelist(modules_dir)
modules_dir <- system.file("modules", package = "sketch") flatten_filelist(modules_dir)
Extract the content of the 'load_script' headers of a sketch R file
get_dependencies(app_script, local_only = TRUE)
get_dependencies(app_script, local_only = TRUE)
app_script |
A character string; the path to the sketch R file. |
local_only |
TRUE / FALSE; if TRUE, exclude the ones that are web link. |
sample_file <- system.file("test_files/test_sketch.R", package = "sketch") cat(readLines(sample_file), sep = "\n") # Preview the file content get_dependencies(sample_file)
sample_file <- system.file("test_files/test_sketch.R", package = "sketch") cat(readLines(sample_file), sep = "\n") # Preview the file content get_dependencies(sample_file)
A list of 'shiny.tag' objects describing a HTML template. The
list must have signature / structure of a named list:
[head = [shiny.tag], body = [shiny.tag]]
default_tags(local = TRUE) basic_tags()
default_tags(local = TRUE) basic_tags()
local |
TRUE / FALSE. If TRUE, the R base module is loaded from the local file stored in the package, otherwise, the module is served via a content delivery network (CDN). |
str(default_tags()) str(basic_tags())
str(default_tags()) str(basic_tags())
Insert a 'sketch' app into an R Markdown document
insert_sketch(file, id, output_dir = NULL, render = TRUE, ...)
insert_sketch(file, id, output_dir = NULL, render = TRUE, ...)
file |
A character string; the path to the 'sketch' file. |
id |
A character string; an unique identifier for the 'sketch' file.
Needed only when |
output_dir |
A character string; a separate directory to save the 'sketch' app. Default to be NULL, which embeds the app in the Rmd file. |
render |
TRUE or FALSE; if TRUE, call doRenderTags; if FALSE, return the 'shiny.tag' object. |
... |
(Optional) Other attributes to pass to iframes. Also supports the 'rules', 'deparsers' and 'debug' options to pass to 'source_r'. |
An HTML string if render
is TRUE, or a 'shiny.tag' object
if render
is FALSE.
# In an R code chunk of an R Markdown document file <- system.file("test_files/test_RMD.R", package = "sketch") insert_sketch(file, style = "width:500px; height:500px;", render = FALSE)
# In an R code chunk of an R Markdown document file <- system.file("test_files/test_RMD.R", package = "sketch") insert_sketch(file, style = "width:500px; height:500px;", render = FALSE)
Predicate for calls
is_call(x, name = NULL, n = NULL, ns = NULL)
is_call(x, name = NULL, n = NULL, ns = NULL)
x |
An object to test. Formulas and quosures are treated literally. |
name |
An optional name that the call should match. It is
passed to |
n |
An optional number of arguments that the call should match. |
ns |
The namespace of the call. If Can be a character vector of namespaces, in which case the call
has to match at least one of them, otherwise |
This function is imported from 'rlang'.
Predicate for symbols, i.e. symbols or syntactic literals
Predicate for infix operators
Predicate for brackets
Predicate for the 'for' keyword
Predicate for the 'if' keyword
Predicate for the 'while' keyword
Predicate for the "function" keyword
Predicate for return
Predicate for assignments
Predicate for assignments
Predicate for the "break" keyword
Predicate for the "next" keyword
Predicate for the "try" keyword
Predicate for the "tryCatch" keyword
Predicate for the "throw" keyword
Predicate for the "list" operator
Predicate for the "data.frame" operators
Predicate for the "summarise" operators
Predicate for the "mutate" operators
Predicate for the "R6Class" function
Predicate for the "new" operator
Predicate for the "typeof" operator
Predicate for the "export" operator
Predicate for the "async" and "await" operators
Predicate for the "let" operator
Predicate for the "const" operator
Predicate for the "var" operator
Predicate for the "dataURI" operator
Predicate for the "ifelse" operator
Predicate for the "lambda" operator
Predicate for the "pipe" operator
Predicate for the "assignment pipe" operator
Predicate for the raw string operator
Predicate for formula
Predicate for the "add" operator
Predicate for the "subtract" operator
Predicate for the "extract" operator
Predicate for the "extractAssign" operator
Predicate for the "extract2" operator
Predicate for the "extract2Assign" operator
Predicate for the HTML tags
Predicate for the d3.js 'attr' function
Predicate for the d3.js 'style' function
Predicate for '.macro'
Predicate for '.data'
is_sym(ast) is_infix(ast) is_wrap(ast) is_call_for(ast) is_call_if(ast) is_call_while(ast) is_call_function(ast) is_call_return(ast) is_call_assignment(ast) is_call_assignment_auto(ast) is_call_break(ast) is_call_next(ast) is_call_try(ast) is_call_tryCatch(ast) is_call_throw(ast) is_call_list(ast) is_call_df(ast) is_call_df_summarise(ast) is_call_df_mutate(ast) is_call_R6Class(ast) is_call_new(ast) is_call_typeof(ast) is_call_export(ast) is_call_async_await(ast) is_call_let(ast) is_call_const(ast) is_call_var(ast) is_call_dataURI(ast) is_call_ifelse(ast) is_call_lambda(ast) is_call_pipe(ast) is_call_assignment_pipe(ast) is_call_raw_string(ast) is_call_formula(ast) is_call_add(ast) is_call_subtract(ast) is_call_extract(ast) is_call_extractAssign(ast) is_call_extract2(ast) is_call_extract2Assign(ast) is_html_tags(ast) is_d3_attr(ast) is_d3_style(ast) is_macro(ast) is_data(ast)
is_sym(ast) is_infix(ast) is_wrap(ast) is_call_for(ast) is_call_if(ast) is_call_while(ast) is_call_function(ast) is_call_return(ast) is_call_assignment(ast) is_call_assignment_auto(ast) is_call_break(ast) is_call_next(ast) is_call_try(ast) is_call_tryCatch(ast) is_call_throw(ast) is_call_list(ast) is_call_df(ast) is_call_df_summarise(ast) is_call_df_mutate(ast) is_call_R6Class(ast) is_call_new(ast) is_call_typeof(ast) is_call_export(ast) is_call_async_await(ast) is_call_let(ast) is_call_const(ast) is_call_var(ast) is_call_dataURI(ast) is_call_ifelse(ast) is_call_lambda(ast) is_call_pipe(ast) is_call_assignment_pipe(ast) is_call_raw_string(ast) is_call_formula(ast) is_call_add(ast) is_call_subtract(ast) is_call_extract(ast) is_call_extractAssign(ast) is_call_extract2(ast) is_call_extract2Assign(ast) is_html_tags(ast) is_d3_attr(ast) is_d3_style(ast) is_macro(ast) is_data(ast)
ast |
A language object. |
Predicate for syntactic literal
is_syntactic_literal(x)
is_syntactic_literal(x)
x |
An object to test. |
This function is imported from 'rlang'.
These functions do nothing. It is created to ensure the keywords 'let' and 'declare' are defined.
let(...) declare(...) const(...)
let(...) declare(...) const(...)
... |
Any arguments |
let (x) let (x = 1, y = 2) declare (x1, x2, x3)
let (x) let (x = 1, y = 2) declare (x1, x2, x3)
License information
license_info(x)
license_info(x)
x |
A character string; name of the library / assets. |
A named list containing the license information and the link from which the information is extracted.
license_info("mathjs") license_info("p5")
license_info("mathjs") license_info("p5")
Support of R functionalities
dp_r_support() dp_auto() dp_dom() dp_d3() dp_macro()
dp_r_support() dp_auto() dp_dom() dp_d3() dp_macro()
Header functions
load_library(package, ...) load_script(src, ...) load_data(x, cache = tempfile(), ...)
load_library(package, ...) load_script(src, ...) load_data(x, cache = tempfile(), ...)
package |
A character string; name of a JavaScript library. |
... |
Additional arguments to pass to header processor. |
src |
A character string; the full web/local path to a JavaScript library. |
x |
A character string; the full path to the file containing the data. |
cache |
A character string; the full path to the cache file. |
A helper function to enable debugger option
local(x, from_local = TRUE)
local(x, from_local = TRUE)
x |
TRUE / FALSE; whether to attach a debugging console to the sketch application. |
from_local |
TRUE / FALSE; whether to load the debugger console from the local package. If FALSE, the console will be loaded from a Content Delivery Network (CDN) link. |
Use 'from_local=TRUE' for self-contained applications, and 'from_local=FALSE' for reduced file size.
# This function is designed to be used in the configuration header, e.g. # config(debug = local(TRUE), rules = basic_rules(), deparsers = basic_deparsers()) local(TRUE)
# This function is designed to be used in the configuration header, e.g. # config(debug = local(TRUE), rules = basic_rules(), deparsers = basic_deparsers()) local(TRUE)
A constructor for a "typed" deparser
make_deparser(predicate_fun, deparse_fun)
make_deparser(predicate_fun, deparse_fun)
predicate_fun |
A function that takes a "lang" object and return a logical. |
deparse_fun |
A function that takes a "lang" object and return a character string. |
A list; a deparser ready to be dispatched by "type".
str(make_deparser(predicate_fun = rlang::is_call, deparse_fun = deparse))
str(make_deparser(predicate_fun = rlang::is_call, deparse_fun = deparse))
Make a handle to process header
make_processor(pred, fun)
make_processor(pred, fun)
pred |
A function, taking a string and returning a logical. |
fun |
A function, taking a string and returning a 'shiny.tag' object. |
A header processor / handler.
Make a AST transformation rule
make_rule(from, to)
make_rule(from, to)
from |
A character string. |
to |
A character string. |
A function that takes a language object and returns a language object.
library(sketch) rule_1 <- make_rule("pi", "Math.PI") expr <- rlang::parse_expr("2 * (3 + pi)") rule_1(expr) # this works but is not the preferred usage rewrite(expr, list(rule_1)) # this is preferred rule_2 <- make_rule("+", "Math.add") rewrite(expr, list(rule_1, rule_2))
library(sketch) rule_1 <- make_rule("pi", "Math.PI") expr <- rlang::parse_expr("2 * (3 + pi)") rule_1(expr) # this works but is not the preferred usage rewrite(expr, list(rule_1)) # this is preferred rule_2 <- make_rule("+", "Math.add") rewrite(expr, list(rule_1, rule_2))
Parse R code
parse_expr(x)
parse_expr(x)
x |
Text containing expressions to parse_expr for
|
This function is imported from 'rlang'.
parse_expr("x <- 1 + 1")
parse_expr("x <- 1 + 1")
Print function for 'sketch_rule' objects
## S3 method for class 'sketch_rule' print(x, ...)
## S3 method for class 'sketch_rule' print(x, ...)
x |
A 'sketch_rule' object. |
... |
(Unused) Optional arguments. |
library(sketch) rule_1 <- make_rule("+", "Math.add") print(rule_1)
library(sketch) rule_1 <- make_rule("+", "Math.add") print(rule_1)
Mapping R operators into JavaScript operators
basic_rules() default_rules()
basic_rules() default_rules()
These functions are used as inputs to compile_r and compile_exprs.
R operators: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Operators
R infix and prefix operators: https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Infix-and-prefix-operators
JavaScript operators: https://www.w3schools.com/js/js_operators.asp
basic_rules() default_rules()
basic_rules() default_rules()
read_multilines
reads one or more lines from
the terminal (in interactive use).
read_multilines(prompt = "")
read_multilines(prompt = "")
prompt |
the string printed when prompting the user for input.
Should usually end with a space |
This function repeatedly calls readline
until enough inputs
are provided to reach a successful parse.
This can only be used in an interactive session.
## Not run: # In an interactive session read_multilines() 1 + 2 # expect immediate success read_multilines() 1 + 2 + 3 # expect success here ## End(Not run)
## Not run: # In an interactive session read_multilines() 1 + 2 # expect immediate success read_multilines() 1 + 2 + 3 # expect success here ## End(Not run)
Interface for AST rewriting
rewrite(ast, rules)
rewrite(ast, rules)
ast |
A language object. |
rules |
A list of functions, each of which is the output from 'make_rule'. |
A language object.
library(sketch) rewrite( ast = rlang::parse_expr("2 * (3 + pi)"), rules = list(make_rule("pi", "Math.PI")) ) rewrite( ast = rlang::parse_expr("2 + pi"), rules = list( make_rule("pi", "Math.PI"), make_rule("+", "Math.add") ) )
library(sketch) rewrite( ast = rlang::parse_expr("2 * (3 + pi)"), rules = list(make_rule("pi", "Math.PI")) ) rewrite( ast = rlang::parse_expr("2 + pi"), rules = list( make_rule("pi", "Math.PI"), make_rule("+", "Math.add") ) )
Run 'Shiny' Application
runShinyApp()
runShinyApp()
## Not run: runShinyApp() ## End(Not run)
## Not run: runShinyApp() ## End(Not run)
Perform pre-transpilation check
safeguard(ast, rules, deparsers)
safeguard(ast, rules, deparsers)
ast |
A language object. |
rules |
A list of functions; the rewriting rules, each of which is the output from make_rule. |
deparsers |
A list of functions; the deparsers, each of which is the output from make_deparser. |
TRUE when the check is complete.
# Expect no warning safeguard(parse_expr("a <- 3"), rules = default_rules(), deparsers = default_deparsers()) # Expect a warning (as `max` is reserved to be a function by the transpiler) safeguard(parse_expr("max <- 3"), rules = default_rules(), deparsers = default_deparsers())
# Expect no warning safeguard(parse_expr("a <- 3"), rules = default_rules(), deparsers = default_deparsers()) # Expect a warning (as `max` is reserved to be a function by the transpiler) safeguard(parse_expr("max <- 3"), rules = default_rules(), deparsers = default_deparsers())
Source active file in 'RStudio'
source_active(...)
source_active(...)
... |
Optional arguments to pass to |
## Not run: # At 'RStudio', opens a 'sketch' R file in the editor, then # run the following: source_active() # This launches the default HTML viewer. ## End(Not run)
## Not run: # At 'RStudio', opens a 'sketch' R file in the editor, then # run the following: source_active() # This launches the default HTML viewer. ## End(Not run)
Serve a compiled 'sketch' JavaScript file
source_js(file, debug = FALSE, asset_tags = default_tags(), launch_browser)
source_js(file, debug = FALSE, asset_tags = default_tags(), launch_browser)
file |
A character string; path to the compiled JS file. |
debug |
TRUE or FALSE; if TRUE, a console for debugging is attached to your app. |
asset_tags |
An optional list of 'shiny.tag' objects to be added to the html
template. The list must have signature / structure of a named list:
|
launch_browser |
A character string; "viewer" or "browser", which calls 'rstudioapi::viewer' and 'utils::browseURL' respectively; use NULL to suppress display. |
## Not run: file <- system.file("test_files/test_source.js", package = "sketch") # The next line launches the default HTML browser source_js(file, debug = TRUE, launch_browser = "browser") ## End(Not run)
## Not run: file <- system.file("test_files/test_source.js", package = "sketch") # The next line launches the default HTML browser source_js(file, debug = TRUE, launch_browser = "browser") ## End(Not run)
Convert a compiled AST into a source map
source_map(ast)
source_map(ast)
ast |
The compiled AST. The JavaScript AST compiled from the R AST. |
A (list of) source map.
This feature is experimental.
Create a source map (.map) file
source_map_from_files(source_file, target_file, ...)
source_map_from_files(source_file, target_file, ...)
source_file |
A character string; the input R file. |
target_file |
A character string; the corresponding JavaScript file. |
... |
Additional arguments to pass to 'rewrite_annotated_exprs'. |
This feature is experimental.
Display the source map in a table
source_map_table(x)
source_map_table(x)
x |
A source map. The output from 'source_map'. |
A data frame.
This feature is experimental.
This function compiles a 'sketch' R file, resolves the dependencies and serves it in the viewer.
source_r(file, debug = FALSE, launch_browser, asset_tags = default_tags(), ...)
source_r(file, debug = FALSE, launch_browser, asset_tags = default_tags(), ...)
file |
A character string; path to the R file. |
debug |
TRUE or FALSE; if TRUE, a console for debugging is attached to your app. |
launch_browser |
A character string; "viewer" or "browser", which calls 'rstudioapi::viewer' and 'utils::browseURL' respectively; use NULL to suppress display. |
asset_tags |
An optional list of 'shiny.tag' objects to be added to the html
template. The list must have signature / structure of a named list:
|
... |
Additional arguments to pass to 'compile_r'. |
## Not run: file <- system.file("test_files/test_source.R", package = "sketch") # The next line launches the default HTML browser source_r(file, debug = TRUE, launch_browser = "browser") ## End(Not run)
## Not run: file <- system.file("test_files/test_source.R", package = "sketch") # The next line launches the default HTML browser source_r(file, debug = TRUE, launch_browser = "browser") ## End(Not run)
This function is the left-inverse of 'combine_rules', i.e.
split_rules(combine_rules(rs, group)) = rs
for any variable 'group'.
It is created to facilitate the addition or removal of rewriting rules.
split_rules(rs)
split_rules(rs)
rs |
A list of (grouped) rewriting rules. Note that a list of n rules without grouping is a list of n groups of single rule. |
Get the source link of a JavaScript library
src(x)
src(x)
x |
A character string; name of the JavaScript library |
A character string; the path to the library.
src("mathjs") src("p5")
src("mathjs") src("p5")
Test a sketch application
test_sketch(app_script, test_script, port = 9454, ...)
test_sketch(app_script, test_script, port = 9454, ...)
app_script |
A character string; the file path to the app. |
test_script |
A character string; the file path to the tests. |
port |
An integer to pass to 'websocket$new()'. |
... |
Additional arguments to pass to source_r. |
A "websocket" object.
## Not run: app_file <- system.file("test_files/test_testthat_app.R", package = "sketch") test_file <- system.file("test_files/test_testthat_test.R", package = "sketch") # This following command will launch the default browser res <- test_sketch(app_file, test_file) ## End(Not run)
## Not run: app_file <- system.file("test_files/test_testthat_app.R", package = "sketch") test_file <- system.file("test_files/test_testthat_test.R", package = "sketch") # This following command will launch the default browser res <- test_sketch(app_file, test_file) ## End(Not run)
It supports csv and json by default and lets users provide custom handlers if other file formats are used.
to_json(input, as_data_frame, read_fun, ...)
to_json(input, as_data_frame, read_fun, ...)
input |
A character string; the path to the input file. |
as_data_frame |
TRUE or FALSE; whether the data are loaded as a data-frame. |
read_fun |
A function to load the input file. Default settings are provided for CSV files and JSON files. The function has to load a data file into an object that can be handled by 'jsonlite::toJSON'. Possible choices include 'utils::read_delim', 'readr::read_csv2', etc. |
... |
Extra arguments to be passed to 'read_fun'. |
Verify a source map
verify_source_map(ast, src_map)
verify_source_map(ast, src_map)
ast |
The compiled AST. The JavaScript AST compiled from the R AST. |
src_map |
The source map. The output from 'source_map'. |
A data frame; a source map table expanded by the 'pass_test' column.
This feature is experimental.
This combines the *-Server family of functions in 'httpuv' with the transpilation functionality provided by 'sketch'.
app
A list of functions that define the application.
server
A server handle to be used by 'stopServer'.
log
A character vector that keep tracks of all the commands sent to the browser session.
ws
A WebSocket channel to handle the communication between the R session and the browser session.
in_handler
A function to handle instructions sent by the browser session.
out_handler
A function to handle instruction sent to the browser session.
env
An environment to store variables temporarily.
port
An integer; the TCP port number.
message
TRUE or FALSE; whether to display a prompt when a server is started and when it is stopped.
connected
TRUE or FALSE; whether a connection has been established. One should ways start the WebSocket server before visiting the web page that connects to the server.
started
TRUE or FALSE; whether a server has been started. Use
the startServer
method to start a server.
startServer()
Start a WebSocket server
websocket$startServer()
stopServer()
Stop a WebSocket server
websocket$stopServer()
listServers()
List all running WebSocket servers
websocket$listServers()
stopAllServers()
Stop all running WebSocket servers
websocket$stopAllServers()
sketch_mode()
Enter sketch mode, in which all commands go through the transpiler before reaching the browser session.
websocket$sketch_mode()
new_app()
Create a blank HTML page with interactive access. This function is designed for newcomers.
websocket$new_app( preamble = list(library = c(), script = c(), data = c()), ... )
preamble
(Optional) A named list; the preamble to include.
Use the name 'lib' for arguments to load_library
, 'script'
for arguments to load_script
and 'data' for arguments to
load_data
. Note that the "dom" and "websocket" modules are
required and loaded by default.
...
Extra parameters to pass to source_r.
The (invisible) temporary file path to the app.
new()
Initialise a WebSocket connection
websocket$new(in_handler, out_handler, message = TRUE, port = 9454)
in_handler
A function to handle incoming message, default to be print which only displays the message without any processing.
out_handler
A function to handle outgoing message, default to be compile_exprs which transpiles R commands into JavaScript commands.
message
TRUE or FALSE; whether to display a prompt when a server is started and when it is stopped.
port
An integer; the TCP port number.
A 'websocket' object.
\dontrun{ # Launch a WebSocket server ws <- websocket$new() ws$startServer() ws$listServers() # Check that a server is running # Launch a 'sketch' application with WebSocket functionality file <- system.file("test_files/test_websocket.R", package = "sketch") source_r(file, debug = TRUE) # Launch the default browser # Enter sketch mode to send commands to the application ws$sketch_mode() # Within sketch mode print("1234") x <- 10 print(x + 1) q() # Back to normal mode, inspect the log and stop the server ws$log ws$stopServer() ws$listServers() # Confirm no server is running }
clone()
The objects of this class are cloneable with this method.
websocket$clone(deep = FALSE)
deep
Whether to make a deep clone.
## ------------------------------------------------ ## Method `websocket$new` ## ------------------------------------------------ ## Not run: # Launch a WebSocket server ws <- websocket$new() ws$startServer() ws$listServers() # Check that a server is running # Launch a 'sketch' application with WebSocket functionality file <- system.file("test_files/test_websocket.R", package = "sketch") source_r(file, debug = TRUE) # Launch the default browser # Enter sketch mode to send commands to the application ws$sketch_mode() # Within sketch mode print("1234") x <- 10 print(x + 1) q() # Back to normal mode, inspect the log and stop the server ws$log ws$stopServer() ws$listServers() # Confirm no server is running ## End(Not run)
## ------------------------------------------------ ## Method `websocket$new` ## ------------------------------------------------ ## Not run: # Launch a WebSocket server ws <- websocket$new() ws$startServer() ws$listServers() # Check that a server is running # Launch a 'sketch' application with WebSocket functionality file <- system.file("test_files/test_websocket.R", package = "sketch") source_r(file, debug = TRUE) # Launch the default browser # Enter sketch mode to send commands to the application ws$sketch_mode() # Within sketch mode print("1234") x <- 10 print(x + 1) q() # Back to normal mode, inspect the log and stop the server ws$log ws$stopServer() ws$listServers() # Confirm no server is running ## End(Not run)