@field-studio/sdk 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +131 -2
  3. package/dist/index.d.ts +97 -0
  4. package/dist/index.js +129 -0
  5. package/dist/node/identity.d.ts +68 -0
  6. package/dist/node/identity.js +1 -0
  7. package/dist/node/index.d.ts +41 -0
  8. package/dist/node/index.js +165 -0
  9. package/dist/react/agent/AgentEditor.d.ts +16 -0
  10. package/dist/react/agent/AgentEditor.js +51 -0
  11. package/dist/react/agent/MCPManager.d.ts +12 -0
  12. package/dist/react/agent/MCPManager.js +72 -0
  13. package/dist/react/agent/SkillImport.d.ts +8 -0
  14. package/dist/react/agent/SkillImport.js +31 -0
  15. package/dist/react/agent/SkillViewer.d.ts +7 -0
  16. package/dist/react/agent/SkillViewer.js +61 -0
  17. package/dist/react/agent/catalog.css +205 -0
  18. package/dist/react/agent/index.d.ts +7 -0
  19. package/dist/react/agent/index.js +5 -0
  20. package/dist/react/agent/skillTitle.d.ts +3 -0
  21. package/dist/react/agent/skillTitle.js +4 -0
  22. package/dist/react/agent/types.d.ts +46 -0
  23. package/dist/react/agent/types.js +1 -0
  24. package/dist/react/assistant/AssistantPanel.d.ts +15 -0
  25. package/dist/react/assistant/AssistantPanel.js +144 -0
  26. package/dist/react/assistant/AssistantProvider.d.ts +119 -0
  27. package/dist/react/assistant/AssistantProvider.js +427 -0
  28. package/dist/react/assistant/QuestionPanel.d.ts +8 -0
  29. package/dist/react/assistant/QuestionPanel.js +32 -0
  30. package/dist/react/assistant/TaskComposer.d.ts +25 -0
  31. package/dist/react/assistant/TaskComposer.js +354 -0
  32. package/dist/react/assistant/TaskFiles.d.ts +24 -0
  33. package/dist/react/assistant/TaskFiles.js +107 -0
  34. package/dist/react/assistant/assistant.css +428 -0
  35. package/dist/react/assistant/composer.css +116 -0
  36. package/dist/react/assistant/files.css +19 -0
  37. package/dist/react/assistant/index.d.ts +10 -0
  38. package/dist/react/assistant/index.js +6 -0
  39. package/dist/react/assistant/layout.d.ts +7 -0
  40. package/dist/react/assistant/layout.js +19 -0
  41. package/dist/react/assistant/messages.d.ts +355 -0
  42. package/dist/react/assistant/messages.js +239 -0
  43. package/dist/react/assistant/questions.css +6 -0
  44. package/dist/react/assistant/types.d.ts +85 -0
  45. package/dist/react/assistant/types.js +1 -0
  46. package/dist/react/auth/AuthShell.d.ts +35 -0
  47. package/dist/react/auth/AuthShell.js +197 -0
  48. package/dist/react/auth/RoleManager.d.ts +23 -0
  49. package/dist/react/auth/RoleManager.js +95 -0
  50. package/dist/react/auth/auth.css +70 -0
  51. package/dist/react/auth/index.d.ts +2 -0
  52. package/dist/react/auth/index.js +1 -0
  53. package/dist/react/index.d.ts +57 -0
  54. package/dist/react/index.js +177 -0
  55. package/dist/react/ui/Controls.d.ts +78 -0
  56. package/dist/react/ui/Controls.js +234 -0
  57. package/dist/react/ui/base.css +261 -0
  58. package/dist/react/ui/controls.css +35 -0
  59. package/dist/react/ui/index.d.ts +2 -0
  60. package/dist/react/ui/index.js +2 -0
  61. package/dist/workspace.d.ts +107 -0
  62. package/dist/workspace.js +139 -0
  63. package/package.json +86 -3
