@astra-spec/ui 0.0.1 → 0.0.3

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 (38) hide show
  1. package/README.md +70 -4
  2. package/TOKENS.md +6 -2
  3. package/components.css +1 -0
  4. package/dist/components/index.d.ts +3 -1
  5. package/dist/components/index.d.ts.map +1 -1
  6. package/dist/components/index.js +2 -1
  7. package/dist/components/index.js.map +1 -1
  8. package/dist/components/record-preview.d.ts +61 -0
  9. package/dist/components/record-preview.d.ts.map +1 -0
  10. package/dist/components/record-preview.js +177 -0
  11. package/dist/components/record-preview.js.map +1 -0
  12. package/dist/lib/labels.d.ts +12 -0
  13. package/dist/lib/labels.d.ts.map +1 -1
  14. package/dist/lib/labels.js +12 -0
  15. package/dist/lib/labels.js.map +1 -1
  16. package/dist/primitives/index.d.ts +3 -1
  17. package/dist/primitives/index.d.ts.map +1 -1
  18. package/dist/primitives/index.js +1 -0
  19. package/dist/primitives/index.js.map +1 -1
  20. package/dist/primitives/preview-popover.d.ts +30 -0
  21. package/dist/primitives/preview-popover.d.ts.map +1 -0
  22. package/dist/primitives/preview-popover.js +132 -0
  23. package/dist/primitives/preview-popover.js.map +1 -0
  24. package/dist/primitives/prose.d.ts +7 -1
  25. package/dist/primitives/prose.d.ts.map +1 -1
  26. package/dist/primitives/prose.js +13 -5
  27. package/dist/primitives/prose.js.map +1 -1
  28. package/package.json +2 -1
  29. package/primitives.css +1 -0
  30. package/src/components/index.ts +11 -1
  31. package/src/components/record-preview.tsx +761 -0
  32. package/src/lib/labels.tsx +27 -0
  33. package/src/primitives/index.ts +14 -1
  34. package/src/primitives/preview-popover.tsx +278 -0
  35. package/src/primitives/prose.tsx +28 -5
  36. package/styles/components/record-preview.css +316 -0
  37. package/styles/primitives/preview-popover.css +76 -0
  38. package/styles/tokens.css +15 -8
@@ -44,6 +44,18 @@ export interface AstraLabels {
44
44
  openPaper: string;
45
45
  locate: string;
46
46
  };
47
+ /** Copy used only by the compact RecordPreview surface. */
48
+ preview: {
49
+ optionDetail: string;
50
+ supportedBy: string;
51
+ evidence: string;
52
+ provenance: string;
53
+ source: string;
54
+ openRecord: (kindLabel: string, recordLabel: string) => string;
55
+ optionStatus: (selected: boolean, excluded: boolean) => string;
56
+ remainingDecisionDetails: (count: number) => string;
57
+ valueSource: (product: string) => string;
58
+ };
47
59
  }
48
60
 
49
61
  const SECTION_NOUNS: Record<keyof AstraLabels['sections'], [string, string]> = {
@@ -97,6 +109,20 @@ export const defaultLabels: AstraLabels = {
97
109
  openPaper: 'Open',
98
110
  locate: 'Locate',
99
111
  },
112
+ preview: {
113
+ optionDetail: 'Option detail',
114
+ supportedBy: 'Supported by',
115
+ evidence: 'Evidence',
116
+ provenance: 'Provenance',
117
+ source: 'Source',
118
+ openRecord: (kindLabel, recordLabel) =>
119
+ `Open ${kindLabel.toLowerCase()} details: ${recordLabel}`,
120
+ optionStatus: (selected, excluded) =>
121
+ `${selected ? 'Selected.' : 'Not selected.'}${excluded ? ' Excluded.' : ''}`,
122
+ remainingDecisionDetails: (count) =>
123
+ `+ ${count} more in the decision details`,
124
+ valueSource: (product) => `from ${product}`,
125
+ },
100
126
  };
101
127
 
102
128
  /** Deep partial of the label set, for host overrides. */
