Last active
December 13, 2023 03:53
-
-
Save Gotfrid/76f2012280597d8b2f53705b809e9f86 to your computer and use it in GitHub Desktop.
shiny.fluent Dropdown component with search capabilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
box::use( | |
shiny[div, moduleServer, NS, observeEvent], | |
shiny.fluent[JS, fluentPage, Dropdown.shinyInput], | |
) | |
DropdownMenuItemType <- function(type) { # nolint | |
JS(paste0("jsmodule['@fluentui/react'].DropdownMenuItemType."), type) | |
} | |
render_search_box <- JS(paste("(option) => { | |
if (option.key !== '__FilterHeader__') { | |
return option.text; | |
} | |
const onChange = (event, newValue) => { | |
const query = newValue.toLocaleLowerCase(); | |
const checkboxLabels = document.querySelectorAll( | |
'div.ms-Checkbox .ms-Checkbox-label' | |
); | |
checkboxLabels.forEach(label => { | |
const text = label.innerText.replace('\\n', '').replace('', '').toLocaleLowerCase(); | |
if (query === '' || text.startsWith(query)) { | |
label.parentElement.style.display = 'flex'; | |
} else { | |
label.parentElement.style.display = 'none'; | |
} | |
}); | |
}; | |
const props = { placeholder: 'Start typing', underlined: true, onChange }; | |
const element = React.createElement(jsmodule['@fluentui/react'].SearchBox, props) | |
return element; | |
}")) | |
#' @export | |
ui <- function(id) { | |
ns <- NS(id) | |
fluentPage( | |
div( | |
style = "height: 100%; width: 50%; margin:auto", | |
Dropdown.shinyInput( | |
inputId = ns("fruit"), | |
label = "Searchable Fruit Selector", | |
multiSelect = TRUE, | |
placeholder = "Placeholder", | |
options = list( | |
list(key = "__FilterHeader__", text = "-", itemType = DropdownMenuItemType("Header")), | |
list(key = "fruitsHeader", text = "Fruit"), | |
list(key = "apple", text = "Apple"), | |
list(key = "banana", text = "Banana"), | |
list(key = "orange", text = "Orange", disabled = TRUE), | |
list(key = "grape", text = "Grape"), | |
list(key = "vegetablesHeader", text = "Vegetables"), | |
list(key = "broccoli", text = "Broccoli"), | |
list(key = "carrot", text = "Carrot"), | |
list(key = "lettuce", text = "Lettuce") | |
), | |
onRenderOption = render_search_box | |
) | |
) | |
) | |
} | |
#' @export | |
server <- function(id) { | |
moduleServer(id, function(input, output, session) { | |
observeEvent(input$fruit, { | |
print(input$fruit) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment