Skip to content

Commit 0535333

Browse files
committed
wip(fields): fillable preference-option arm on RegistryRefField
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L9qibzyvUbUU6pC3x3Amrx
1 parent 23cf11a commit 0535333

2 files changed

Lines changed: 364 additions & 21 deletions

File tree

‎ui/packages/fields/src/widgets/RegistryRefField.tsx‎

Lines changed: 282 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,29 @@
77
*/
88

99
import React from 'react';
10-
import { AlertTriangle } from 'lucide-react';
11-
import { Combobox, EmptyValue, Input, cn } from '@object-ui/components';
12-
import { SchemaRendererContext } from '@object-ui/react';
10+
import { AlertTriangle, Check, ChevronsUpDown } from 'lucide-react';
11+
import {
12+
Button,
13+
Combobox,
14+
Command,
15+
CommandEmpty,
16+
CommandGroup,
17+
CommandInput,
18+
CommandItem,
19+
CommandList,
20+
EmptyValue,
21+
Input,
22+
Popover,
23+
PopoverContent,
24+
PopoverTrigger,
25+
cn,
26+
} from '@object-ui/components';
27+
import { SchemaRendererContext, type ApiFetch } from '@object-ui/react';
1328
import { AUDIENCE_ANCHOR_POSITIONS } from '@objectstack/spec';
1429
import { MCP_AGENT_PERMISSION_SETS } from '@objectstack/spec/ai';
1530
import type { FieldWidgetComponentProps } from './types.js';
16-
import { registryLister, type RegistryItemHeader } from './registryCatalog.js';
31+
import { registryLister, type RegistryItemHeader, type RegistryLister } from './registryCatalog.js';
32+
import { loadPreferenceOptions, type PreferenceList, type PreferenceOptionItem } from './preferenceOptions.js';
1733
import { toDomProps } from './toDomProps.js';
1834
import { useFieldTranslation } from './useFieldTranslation.js';
1935

@@ -67,6 +83,23 @@ import { useFieldTranslation } from './useFieldTranslation.js';
6783
*
6884
* ⛔ No arm writes anything but a name the person picked or typed: no label,
6985
* no id, no first-item default.
86+
*
87+
* ## The fillable arm — `notification-topic` / `notification-channel`
88+
*
89+
* A notification preference's `topic` and `channel`, and a template's `topic`,
90+
* are free text the server stores as written (#30208 row 6, ruling E on
91+
* #30527): the list is a suggestion, never a closed set. So the same four-arm
92+
* machinery reads a different catalog — the preference options door
93+
* (`./preferenceOptions.ts`), through the host's authenticated fetch — and
94+
* differs from the registry arm in exactly what an open list needs:
95+
*
96+
* - FAILED, IDLE or an empty list: the plain text box, with no notice;
97+
* - LOADED: a picker that lists the served values in the door's order (`*`
98+
* first) and ALSO commits whatever the person types, verbatim;
99+
* - a stored or typed value the list does not hold is kept, marked "not in
100+
* the list" — never refused, never rewritten;
101+
* - a channel the door marks not configured is listed, labelled so, and
102+
* selectable.
70103
*/
71104

72105
export type { RegistryItemHeader };
@@ -123,47 +156,70 @@ function nonGrantableNames(type: string): ReadonlySet<string> {
123156
return NO_EXCLUSIONS;
124157
}
125158

159+
/**
160+
* Where a catalog is read from: whether an origin can answer at all, and the
161+
* read. One module-level reader per arm, so the read's identity never moves
162+
* between renders.
163+
*/
164+
interface CatalogReader<Origin> {
165+
readerOf(origin: unknown): Origin | null;
166+
read(origin: Origin, list: string): Promise<RegistryItemHeader[]>;
167+
}
168+
169+
/** The registry arm: `DataSource.listMetadataItems(type)`. */
170+
const REGISTRY_READER: CatalogReader<RegistryLister> = {
171+
readerOf: registryLister,
172+
read: (source, type) => source.listMetadataItems(type),
173+
};
174+
175+
/** The fillable arm: the preference options door, through the host's fetch. */
176+
const PREFERENCE_READER: CatalogReader<ApiFetch> = {
177+
readerOf: (origin) => (typeof origin === 'function' ? (origin as ApiFetch) : null),
178+
read: (doFetch, list) => loadPreferenceOptions(doFetch).then((options) => options[list as PreferenceList]),
179+
};
180+
126181
/** A settled answer, with the inputs it answers for. */
127182
interface SettledCatalog {
128-
dataSource: unknown;
129-
type: string;
183+
origin: unknown;
184+
list: string;
130185
state: RegistryCatalogState;
131186
}
132187

133188
/**
134-
* Load one registry type's catalog. Keyed on the data source and the type it
135-
* reads — the inputs the request is made from — and nothing memoised.
189+
* Load one catalog. Keyed on the origin it is read from (the data source, or
190+
* the host's fetch) and the list it reads — the inputs the request is made
191+
* from — and nothing memoised.
136192
*
137193
* The arm is DERIVED from those inputs on every render rather than written
138-
* into state ahead of the request: no lister is IDLE, and a lister whose
139-
* answer for exactly these inputs has not settled is LOADING. So an answer to
140-
* an older data source or type can never be shown as the current one, and the
141-
* effect only ever writes a settled answer.
194+
* into state ahead of the request: an origin that cannot answer is IDLE, and
195+
* one whose answer for exactly these inputs has not settled is LOADING. So an
196+
* answer to an older origin or list can never be shown as the current one, and
197+
* the effect only ever writes a settled answer.
142198
*/
143-
function useRegistryCatalog(dataSource: unknown, type: string): RegistryCatalogState {
199+
function useCatalog<Origin>(reader: CatalogReader<Origin>, origin: unknown, list: string): RegistryCatalogState {
144200
const [settled, setSettled] = React.useState<SettledCatalog | null>(null);
145201

146202
React.useEffect(() => {
147-
const source = registryLister(dataSource);
203+
const source = reader.readerOf(origin);
148204
if (!source) return;
149205
let cancelled = false;
150-
source.listMetadataItems(type).then(
206+
reader.read(source, list).then(
151207
(items) => {
152-
if (!cancelled) setSettled({ dataSource, type, state: { status: 'loaded', items } });
208+
if (!cancelled) setSettled({ origin, list, state: { status: 'loaded', items } });
153209
},
154210
(err: unknown) => {
155211
if (!cancelled) {
156-
setSettled({ dataSource, type, state: { status: 'error', message: failureMessage(err) } });
212+
setSettled({ origin, list, state: { status: 'error', message: failureMessage(err) } });
157213
}
158214
},
159215
);
160216
return () => {
161217
cancelled = true;
162218
};
163-
}, [dataSource, type]);
219+
}, [reader, origin, list]);
164220

165-
if (!registryLister(dataSource)) return IDLE;
166-
return settled && settled.dataSource === dataSource && settled.type === type ? settled.state : LOADING;
221+
if (!reader.readerOf(origin)) return IDLE;
222+
return settled && settled.origin === origin && settled.list === list ? settled.state : LOADING;
167223
}
168224

169225
/** What one item reads as: its label beside its name, or the name alone. */
@@ -188,7 +244,7 @@ export function RegistryRefField({
188244
const ctx = React.useContext(SchemaRendererContext);
189245
const { t } = useFieldTranslation();
190246
const dataSource = props.dataSource ?? ctx?.dataSource ?? null;
191-
const catalog = useRegistryCatalog(dataSource, registryType);
247+
const catalog = useCatalog(REGISTRY_READER, dataSource, registryType);
192248
const excluded = nonGrantableNames(registryType);
193249
const current = typeof value === 'string' ? value : '';
194250
const testId = `registry-ref-${registryType}`;
@@ -304,4 +360,209 @@ export function PermissionRefField(props: FieldWidgetComponentProps<string>) {
304360
return <RegistryRefField {...props} registryType="permission" />;
305361
}
306362

363+
/** What one listed preference value reads as. */
364+
function preferenceText(
365+
item: PreferenceOptionItem,
366+
list: PreferenceList,
367+
t: (key: string, params?: Record<string, unknown>) => string,
368+
): string {
369+
if (item.wildcard) {
370+
return t(list === 'topics' ? 'fields.preferenceOption.allTopics' : 'fields.preferenceOption.allChannels', {
371+
value: item.name,
372+
});
373+
}
374+
if (!item.configured) return t('fields.preferenceOption.notConfigured', { value: item.name });
375+
return item.name;
376+
}
377+
378+
interface FillableOption {
379+
value: string;
380+
label: string;
381+
notConfigured: boolean;
382+
}
383+
384+
function matchesSearch(option: FillableOption, needle: string): boolean {
385+
if (!needle) return true;
386+
const q = needle.toLowerCase();
387+
return option.value.toLowerCase().includes(q) || option.label.toLowerCase().includes(q);
388+
}
389+
390+
export interface PreferenceOptionFieldProps extends FieldWidgetComponentProps<string> {
391+
/** Which of the preference options door's two lists this field offers. */
392+
preferenceList: PreferenceList;
393+
}
394+
395+
/**
396+
* The fillable arm (see the file header): a value from the preference options
397+
* list, or whatever the person types.
398+
*/
399+
export function PreferenceOptionField({
400+
preferenceList,
401+
value,
402+
onChange,
403+
readonly,
404+
className,
405+
error,
406+
...props
407+
}: PreferenceOptionFieldProps) {
408+
const ctx = React.useContext(SchemaRendererContext);
409+
const { t } = useFieldTranslation();
410+
const doFetch: ApiFetch | undefined = ctx?.apiFetch ?? (typeof fetch === 'function' ? fetch : undefined);
411+
const catalog = useCatalog(PREFERENCE_READER, doFetch, preferenceList);
412+
const [open, setOpen] = React.useState(false);
413+
const [search, setSearch] = React.useState('');
414+
const current = typeof value === 'string' ? value : '';
415+
const testId = `preference-option-${preferenceList}`;
416+
417+
const listed = catalog.status === 'loaded' ? (catalog.items as PreferenceOptionItem[]) : null;
418+
const entry = listed?.find((item) => item.name === current);
419+
const notInList = listed !== null && listed.length > 0 && current !== '' && !entry;
420+
const notInListText = t('fields.preferenceOption.notInList', { value: current });
421+
422+
if (readonly) {
423+
if (!current) return <EmptyValue />;
424+
return (
425+
<span className={cn('text-sm', className)} data-testid={testId} data-not-in-list={notInList || undefined}>
426+
{notInList ? notInListText : entry ? preferenceText(entry, preferenceList, t) : current}
427+
</span>
428+
);
429+
}
430+
431+
const domProps = toDomProps(props);
432+
const disabled = props.disabled;
433+
434+
if (catalog.status === 'loading') {
435+
return (
436+
<Input
437+
{...domProps}
438+
data-testid={`${testId}-input`}
439+
value={current}
440+
disabled
441+
readOnly
442+
placeholder={t('common.loading')}
443+
className={className}
444+
aria-invalid={!!error}
445+
/>
446+
);
447+
}
448+
449+
// A failed or empty answer is no list at all: the plain text box, with no
450+
// notice, writing exactly what is typed.
451+
if (!listed || listed.length === 0) {
452+
return (
453+
<Input
454+
{...domProps}
455+
data-testid={`${testId}-input`}
456+
value={current}
457+
onChange={(e) => onChange(e.target.value)}
458+
disabled={disabled}
459+
className={className}
460+
aria-invalid={!!error}
461+
/>
462+
);
463+
}
464+
465+
const options: FillableOption[] = listed.map((item) => ({
466+
value: item.name,
467+
label: preferenceText(item, preferenceList, t),
468+
notConfigured: !item.configured,
469+
}));
470+
// A stored value the list does not hold stays its own option, marked.
471+
if (notInList) options.unshift({ value: current, label: notInListText, notConfigured: false });
472+
473+
const filtered = options.filter((option) => matchesSearch(option, search.trim()));
474+
// The typed text is offered as written whenever it is not already a value.
475+
const offerTyped = search.trim() !== '' && !options.some((option) => option.value === search);
476+
const commit = (next: string) => {
477+
onChange(next);
478+
setOpen(false);
479+
setSearch('');
480+
};
481+
482+
// DOM pass-through onto the trigger, the widget's focusable control
483+
// (objectui#3318). `name` is withheld: the trigger is a button, not a
484+
// submission control (the `ObjectRefField` reasoning).
485+
const { name: _domName, ...triggerDomProps } = domProps;
486+
return (
487+
<Popover
488+
open={open}
489+
onOpenChange={(next) => {
490+
setOpen(next);
491+
if (!next) setSearch('');
492+
}}
493+
>
494+
<PopoverTrigger asChild>
495+
<Button
496+
type="button"
497+
{...triggerDomProps}
498+
variant="outline"
499+
role="combobox"
500+
aria-expanded={open}
501+
aria-invalid={!!error}
502+
data-testid={testId}
503+
data-not-in-list={notInList || undefined}
504+
disabled={disabled}
505+
className={cn('w-full min-w-0 justify-between font-normal', className)}
506+
>
507+
<span className={cn('truncate', !current && 'text-muted-foreground')}>
508+
{current ? (options.find((option) => option.value === current)?.label ?? current) : t('common.select')}
509+
</span>
510+
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
511+
</Button>
512+
</PopoverTrigger>
513+
<PopoverContent className="w-[var(--radix-popover-trigger-width)] min-w-[200px] p-0">
514+
<Command shouldFilter={false}>
515+
<CommandInput
516+
value={search}
517+
onValueChange={setSearch}
518+
placeholder={t('table.search')}
519+
data-testid={`${testId}-search`}
520+
/>
521+
<CommandList>
522+
{!offerTyped && filtered.length === 0 ? <CommandEmpty>{t('common.noResults')}</CommandEmpty> : null}
523+
{offerTyped ? (
524+
<CommandGroup>
525+
<CommandItem
526+
value={`typed:${search}`}
527+
onSelect={() => commit(search)}
528+
data-testid={`${testId}-use-typed`}
529+
>
530+
{t('fields.preferenceOption.useTyped', { value: search })}
531+
</CommandItem>
532+
</CommandGroup>
533+
) : null}
534+
{filtered.length > 0 ? (
535+
<CommandGroup>
536+
{filtered.map((option) => (
537+
<CommandItem
538+
key={option.value}
539+
value={`listed:${option.value}`}
540+
onSelect={() => commit(option.value)}
541+
data-not-configured={option.notConfigured || undefined}
542+
>
543+
<Check
544+
className={cn('mr-2 h-4 w-4', current === option.value ? 'opacity-100' : 'opacity-0')}
545+
/>
546+
{option.label}
547+
</CommandItem>
548+
))}
549+
</CommandGroup>
550+
) : null}
551+
</CommandList>
552+
</Command>
553+
</PopoverContent>
554+
</Popover>
555+
);
556+
}
557+
558+
/** `notification-topic`: a notification topic, from the list or typed. */
559+
export function NotificationTopicField(props: FieldWidgetComponentProps<string>) {
560+
return <PreferenceOptionField {...props} preferenceList="topics" />;
561+
}
562+
563+
/** `notification-channel`: a notification channel, from the list or typed. */
564+
export function NotificationChannelField(props: FieldWidgetComponentProps<string>) {
565+
return <PreferenceOptionField {...props} preferenceList="channels" />;
566+
}
567+
307568
export default RegistryRefField;

0 commit comments

Comments
 (0)