zachcp / chemdoodle

htmlwidgets for chemdoodle web components
http://zachcp.github.io/chemdoodle/
18 stars 9 forks source link

include shiny app as functions #6

Open chapmandu2 opened 8 years ago

chapmandu2 commented 8 years ago

It can be useful wrapping shiny apps in functions that can then be contained within the package in the normal way. Your example below:

cdShinyServer <- function(input, output) {   
    mol <- reactiveValues(moleculedata = NULL)
        observeEvent(input$moleculedata, {
        moljson <- input$moleculedata
        mol$moleculedata <- processChemDoodleJson(moljson)
    })

    output$atomnumber <- renderText({
        if (is.null(mol$moleculedata)){
            return("Choose a Molecule and Click the Button!")
        } else {
            atomcount <- mol$moleculedata$getAtomCount()
            return(paste("This Molecule has",atomcount, "atoms."))
        }
    })
}

cdShinyUI <- function() {
    miniUI::miniPage(
        mainPanel(h1(textOutput("atomnumber"))),
        miniUI::miniContentPanel(chemdoodle_sketcher(mol=NULL)),
        miniUI::gadgetTitleBar("Draw A Molecule", right = miniUI::miniTitleBarButton("done", "Done", primary = TRUE)),

        tags$script('
                    document.getElementById("done").onclick = function() {
                    var mol = sketcher.getMolecule();
                    var jsonmol = new ChemDoodle.io.JSONInterpreter().molTo(mol);
                    Shiny.onInputChange("moleculedata", jsonmol);};'
        ))
}

cdShinyApp <- function() {

    shiny::shinyApp(
        ui = cdShinyUI(),
        server = function(input, output) {
            cdShinyServer(input, output)
        }
    )
}

Can then run as follows: cdShinyApp()