@cloudlet/toast 1.0.0 → 1.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 (44) hide show
  1. package/CHANGELOG.md +57 -12
  2. package/README.md +20 -6
  3. package/dist/contracts/controller.d.ts +7 -2
  4. package/dist/contracts/controller.d.ts.map +1 -1
  5. package/dist/contracts/internal.d.ts +23 -0
  6. package/dist/contracts/internal.d.ts.map +1 -1
  7. package/dist/contracts/notifications.d.ts +38 -6
  8. package/dist/contracts/notifications.d.ts.map +1 -1
  9. package/dist/contracts/snapshots.d.ts +3 -1
  10. package/dist/contracts/snapshots.d.ts.map +1 -1
  11. package/dist/core/bridge.js +216 -148
  12. package/dist/core/bridge.js.map +1 -1
  13. package/dist/core/controller.d.ts +11 -2
  14. package/dist/core/controller.d.ts.map +1 -1
  15. package/dist/core/controller.js +310 -284
  16. package/dist/core/controller.js.map +1 -1
  17. package/dist/core/validation.d.ts.map +1 -1
  18. package/dist/core/validation.js +181 -89
  19. package/dist/core/validation.js.map +1 -1
  20. package/dist/react/card.d.ts +4 -2
  21. package/dist/react/card.d.ts.map +1 -1
  22. package/dist/react/card.js +146 -34
  23. package/dist/react/card.js.map +1 -1
  24. package/dist/react/host.d.ts.map +1 -1
  25. package/dist/react/host.js +8 -4
  26. package/dist/react/host.js.map +1 -1
  27. package/dist/react/plan.d.ts.map +1 -1
  28. package/dist/react/plan.js +1 -0
  29. package/dist/react/plan.js.map +1 -1
  30. package/dist/react.d.ts +3 -1
  31. package/dist/react.d.ts.map +1 -1
  32. package/dist/styles.css +1 -1
  33. package/package.json +1 -1
  34. package/src/contracts/controller.ts +7 -2
  35. package/src/contracts/internal.ts +20 -0
  36. package/src/contracts/notifications.ts +45 -6
  37. package/src/contracts/snapshots.ts +3 -0
  38. package/src/core/bridge.ts +62 -6
  39. package/src/core/controller.ts +37 -5
  40. package/src/core/validation.ts +49 -4
  41. package/src/react/card.tsx +89 -6
  42. package/src/react/host.tsx +12 -3
  43. package/src/react/plan.ts +2 -1
  44. package/src/react.ts +3 -1
@@ -1,8 +1,8 @@
1
1
  import { Component, Suspense, useEffect, useId, useRef, useState } from 'react';
2
- import type { ComponentPropsWithRef, ReactNode } from 'react';
3
- import type { HostLease, RendererBridge } from '../contracts/internal.js';
2
+ import type { ComponentPropsWithRef, KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';
3
+ import type { FormDraft, HostLease, RendererBridge } from '../contracts/internal.js';
4
4
  import type { NotificationHandle } from '../contracts/identity.js';
5
- import type { NotificationKind } from '../contracts/notifications.js';
5
+ import type { FormAction, FormField, NotificationKind } from '../contracts/notifications.js';
6
6
  import type { NotificationSnapshot } from '../contracts/snapshots.js';
7
7
  import type { CloudletLabels, CloudletPart, ToasterProps } from '../react.js';
8
8
 
@@ -15,6 +15,7 @@ export const defaultLabels: CloudletLabels = {
15
15
  ...(missed > 0 ? [`${missed} missed`] : [])].join(', '),
16
16
  page: (index, total) => `${index} of ${total}`,
17
17
  overflowCount: count => `${count} missed notifications`,
18
+ draft: 'Draft',
18
19
  };
19
20
 
20
21
  interface SlotProps {
@@ -180,9 +181,9 @@ export function SlidePreview({ notification, labels, part }: { notification: Not
180
181
  }
181
182
 
182
183
  /** Island slide body: description, progress, actions and the action error. */
183
- export function Body({ notification, bridge, lease, labels, navigate, slot, part }: {
184
- notification: NotificationSnapshot<ReactNode>; bridge: RendererBridge<ReactNode>; lease: HostLease;
185
- labels: CloudletLabels; navigate: (handle: NotificationHandle) => void; slot: (value: ReactNode) => ReactNode; part: PartClass;
184
+ export function Body({ notification, form, bridge, lease, labels, navigate, slot, part, titleId }: {
185
+ notification: NotificationSnapshot<ReactNode>; form: FormDraft | undefined; bridge: RendererBridge<ReactNode>; lease: HostLease;
186
+ labels: CloudletLabels; navigate: (handle: NotificationHandle) => void; slot: (value: ReactNode) => ReactNode; part: PartClass; titleId: string;
186
187
  }) {
187
188
  const { handle, content, operation, action, kind } = notification;
188
189
  // The primary action is tinted with the status; retry and cancel stay neutral.
@@ -199,6 +200,8 @@ export function Body({ notification, bridge, lease, labels, navigate, slot, part
199
200
  {content.description.kind === 'text' && <p>{content.description.text}</p>}
200
201
  {content.description.kind === 'rich' && slot(content.description.content)}
201
202
  </div>}
203
+ {command?.kind === 'form' && form && <Form key={formKey(command)} action={command} draft={form} notification={notification}
204
+ bridge={bridge} lease={lease} part={part} titleId={titleId} actionErrorId={`${id}-action-error`} />}
202
205
  <div className={part('actions', 'cloudlet-actions')}>
203
206
  {command?.kind === 'command' && control('action', command.label, () => {
204
207
  if (action.status !== 'pending') bridge.invokeAction(lease, handle);
@@ -217,6 +220,86 @@ export function Body({ notification, bridge, lease, labels, navigate, slot, part
217
220
  </div>;
218
221
  }
219
222
 
223
+ // A new form action object starts a new draft in the controller, so its fields remount with the new defaults.
224
+ const formKeys = new WeakMap<FormAction, number>();
225
+ let nextFormKey = 0;
226
+ function formKey(action: FormAction): number {
227
+ let key = formKeys.get(action);
228
+ if (key === undefined) formKeys.set(action, key = ++nextFormKey);
229
+ return key;
230
+ }
231
+
232
+ const TEXTAREA_ROWS = [3, 6] as const;
233
+
234
+ /** Rows instead of a height: a strict CSP forbids style attributes, and rows grow with the text. */
235
+ function fitRows(element: HTMLTextAreaElement): void {
236
+ element.rows = TEXTAREA_ROWS[0];
237
+ while (element.scrollHeight > element.clientHeight && element.rows < TEXTAREA_ROWS[1]) element.rows += 1;
238
+ }
239
+
240
+ /**
241
+ * Look A: each field is a filled pill; the round submit button sits beside the last one. The fields
242
+ * are uncontrolled: their text lives in the controller's draft and seeds them on mount, so typing
243
+ * never waits for a snapshot round trip.
244
+ */
245
+ function Form({ action, draft, notification, bridge, lease, part, titleId, actionErrorId }: {
246
+ action: FormAction; draft: FormDraft; notification: NotificationSnapshot<ReactNode>; bridge: RendererBridge<ReactNode>;
247
+ lease: HostLease; part: PartClass; titleId: string; actionErrorId: string;
248
+ }) {
249
+ const id = useId();
250
+ const fields = useRef(new Map<string, HTMLInputElement | HTMLTextAreaElement>());
251
+ const pending = notification.action.status === 'pending';
252
+ const failed = notification.action.status === 'failed';
253
+ const formError = draft.errors.form;
254
+ const submit = () => {
255
+ if (pending) return;
256
+ const result = bridge.invokeAction(lease, notification.handle);
257
+ if (result.status !== 'invalid') return;
258
+ const first = action.fields.find(field => result.errors.fields[field.name] !== undefined);
259
+ if (first) fields.current.get(first.name)?.focus();
260
+ };
261
+ const field = (field: FormField, index: number, last: boolean) => {
262
+ const fieldId = `${id}-${index}`;
263
+ const error = draft.errors.fields[field.name];
264
+ const props = {
265
+ id: fieldId, name: field.name, className: part('field', 'cloudlet-field'), defaultValue: draft.values[field.name] ?? '',
266
+ placeholder: field.placeholder ?? field.label, required: field.required, maxLength: field.maxLength,
267
+ autoComplete: field.autoComplete, inputMode: field.inputMode, readOnly: pending,
268
+ 'aria-invalid': error === undefined ? undefined : true, 'aria-describedby': error === undefined ? undefined : `${fieldId}-error`,
269
+ };
270
+ const change = (element: HTMLInputElement | HTMLTextAreaElement) => bridge.setFormValue(lease, notification.handle, field.name, element.value);
271
+ return <div key={field.name} className="cloudlet-form-row">
272
+ <label htmlFor={fieldId} className="cloudlet-live">{field.label}</label>
273
+ {field.kind === 'text'
274
+ ? <input type="text" {...props} ref={element => { if (element) fields.current.set(field.name, element); }}
275
+ onChange={event => change(event.currentTarget)} />
276
+ : <textarea {...props} rows={TEXTAREA_ROWS[0]} ref={element => {
277
+ if (!element) return;
278
+ fields.current.set(field.name, element);
279
+ fitRows(element);
280
+ }} onChange={event => { change(event.currentTarget); fitRows(event.currentTarget); }}
281
+ onKeyDown={(event: ReactKeyboardEvent<HTMLTextAreaElement>) => {
282
+ // Enter starts a new line in a textarea; ⌘ or Ctrl with Enter sends.
283
+ if (event.key !== 'Enter' || !(event.metaKey || event.ctrlKey) || event.nativeEvent.isComposing) return;
284
+ event.preventDefault();
285
+ submit();
286
+ }} />}
287
+ {last && <button type="submit" data-cloudlet-control="action" className={part('action', 'cloudlet-action cloudlet-submit')}
288
+ aria-label={action.label} aria-disabled={pending} aria-busy={pending}
289
+ aria-describedby={failed ? actionErrorId : formError ? `${id}-error` : undefined}>
290
+ {pending ? <svg aria-hidden="true" viewBox="0 0 16 16" className="cloudlet-spinner"><circle cx="8" cy="8" r="5.5" strokeDasharray="22 13" /></svg>
291
+ : glyph('M8 13V3m0 0L3.5 7.5M8 3l4.5 4.5')}
292
+ </button>}
293
+ {error !== undefined && <p id={`${fieldId}-error`} className={part('field-error', 'cloudlet-field-error')}>{error}</p>}
294
+ </div>;
295
+ };
296
+ return <form className={part('form', 'cloudlet-form')} noValidate aria-labelledby={titleId}
297
+ onSubmit={event => { event.preventDefault(); submit(); }}>
298
+ {action.fields.map((item, index) => field(item, index, index === action.fields.length - 1))}
299
+ {formError && <p id={`${id}-error`} className="cloudlet-action-error">{formError}</p>}
300
+ </form>;
301
+ }
302
+
220
303
  export function closeButton(labels: CloudletLabels, part: PartClass, onClick: () => void) {
221
304
  return control('close', glyph('m4.5 4.5 7 7m0-7-7 7'), onClick, { 'aria-label': labels.close, className: part('close', 'cloudlet-close') });
222
305
  }
@@ -698,7 +698,10 @@ function createHostRuntime(owner: Host) {
698
698
  const visibility = () => pause('document-hidden', doc.visibilityState === 'hidden');
699
699
  // A pointer press outside the open Island collapses it to the stack.
700
700
  const outside = (event: Event) => {
701
- if (bridge.getSnapshot().island.open && event.target instanceof view.Node && !root.contains(event.target)) bridge.collapseIsland(lease);
701
+ const snapshot = bridge.getSnapshot();
702
+ // Unsent text holds the Island open; Escape and the pill's own controls still collapse it.
703
+ const draft = snapshot.notifications.some(item => item.handle === snapshot.island.current && item.draft);
704
+ if (snapshot.island.open && !draft && event.target instanceof view.Node && !root.contains(event.target)) bridge.collapseIsland(lease);
702
705
  };
703
706
  // No mouseout reaches the host when the hovered card is removed or hidden under a still pointer
704
707
  // (React then never sees the leave): the next pointer over anything outside releases the pause.
@@ -809,11 +812,15 @@ function createHostRuntime(owner: Host) {
809
812
  function onIslandKey(event: ReactKeyboardEvent, stack: readonly NotificationHandle[], index: number, rtl: boolean) {
810
813
  if (event.defaultPrevented) return;
811
814
  let next: number | null = null;
815
+ // An IME composition owns Escape and the arrows until it ends.
816
+ if (event.nativeEvent.isComposing) return;
812
817
  if (event.key === 'Escape') {
813
818
  event.preventDefault();
814
819
  bridge.collapseIsland(lease);
815
820
  return;
816
821
  }
822
+ // The arrows, Home and End move the caret inside a form field.
823
+ if ((event.target as Element).closest('input, textarea')) return;
817
824
  // A focused scrolling body keeps Home/End for its own scroll.
818
825
  if ((event.key === 'Home' || event.key === 'End') && event.target === bodyElement() && bodyElement()?.tabIndex === 0) return;
819
826
  if (event.key === 'Home') next = 0;
@@ -893,7 +900,8 @@ function createHostRuntime(owner: Host) {
893
900
  <Heading notification={presented} slot={slot} part={part} titleId={`${islandId}-title`} />
894
901
  <div className="cloudlet-heading-out" aria-hidden="true" />
895
902
  </div>
896
- {open && <Body notification={presented} bridge={bridge} lease={lease} labels={labels} navigate={navigate} slot={slot} part={part} />}
903
+ {open && <Body notification={presented} form={snapshot.forms.find(form => form.handle === presented.handle)} bridge={bridge}
904
+ lease={lease} labels={labels} navigate={navigate} slot={slot} part={part} titleId={`${islandId}-title`} />}
897
905
  <div className="cloudlet-body-out" aria-hidden="true" />
898
906
  </div>}
899
907
  {preview && <div ref={inertRef} className="cloudlet-peek" aria-hidden="true"><SlidePreview notification={preview} labels={labels} part={part} /></div>}
@@ -914,7 +922,8 @@ function createHostRuntime(owner: Host) {
914
922
  </div>
915
923
  {presented && !open && <button type="button" className={part('pill', 'cloudlet-pill')} data-cloudlet-pill=""
916
924
  aria-expanded="false" aria-controls={islandId} onClick={() => bridge.openIsland(lease, 'user')}
917
- aria-label={format(labels.stackSummary, defaultLabels.stackSummary, presented.content.title, total, missed)} />}
925
+ aria-label={[format(labels.stackSummary, defaultLabels.stackSummary, presented.content.title, total, missed),
926
+ ...(presented.draft ? [labels.draft] : [])].join(', ')} />}
918
927
  <span className={part('badge', 'cloudlet-badge')} aria-hidden="true"><span className="cloudlet-badge-value">{badgeCount}</span><span className="cloudlet-badge-out" /></span>
919
928
  </div>
920
929
  <div ref={exitRef} className="cloudlet-exit" aria-hidden="true" />
package/src/react/plan.ts CHANGED
@@ -59,7 +59,8 @@ function bodyKey(item: Presented) {
59
59
  const { content, operation, action } = item;
60
60
  const description = content.description;
61
61
  return [description?.kind, description?.kind === 'text' ? description.text : '', content.progress?.kind,
62
- content.action?.kind, content.action?.label, action.status === 'failed' ? action.message : '',
62
+ content.action?.kind, content.action?.label, content.action?.kind === 'form' ? content.action.fields.map(field => field.name).join('\u0001') : '',
63
+ action.status === 'failed' ? action.message : '',
63
64
  operation?.status, operation?.canRetry, operation?.canCancel].join('\u0000');
64
65
  }
65
66
 
package/src/react.ts CHANGED
@@ -57,6 +57,8 @@ export interface CloudletLabels {
57
57
  /** 1-based slide position. */
58
58
  readonly page: (index: number, total: number) => string;
59
59
  readonly overflowCount: (count: number) => string;
60
+ /** Added to the collapsed stack button's name while the presented form holds unsent text. */
61
+ readonly draft: string;
60
62
  }
61
63
 
62
64
  export interface AnnouncementFormatters {
@@ -158,7 +160,7 @@ export interface ToasterMotion {
158
160
 
159
161
  /** Styling hooks of the renderer; see `ToasterProps.classNames`. */
160
162
  export type CloudletPart = 'host' | 'stack' | 'pill' | 'tail' | 'badge' | 'island' | 'header' | 'icon' | 'title'
161
- | 'close' | 'body' | 'description' | 'actions' | 'action' | 'indicator' | 'overflow';
163
+ | 'close' | 'body' | 'description' | 'actions' | 'action' | 'indicator' | 'overflow' | 'form' | 'field' | 'field-error';
162
164
 
163
165
  export interface ToasterProps {
164
166
  readonly position?: 'auto' | 'top-center' | 'bottom-center';