@@ -0,0 +1,177 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useAssistantDisplay } from './assistant/messages.js';
3
+ import { createContext, useContext, useEffect, useMemo, useRef, useState, } from 'react';
4
+ const PlatformContext = createContext(null);
5
+ const ActionContext = createContext(null);
6
+ function createActionBridge(client) {
7
+ let registration = null;
8
+ const completed = new Map();
9
+ const delivered = new Set();
10
+ const pending = new Map();
11
+ return {
12
+ registerActions(handlers, view) {
13
+ const entry = { handlers, view };
14
+ registration = entry;
15
+ return () => {
16
+ if (registration === entry)
17
+ registration = null;
18
+ };
19
+ },
20
+ handleAction(taskId, action) {
21
+ if (!action || !/^[A-Za-z0-9_-]+$/.test(action.id))
22
+ return Promise.reject(new Error('Invalid UI action'));
23
+ const key = taskId + ':' + action.id;
24
+ if (delivered.has(key))
25
+ return Promise.resolve();
26
+ const running = pending.get(key);
27
+ if (running)
28
+ return running;
29
+ const operation = (async () => {
30
+ const fingerprint = JSON.stringify(action);
31
+ let record = completed.get(key);
32
+ if (record && record.fingerprint !== fingerprint)
33
+ throw new Error('UI action changed');
34
+ if (!record) {
35
+ const entry = registration;
36
+ const view = entry?.view(action);
37
+ const handler = entry?.handlers[action.name];
38
+ const body = {
39
+ status: 'rejected',
40
+ view_instance_id: action.view_instance_id,
41
+ from_revision: action.revision,
42
+ to_revision: view?.revision ?? action.revision,
43
+ };
44
+ if (!view ||
45
+ action.view_instance_id !== view.view_instance_id ||
46
+ action.revision !== view.revision)
47
+ body.error_code = 'CONTEXT_STALE';
48
+ else if (!Number.isFinite(Date.parse(action.expires_at)) ||
49
+ Date.parse(action.expires_at) <= Date.now()) {
50
+ body.status = 'expired';
51
+ body.error_code = 'ACTION_EXPIRED';
52
+ }
53
+ else if (!handler ||
54
+ !['navigation', 'filter', 'draft'].includes(handler.kind))
55
+ body.error_code = 'ACTION_NOT_REGISTERED';
56
+ else if (view.hasDraft)
57
+ body.error_code = 'UNSAVED_DRAFT';
58
+ else if (!action.arguments ||
59
+ typeof action.arguments !== 'object' ||
60
+ Array.isArray(action.arguments))
61
+ body.error_code = 'INVALID_ARGUMENTS';
62
+ else {
63
+ try {
64
+ body.result = await handler.handle(action.arguments);
65
+ body.status = 'succeeded';
66
+ body.to_revision = entry.view(action).revision;
67
+ }
68
+ catch {
69
+ body.status = 'failed';
70
+ body.error_code = 'ACTION_FAILED';
71
+ }
72
+ }
73
+ record = { fingerprint, body };
74
+ completed.set(key, record);
75
+ }
76
+ await client.tasks.actionResult(taskId, action.id, record.body, {
77
+ idempotencyKey: 'ui-action:' + key,
78
+ });
79
+ delivered.add(key);
80
+ })();
81
+ pending.set(key, operation);
82
+ void operation.finally(() => pending.delete(key)).catch(() => { });
83
+ return operation;
84
+ },
85
+ };
86
+ }
87
+ /** Share one explicit host workspace transport with all platform components. */
88
+ export function PlatformProvider({ client, children, }) {
89
+ const bridge = useMemo(() => createActionBridge(client), [client]);
90
+ return (_jsx(PlatformContext.Provider, { value: client, children: _jsx(ActionContext.Provider, { value: bridge, children: children }) }));
91
+ }
92
+ /** Access the host-provided client without changing global fetch or credentials. */
93
+ export function usePlatform() {
94
+ const client = useContext(PlatformContext);
95
+ if (!client)
96
+ throw new Error('PlatformProvider is required');
97
+ return client;
98
+ }
99
+ /** Poll authoritative task state; cancel pending reads and timers when the task or host changes. */
100
+ export function useTaskSubscription(id, interval = 1500) {
101
+ const client = usePlatform();
102
+ const [data, setData] = useState(null);
103
+ const [error, setError] = useState(null);
104
+ useEffect(() => {
105
+ let active = true;
106
+ let timer;
107
+ const controller = new AbortController();
108
+ setData(null);
109
+ setError(null);
110
+ async function read() {
111
+ try {
112
+ const next = await client.request(`/tasks/${encodeURIComponent(id)}`, {
113
+ signal: controller.signal,
114
+ });
115
+ if (!active)
116
+ return;
117
+ setData(next);
118
+ if (!['completed', 'succeeded', 'failed', 'cancelled'].includes(next.status))
119
+ timer = setTimeout(() => void read(), interval);
120
+ }
121
+ catch (e) {
122
+ if (active)
123
+ setError(e instanceof Error ? e : new Error('Task unavailable'));
124
+ }
125
+ }
126
+ if (id)
127
+ void read();
128
+ return () => {
129
+ active = false;
130
+ controller.abort();
131
+ if (timer)
132
+ clearTimeout(timer);
133
+ };
134
+ }, [client, id, interval]);
135
+ return { data, error };
136
+ }
137
+ /** Register only local UI effects and handle view-bound server requests. */
138
+ export function usePlatformActions() {
139
+ const bridge = useContext(ActionContext);
140
+ if (!bridge)
141
+ throw new Error('PlatformProvider is required');
142
+ return bridge;
143
+ }
144
+ /** Collect human acceptance or a revision request without invoking business approvals. */
145
+ export function TaskReviewControls({ task, busy = false, onReview, }) {
146
+ const { messages } = useAssistantDisplay();
147
+ const [editing, setEditing] = useState(false), [comment, setComment] = useState(''), [saving, setSaving] = useState(false), [error, setError] = useState('');
148
+ const intent = useRef(null);
149
+ if (!task.hasResult || !['completed', 'succeeded', 'failed'].includes(task.status))
150
+ return null;
151
+ const disabled = busy || saving;
152
+ async function submit(decision) {
153
+ const text = decision === 'changes_requested' ? comment.trim() : '';
154
+ if (disabled || (decision === 'changes_requested' && !text))
155
+ return;
156
+ const signature = JSON.stringify([task.id, task.version, decision, text]);
157
+ if (intent.current?.signature !== signature)
158
+ intent.current = { signature, value: { idempotencyKey: crypto.randomUUID() } };
159
+ setSaving(true);
160
+ setError('');
161
+ try {
162
+ await onReview(decision, text, intent.current.value);
163
+ setEditing(false);
164
+ setComment('');
165
+ }
166
+ catch (e) {
167
+ setError(e instanceof Error ? e.message : messages.reviewError);
168
+ }
169
+ finally {
170
+ setSaving(false);
171
+ }
172
+ }
173
+ return (_jsxs("section", { className: "task-review", "aria-label": messages.review, children: [_jsx("h4", { children: messages.review }), task.reviewStatus === 'accepted' ? (_jsx("p", { role: "status", children: messages.accepted })) : task.reviewStatus === 'changes_requested' ? (_jsx("p", { role: "status", children: messages.changesRequested })) : (_jsxs(_Fragment, { children: [_jsx("p", { className: "muted", children: messages.reviewHint }), _jsxs("div", { className: "action-row", children: [_jsx("button", { className: "button small", disabled: disabled, onClick: () => void submit('accepted'), children: messages.accept }), _jsx("button", { className: "button small", disabled: disabled, onClick: () => setEditing(true), children: messages.requestChanges })] }), editing && (_jsxs("form", { onSubmit: (event) => {
174
+ event.preventDefault();
175
+ void submit('changes_requested');
176
+ }, children: [_jsxs("label", { children: [messages.reason, _jsx("textarea", { required: true, maxLength: 2000, rows: 2, value: comment, disabled: disabled, onChange: (event) => setComment(event.target.value) })] }), _jsxs("div", { className: "action-row", children: [_jsx("button", { className: "button small", disabled: disabled || !comment.trim(), children: messages.submitChanges }), _jsx("button", { type: "button", className: "button small", disabled: disabled, onClick: () => setEditing(false), children: messages.cancel })] })] }))] })), error && _jsx("p", { role: "alert", children: error })] }));
177
+ }
@@ -0,0 +1,78 @@
1
+ import { type ButtonHTMLAttributes, type ReactNode, type RefObject } from 'react';
2
+ import './controls.css';
3
+ type SelectProps = {
4
+ children: ReactNode;
5
+ value?: string | number;
6
+ defaultValue?: string | number;
7
+ name?: string;
8
+ id?: string;
9
+ disabled?: boolean;
10
+ required?: boolean;
11
+ className?: string;
12
+ selectedLabel?: ReactNode;
13
+ 'aria-label'?: string;
14
+ onChange?: (event: {
15
+ target: {
16
+ value: string;
17
+ };
18
+ }) => void;
19
+ };
20
+ /** Choose an option with a project-styled popup and native form value. */
21
+ export declare function Select({ children, value, defaultValue, name, id, disabled, required, className, selectedLabel, onChange, ...aria }: SelectProps): import("react").JSX.Element;
22
+ type DialogRegion = {
23
+ background: RefObject<HTMLElement | null>;
24
+ portal: RefObject<HTMLElement | null>;
25
+ overlayClassName: string;
26
+ };
27
+ /** Limit dialogs to a host surface while sibling surfaces remain interactive. */
28
+ export declare function DialogScope({ background, portal, overlayClassName, children }: DialogRegion & {
29
+ children: ReactNode;
30
+ }): import("react").JSX.Element;
31
+ /** Show a dialog with Escape, backdrop dismissal and scope-aware focus. */
32
+ export declare function Dialog({ title, lang, closeLabel, closeOnBackdrop, closeDisabled, onClose, className, children }: {
33
+ title: string;
34
+ lang?: string;
35
+ closeLabel?: string;
36
+ closeOnBackdrop?: boolean;
37
+ closeDisabled?: boolean;
38
+ onClose: () => void;
39
+ className?: string;
40
+ children: ReactNode;
41
+ }): import("react").ReactPortal;
42
+ type CheckboxProps = Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'onChange' | 'value' | 'defaultChecked'> & {
43
+ checked?: boolean;
44
+ defaultChecked?: boolean;
45
+ value?: string;
46
+ onChange?: (event: {
47
+ target: {
48
+ checked: boolean;
49
+ };
50
+ }) => void;
51
+ };
52
+ /** Draw a project checkbox while preserving labels, keyboard activation and form values. */
53
+ export declare function Checkbox({ checked, defaultChecked, value, name, disabled, className, onChange, onClick, ...props }: CheckboxProps): import("react").JSX.Element;
54
+ type RadioOption = {
55
+ value: string;
56
+ label: ReactNode;
57
+ description?: ReactNode;
58
+ disabled?: boolean;
59
+ };
60
+ /** Select one option using project styling, arrow navigation and a single tab stop. */
61
+ export declare function RadioGroup({ options, value, onChange, disabled, name, ...aria }: {
62
+ options: RadioOption[];
63
+ value?: string;
64
+ onChange: (value: string) => void;
65
+ disabled?: boolean;
66
+ name?: string;
67
+ 'aria-label': string;
68
+ }): import("react").JSX.Element;
69
+ /** Open the system file picker through a styled, explicitly labeled control. */
70
+ export declare function FilePicker({ label, files, onChange, accept, multiple, disabled }: {
71
+ label: string;
72
+ files: File[];
73
+ onChange: (files: File[]) => void;
74
+ accept?: string;
75
+ multiple?: boolean;
76
+ disabled?: boolean;
77
+ }): import("react").JSX.Element;
78
+ export {};
@@ -0,0 +1,234 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Children, createContext, isValidElement, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from 'react';
3
+ import { createPortal } from 'react-dom';
4
+ import { Check, ChevronDown, FileUp, X } from 'lucide-react';
5
+ import './controls.css';
6
+ /** Choose an option with a project-styled popup and native form value. */
7
+ export function Select({ children, value, defaultValue, name, id, disabled, required, className = '', selectedLabel, onChange, ...aria }) {
8
+ const dialogScope = useContext(DialogRegionContext);
9
+ const options = Children.toArray(children).filter(isValidElement).map(child => {
10
+ const props = child.props;
11
+ return { value: String(props.value ?? props.children), label: props.children, disabled: props.disabled };
12
+ });
13
+ const [internal, setInternal] = useState(String(defaultValue ?? options.find(option => !option.disabled)?.value ?? ''));
14
+ const selected = String(value ?? internal);
15
+ const [open, setOpen] = useState(false);
16
+ const [active, setActive] = useState(0);
17
+ const [position, setPosition] = useState({ top: 0, left: 0, minWidth: 0, maxWidth: undefined, maxHeight: 240 });
18
+ const trigger = useRef(null);
19
+ const list = useRef(null);
20
+ const listId = useId();
21
+ const enabled = options.map((option, index) => option.disabled ? -1 : index).filter(index => index >= 0);
22
+ const menuBounds = () => {
23
+ const overlay = dialogScope ? trigger.current?.closest('.overlay') : null;
24
+ return overlay?.getBoundingClientRect() ?? { top: 0, left: 0, right: window.innerWidth, bottom: window.innerHeight };
25
+ };
26
+ const show = () => {
27
+ if (disabled || !enabled.length)
28
+ return;
29
+ const rect = trigger.current.getBoundingClientRect();
30
+ const bounds = menuBounds();
31
+ const maxWidth = Math.max(0, bounds.right - bounds.left - 16);
32
+ setPosition({ top: 0, left: 0, minWidth: Math.min(rect.width, maxWidth), maxWidth, maxHeight: 240 });
33
+ const index = options.findIndex(option => option.value === selected && !option.disabled);
34
+ setActive(index >= 0 ? index : enabled[0]);
35
+ setOpen(true);
36
+ };
37
+ useLayoutEffect(() => {
38
+ if (!open || !trigger.current || !list.current)
39
+ return;
40
+ const rect = trigger.current.getBoundingClientRect();
41
+ const menu = list.current.getBoundingClientRect();
42
+ const bounds = menuBounds();
43
+ const below = Math.max(0, bounds.bottom - rect.bottom - 12);
44
+ const above = Math.max(0, rect.top - bounds.top - 12);
45
+ const opensAbove = below < menu.height && above > below;
46
+ const maxHeight = Math.min(240, opensAbove ? above : below);
47
+ const height = Math.min(menu.height, maxHeight);
48
+ setPosition(previous => ({ ...previous,
49
+ top: Math.max(bounds.top + 8, opensAbove ? rect.top - height - 4 : rect.bottom + 4),
50
+ left: Math.max(bounds.left + 8, Math.min(rect.left, bounds.right - menu.width - 8)),
51
+ maxHeight,
52
+ }));
53
+ }, [open]);
54
+ const choose = (index) => {
55
+ const option = options[index];
56
+ if (!option || option.disabled || disabled)
57
+ return;
58
+ setInternal(option.value);
59
+ onChange?.({ target: { value: option.value } });
60
+ setOpen(false);
61
+ trigger.current?.focus();
62
+ };
63
+ useEffect(() => {
64
+ if (!open)
65
+ return;
66
+ const outside = (event) => {
67
+ if (!trigger.current?.contains(event.target) && !list.current?.contains(event.target))
68
+ setOpen(false);
69
+ };
70
+ const close = (event) => {
71
+ if (!(event.target instanceof Node) || !list.current?.contains(event.target))
72
+ setOpen(false);
73
+ };
74
+ document.addEventListener('pointerdown', outside);
75
+ window.addEventListener('resize', close);
76
+ window.addEventListener('scroll', close, true);
77
+ return () => {
78
+ document.removeEventListener('pointerdown', outside);
79
+ window.removeEventListener('resize', close);
80
+ window.removeEventListener('scroll', close, true);
81
+ };
82
+ }, [open]);
83
+ useEffect(() => { if (open)
84
+ list.current?.querySelector('[data-active="true"]')?.scrollIntoView?.({ block: 'nearest' }); }, [active, open]);
85
+ return _jsxs("span", { className: `ui-select ${className}`, children: [_jsxs("button", { ...aria, id: id, ref: trigger, type: "button", className: "ui-select-trigger", role: "combobox", "aria-haspopup": "listbox", "aria-required": required || undefined, "aria-expanded": open, "aria-controls": open ? listId : undefined, "aria-activedescendant": open ? `${listId}-${active}` : undefined, disabled: disabled, onBlur: event => { if (!list.current?.contains(event.relatedTarget))
86
+ setOpen(false); }, onClick: () => open ? setOpen(false) : show(), onKeyDown: event => {
87
+ if (event.key === 'Escape' || event.key === 'Tab') {
88
+ if (event.key === 'Escape' && open)
89
+ event.stopPropagation();
90
+ setOpen(false);
91
+ return;
92
+ }
93
+ if (['ArrowDown', 'ArrowUp', 'Home', 'End', 'Enter', ' '].includes(event.key)) {
94
+ event.preventDefault();
95
+ if (!open) {
96
+ show();
97
+ return;
98
+ }
99
+ if (event.key === 'Enter' || event.key === ' ') {
100
+ choose(active);
101
+ return;
102
+ }
103
+ const current = enabled.indexOf(active);
104
+ setActive(event.key === 'Home' ? enabled[0] : event.key === 'End' ? enabled[enabled.length - 1] : enabled[(current + (event.key === 'ArrowUp' ? -1 : 1) + enabled.length) % enabled.length]);
105
+ }
106
+ else if (event.key.length === 1 && !event.ctrlKey && !event.metaKey) {
107
+ const index = options.findIndex(option => !option.disabled && String(option.label).toLocaleLowerCase().startsWith(event.key.toLocaleLowerCase()));
108
+ if (index >= 0) {
109
+ event.preventDefault();
110
+ if (open)
111
+ setActive(index);
112
+ else
113
+ choose(index);
114
+ }
115
+ }
116
+ }, children: [_jsx("span", { children: selectedLabel ?? options.find(option => option.value === selected)?.label ?? 'Choose an option' }), _jsx(ChevronDown, { size: 14, "aria-hidden": "true" })] }), (name || required) && _jsx("input", { type: required ? "text" : "hidden", className: "ui-select-value", tabIndex: -1, "aria-hidden": "true", name: name, value: selected, required: required, disabled: disabled, onChange: () => { }, onInvalid: event => { event.preventDefault(); trigger.current?.focus(); show(); } }), open && createPortal(_jsx("div", { ref: list, id: listId, role: "listbox", "aria-label": aria['aria-label'] ?? 'Options', className: "ui-select-menu", style: position, children: options.map((option, index) => _jsxs("div", { id: `${listId}-${index}`, role: "option", "aria-selected": selected === option.value, "aria-disabled": option.disabled || undefined, "data-active": active === index, className: "ui-select-option", onPointerDown: event => event.preventDefault(), onMouseDown: event => event.preventDefault(), onClick: () => choose(index), onPointerMove: () => !option.disabled && setActive(index), children: [_jsx("span", { children: option.label }), selected === option.value && _jsx(Check, { size: 14, "aria-hidden": "true" })] }, option.value)) }), document.body)] });
117
+ }
118
+ // Open dialogs register here so only the topmost one reacts to Escape and Tab.
119
+ const dialogStack = [];
120
+ const DialogRegionContext = createContext(null);
121
+ const regionDialogs = new WeakMap();
122
+ /** Limit dialogs to a host surface while sibling surfaces remain interactive. */
123
+ export function DialogScope({ background, portal, overlayClassName, children }) {
124
+ return (_jsx(DialogRegionContext.Provider, { value: { background, portal, overlayClassName }, children: children }));
125
+ }
126
+ /** Show a dialog with Escape, backdrop dismissal and scope-aware focus. */
127
+ export function Dialog({ title, lang, closeLabel = `Close ${title}`, closeOnBackdrop = true, closeDisabled = false, onClose, className = '', children }) {
128
+ const scope = useContext(DialogRegionContext);
129
+ const background = scope?.background;
130
+ const dialog = useRef(null);
131
+ const closeRef = useRef(() => { });
132
+ closeRef.current = () => { if (!closeDisabled)
133
+ onClose(); };
134
+ useLayoutEffect(() => {
135
+ const frame = dialog.current;
136
+ const surface = background?.current;
137
+ const close = () => closeRef.current();
138
+ dialogStack.push(close);
139
+ const previous = document.activeElement;
140
+ if (surface) {
141
+ regionDialogs.set(surface, (regionDialogs.get(surface) ?? 0) + 1);
142
+ surface.setAttribute('inert', '');
143
+ }
144
+ const fields = 'input:not([type=hidden]):not([hidden]):not([tabindex="-1"]):not(:disabled),select:not(:disabled),textarea:not(:disabled)';
145
+ (frame.querySelector(fields) ?? frame.querySelector('button:not(:disabled)') ?? frame).focus();
146
+ const handler = (event) => {
147
+ if (dialogStack[dialogStack.length - 1] !== close)
148
+ return;
149
+ if (surface && !frame.contains(document.activeElement))
150
+ return;
151
+ if (event.key === 'Escape') {
152
+ event.preventDefault();
153
+ close();
154
+ }
155
+ if (event.key === 'Tab' && !surface) {
156
+ const nodes = frame.querySelectorAll(`button:not(:disabled):not([tabindex="-1"]),${fields},a[href]`);
157
+ if (!nodes.length)
158
+ return;
159
+ const first = nodes[0], last = nodes[nodes.length - 1];
160
+ if (event.shiftKey && document.activeElement === first) {
161
+ event.preventDefault();
162
+ last.focus();
163
+ }
164
+ else if (!event.shiftKey && document.activeElement === last) {
165
+ event.preventDefault();
166
+ first.focus();
167
+ }
168
+ }
169
+ };
170
+ document.addEventListener('keydown', handler);
171
+ return () => {
172
+ const index = dialogStack.lastIndexOf(close);
173
+ if (index >= 0)
174
+ dialogStack.splice(index, 1);
175
+ document.removeEventListener('keydown', handler);
176
+ if (surface) {
177
+ const count = (regionDialogs.get(surface) ?? 1) - 1;
178
+ if (count)
179
+ regionDialogs.set(surface, count);
180
+ else {
181
+ regionDialogs.delete(surface);
182
+ surface.removeAttribute('inert');
183
+ }
184
+ }
185
+ if (!surface || frame.contains(document.activeElement) || document.activeElement === document.body)
186
+ previous?.focus();
187
+ };
188
+ }, [background]);
189
+ return createPortal(_jsx("div", { className: scope ? `overlay ${scope.overlayClassName}` : 'overlay', onClick: event => { if (closeOnBackdrop && event.target === event.currentTarget)
190
+ closeRef.current(); }, children: _jsxs("div", { className: `dialog ${className}`.trimEnd(), role: "dialog", lang: lang, "aria-modal": scope ? undefined : true, "aria-label": title, ref: dialog, tabIndex: -1, children: [_jsxs("div", { className: "dialog-header", children: [_jsx("h2", { children: title }), _jsx("button", { type: "button", className: "icon-button", "aria-label": closeLabel, disabled: closeDisabled, onClick: () => closeRef.current(), children: _jsx(X, { size: 18, "aria-hidden": "true" }) })] }), children] }) }), scope?.portal.current ?? document.body);
191
+ }
192
+ /** Draw a project checkbox while preserving labels, keyboard activation and form values. */
193
+ export function Checkbox({ checked, defaultChecked = false, value = 'on', name, disabled, className = '', onChange, onClick, ...props }) {
194
+ const [internal, setInternal] = useState(defaultChecked);
195
+ const selected = checked ?? internal;
196
+ const control = useRef(null);
197
+ useEffect(() => {
198
+ const form = control.current?.closest('form');
199
+ const reset = () => setInternal(defaultChecked);
200
+ form?.addEventListener('reset', reset);
201
+ return () => form?.removeEventListener('reset', reset);
202
+ }, [defaultChecked]);
203
+ return _jsxs(_Fragment, { children: [name && selected && _jsx("input", { type: "hidden", name: name, value: value, disabled: disabled }), _jsx("button", { ...props, ref: control, type: "button", role: "checkbox", "aria-checked": selected, disabled: disabled, className: `ui-checkbox ${className}`, onClick: event => {
204
+ onClick?.(event);
205
+ if (event.defaultPrevented)
206
+ return;
207
+ if (checked === undefined)
208
+ setInternal(!selected);
209
+ onChange?.({ target: { checked: !selected } });
210
+ }, children: selected && _jsx(Check, { size: 13, "aria-hidden": "true" }) })] });
211
+ }
212
+ /** Select one option using project styling, arrow navigation and a single tab stop. */
213
+ export function RadioGroup({ options, value, onChange, disabled = false, name, ...aria }) {
214
+ const controls = useRef([]);
215
+ const enabled = options.map((option, index) => option.disabled ? -1 : index).filter(index => index >= 0);
216
+ const selected = options.findIndex(option => option.value === value && !option.disabled);
217
+ return _jsxs("div", { className: "ui-radio-group", role: "radiogroup", ...aria, "aria-disabled": disabled || undefined, children: [name && value !== undefined && _jsx("input", { type: "hidden", name: name, value: value, disabled: disabled }), options.map((option, index) => _jsxs("button", { ref: element => { controls.current[index] = element; }, className: "ui-radio-option", type: "button", role: "radio", "aria-checked": value === option.value, disabled: disabled || option.disabled, tabIndex: index === (selected >= 0 ? selected : enabled[0]) ? 0 : -1, onClick: () => onChange(option.value), onKeyDown: event => {
218
+ if (!['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp', 'Home', 'End'].includes(event.key))
219
+ return;
220
+ event.preventDefault();
221
+ const position = enabled.indexOf(index);
222
+ const next = event.key === 'Home' ? enabled[0] : event.key === 'End' ? enabled[enabled.length - 1]
223
+ : enabled[(position + (['ArrowLeft', 'ArrowUp'].includes(event.key) ? -1 : 1) + enabled.length) % enabled.length];
224
+ if (next === undefined)
225
+ return;
226
+ onChange(options[next].value);
227
+ controls.current[next]?.focus();
228
+ }, children: [_jsx("span", { className: "ui-radio-mark", "aria-hidden": "true" }), _jsxs("span", { children: [option.label, option.description && _jsx("small", { children: option.description })] })] }, option.value))] });
229
+ }
230
+ /** Open the system file picker through a styled, explicitly labeled control. */
231
+ export function FilePicker({ label, files, onChange, accept, multiple, disabled }) {
232
+ const input = useRef(null);
233
+ return _jsxs("div", { className: "ui-file-picker", children: [_jsx("input", { ref: input, hidden: true, type: "file", "aria-label": label, accept: accept, multiple: multiple, disabled: disabled, onChange: event => { onChange(Array.from(event.target.files ?? [])); event.target.value = ''; } }), _jsxs("button", { type: "button", className: "button ui-file-button", disabled: disabled, onClick: () => input.current?.click(), children: [_jsx(FileUp, { size: 16, "aria-hidden": "true" }), "Select ", label] }), _jsx("span", { className: "ui-file-name", title: files.map(file => file.name).join(', '), children: files.length ? files.map(file => file.name).join(', ') : 'No files selected' })] });
234
+ }