Reimplement the multiselect as a custom element
What i really set off on was to refactor the multiselect’s x-data context to a separate JavaScript file. I did not see the need at first, thinking that it would not matter because it was used only in a template and i was not duplicating the code in my files. However, i then realized that having the context in the template means the visitor has to download it each and every time it accesses a form with a multiselect, even if nothing changed, and, worse, it would download it multiple times if there were many multiselect controls. It makes more sense to put all that into a file that the browser would only download and parse once, if the proper caching is set. Once i realized that, it was a shame that AlpineJS has no way to do the same for the HTML structure[0], for the exact same reasons: not wanting to download many times the same extra <template> and other markup required to build the control for JavaScript users. And then i remembered that this is supposed to be custom element’s main selling point. At first i tried to create a shadow DOW to replace the <select> with the same <div> and <ul> that i used with Alpine, but it turns out that <select> is not one of the allowed elements that can have a shadow root attached[0]. Therefore, i changed the custom element to extend the <div> for the <select> and <label> instead—the same element that had the x-init context—, but i would have to define or include all the styles inside the shadow DOM, and bring the lang attribute, for it to look like it did before. Out with the shadow DOM, and modify the <div>’s contents instead. At this point the code was so far removed from the declarative way that AlpineJS promotes that i did not see much value on using it, except for its reactivity. But, given that this is such a small component, at the end decided to write it all in plain JavaScript. It is more code, at least looking only at the code i had to write, but i love how i only have to add an is="numerus-multiselect" attribute to HTML for it to work. [0]: https://github.com/alpinejs/alpine/discussions/1205 [1]: https://developer.mozilla.org/en-US/docs/Web/API/Element/attachShadow
This commit is contained in:
parent
1c9fe14ab9
commit
2dde25c862
|
@ -589,11 +589,11 @@ main > nav {
|
|||
}
|
||||
|
||||
/* Multiselect */
|
||||
.multiselect {
|
||||
[is="numerus-multiselect"] {
|
||||
max-width: 35rem;
|
||||
}
|
||||
|
||||
.multiselect .tags, .multiselect .options {
|
||||
[is="numerus-multiselect"] .tags, [is="numerus-multiselect"] .options {
|
||||
font-size: 1em;
|
||||
list-style: none;
|
||||
color: var(--numerus--text-color);
|
||||
|
@ -602,7 +602,7 @@ main > nav {
|
|||
border-radius: 0;
|
||||
}
|
||||
|
||||
.multiselect .tags {
|
||||
[is="numerus-multiselect"] .tags {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 1rem;
|
||||
|
@ -613,7 +613,7 @@ main > nav {
|
|||
min-width: 20rem;
|
||||
}
|
||||
|
||||
.multiselect .tags:after {
|
||||
[is="numerus-multiselect"] .tags:after {
|
||||
content: '';
|
||||
border-top: 6px solid black;
|
||||
border-left: 6px solid transparent;
|
||||
|
@ -625,22 +625,22 @@ main > nav {
|
|||
cursor: pointer;
|
||||
}
|
||||
|
||||
.multiselect .tag {
|
||||
[is="numerus-multiselect"] .tag {
|
||||
background-color: var(--numerus--color--hay);
|
||||
}
|
||||
|
||||
.multiselect .tag button {
|
||||
[is="numerus-multiselect"] .tag button {
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
background: transparent;
|
||||
min-width: initial;
|
||||
}
|
||||
|
||||
.multiselect .tag button:hover {
|
||||
[is="numerus-multiselect"] .tag button:hover {
|
||||
background: rgba(255, 255, 255, .4);
|
||||
}
|
||||
|
||||
.multiselect .tags input {
|
||||
[is="numerus-multiselect"] .tags input {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
|
@ -651,22 +651,23 @@ main > nav {
|
|||
appearance: none;
|
||||
}
|
||||
|
||||
.multiselect .options {
|
||||
[is="numerus-multiselect"] .options {
|
||||
padding: 0;
|
||||
border-top: 0;
|
||||
position: absolute;
|
||||
left: 0;
|
||||
right: 0;
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.multiselect .options li {
|
||||
[is="numerus-multiselect"] .options li {
|
||||
display: block;
|
||||
width: 100%;
|
||||
cursor: pointer;
|
||||
padding: 1rem 2rem;
|
||||
}
|
||||
|
||||
.multiselect .options li:hover {
|
||||
[is="numerus-multiselect"] .options li:hover {
|
||||
background-color: var(--numerus--color--light-gray);
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,203 @@
|
|||
class Multiselect extends HTMLDivElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.initialized = false;
|
||||
this.toSearch = '';
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
if (!this.initialized) {
|
||||
for (const child of this.children) {
|
||||
switch (child.nodeName) {
|
||||
case 'SELECT':
|
||||
this.select = child;
|
||||
break;
|
||||
case 'LABEL':
|
||||
this.label = child;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (this.label && this.select) {
|
||||
this.init();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init() {
|
||||
this.initialized = true;
|
||||
|
||||
this.select.style.display = 'none';
|
||||
for (const option of this.select.options) {
|
||||
option.dataset.numerusSearch = Multiselect.normalize(option.textContent);
|
||||
}
|
||||
|
||||
this.tags = document.createElement('div');
|
||||
this.append(this.tags);
|
||||
this.tags.classList.add('tags');
|
||||
this.tags.addEventListener('click', () => this.toggle());
|
||||
|
||||
this.search = document.createElement('input');
|
||||
this.tags.append(this.search);
|
||||
this.search.id = this.select.id;
|
||||
this.select.removeAttribute('id');
|
||||
this.search.addEventListener('input', (e) => {
|
||||
this.open();
|
||||
this.filter(e.target.value);
|
||||
});
|
||||
this.search.addEventListener('keydown', (e) => {
|
||||
switch (e.code) {
|
||||
case "Enter":
|
||||
e.preventDefault();
|
||||
this.selectFirst();
|
||||
break;
|
||||
case "Backspace":
|
||||
if (e.target.value === '') {
|
||||
this.deselectLast();
|
||||
}
|
||||
break;
|
||||
case "Escape":
|
||||
this.close();
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
// Must come after the search input
|
||||
this.tags.append(this.label);
|
||||
|
||||
this.options = document.createElement('ul');
|
||||
this.append(this.options);
|
||||
this.options.classList.add('options');
|
||||
this.close();
|
||||
|
||||
window.addEventListener('focusin', (e) => {
|
||||
if (this.contains(e.target)) return;
|
||||
this.close();
|
||||
});
|
||||
|
||||
document.addEventListener('click', (e) => {
|
||||
if (this.contains(e.target)) return;
|
||||
if (!e.target.isConnected) return;
|
||||
this.close();
|
||||
});
|
||||
|
||||
this.rebuild();
|
||||
}
|
||||
|
||||
rebuildOptions() {
|
||||
this.options.innerHTML = '';
|
||||
for (const option of this.select.options) {
|
||||
if (!this.isOptionSelectable(option)) {
|
||||
continue;
|
||||
}
|
||||
const li = document.createElement('li');
|
||||
this.options.append(li);
|
||||
li.textContent = option.textContent;
|
||||
li.addEventListener('click', () => this.selectOption(option, true));
|
||||
}
|
||||
}
|
||||
|
||||
isOptionSelectable(option) {
|
||||
if (option.selected) {
|
||||
return false;
|
||||
}
|
||||
return this.toSearch === '' || option.dataset.numerusSearch.includes(this.toSearch);
|
||||
}
|
||||
|
||||
selectOption(option, selected) {
|
||||
option.selected = selected;
|
||||
this.toSearch = this.search.value = '';
|
||||
this.rebuild();
|
||||
}
|
||||
|
||||
selectFirst() {
|
||||
if (!this.isOpen()) {
|
||||
return;
|
||||
}
|
||||
for (const option of this.select.options) {
|
||||
if (this.isOptionSelectable(option)) {
|
||||
this.selectOption(option, true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deselectLast() {
|
||||
const options = this.select.options;
|
||||
for (let i = options.length - 1; i >= 0; i--) {
|
||||
const option = options[i];
|
||||
if (option.selected) {
|
||||
this.selectOption(option, false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
rebuild() {
|
||||
this.rebuildTags();
|
||||
this.rebuildOptions();
|
||||
}
|
||||
|
||||
rebuildTags() {
|
||||
this.tags.querySelectorAll('.tag').forEach((tag) => tag.remove());
|
||||
let empty = true;
|
||||
for (const option of this.select.options) {
|
||||
if (!option.selected) {
|
||||
continue;
|
||||
}
|
||||
empty = false;
|
||||
const tag = document.createElement('div');
|
||||
this.tags.insertBefore(tag, this.search);
|
||||
tag.classList.add('tag');
|
||||
tag.dataset.numerusSearch = option.dataset.numerusSearch;
|
||||
|
||||
const span = document.createElement('span');
|
||||
tag.append(span);
|
||||
span.textContent = option.textContent;
|
||||
|
||||
const button = document.createElement('button');
|
||||
tag.append(button);
|
||||
button.type = 'button';
|
||||
button.textContent = '×';
|
||||
button.addEventListener('click', (e) => {
|
||||
e.stopPropagation();
|
||||
this.selectOption(option, false)
|
||||
});
|
||||
}
|
||||
if (empty) {
|
||||
this.search.setAttribute('placeholder', this.label.textContent);
|
||||
} else {
|
||||
this.search.removeAttribute('placeholder');
|
||||
}
|
||||
}
|
||||
|
||||
close() {
|
||||
this.options.style.display = 'none';
|
||||
}
|
||||
|
||||
open() {
|
||||
this.options.removeAttribute('style');
|
||||
}
|
||||
|
||||
toggle() {
|
||||
if (this.isOpen()) {
|
||||
this.close();
|
||||
} else {
|
||||
this.open();
|
||||
}
|
||||
}
|
||||
|
||||
isOpen() {
|
||||
return !this.options.hasAttribute('style');
|
||||
}
|
||||
|
||||
filter(search) {
|
||||
this.toSearch = Multiselect.normalize(search);
|
||||
this.rebuildOptions()
|
||||
}
|
||||
|
||||
static normalize(s) {
|
||||
return s.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase().trim();
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define('numerus-multiselect', Multiselect, {extends: 'div'});
|
|
@ -5,7 +5,7 @@
|
|||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>{{ template "title" . }} — Numerus</title>
|
||||
<link rel="stylesheet" type="text/css" media="screen" href="/static/numerus.css">
|
||||
<script defer src="/static/alpinejs@3.12.0.min.js"></script>
|
||||
<script type="module" src="/static/numerus.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
|
|
|
@ -40,81 +40,7 @@
|
|||
|
||||
{{ define "select-field" -}}
|
||||
{{- /*gotype: dev.tandem.ws/tandem/numerus/pkg.SelectField*/ -}}
|
||||
<div class="input{{ if .Errors }} has-errors{{ end }}"
|
||||
{{- if .Multiple }}
|
||||
@focusin.window="! $el.contains($event.target) && close() "
|
||||
@click.away="close()"
|
||||
x-data="{
|
||||
options: [],
|
||||
name: '',
|
||||
filter: '',
|
||||
open: false,
|
||||
init() {
|
||||
const select = $el.querySelector('select');
|
||||
this.name = select.name;
|
||||
for (const option of select.options) {
|
||||
this.options.push({
|
||||
value: option.value,
|
||||
label: option.innerText,
|
||||
search: this.normalize(option.innerText),
|
||||
selected: option.getAttribute('selected') !== null,
|
||||
});
|
||||
}
|
||||
select.remove();
|
||||
const template = $el.querySelector('template');
|
||||
const input = template.content.querySelector('input');
|
||||
const label = $el.querySelector('label');
|
||||
input.after(label);
|
||||
},
|
||||
selected() {
|
||||
return this.options.filter(option => option.selected);
|
||||
},
|
||||
normalize(s) {
|
||||
return s.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase();
|
||||
},
|
||||
unselected() {
|
||||
const filter = this.normalize(this.filter);
|
||||
return this.options.filter(option => !option.selected && (filter === '' || option.search.includes(filter)));
|
||||
},
|
||||
empty() {
|
||||
return this.selected().length === 0;
|
||||
},
|
||||
selectOption(option) {
|
||||
option.selected = true;
|
||||
this.filter = '';
|
||||
},
|
||||
selectFirst() {
|
||||
if (!this.open) {
|
||||
return;
|
||||
}
|
||||
const all = this.unselected();
|
||||
if (all.length === 0) {
|
||||
return;
|
||||
}
|
||||
this.selectOption(all[0]);
|
||||
},
|
||||
unselectLast() {
|
||||
if (this.filter !== '') {
|
||||
return;
|
||||
}
|
||||
const all = this.selected();
|
||||
if (all.length === 0) {
|
||||
return;
|
||||
}
|
||||
all[all.length - 1].selected = false;
|
||||
},
|
||||
toggle() {
|
||||
if (this.open) {
|
||||
return this.close();
|
||||
}
|
||||
this.open = true;
|
||||
},
|
||||
close() {
|
||||
this.open = false;
|
||||
},
|
||||
}"
|
||||
{{- end -}}
|
||||
>
|
||||
<div class="input{{ if .Errors }} has-errors{{ end }}"{{ if .Multiple }} is="numerus-multiselect"{{ end -}}>
|
||||
<select id="{{ .Name }}-field" name="{{ .Name }}"
|
||||
{{- range $attribute := .Attributes }} {{$attribute}} {{ end -}}
|
||||
{{ if .Multiple }} multiple="multiple"{{ end -}}
|
||||
|
@ -139,37 +65,6 @@
|
|||
</optgroup>
|
||||
{{- end }}
|
||||
</select>
|
||||
{{- if .Multiple }}
|
||||
<template x-if="true">
|
||||
<div class="multiselect">
|
||||
<div class="tags" :class="{'empty': empty()}"
|
||||
@click="toggle()"
|
||||
>
|
||||
<template x-for="option in selected()">
|
||||
<div class="tag">
|
||||
<input type="hidden" :name="name" :value="option.value">
|
||||
<span x-text="option.label"></span>
|
||||
<button type="button" @click.stop="option.selected = false">×</button>
|
||||
</div>
|
||||
</template>
|
||||
<input id="{{ .Name }}-field" :placeholder="empty() && '{{ .Label }}'" x-model="filter"
|
||||
@input="open = true"
|
||||
@keydown.escape="close()"
|
||||
@keydown.prevent.enter="selectFirst()"
|
||||
@keydown.backspace="unselectLast()"
|
||||
>
|
||||
</div>
|
||||
<ul class="options" x-show.transition="open">
|
||||
<template x-for="option in unselected()">
|
||||
<li
|
||||
x-text="option.label"
|
||||
@click.stop="selectOption(option)"
|
||||
></li>
|
||||
</template>
|
||||
</ul>
|
||||
</div>
|
||||
</template>
|
||||
{{ end -}}
|
||||
<label for="{{ .Name }}-field">{{ .Label }}</label>
|
||||
{{- if .Errors }}
|
||||
<ul>
|
||||
|
|
Loading…
Reference in New Issue