From 30a8f67e8e0de6c239e8c686e4f5ae582361bbcf Mon Sep 17 00:00:00 2001 From: Timothy Date: Sat, 18 Jul 2026 00:58:02 +0200 Subject: [PATCH] feat(176): field-catalog api + useSearchFields hook Task 6: getSearchFields() client fn + SearchField type in api/search.ts, and the useSearchFields() hook in builder/rules/fieldCatalog.ts that reshapes the catalog into fieldTypes (name -> FieldType) and byGroup views for the rule builder (Tasks 7-8). Generated SearchFieldResponseModel has all-nullable fields (name/label/ type/group/values), unlike the brief's non-null assumption -- adapted by dropping fields with a null name and defaulting group to 'Other' / type to 'text' rather than indexing under undefined. --- web/src/api/search.test.ts | 29 +++++++- web/src/api/search.ts | 10 +++ web/src/builder/rules/fieldCatalog.test.ts | 78 ++++++++++++++++++++++ web/src/builder/rules/fieldCatalog.ts | 58 ++++++++++++++++ 4 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 web/src/builder/rules/fieldCatalog.test.ts create mode 100644 web/src/builder/rules/fieldCatalog.ts diff --git a/web/src/api/search.test.ts b/web/src/api/search.test.ts index ed2b5ec22..5a1d28c9c 100644 --- a/web/src/api/search.test.ts +++ b/web/src/api/search.test.ts @@ -1,5 +1,5 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { getSearchAllItems, getSearchResults, toAddItemsRequestFromSearch } from './search'; +import { getSearchAllItems, getSearchFields, getSearchResults, toAddItemsRequestFromSearch } from './search'; const emptyGroup = { totalCount: 0, items: [] }; const sampleResults = { @@ -84,6 +84,33 @@ describe('getSearchAllItems', () => { }); }); +describe('getSearchFields', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('GETs /api/v1/search/fields and returns the parsed array', async () => { + const sampleFields = [ + { name: 'title', label: 'Title', type: 'text', group: 'General', values: null }, + { name: 'year', label: 'Year', type: 'number', group: 'General', values: null } + ]; + const fetchSpy = vi.spyOn(window, 'fetch').mockResolvedValue( + new Response(JSON.stringify(sampleFields), { + headers: { 'Content-Type': 'application/json' }, + status: 200 + }) + ); + + const result = await getSearchFields(); + + const [url, init] = fetchSpy.mock.calls[0]; + expect(url).toBe('/api/v1/search/fields'); + expect((init?.method ?? 'GET').toUpperCase()).toBe('GET'); + expect(result).toEqual(sampleFields); + }); +}); + describe('toAddItemsRequestFromSearch', () => { it('fills every bucket, defaulting null arrays to []', () => { expect( diff --git a/web/src/api/search.ts b/web/src/api/search.ts index f09be2766..1c1d2c607 100644 --- a/web/src/api/search.ts +++ b/web/src/api/search.ts @@ -5,6 +5,16 @@ import type { AddItemsToCollectionRequest } from './collections'; export type SearchResults = components['schemas']['SearchResultsResponseModel']; export type SearchResultGroup = components['schemas']['SearchResultGroupResponseModel']; +// Generated fields are all nullable (open-api-typescript reflects the C# model's nullable strings); +// callers (fieldCatalog.ts) filter out entries missing a name before indexing by it. +export type SearchField = components['schemas']['SearchFieldResponseModel']; + +// Backs the rule builder's field picker (#176): the catalog of fields a search/smart-collection rule +// can filter on, with their type + UI grouping. +export function getSearchFields(): Promise { + return request('/api/v1/search/fields'); +} + // The ten media-item id arrays a search query resolves to, one bucket per addable kind. Wire keys // match AddItemsToCollectionRequest exactly, so a result pipes straight into addItemsToCollection / // addItemsToPlaylist via toAddItemsRequestFromSearch below. diff --git a/web/src/builder/rules/fieldCatalog.test.ts b/web/src/builder/rules/fieldCatalog.test.ts new file mode 100644 index 000000000..119eeae95 --- /dev/null +++ b/web/src/builder/rules/fieldCatalog.test.ts @@ -0,0 +1,78 @@ +import { renderHook, waitFor } from '@testing-library/react'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { useSearchFields } from './fieldCatalog'; + +function jsonResponse(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + headers: { 'Content-Type': 'application/json' }, + status + }); +} + +describe('useSearchFields', () => { + beforeEach(() => { + window.localStorage.clear(); + vi.restoreAllMocks(); + }); + + it('starts loading, then exposes fields/fieldTypes/byGroup on success', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + jsonResponse([ + { name: 'title', label: 'Title', type: 'text', group: 'General', values: null }, + { name: 'year', label: 'Year', type: 'number', group: 'General', values: null }, + { name: 'genre', label: 'Genre', type: 'enum', group: 'Metadata', values: ['Action', 'Drama'] } + ]) + ); + + const { result } = renderHook(() => useSearchFields()); + + expect(result.current.status).toBe('loading'); + + await waitFor(() => expect(result.current.status).toBe('success')); + + expect(result.current.fields).toHaveLength(3); + expect(result.current.fieldTypes).toEqual({ title: 'text', year: 'number', genre: 'enum' }); + expect(result.current.byGroup).toEqual([ + { + group: 'General', + fields: [ + { name: 'title', label: 'Title', type: 'text', group: 'General', values: null }, + { name: 'year', label: 'Year', type: 'number', group: 'General', values: null } + ] + }, + { + group: 'Metadata', + fields: [{ name: 'genre', label: 'Genre', type: 'enum', group: 'Metadata', values: ['Action', 'Drama'] }] + } + ]); + }); + + it('drops fields with a null name and falls back group/type defaults', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue( + jsonResponse([ + { name: null, label: 'Broken', type: 'text', group: 'General', values: null }, + { name: 'untyped', label: 'Untyped', type: null, group: null, values: null } + ]) + ); + + const { result } = renderHook(() => useSearchFields()); + + await waitFor(() => expect(result.current.status).toBe('success')); + + expect(result.current.fields).toHaveLength(1); + expect(result.current.fieldTypes).toEqual({ untyped: 'text' }); + expect(result.current.byGroup).toEqual([ + { group: 'Other', fields: [{ name: 'untyped', label: 'Untyped', type: null, group: null, values: null }] } + ]); + }); + + it('sets status to error when the fetch fails', async () => { + vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ status: 500, title: 'Server error' }, 500)); + + const { result } = renderHook(() => useSearchFields()); + + await waitFor(() => expect(result.current.status).toBe('error')); + + expect(result.current.fields).toEqual([]); + }); +}); diff --git a/web/src/builder/rules/fieldCatalog.ts b/web/src/builder/rules/fieldCatalog.ts new file mode 100644 index 000000000..47d599671 --- /dev/null +++ b/web/src/builder/rules/fieldCatalog.ts @@ -0,0 +1,58 @@ +import { useEffect, useState } from 'react'; +import { getSearchFields, type SearchField } from '../../api/search'; +import type { FieldType } from './types'; + +const DEFAULT_GROUP = 'Other'; +const DEFAULT_FIELD_TYPE: FieldType = 'text'; + +export interface FieldCatalog { + fields: SearchField[]; + fieldTypes: Record; + byGroup: Array<{ group: string; fields: SearchField[] }>; + status: 'loading' | 'success' | 'error'; +} + +// Field-catalog client for the rule builder (#176 Task 6): fetches the server's field list once and +// reshapes it into the two views the builder UI needs — a name -> FieldType lookup (for picking +// operators) and a group -> fields listing (for the field picker). Generated SearchField fields are +// all nullable (open-api-typescript mirrors the C# model's nullable strings), so entries missing a +// `name` are dropped rather than indexed under `undefined`. +export function useSearchFields(): FieldCatalog { + const [fields, setFields] = useState([]); + const [status, setStatus] = useState<'loading' | 'success' | 'error'>('loading'); + + useEffect(() => { + let active = true; + getSearchFields() + .then((f) => { + if (active) { + setFields(f); + setStatus('success'); + } + }) + .catch(() => { + if (active) setStatus('error'); + }); + return () => { + active = false; + }; + }, []); + + const namedFields = fields.filter((f): f is SearchField & { name: string } => Boolean(f.name)); + + const fieldTypes: Record = {}; + for (const f of namedFields) { + fieldTypes[f.name] = (f.type as FieldType | null) ?? DEFAULT_FIELD_TYPE; + } + + const groups = new Map(); + for (const f of namedFields) { + const group = f.group ?? DEFAULT_GROUP; + const list = groups.get(group) ?? []; + list.push(f); + groups.set(group, list); + } + const byGroup = [...groups.entries()].map(([group, gf]) => ({ group, fields: gf })); + + return { fields: namedFields, fieldTypes, byGroup, status }; +}