@@ -122,6 +148,7 @@ function merge(base: AstraLabels, overrides: AstraLabelOverrides): AstraLabels {
122
148
  kinds: { ...base.kinds, ...defined(overrides.kinds ?? {}) },
123
149
  empty: { ...base.empty, ...defined(overrides.empty ?? {}) },
124
150
  actions: { ...base.actions, ...defined(overrides.actions ?? {}) },
151
+ preview: { ...base.preview, ...defined(overrides.preview ?? {}) },
125
152
  } as AstraLabels;
126
153
  }
127
154
 
@@ -8,6 +8,11 @@ export { surfaceGlyph } from './kind.js';
8
8
  export type { SurfaceKind } from './kind.js';
9
9
  export { Button, IconButton } from './button.js';
10
10
  export type { ButtonProps, ButtonSize, ButtonTone, ButtonVariant, IconButtonProps } from './button.js';
11
+ export { PreviewPopover } from './preview-popover.js';
12
+ export type {
13
+ PreviewPopoverPortalProps,
14
+ PreviewPopoverProps,
15
+ } from './preview-popover.js';
11
16
  export { Badge } from './badge.js';
12
17
  export type { BadgeProps, BadgeStatus, BadgeTone } from './badge.js';
13
18
  export { SurfaceHeader } from './surface-header.js';
@@ -45,4 +50,12 @@ export type { RelationItem, RelationListProps } from './relation-list.js';
45
50
  export { CountHeading, DetailLayout, DetailMain, DetailRail, DetailSection } from './detail-layout.js';
46
51
  export type { CountHeadingProps, DetailLayoutMode, DetailLayoutProps, DetailRailProps, DetailSectionProps } from './detail-layout.js';
47
52
  export { Prose, parseProse, renderProse } from './prose.js';
48
- export type { ProseContext, ProseField, ProseProps, ProseToken, TextRenderer } from './prose.js';
53
+ export type {
54
+ ProseContext,
55
+ ProseField,
56
+ ProseMathMacros,
57
+ ProseProps,
58
+ ProseRenderOptions,
59
+ ProseToken,
60
+ TextRenderer,
61
+ } from './prose.js';
@@ -0,0 +1,278 @@
1
+ /* eslint-disable react-hooks/refs, @typescript-eslint/unbound-method --
2
+ * Floating UI intentionally exposes callback refs and middleware ref objects
3
+ * that are passed through during render; none of these APIs read `.current`.
4
+ */
5
+ import {
6
+ FloatingArrow,
7
+ FloatingFocusManager,
8
+ FloatingNode,
9
+ FloatingPortal,
10
+ FloatingTree,
11
+ arrow,
12
+ autoUpdate,
13
+ flip,
14
+ offset,
15
+ safePolygon,
16
+ shift,
17
+ size,
18
+ useClientPoint,
19
+ useDismiss,
20
+ useFloating,
21
+ useFloatingNodeId,
22
+ useFloatingParentNodeId,
23
+ useFocus,
24
+ useHover,
25
+ useInteractions,
26
+ useRole,
27
+ useTransitionStatus,
28
+ } from '@floating-ui/react';
29
+ import {
30
+ useCallback,
31
+ useId,
32
+ useRef,
33
+ useState,
34
+ type HTMLAttributes,
35
+ type ReactElement,
36
+ type ReactNode,
37
+ } from 'react';
38
+ import { cn } from '../lib/cn.js';
39
+ import { Slot } from '../lib/slot.js';
40
+ import { useDialogDismissGuard, useOptionalDialog } from './dialog.js';
41
+ import type { SurfaceKind } from './kind.js';
42
+
43
+ const ARROW_HEIGHT = 7;
44
+ const REFERENCE_GAP = 6;
45
+ const VIEWPORT_PADDING = 8;
46
+
47
+ export interface PreviewPopoverPortalProps
48
+ extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
49
+ [attribute: `data-${string}`]: string | number | boolean | null | undefined;
50
+ 'data-astra-color-scheme'?: 'light' | 'dark' | undefined;
51
+ }
52
+
53
+ export interface PreviewPopoverProps
54
+ extends Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'content'> {
55
+ /** A single focusable element. Non-focusable elements receive `tabIndex=0`. */
56
+ trigger: ReactElement;
57
+ children: ReactNode;
58
+ /** Accessible name for the non-modal preview dialog. */
59
+ label: string;
60
+ kind?: SurfaceKind | undefined;
61
+ disabled?: boolean | undefined;
62
+ open?: boolean | undefined;
63
+ defaultOpen?: boolean | undefined;
64
+ onOpenChange?: ((open: boolean) => void) | undefined;
65
+ openDelay?: number | undefined;
66
+ closeDelay?: number | undefined;
67
+ /** Optional portal mount. The document body is used by default. */
68
+ portalRoot?: HTMLElement | ShadowRoot | null | undefined;
69
+ /** Host scope and scheme attributes belong here because portals do not inherit DOM ancestry. */
70
+ portalProps?: PreviewPopoverPortalProps | undefined;
71
+ }
72
+
73
+ function PreviewPopoverInner({
74
+ trigger,
75
+ children,
76
+ label,
77
+ kind,
78
+ disabled = false,
79
+ open: controlledOpen,
80
+ defaultOpen = false,
81
+ onOpenChange,
82
+ openDelay = 120,
83
+ closeDelay = 60,
84
+ portalRoot,
85
+ portalProps,
86
+ className,
87
+ ...props
88
+ }: PreviewPopoverProps) {
89
+ const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen);
90
+ const open = !disabled && (controlledOpen ?? uncontrolledOpen);
91
+ const nodeId = useFloatingNodeId();
92
+ const contentId = useId();
93
+ const arrowRef = useRef<SVGSVGElement>(null);
94
+ const cursorX = useRef<number | null>(null);
95
+ const [pinnedX, setPinnedX] = useState<number | null>(null);
96
+ const [automaticPortalRoot, setAutomaticPortalRoot] =
97
+ useState<HTMLDialogElement | null | undefined>(undefined);
98
+
99
+ const setOpen = useCallback((next: boolean, event?: Event) => {
100
+ if (next) {
101
+ setPinnedX(event instanceof MouseEvent ? cursorX.current : null);
102
+ }
103
+ if (controlledOpen === undefined) setUncontrolledOpen(next);
104
+ onOpenChange?.(next);
105
+ }, [controlledOpen, onOpenChange]);
106
+
107
+ const { refs, floatingStyles, context, placement } = useFloating({
108
+ nodeId,
109
+ open,
110
+ onOpenChange: setOpen,
111
+ placement: 'top',
112
+ strategy: 'fixed',
113
+ whileElementsMounted: autoUpdate,
114
+ middleware: [
115
+ offset(ARROW_HEIGHT + REFERENCE_GAP),
116
+ flip({ padding: VIEWPORT_PADDING }),
117
+ shift({ padding: VIEWPORT_PADDING }),
118
+ size({
119
+ padding: 12,
120
+ apply({ availableHeight, elements }) {
121
+ elements.floating.style.setProperty(
122
+ '--astra-preview-available-height',
123
+ `${Math.max(180, availableHeight)}px`,
124
+ );
125
+ },
126
+ }),
127
+ arrow({ element: arrowRef, padding: VIEWPORT_PADDING }),
128
+ ],
129
+ });
130
+
131
+ const hover = useHover(context, {
132
+ enabled: !disabled,
133
+ delay: { open: openDelay, close: closeDelay },
134
+ handleClose: safePolygon({ buffer: 1 }),
135
+ move: false,
136
+ });
137
+ const focus = useFocus(context, { enabled: !disabled });
138
+ const point = useClientPoint(context, {
139
+ enabled: !disabled,
140
+ axis: 'x',
141
+ x: pinnedX,
142
+ });
143
+ const dialog = useOptionalDialog();
144
+ const inModalDialog = dialog?.mode === 'modal';
145
+ useDialogDismissGuard(open && !disabled && inModalDialog, () => {
146
+ setOpen(false);
147
+ });
148
+ const dismiss = useDismiss(context, {
149
+ enabled: !disabled,
150
+ escapeKey: !inModalDialog,
151
+ bubbles: { escapeKey: false },
152
+ });
153
+ const role = useRole(context, { enabled: !disabled, role: 'dialog' });
154
+ const { getReferenceProps, getFloatingProps } = useInteractions([
155
+ hover,
156
+ focus,
157
+ point,
158
+ dismiss,
159
+ role,
160
+ ]);
161
+ const { isMounted, status } = useTransitionStatus(context, {
162
+ duration: { open: 120, close: 80 },
163
+ });
164
+ const setFloatingReference = refs.setReference;
165
+ const setReference = useCallback((element: HTMLElement | null) => {
166
+ setFloatingReference(element);
167
+ const nextRoot = element
168
+ ? (element.closest<HTMLDialogElement>('dialog') ?? null)
169
+ : undefined;
170
+ setAutomaticPortalRoot((currentRoot) =>
171
+ currentRoot === nextRoot ? currentRoot : nextRoot,
172
+ );
173
+ }, [setFloatingReference, setAutomaticPortalRoot]);
174
+
175
+ const reference = (
176
+ <Slot
177
+ ref={setReference}
178
+ {...getReferenceProps({
179
+ ...(!disabled
180
+ ? {
181
+ tabIndex: 0,
182
+ 'aria-haspopup': 'dialog',
183
+ 'aria-expanded': open,
184
+ 'aria-controls': open ? contentId : undefined,
185
+ }
186
+ : {}),
187
+ onMouseEnter(event) {
188
+ cursorX.current = event.clientX;
189
+ },
190
+ onMouseMove(event) {
191
+ cursorX.current = event.clientX;
192
+ },
193
+ })}
194
+ >
195
+ {trigger}
196
+ </Slot>
197
+ );
198
+
199
+ const resolvedPortalRoot = portalRoot === undefined
200
+ ? (automaticPortalRoot ?? undefined)
201
+ : portalRoot;
202
+ const portalRootReady = portalRoot !== undefined || automaticPortalRoot !== undefined;
203
+ // A nested, unschemed `.astra-ui` would redeclare the base tokens and mask
204
+ // theme overrides inherited from an explicitly scoped portal mount.
205
+ const inheritsAstraScope = portalProps === undefined &&
206
+ typeof HTMLElement !== 'undefined' &&
207
+ resolvedPortalRoot instanceof HTMLElement &&
208
+ resolvedPortalRoot.closest('.astra-ui') !== null;
209
+ const portalClassName = cn(
210
+ !inheritsAstraScope && 'astra-ui',
211
+ 'astra-preview-popover-portal',
212
+ portalProps?.className,
213
+ );
214
+
215
+ return (
216
+ <>
217
+ {reference}
218
+ <FloatingNode id={nodeId}>
219
+ {isMounted && portalRootReady ? (
220
+ <FloatingPortal root={resolvedPortalRoot} preserveTabOrder>
221
+ <div
222
+ data-slot="preview-popover-portal"
223
+ {...portalProps}
224
+ className={portalClassName}
225
+ >
226
+ <FloatingFocusManager
227
+ context={context}
228
+ modal={false}
229
+ initialFocus={-1}
230
+ >
231
+ <div
232
+ data-slot="preview-popover"
233
+ {...getFloatingProps(props)}
234
+ id={contentId}
235
+ ref={refs.setFloating}
236
+ style={{ ...floatingStyles, ...props.style }}
237
+ className={cn('astra-preview-popover', className)}
238
+ aria-label={label}
239
+ aria-modal="false"
240
+ data-kind={kind}
241
+ data-placement={placement}
242
+ data-status={status}
243
+ >
244
+ <div className="astra-preview-popover__surface">
245
+ <div className="astra-preview-popover__scroll">{children}</div>
246
+ <FloatingArrow
247
+ ref={arrowRef}
248
+ context={context}
249
+ className="astra-preview-popover__arrow"
250
+ height={ARROW_HEIGHT}
251
+ width={ARROW_HEIGHT * 2}
252
+ />
253
+ </div>
254
+ </div>
255
+ </FloatingFocusManager>
256
+ </div>
257
+ </FloatingPortal>
258
+ ) : null}
259
+ </FloatingNode>
260
+ </>
261
+ );
262
+ }
263
+
264
+ /**
265
+ * Cursor-anchored, non-modal preview opened by hover or keyboard focus.
266
+ * The outermost instance creates the Floating UI tree needed by nested previews.
267
+ */
268
+ export function PreviewPopover(props: PreviewPopoverProps) {
269
+ const parentId = useFloatingParentNodeId();
270
+ if (parentId === null) {
271
+ return (
272
+ <FloatingTree>
273
+ <PreviewPopoverInner {...props} />
274
+ </FloatingTree>
275
+ );
276
+ }
277
+ return <PreviewPopoverInner {...props} />;
278
+ }
@@ -17,6 +17,14 @@ export type ProseToken =
17
17
  | { type: 'inlineMath'; value: string }
