Created
January 28, 2025 15:07
-
-
Save mkrcah/832dfd9b6db15cb6269e6f908254facf to your computer and use it in GitHub Desktop.
TomSelect + DataStar + Clojure
This file contains hidden or 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
(ns web.components.select | |
(:require [hiccup2.core :as h])) | |
(defn globalInit [] | |
[:script | |
{:type "text/javascript"} | |
(h/raw | |
"function initializeTomSelect(selector, options = {}) { | |
var input = document.querySelector(selector); | |
var value = input.value | |
var control = input.tomselect; | |
control && control.destroy(); | |
control = new TomSelect(selector, options) | |
control && control.setValue(value); | |
} | |
function updateTomSelectFromSignal(selector, signalVal) { | |
var input = document.querySelector(selector); | |
var control = input.tomselect; | |
control && control.setValue(signalVal); | |
} | |
")]) | |
(defn final-attrs [html-attrs] | |
(def html-attrs html-attrs) | |
(cond-> | |
html-attrs | |
true | |
(assoc :data-on-load | |
(format "initializeTomSelect('#%s', {})" (:id html-attrs))) | |
(-> html-attrs :data-bind) | |
(assoc :data-on-signals-change | |
(format "updateTomSelectFromSignal('#%s', $%s)" | |
(:id html-attrs) | |
(-> html-attrs :data-bind))))) | |
(defn Select | |
":placeholder and :id html attrs are required" | |
[options html-attrs] | |
{:pre [(and (contains? html-attrs :id) "Required to initialize with js")]} | |
[:span | |
[:select (final-attrs html-attrs) | |
[:option {:value ""} (:placeholder html-attrs)] | |
(conj | |
(for [{:keys [text value]} options] | |
[:option {:value value} text]) | |
[:option])]]) | |
(comment | |
(Select [{:text "Trip 1" :value 1} | |
{:text "Trip 2" :value 2}] | |
{:id "select-a-trip" | |
:placeholder "Select a trip" | |
:data-bind "trip-id"})) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment