feat(filters): add searchable creatable value inputs

Build a theme-aligned combobox on the shared reka-ui primitives. Rank stored keys before bilingual descriptions, allow validated custom values, and preserve unconfirmed multi-value drafts instead of silently committing them.
This commit is contained in:
翅膀 committed 2026-10-17 05:44:07 +08:00
1 parent a3e9ab26a7
commit 2ebce8495d
4 files changed
+653 -1

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@ Core pipeline: GitHub Webhook → Worker (verify + filter + format) → Discord
## Key Decisions
- Runtime: Cloudflare Workers via the Nitro `cloudflare_module` preset (`_worker.js`), H3 event handlers in `server/routes/`
- UI: Vue 3 + Tailwind CSS v4 (`@tailwindcss/vite`) + `@elysola/ui` (Nuxt module, `Rc` prefix); admin console is a client-side SPA (`routeRules: "/admin/**": { ssr: false }`), home/legal pages render server-side; app-level composites (`ConfirmDialog`) are built on the reka-ui primitives that `@elysola/ui` ships (same copy, pre-bundled via `vite.optimizeDeps.include` so dev keeps a single instance and dialogs/popovers stack correctly) and styled like their Rc counterparts
- UI: Vue 3 + Tailwind CSS v4 (`@tailwindcss/vite`) + `@elysola/ui` (Nuxt module, `Rc` prefix); admin console is a client-side SPA (`routeRules: "/admin/**": { ssr: false }`), home/legal pages render server-side; app-level composites (`FilterCombobox`, `ConfirmDialog`) are built on the reka-ui primitives that `@elysola/ui` ships (same copy, pre-bundled via `vite.optimizeDeps.include` so dev keeps a single instance and dialogs/popovers stack correctly) and styled like their Rc counterparts
- Styling: Elysola UI supplies semantic components and blue theme tokens; `app/assets/css/main.css` retains `--wh-*` RGB-triplet aliases for app-specific Tailwind utilities and bespoke layouts (avoiding collision with Elysola's `--surface`/`--text`/`--border` hex tokens); theme switching supports auto/light/dark via `useTheme` / `ThemeToggle`, toggling `<html>.dark` with inline anti-flash head script
- Discord interactions: HTTPS Interactions Endpoint (`POST /discord/interactions`, Ed25519-signed) — no Discord Gateway / Durable Object; bot stays offline, messages always sent via REST
- Storage: D1 is the source of truth for config (routes/groups via `d1_routes`/`d1_groups`, see `server/lib/storage/config-store.ts`; each route's per-group order lives in `d1_routes.position` — migration 0012 — and routes load ordered by `group_id, position, id`, falling back to id order on an unmigrated database), send/audit logs, dedup (`dedup_keys`), delivery state (`delivery_state`) and message tracking (`message_tracking` via `server/lib/storage/d1.ts` `canUseD1` gate). KV keeps only cache + short-lived/ephemeral state (tokens, OAuth state, admin sessions, `msg:*`-adjacent locks, per-group secrets `tenant:*`, invites, i18n overrides) with explicit TTLs. R2 parks oversized queue payloads (`webhooks/YYYY/MM/DD/*.json`, `server/lib/storage/payload.ts`) instead of KV. A `storage-prune` scheduled task cleans up expired dedup/delivery/message-tracking rows
+226
View File
@@ -795,6 +795,232 @@
grid-area: name;
}
/* ---- Filter combobox (FilterCombobox.vue; its popover is portaled, so not scoped) ---- */
.filter-combo {
position: relative;
width: 100%;
min-width: 0;
}
.filter-combo-anchor {
display: flex;
min-height: 2.25rem;
width: 100%;
align-items: center;
gap: 0.25rem;
border-radius: 0.5rem;
background: rgb(var(--wh-surface));
padding: 0 0.375rem 0 0.75rem;
box-shadow:
inset 0 0 0 1px rgb(var(--wh-border-strong)),
0 1px 2px rgb(0 0 0 / 0.05);
cursor: text;
transition: box-shadow 150ms ease;
}
.filter-combo-anchor:focus-within {
box-shadow: inset 0 0 0 2px rgb(var(--wh-accent));
}
.filter-combo-anchor.is-invalid {
box-shadow: inset 0 0 0 1px rgb(var(--wh-bad));
}
.filter-combo-anchor.is-invalid:focus-within {
box-shadow: inset 0 0 0 2px rgb(var(--wh-bad));
}
.filter-combo-anchor.is-multi {
flex-wrap: wrap;
padding: 0.25rem 0.375rem 0.25rem 0.375rem;
}
.filter-combo-chip {
display: inline-flex;
max-width: 100%;
align-items: center;
gap: 0.25rem;
border-radius: 0.375rem;
background: rgb(var(--wh-accent-dim));
padding: 0.125rem 0.25rem 0.125rem 0.5rem;
color: rgb(var(--wh-accent-text));
font-family: var(--font-mono);
font-size: 0.72rem;
font-weight: 500;
line-height: 1.25rem;
}
.filter-combo-chip.is-invalid {
background: rgb(var(--wh-bad-dim));
color: rgb(var(--wh-bad));
text-decoration: line-through;
text-decoration-color: rgb(var(--wh-bad) / 0.6);
}
.filter-combo-chip.is-invalid .filter-combo-chip-x {
color: rgb(var(--wh-bad));
}
.filter-combo-chip-text {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.filter-combo-chip-x {
display: grid;
flex: none;
width: 1.125rem;
height: 1.125rem;
place-items: center;
border-radius: 9999px;
color: rgb(var(--wh-accent));
cursor: pointer;
}
.filter-combo-chip-x:hover {
background: rgb(var(--wh-accent) / 0.15);
}
.filter-combo-chip-x:focus-visible {
outline: 2px solid rgb(var(--wh-accent));
outline-offset: 1px;
}
.filter-combo-input {
min-width: 4rem;
flex: 1 1 4rem;
border: 0;
background: transparent;
padding: 0.375rem 0;
color: rgb(var(--wh-text));
font-size: 0.8125rem;
outline: none;
}
.filter-combo-anchor.is-multi .filter-combo-input {
padding-left: 0.375rem;
}
.filter-combo-input.is-mono {
font-family: var(--font-mono);
font-size: 0.78rem;
}
.filter-combo-input::placeholder {
color: rgb(var(--wh-faint));
}
.filter-combo-trigger {
display: grid;
flex: none;
width: 1.5rem;
height: 1.5rem;
place-items: center;
border-radius: 0.375rem;
color: rgb(var(--wh-faint));
}
.filter-combo-trigger:hover {
color: rgb(var(--wh-text));
}
.filter-combo-error {
margin: 0.3rem 0 0;
color: rgb(var(--wh-bad));
font-size: 0.72rem;
}
.filter-combo-pending {
margin: 0.3rem 0 0;
color: rgb(var(--wh-warn));
font-size: 0.72rem;
}
.filter-combo-content {
z-index: 55;
width: max(var(--reka-combobox-trigger-width), 17rem);
max-width: calc(100vw - 1rem);
overflow: hidden;
border-radius: 0.5rem;
background: rgb(var(--wh-surface));
box-shadow:
inset 0 0 0 1px rgb(var(--wh-border)),
0 4px 6px -1px rgb(0 0 0 / 0.1),
0 2px 4px -2px rgb(0 0 0 / 0.1);
color: rgb(var(--wh-text));
}
.filter-combo-content[data-state="open"] {
animation: filter-combo-in 120ms ease-out;
}
@keyframes filter-combo-in {
from {
opacity: 0;
transform: translateY(-2px);
}
}
.filter-combo-viewport {
max-height: min(18rem, var(--reka-combobox-content-available-height, 18rem));
overflow-y: auto;
padding: 0.25rem;
overscroll-behavior: contain;
}
.filter-combo-group {
padding: 0.5rem 0.625rem 0.25rem;
color: rgb(var(--wh-faint));
font-size: 0.65rem;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.filter-combo-item {
position: relative;
display: flex;
min-height: 2rem;
align-items: center;
gap: 0.75rem;
border-radius: 0.375rem;
padding: 0.375rem 2rem 0.375rem 0.625rem;
font-size: 0.8125rem;
outline: none;
cursor: pointer;
user-select: none;
}
.filter-combo-item[data-highlighted] {
background: rgb(var(--wh-surface-3));
}
.filter-combo-item-value {
flex: none;
font-family: var(--font-mono);
font-size: 0.78rem;
}
.filter-combo-item-hint {
min-width: 0;
flex: 1 1 auto;
overflow: hidden;
color: rgb(var(--wh-muted));
font-size: 0.75rem;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.filter-combo-item-check {
position: absolute;
right: 0.5rem;
display: grid;
place-items: center;
color: rgb(var(--wh-accent));
}
.filter-combo-item.is-create {
color: rgb(var(--wh-accent));
font-weight: 600;
}
.filter-combo-item-create {
min-width: 0;
overflow-wrap: anywhere;
}
.filter-combo-note {
margin: 0;
padding: 0.75rem 0.625rem;
color: rgb(var(--wh-faint));
font-size: 0.75rem;
text-align: center;
}
.filter-combo-note.is-error {
color: rgb(var(--wh-bad));
text-align: left;
}
@media (pointer: coarse) {
.filter-combo-item {
min-height: 2.5rem;
}
}
@media (prefers-reduced-motion: reduce) {
.filter-combo-content[data-state="open"] {
animation: none;
}
}
.node-editor {
@apply mb-1;
}
+416
View File
@@ -0,0 +1,416 @@
<template>
<ComboboxRoot
ref="rootRef"
v-model:open="open"
:model-value="multiple ? values : single || undefined"
:multiple="multiple"
ignore-filter
open-on-click
:reset-search-term-on-blur="false"
:reset-search-term-on-select="false"
class="filter-combo"
>
<ComboboxAnchor
class="filter-combo-anchor"
:class="{ 'is-multi': multiple, 'is-invalid': !!commitError }"
@click="focusInput"
>
<template v-if="multiple">
<span
v-for="(v, i) in values"
:key="v"
class="filter-combo-chip"
:class="{ 'is-invalid': !!chipError(v) }"
:title="chipError(v) ? t(chipError(v)!) : hintOf(v)"
>
<span class="filter-combo-chip-text">{{ v }}</span>
<button
type="button"
class="filter-combo-chip-x"
:aria-label="t('combo.remove', { value: v })"
@pointerdown.stop
@click.stop="removeAt(i)"
>
<X :size="12" />
</button>
</span>
</template>
<ComboboxInput
:id="inputId"
v-model="inputText"
class="filter-combo-input"
:class="{ 'is-mono': mono }"
:placeholder="multiple && values.length ? '' : placeholder"
:aria-label="label"
:aria-invalid="commitError ? true : undefined"
:title="multiple ? undefined : hintOf(single) || undefined"
@keydown="onKeydown"
@focus="focused = true"
@blur="onBlur"
/>
<ComboboxTrigger class="filter-combo-trigger" tabindex="-1" :aria-label="label">
<ChevronDown :size="14" />
</ComboboxTrigger>
</ComboboxAnchor>
<p v-if="commitError" class="filter-combo-error">{{ t(commitError) }}</p>
<p v-else-if="pending && !focused" class="filter-combo-pending">
{{ t("combo.pending", { value: draftText }) }}
</p>
<ComboboxPortal>
<ComboboxContent
position="popper"
align="start"
:side-offset="4"
:collision-padding="8"
:data-filter-combo="uid"
class="filter-combo-content"
@pointerdown="markPointerInside"
>
<ComboboxViewport class="filter-combo-viewport">
<ComboboxGroup v-for="section in sections" :key="section.name">
<ComboboxLabel v-if="section.name" class="filter-combo-group">
{{ section.name }}
</ComboboxLabel>
<ComboboxItem
v-for="opt in section.options"
:key="opt.value"
:value="opt.value"
:title="opt.hint"
class="filter-combo-item"
@select="onPick($event, opt.value)"
>
<span class="filter-combo-item-value">{{ opt.value }}</span>
<span v-if="opt.hint" class="filter-combo-item-hint">{{ opt.hint }}</span>
<ComboboxItemIndicator class="filter-combo-item-check">
<Check :size="14" />
</ComboboxItemIndicator>
</ComboboxItem>
</ComboboxGroup>
<ComboboxItem
v-if="canCreate"
:value="CREATE_VALUE"
class="filter-combo-item is-create"
@select="onCreate"
>
<Plus :size="14" class="shrink-0" />
<span class="filter-combo-item-create">{{
t("combo.useValue", { value: draftText })
}}</span>
</ComboboxItem>
<p v-if="liveError && !sections.length" class="filter-combo-note is-error">
{{ t(liveError) }}
</p>
<p v-else-if="!sections.length && !canCreate" class="filter-combo-note">
{{ creatable ? t("combo.typeToAdd") : t("combo.empty") }}
</p>
</ComboboxViewport>
</ComboboxContent>
</ComboboxPortal>
</ComboboxRoot>
</template>
<script setup lang="ts">
import { Check, ChevronDown, Plus, X } from "lucide-vue-next";
import {
ComboboxAnchor,
ComboboxContent,
ComboboxGroup,
ComboboxInput,
ComboboxItem,
ComboboxItemIndicator,
ComboboxLabel,
ComboboxPortal,
ComboboxRoot,
ComboboxTrigger,
ComboboxViewport,
} from "reka-ui";
import type { ComboOption } from "~/utils/filter-catalog";
/**
* Searchable dropdown for the filter editor. Options carry the stored English
* key plus localized descriptions; search matches the key first, then either
* language. With `creatable`, typed text can be added as a custom value once
* `validate` accepts it — otherwise typing only searches.
*
* Built on the reka-ui primitives that @elysola/ui ships (and styled
* like RcCombobox / RcTagInput). It deliberately uses that same reka-ui copy
* rather than a separate dependency so its popover stacks with Rc dialogs.
*/
const props = withDefaults(
defineProps<{
modelValue: string | string[];
options: ComboOption[];
multiple?: boolean;
creatable?: boolean;
/** Returns an i18n error key for an unusable custom value. */
validate?: (value: string) => string | null;
placeholder?: string;
label?: string;
mono?: boolean;
/**
* Multi-value fields: the typed text not added yet (`v-model:draft`), so
* the owner can refuse to save it and restore it after a remount.
*/
draft?: string;
}>(),
{
multiple: false,
creatable: false,
validate: undefined,
placeholder: "",
label: "",
mono: true,
draft: "",
},
);
const emit = defineEmits<{
(e: "update:modelValue", value: string | string[]): void;
(e: "update:draft", value: string): void;
}>();
const { t } = useI18n();
/** Item value of the "use typed text" entry (never a real option value). */
const CREATE_VALUE = "\u0000create";
const uid = useId();
const inputId = `filter-combo-${uid}`;
const rootRef = ref<{ highlightedElement?: HTMLElement } | null>(null);
const open = ref(false);
// A multi-value draft kept by the owner comes back after a remount.
const draft = ref(props.multiple ? props.draft : "");
const typing = ref(!!draft.value.trim());
const commitError = ref<string | null>(
typing.value ? (props.validate?.(draft.value.trim()) ?? null) : null,
);
const pointerInside = ref(false);
const focused = ref(false);
const values = computed(() =>
Array.isArray(props.modelValue) ? props.modelValue : props.modelValue ? [props.modelValue] : [],
);
const single = computed(() => (Array.isArray(props.modelValue) ? "" : props.modelValue));
const draftText = computed(() => draft.value.trim());
const query = computed(() => (typing.value ? draftText.value.toLowerCase() : ""));
const inputText = computed({
get: () => (props.multiple || typing.value ? draft.value : single.value),
set: (text: string) => {
draft.value = text;
typing.value = true;
commitError.value = null;
},
});
/** Search score: lower is better, -1 = no match. The English key ranks first. */
function score(opt: ComboOption, q: string): number {
const value = opt.value.toLowerCase();
const snake = q.replace(/\s+/g, "_");
if (value === q) return 0;
if (value.startsWith(q) || value.startsWith(snake)) return 1;
if (value.includes(q) || value.includes(snake)) return 2;
if (opt.hint?.toLowerCase().includes(q)) return 3;
if (opt.keywords?.some((k) => k.toLowerCase().includes(q))) return 4;
return -1;
}
const sections = computed(() => {
const q = query.value;
if (q) {
const ranked = props.options
.map((opt, index) => ({ opt, index, s: score(opt, q) }))
.filter((r) => r.s >= 0)
.sort((a, b) => a.s - b.s || a.index - b.index)
.map((r) => r.opt);
return ranked.length ? [{ name: "", options: ranked }] : [];
}
const groups: { name: string; options: ComboOption[] }[] = [];
for (const opt of props.options) {
const name = opt.group ?? "";
const last = groups[groups.length - 1];
if (last && last.name === name) last.options.push(opt);
else groups.push({ name, options: [opt] });
}
return groups;
});
const liveError = computed(() =>
props.creatable && typing.value && draftText.value
? (props.validate?.(draftText.value) ?? null)
: null,
);
const canCreate = computed(() => {
if (!props.creatable || !typing.value || !draftText.value || liveError.value) return false;
const text = draftText.value.toLowerCase();
return (
!props.options.some((o) => o.value.toLowerCase() === text) &&
!values.value.some((v) => v.toLowerCase() === text)
);
});
/**
* Typed text in a multi-value field that has not been added yet. It is never
* added implicitly (it may just be a search), so the route form refuses to
* save until it is added with Enter or cleared.
*/
const pending = computed(
() => props.multiple && typing.value && !!draftText.value && !commitError.value,
);
watch(draft, (text) => {
if (props.multiple) emit("update:draft", text);
});
watch(open, (isOpen) => {
if (isOpen) {
// Single-value fields opened by a click or arrow key: typing replaces the
// current value. Opened by typing, the typed text must stay as it is.
if (!props.multiple) nextTick(() => !typing.value && inputEl()?.select());
return;
}
if (!props.multiple && !props.creatable) resetDraft();
});
/** Error of an already-added value (e.g. after the filter type changed). */
function chipError(value: string): string | null {
return props.validate?.(value) ?? null;
}
function hintOf(value: string): string {
return props.options.find((o) => o.value === value)?.hint ?? "";
}
function inputEl(): HTMLInputElement | null {
return document.getElementById(inputId) as HTMLInputElement | null;
}
function focusInput(): void {
inputEl()?.focus();
}
function resetDraft(): void {
draft.value = "";
typing.value = false;
commitError.value = null;
}
function setValues(next: string[]): void {
emit("update:modelValue", next);
}
function choose(value: string): void {
if (props.multiple) {
const exists = values.value.includes(value);
setValues(exists ? values.value.filter((v) => v !== value) : [...values.value, value]);
resetDraft();
nextTick(focusInput);
return;
}
emit("update:modelValue", value);
resetDraft();
open.value = false;
nextTick(focusInput);
}
/** Commit typed text as a custom value; false (with an error shown) when invalid. */
function commitDraft(): boolean {
const text = draftText.value;
if (!text) {
// Clearing a single free-form value (e.g. the field path) removes it.
if (!props.multiple && typing.value && single.value) emit("update:modelValue", "");
resetDraft();
return true;
}
const err = props.validate?.(text) ?? null;
if (err) {
commitError.value = err;
return false;
}
if (props.multiple) {
if (!values.value.includes(text)) setValues([...values.value, text]);
} else if (text !== single.value) {
emit("update:modelValue", text);
}
resetDraft();
return true;
}
function removeAt(index: number): void {
setValues(values.value.filter((_, i) => i !== index));
focusInput();
}
function onPick(event: Event, value: string): void {
// We own the model: stop reka from applying (or toggling) the value itself.
event.preventDefault();
choose(value);
}
function onCreate(event: Event): void {
event.preventDefault();
if (commitDraft() && !props.multiple) open.value = false;
nextTick(focusInput);
}
function markPointerInside(): void {
pointerInside.value = true;
setTimeout(() => (pointerInside.value = false), 0);
}
function onBlur(event: FocusEvent): void {
focused.value = false;
const next = event.relatedTarget as HTMLElement | null;
// Focus moving into our own list means an option is being clicked.
if (pointerInside.value || next?.closest?.(`[data-filter-combo="${uid}"]`)) return;
if (!typing.value) return;
if (!props.creatable) {
resetDraft();
return;
}
if (!props.multiple) {
// A single free-form value (the field path) behaves like a text input.
commitDraft();
return;
}
// Only an exact suggestion is unambiguous enough to add on its own; any
// other text stays pending (it may be a search) until Enter or clearing.
const text = draftText.value.toLowerCase();
const match = props.options.find((o) => o.value.toLowerCase() === text);
if (!match) return;
if (!values.value.includes(match.value)) setValues([...values.value, match.value]);
resetDraft();
}
defineExpose({
/** Whether the field shows text that was rejected and is not its value. */
hasInvalidDraft: (): boolean => !!commitError.value,
});
function isComposing(event: KeyboardEvent): boolean {
return event.isComposing || event.keyCode === 229;
}
function onKeydown(event: KeyboardEvent): void {
if (isComposing(event)) return;
if (event.key === "Enter") {
// Never let Enter submit the surrounding form.
const handled = event.defaultPrevented;
event.preventDefault();
if (handled && rootRef.value?.highlightedElement) return;
if (props.creatable && draftText.value) {
if (commitDraft() && !props.multiple) open.value = false;
} else if (!open.value) {
open.value = true;
}
return;
}
if (event.key === "Backspace" && props.multiple && !draft.value && values.value.length) {
event.preventDefault();
removeAt(values.value.length - 1);
}
}
</script>
+10
View File
@@ -283,6 +283,11 @@ const en: Dict = {
"routeEditor.errPath": "Field filters need a path",
"routeEditor.errValues": "Add at least one value",
"routeEditor.errGroupEmpty": "Group needs at least one condition",
"combo.empty": "No matches",
"combo.typeToAdd": "Type a value to add it",
"combo.useValue": "Use “{value}”",
"combo.remove": "Remove {value}",
"combo.pending": 'Not added yet: press Enter to add "{value}"',
"valid.tooLong": "Patterns longer than 200 characters never match",
"valid.regex": "Invalid regular expression",
"valid.number": "Comparison operators need a number",
@@ -702,6 +707,11 @@ const zh: Dict = {
"routeEditor.errPath": "字段过滤需要路径",
"routeEditor.errValues": "至少需要一个值",
"routeEditor.errGroupEmpty": "分组至少需要一个条件",
"combo.empty": "无匹配项",
"combo.typeToAdd": "输入内容后即可添加",
"combo.useValue": "使用“{value}”",
"combo.remove": "移除 {value}",
"combo.pending": "尚未添加:按回车添加“{value}”",
"valid.tooLong": "超过 200 个字符的模式永远不会匹配",
"valid.regex": "无效的正则表达式",
"valid.number": "比较运算需要数字",