18
18
  | { type: 'math'; value: string };
19
19
 
20
+ /** String macro expansions accepted by the built-in KaTeX renderer. */
21
+ export type ProseMathMacros = Readonly<Record<string, string>>;
22
+
23
+ export interface ProseRenderOptions {
24
+ /** Host-normalized math macros, such as `{ '\\vect': '\\mathbf{#1}' }`. */
25
+ macros?: ProseMathMacros | undefined;
26
+ }
27
+
20
28
  /** Balanced tokens: display math first, then `code`, then inline math. */
21
29
  const PROSE_TOKEN = /(\$\$[\s\S]+?\$\$|`[^`\n]+`|\$[^$\n]+\$)/g;
22
30
 
@@ -37,8 +45,20 @@ export function parseProse(text: string): ProseToken[] {
37
45
  return nodes;
38
46
  }
39
47
 
40
- function renderMath(value: string, displayMode: boolean): string {
41
- return renderToString(value, { displayMode, output: 'htmlAndMathml', strict: 'ignore', throwOnError: false });
48
+ function renderMath(
49
+ value: string,
50
+ displayMode: boolean,
51
+ macros?: ProseMathMacros,
52
+ ): string {
53
+ return renderToString(value, {
54
+ displayMode,
55
+ output: 'htmlAndMathml',
56
+ strict: 'ignore',
57
+ throwOnError: false,
58
+ // KaTeX may mutate its macro object for global definitions. Keep a host's
59
+ // shared configuration immutable across independent prose fields.
60
+ ...(macros ? { macros: { ...macros } } : {}),
61
+ });
42
62
  }
43
63
 
44
64
  /**
@@ -46,16 +66,19 @@ function renderMath(value: string, displayMode: boolean): string {
46
66
  * typeset with KaTeX (load `katex/dist/katex.css`; the stylesheet bundles
47
67
  * import it). Text without those markers is returned as is.
48
68
  */
49
- export function renderProse(text: string): ReactNode {
69
+ export function renderProse(
70
+ text: string,
71
+ options: ProseRenderOptions = {},
72
+ ): ReactNode {
50
73
  if (!/[`$]/.test(text)) return text;
51
74
  return parseProse(text).map((node, index) => {
52
75
  switch (node.type) {
53
76
  case 'inlineCode':
54
77
  return <code key={index}>{node.value}</code>;
55
78
  case 'inlineMath':
56
- return <span key={index} className="astra-prose__inline-math" dangerouslySetInnerHTML={{ __html: renderMath(node.value, false) }} />;
79
+ return <span key={index} className="astra-prose__inline-math" dangerouslySetInnerHTML={{ __html: renderMath(node.value, false, options.macros) }} />;
57
80
  case 'math':
58
- return <div key={index} className="astra-prose__display-math" dangerouslySetInnerHTML={{ __html: renderMath(node.value, true) }} />;
81
+ return <div key={index} className="astra-prose__display-math" dangerouslySetInnerHTML={{ __html: renderMath(node.value, true, options.macros) }} />;
59
82
  default:
60
83
  return <Fragment key={index}>{node.value}</Fragment>;
61
84
  }