Spaces:
Paused

assistant / ui /web /src /components /chat /MiniSelect.svelte
localailb's picture
Deploy Full LocalAiLab Application (FastAPI + Svelte + Agents)
bc9f3e6 verified
Raw History Blame Contribute Delete
9.36 kB
<script>
import "./MiniSelect.css";
/**
* Custom dropdown that replaces the native <select> for the collapsed
* Generation Settings controls (context window, RAG theme/subtheme
* filters, vision projector, analysis type). A native select's option
* popup is an OS-level window that WebView2 clips/hit-tests incorrectly
* when it would open past the bottom edge of the app window — the "menu
* opens but clicking an option doesn't apply" bug. This one is pure DOM:
* a button that toggles an in-page absolute-positioned option list, so
* option clicks always land. The menu flips above the trigger when there
* is no room below, so it can never be cut off by the window edge.
*
* `value` is a string (e.g. the context-window label, a theme name, an
* analysis key — whatever the parent persisted) OR, with `multiple`, an
* ARRAY of selected values (the RAG tab's multi-select Theme/Subtheme/
* File filters). `options` may be plain strings (value === label) or
* { value, label } pairs (translated labels whose value differs, like
* the analysis presets).
*/
let {
value = $bindable(""),
options = [],
/** Label shown when the value is empty and selectable as the "" entry
* (e.g. RAG "All" filter, vision "Auto" projector). Pass "" to omit.
* In `multiple` mode the empty entry acts as "clear all selections". */
emptyLabel = "",
/** `multiple` mode: `value` is an ARRAY; option clicks toggle
* membership and keep the menu open, so several can be picked in one
* visit. The empty entry (when `emptyLabel` is set) clears the array.
*/
multiple = false,
/** `creatable` mode: a "+ Add new" input at the bottom of the menu lets
* the user type a value that doesn't exist yet and add it to the
* selection (the KB tab's tag dropdowns — a fresh upload can be tagged
* with a brand-new theme/subtheme, which the pick-only lists can't).
* The new value rides in the bound `value` array; it also appears as a
* checked option for the rest of the session (the entries logic appends
* selected values missing from `options`). */
creatable = false,
/** `creatable` mode: the placeholder text of the add-new input. */
createLabel = "",
/** `multiple` mode: the trigger text when nothing is selected (e.g.
* "None selected"). */
noneLabel = "",
/** Resolved i18n tooltip text passed from the parent (the styled
* Tooltip singleton needs a data-tooltip on every interactive element;
* the trigger and the option buttons all carry it). */
tip = "",
/** Fired when the menu opens (RAG loads its theme list on demand). */
onopen = () => {},
/** Fired after a pick commits the new value (the parents persist the
* setting via saveSetting, reading the bound value — which has already
* propagated when this runs). */
onchange = () => {},
} = $props();
let open = $state(false);
let up = $state(false);
let menu = $state(null);
let root = $state(null);
let createInput = $state(null);
function addNew() {
const v = (createInput?.value || "").trim();
if (!v) return;
const cur = Array.isArray(value) ? value.slice() : [];
if (!cur.includes(v)) {
value = [...cur, v];
onchange();
}
if (createInput) createInput.value = "";
}
const norm = (o) => (typeof o === "string" ? { value: o, label: o } : o);
/** The full option list: the empty entry first when requested, then the
* parent's options, then an out-of-list current value (RAG's subtheme can
* hold a theme that isn't in the freshly-loaded list yet). */
const entries = $derived.by(() => {
const list = [];
const present = (v) => list.some((e) => e.value === v);
if (emptyLabel !== "" && !present("")) list.push({ value: "", label: emptyLabel });
for (const o of options) {
const n = norm(o);
if (!present(n.value)) list.push(n);
}
if (multiple) {
// Keep every selected value visible & toggleable, even ones that are
// not in the freshly-loaded options list yet.
const sel = Array.isArray(value) ? value : [];
for (const cur of sel) {
if (cur && !present(cur)) {
const match = options.map(norm).find((n) => n.value === cur);
list.push(match ? { ...match } : { value: cur, label: cur });
}
}
} else {
const cur = value ?? "";
if (cur && !present(cur)) {
const match = options.map(norm).find((n) => n.value === cur);
list.push(match ? { ...match } : { value: cur, label: cur });
}
}
return list;
});
const selected = $derived(multiple ? (Array.isArray(value) ? value : []) : null);
const shown = $derived.by(() => {
if (!multiple) {
return entries.find((e) => e.value === value)?.label ?? value ?? emptyLabel ?? "—";
}
const sel = selected.map((v) => entries.find((e) => e.value === v)?.label ?? v);
if (sel.length === 0) return noneLabel || emptyLabel || "—";
return sel.join(", ");
});
function flip() {
if (!root) return;
const r = root.getBoundingClientRect();
const h = menu ? menu.offsetHeight : 0;
const below = window.innerHeight - r.bottom - 8;
const above = r.top - 8;
up = h > below && above > below;
}
function toggle() {
if (open) {
close();
return;
}
open = true;
onopen();
requestAnimationFrame(flip);
}
function close() {
open = false;
}
function pick(opt) {
if (multiple) {
const cur = selected.slice();
if (opt === "") {
value = [];
} else if (cur.includes(opt)) {
value = cur.filter((v) => v !== opt);
} else {
value = [...cur, opt];
}
onchange();
return; // stay open so several can be picked in one visit
}
if (opt !== value) {
value = opt;
onchange();
}
close();
}
function onMenuKeydown(e) {
if (!open) return;
const list = Array.from(menu?.querySelectorAll(".minisel-opt") ?? []);
if (list.length === 0) return;
const idx = list.indexOf(document.activeElement);
if (e.key === "ArrowDown") {
e.preventDefault();
list[(idx + 1) % list.length].focus();
} else if (e.key === "ArrowUp") {
e.preventDefault();
list[(idx - 1 + list.length) % list.length].focus();
} else if (e.key === "Escape") {
e.preventDefault();
close();
root?.querySelector(".minisel-trigger")?.focus();
}
}
// Close on outside pointer-down and Escape, exactly like a native select
// commits/dismisses.
$effect(() => {
if (!open) return;
const onDown = (e) => {
if (root && !root.contains(e.target)) close();
};
const onKey = (e) => {
if (e.key === "Escape") close();
};
window.addEventListener("mousedown", onDown);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", onDown);
window.removeEventListener("keydown", onKey);
};
});
// Re-flip the menu if the layout shifts while it is open.
$effect(() => {
if (open) flip();
});
</script>
<div class="minisel" bind:this={root}>
<button
type="button"
class="minisel-trigger"
data-tooltip={tip}
aria-label={tip || shown}
aria-haspopup="listbox"
aria-expanded={open}
onclick={toggle}
onkeydown={(e) => {
if (e.key === "ArrowDown") {
e.preventDefault();
if (!open) toggle();
requestAnimationFrame(() => {
menu?.querySelector(".minisel-opt")?.focus();
});
} else if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
toggle();
}
}}
>
<span class="minisel-val">{shown}</span>
<span class="minisel-caret" aria-hidden="true">â–¾</span>
</button>
{#if open}
<ul class="minisel-menu" class:up={up} bind:this={menu} role="listbox" onkeydown={onMenuKeydown}>
{#each entries as e (e.value)}
<li role="none">
<button
type="button"
class="minisel-opt"
class:checked={multiple && selected.includes(e.value)}
role="option"
aria-selected={multiple ? selected.includes(e.value) : e.value === value}
data-tooltip={tip}
onclick={() => pick(e.value)}
onfocus={flip}
>
{#if multiple}<span class="minisel-check" aria-hidden="true">✓</span>{/if}
{e.label}
</button>
</li>
{/each}
{#if creatable}
<li role="none" class="minisel-create">
<input
type="text"
class="minisel-create-input"
placeholder={createLabel}
aria-label={createLabel || tip}
data-tooltip={tip}
bind:this={createInput}
onkeydown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
addNew();
} else if (e.key === "Escape") {
e.preventDefault();
close();
root?.querySelector(".minisel-trigger")?.focus();
}
}}
onclick={(e) => e.stopPropagation()}
/>
</li>
{/if}
</ul>
{/if}
</div>