rstudioapi::viewer 程序化删除选项

rstudioapi::viewer programmatic deletion option

rstudioapi::viewer 可以从临时目录呈现静态 html 页面,如下例所示。

dir <- tempfile()
dir.create(dir)
htmlFile <- file.path(dir, "index.html")
writeLines(
  '<h1 style="text-align: center;">Thank you for using <span style="color: #ff0000;">Tidycells</span></h1>
<p style="text-align: center;">It is an <span style="color: #ff6600;"><strong>assistant</strong> </span>for you</p>
<p style="text-align: center;">It is <span style="text-decoration: underline;">yet to <span style="color: #0000ff; text-decoration: underline;">evolve</span></span></p>',
  htmlFile
)
suppressWarnings(rstudioapi::viewer(htmlFile))    

但是,我无法使用 R 代码删除查看器对象。

截图

如果有人点击删除按钮("Remove current viewer item"),当前项目将被删除。

我一直在寻找一种编程方式来做到这一点。

也许 rstudioapi::viewer(htmlFile) 会 return 一个 id 并且可以用来从查看器窗格中删除特定项目。

我终于做到了

runApp_nb <- function(sa, pin_port = NULL){


  viewer <- getOption("viewer")
  if(!is.null(viewer)){

    if(!is.null(pin_port) && is.integer(pin_port)){
      port <- pin_port
    }else{
      port <- as.integer(sample(3000:49000, 1))
    }

    x <- callr::r_bg(function(x, y){shiny::runApp(x, port = y)}, args = list(sa , port))
    viewer(paste0("http://localhost:",port,"/"))
    return(invisible(x))
  }

  cat("\nThis is designed for RStudio\n")

  return(invisible(0))

}

然后

x <- runApp_nb(shinyApp(ui = ui, server = server))

终于手术后

x$kill_tree()