-
Notifications
You must be signed in to change notification settings - Fork 24
/
jsonedit_gadget.R
70 lines (62 loc) · 2.16 KB
/
jsonedit_gadget.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#' Shiny Gadget for 'jsonedit'
#'
#' Provides a \href{http://shiny.rstudio.com/articles/gadgets.html}{Shiny gadget}
#' interface for \code{jsonedit} to interactively edit and return the
#' changes for use in R.
#'
#' @param height,width any valid \code{CSS} size unit for the
#' height and width of the gadget
#' @param ... arguments for \code{\link{jsonedit}}
#'
#' @example ./inst/examples/examples_gadget.R
#' @export
jsonedit_gadget <- function(..., height = NULL, width = NULL) {
# modeled after chemdoodle gadget
# https://github.com/zachcp/chemdoodle/blob/master/R/chemdoodle_sketcher_gadgets.R
if(interactive()) {
if(!requireNamespace("miniUI")) {
userChoice <- readline(prompt = "The package \"miniUI\" is required but not installed. Do you wish to install it? (y/n or ENTER/ESC):")
if(tolower(userChoice) %in% c("y", "", "yes")) {
utils::install.packages("miniUI") #shiny is also installed with miniUI
}
}
}
stopifnot(requireNamespace("miniUI"), requireNamespace("shiny"))
ui <- miniUI::miniPage(
miniUI::miniContentPanel(
jsonedit(
...,
onChange = htmlwidgets::JS('function(after, before, patch) {
Shiny.onInputChange("jsoneditordata", after.json);
}')
),
height=NULL,
width=NULL
),
miniUI::gadgetTitleBar("Edit Data", right = miniUI::miniTitleBarButton("done", "Done", primary = TRUE))
)
server <- function(input, output, session) {
shiny::observeEvent(input$done, { shiny::stopApp(input$jsoneditordata) })
shiny::observeEvent(input$cancel, { shiny::stopApp (NULL) })
}
shiny::runGadget(
ui,
server,
viewer = shiny::dialogViewer("View and Edit Data"),
stopOnCancel = FALSE
)
}
#' jsoneditAddin
#'
#' This uses the gadget as an addin, so you can select objects then
#' activate the addin in RStudio either via menu or a hotkey.
#'
#' @keywords internal
jsoneditAddin <- function(){
# Get the document context.
context <- rstudioapi::getActiveDocumentContext()
# Set the default data to use based on the selection.
text <- context$selection[[1]]$text
obj <- get(text, envir = .GlobalEnv)
jsonedit_gadget(obj)
}