import {Controller} from "@hotwired/stimulus"; import "tom-select/dist/css/tom-select.bootstrap5.css"; import '../../css/components/tom-select_extensions.css'; import TomSelect from "tom-select"; import {marked} from "marked"; export default class extends Controller { _tomSelect; connect() { let settings = { allowEmptyOption: true, plugins: ['dropdown_input'], searchField: ["name", "description", "category", "footprint"], valueField: "id", labelField: "name", preload: "focus", render: { item: (data, escape) => { return '' + (data.image ? "" : "") + escape(data.name) + ''; }, option: (data, escape) => { if(data.text) { return '' + escape(data.text) + ''; } let tmp = '
' + "
" + (data.image ? "" : "") + "
" + "
" + '
' + escape(data.name) + '
' + (data.description ? '

' + marked.parseInline(data.description) + '

' : "") + (data.category ? '

' + escape(data.category) : ""); if (data.footprint) { //If footprint is defined for the part show it next to the category tmp += ' ' + escape(data.footprint); } return tmp + '

' + '
'; } } }; if (this.element.dataset.autocomplete) { const base_url = this.element.dataset.autocomplete; settings.valueField = "id"; settings.load = (query, callback) => { const url = base_url.replace('__QUERY__', encodeURIComponent(query)); fetch(url) .then(response => response.json()) .then(json => {callback(json);}) .catch(() => { callback() }); }; this._tomSelect = new TomSelect(this.element, settings); //this._tomSelect.clearOptions(); } } disconnect() { super.disconnect(); //Destroy the TomSelect instance this._tomSelect.destroy(); } }