Reputation: 480
I have a small dummy application with textareaInput. Right now the user can input anything he wants inside this box. Can we have put a link so that it highlights. For example when the user puts This is the link : https://timesofindia.indiatimes.com/defaultinterstitial.cms
, the link here should be populate as a link and not as a text
ui <- fluidPage(
textAreaInput("caption", "Caption", "Data Summary", width = "1000px"),
verbatimTextOutput("value")
)
server <- function(input, output) {
output$value <- renderText({ input$caption })
}
shinyApp(ui, server)
}
Upvotes: 0
Views: 44
Reputation: 7340
Here is what you want
library(stringr)
library(spsUtil)
library(glue)
library(shiny)
ui <- fluidPage(
textAreaInput("caption", "Caption", "Data Summary", width = "1000px"),
uiOutput("value")
)
server <- function(input, output) {
url <- reactive({
req(input$caption)
list(
match = str_match_all(input$caption, "http[s]{0,1}://[^ ]+") %>% unlist(),
url = input$caption
)
}) %>% debounce(1000)
output$value <- renderUI({
req(url()$url)
formater <- function(x){glue::glue("<a href='{x}'>{str_remove(x, 'http[s]{0,1}://')}</a>")}
url <- url()$url
for(i in url()$match) {
if(quiet(checkUrl(i, timeout = 0.5))){
url <- str_replace(url, i, formater)
}
}
p(
HTML(url)
)
})
}
shinyApp(ui, server)
This works no matter what you put inside the textarea, along as some text starts with http(s)
, then it will pass to a URL checker and try to reach the URL. If successful, then formats the string to be a link and remove http(s)://
.
First text is processed inside url
reactive to find all the possible URLs. It has a debounce of 1000, meaning we only check for URLs at most 1 once per second. If users keep typing, it will only be checked every 1 s.
The reactive is passed to the UI rendering part. Here we use quiet
and checkUrl
from {spsUtil} package to silently check URLs with a timeout of 0.5 second (if we can't get it within 0.5 s, return FALSE).
If the url is okay, then we replace the original text with a link.
try https://www.google.com sdasd http://apple.com ssd https://random.as.com
Upvotes: 1