fix(filters): builder UX round one — incomplete rules, group removal, field menu (user report)

- Root bug: incomplete rules (the ready rule, every new group's first
  rule) were sent to the server — the live-count fetch toasted a 400
  and every suggestion fetch failed silently (why author typing showed
  no dropdown). Fix: completedTree() prunes incomplete rules and empty
  groups; the count fetch skips when nothing is complete, suggestion
  fetches send only the other COMPLETED rules, and serialization wires
  only completed rules (an unfinished rule was never a filter).
- Group remove button was x-show'd away on depth-0 groups — exactly
  where user groups live. Always visible now.
- Field menu: filter input at the top (Enter prevented), no-match
  state; group headers restyled as flush-left tinted sticky bands with
  options tabbed in beneath (user's layout pick).
- toast.ts: filter-count fetches join the suggestion-fetch exemption
  (a failed background hint never interrupts).
This commit is contained in:
John O'Keefe committed 2026-10-20 15:04:19 -04:00
1 parent 4ee24e7152
commit 04b36f0563
6 files changed
+134 -23

No files matched your search

+81 -10
View File
@@ -284,6 +284,44 @@ function isFlatable(tree: FilterGroupState): boolean {
return true;
}
// pruneIncomplete deep-clones the tree keeping only COMPLETE rules (an
// operator that takes values must have trimmed, non-empty ones), drops
// groups left empty, and can exclude the rule being edited (suggestion
// symmetry). Returns null when nothing complete remains — callers then
// send NO tree at all (an empty group is a server-side 400).
function pruneIncomplete(
group: FilterGroupState,
excludePath: number[] | null,
path: number[] = [],
): FilterGroupState | null {
const children: (FilterRuleState | FilterGroupState)[] = [];
group.children.forEach((child, idx) => {
const childPath = [...path, idx];
if (excludePath && childPath.join("-") === excludePath.join("-")) return;
if (!isRule(child)) {
const pruned = pruneIncomplete(child, excludePath, childPath);
if (pruned && pruned.children.length > 0) children.push(pruned);
return;
}
const arity = OPS[child.op]?.arity ?? "many";
const vals = (child.values ?? []).map((v) => (v ?? "").trim());
if (arity === "none") {
children.push({ field: child.field, op: child.op, values: [] });
return;
}
const kept = vals.filter((v) => v !== "");
if (kept.length === 0) return;
if (arity === "two") {
if (kept.length < 2) return;
children.push({ field: child.field, op: child.op, values: vals });
return;
}
children.push({ field: child.field, op: child.op, values: [kept.join(",")] });
});
if (children.length === 0) return null;
return { mode: group.mode, children };
}
// ─── row projection (flat rendering of the nested tree) ─────────────
export interface BuilderRow {
@@ -356,6 +394,7 @@ export function filterBuilderData() {
matchCount: null as number | null,
matchCountLoading: false,
openMenu: "" as string, // "<rowKey>:field" | "<rowKey>:op" | "<rowKey>:value" | ""
fieldFilter: "" as string, // the field menu's filter input
suggestions: {} as Record<string, Suggestion[]>,
suggestionsOpen: "" as string, // rowKey whose value menu is open
idLabels: {} as Record<string, string>, // id → display, from suggestion fetches
@@ -530,11 +569,29 @@ export function filterBuilderData() {
// ── menus ───────────────────────────────────────────────────────
toggleMenu(menuKey: string): void {
this.openMenu = this.openMenu === menuKey ? "" : menuKey;
if (this.openMenu.endsWith(":field")) {
this.fieldFilter = "";
}
if (this.openMenu.endsWith(":value")) {
this.suggestionsOpen = this.openMenu.split(":")[0];
}
},
// visibleFieldGroups — the field menu's groups, filtered by the
// menu's filter input (label or key substring, case-insensitive);
// groups with no matches hide.
get visibleFieldGroups(): { group: string; fields: FieldMeta[] }[] {
const q = this.fieldFilter.trim().toLowerCase();
if (!q) return FIELD_GROUPS;
return FIELD_GROUPS.map((g) => ({
group: g.group,
fields: g.fields.filter(
(f) =>
f.label.toLowerCase().includes(q) || f.key.toLowerCase().includes(q),
),
})).filter((g) => g.fields.length > 0);
},
// ── suggestions (field-aware, under the OTHER rules) ────────────
scheduleSuggestions(rowKey: string, path: number[], rule: FilterRuleState): void {
if (this._suggestTimer !== null) window.clearTimeout(this._suggestTimer);
@@ -552,10 +609,11 @@ export function filterBuilderData() {
const token = localStorage.getItem("token");
if (!token) return;
// Symmetry: the tree sent EXCLUDES the rule being edited — the
// menu is computed under every OTHER completed rule.
const others = this.treeWithout(path);
// menu is computed under every OTHER COMPLETED rule (incomplete
// rules are not filters; sending them would be a 400).
const others = this.completedTree(path);
const params = new URLSearchParams();
params.set(meta.valueKind === "id" ? rule.field : rule.field, typed.trim() || " ");
params.set(rule.field, typed.trim() || " ");
if (others) params.set("qf", JSON.stringify(others));
const currentLibraryId = (
document.getElementById("library-select") as HTMLSelectElement
@@ -611,12 +669,15 @@ export function filterBuilderData() {
async fetchMatchCount(): Promise<void> {
const token = localStorage.getItem("token");
if (!token) return;
if (this.filterTree.children.length === 0) {
// Incomplete rules are NOT filters yet — the count runs on the
// completed tree only (an incomplete rule would be a 400).
const completed = this.completedTree(null);
if (!completed) {
this.matchCount = null;
return;
}
const params = new URLSearchParams();
params.set("qf", JSON.stringify(this.filterTree));
params.set("qf", JSON.stringify(completed));
const currentLibraryId = (
document.getElementById("library-select") as HTMLSelectElement
)?.value;
@@ -658,18 +719,28 @@ export function filterBuilderData() {
serializeFilters():
| { mode: "flat"; params: Record<string, string> }
| { mode: "qf"; qf: string } {
if (this.filterTree.children.length === 0) {
// The COMPLETED tree is what the wire sees — an incomplete rule
// was never a filter, so applying must not send it (the server
// would 400 and the grid would break).
const completed = this.completedTree(null);
if (!completed) {
return { mode: "flat", params: {} };
}
if (isFlatable(this.filterTree as FilterGroupState)) {
if (isFlatable(completed)) {
const params: Record<string, string> = {};
for (const child of this.filterTree.children) {
for (const child of completed.children) {
if (!isRule(child)) continue;
Object.assign(params, ruleToFlatParam(child));
const rule = child as FilterRuleState;
Object.assign(params, ruleToFlatParam(rule));
}
return { mode: "flat", params };
}
return { mode: "qf", qf: JSON.stringify(this.filterTree) };
return { mode: "qf", qf: JSON.stringify(completed) };
},
// completedTree — the pruned clone (see pruneIncomplete).
completedTree(excludePath: number[] | null): FilterGroupState | null {
return pruneIncomplete(this.filterTree as FilterGroupState, excludePath);
},
syncFormInputs(): void {
const form = document.getElementById("filter-form") as HTMLFormElement | null;
+6 -1
View File
@@ -186,7 +186,12 @@ const suggestionFieldRe =
/[?&](author|narrator|contributor|publisher|imprint|edition|genre|tags|story_arc|age_rating|title|subtitle|language|format_group|mime_type|manga_type|reading_direction|series|note_text|highlight_text|collection|library|added_by)=/;
function isSuggestionFetch(input: Parameters<typeof fetch>[0]): boolean {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
if (!url.includes("/api/media-items/search?")) return false;
// The builder's live-count endpoint is a background hint too — a
// failed count must never interrupt with a toast.
if (!url.includes("/api/media-items/search?") && !url.includes("/api/media-items/filter-count?")) {
return false;
}
if (url.includes("/api/media-items/filter-count?")) return true;
return suggestionFieldRe.test(url) && !/[?&](q|sort)=/.test(url);
}
+35 -4
View File
@@ -1965,11 +1965,41 @@
}
.fb-menu-group {
font-size: 0.65rem;
font-weight: 700;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.05em;
letter-spacing: 0.09em;
color: var(--text-secondary);
padding: 0.5rem 0.75rem 0.15rem;
padding: 0.4rem 0.75rem 0.3rem;
margin-top: 0.3rem;
background-color: color-mix(in srgb, var(--text-primary) 5%, transparent);
border-top: 1px solid var(--border);
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 1;
}
.fb-menu-filter-wrap {
padding: 0.4rem 0.5rem;
border-bottom: 1px solid var(--border);
background-color: var(--bg-primary);
}
.fb-menu-filter {
width: 100%;
font-size: 0.8rem;
padding: 0.3rem 0.5rem;
border-radius: 0.4rem;
border: 1px solid var(--border);
background-color: var(--bg-primary);
color: var(--text-primary);
outline: none;
}
.fb-menu-filter:focus {
border-color: color-mix(in srgb, var(--accent) 45%, var(--border));
}
.fb-menu-empty {
font-size: 0.78rem;
color: var(--text-secondary);
padding: 0.6rem 0.75rem;
}
.fb-menu-item {
display: flex;
@@ -1979,7 +2009,8 @@
gap: 0.5rem;
text-align: left;
font-size: 0.8rem;
padding: 0.35rem 0.75rem;
/* tabbed in under the flush-left group headers */
padding: 0.35rem 0.75rem 0.35rem 1.7rem;
color: var(--text-primary);
cursor: pointer;
}
+1 -1
View File
@@ -1,2 +1,2 @@
*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }
/*! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Noto Sans SC,Noto Sans TC,Noto Sans JP,Noto Sans KR,PingFang SC,Microsoft YaHei,Hiragino Sans,Apple SD Gothic Neo,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}input:where(:not([type])),input:where([type=date]),input:where([type=datetime-local]),input:where([type=email]),input:where([type=month]),input:where([type=number]),input:where([type=password]),input:where([type=search]),input:where([type=tel]),input:where([type=text]),input:where([type=time]),input:where([type=url]),input:where([type=week]),select,select:where([multiple]),textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:#fff;border-color:#6b7280;border-width:1px;border-radius:0;padding:.5rem .75rem;font-size:1rem;line-height:1.5rem;--tw-shadow:0 0 #0000}input:where(:not([type])):focus,input:where([type=date]):focus,input:where([type=datetime-local]):focus,input:where([type=email]):focus,input:where([type=month]):focus,input:where([type=number]):focus,input:where([type=password]):focus,input:where([type=search]):focus,input:where([type=tel]):focus,input:where([type=text]):focus,input:where([type=time]):focus,input:where([type=url]):focus,input:where([type=week]):focus,select:focus,select:where([multiple]):focus,textarea:focus{outline:2px solid transparent;outline-offset:2px;--tw-ring-inset:var(--tw-empty,/*!*/ /*!*/);--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#2563eb;--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow);border-color:#2563eb}input::-moz-placeholder,textarea::-moz-placeholder{color:#6b7280;opacity:1}input::placeholder,textarea::placeholder{color:#6b7280;opacity:1}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-date-and-time-value{min-height:1.5em;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-meridiem-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-year-field{padding-top:0;padding-bottom:0}select{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath Line truncated
/*! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Noto Sans SC,Noto Sans TC,Noto Sans JP,Noto Sans KR,PingFang SC,Microsoft YaHei,Hiragino Sans,Apple SD Gothic Neo,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}input:where(:not([type])),input:where([type=date]),input:where([type=datetime-local]),input:where([type=email]),input:where([type=month]),input:where([type=number]),input:where([type=password]),input:where([type=search]),input:where([type=tel]),input:where([type=text]),input:where([type=time]),input:where([type=url]),input:where([type=week]),select,select:where([multiple]),textarea{-webkit-appearance:none;-moz-appearance:none;appearance:none;background-color:#fff;border-color:#6b7280;border-width:1px;border-radius:0;padding:.5rem .75rem;font-size:1rem;line-height:1.5rem;--tw-shadow:0 0 #0000}input:where(:not([type])):focus,input:where([type=date]):focus,input:where([type=datetime-local]):focus,input:where([type=email]):focus,input:where([type=month]):focus,input:where([type=number]):focus,input:where([type=password]):focus,input:where([type=search]):focus,input:where([type=tel]):focus,input:where([type=text]):focus,input:where([type=time]):focus,input:where([type=url]):focus,input:where([type=week]):focus,select:focus,select:where([multiple]):focus,textarea:focus{outline:2px solid transparent;outline-offset:2px;--tw-ring-inset:var(--tw-empty,/*!*/ /*!*/);--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:#2563eb;--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow);border-color:#2563eb}input::-moz-placeholder,textarea::-moz-placeholder{color:#6b7280;opacity:1}input::placeholder,textarea::placeholder{color:#6b7280;opacity:1}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-date-and-time-value{min-height:1.5em;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit,::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-meridiem-field,::-webkit-datetime-edit-millisecond-field,::-webkit-datetime-edit-minute-field,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-second-field,::-webkit-datetime-edit-year-field{padding-top:0;padding-bottom:0}select{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3E%3Cpath Line truncated