@leitware/composables 1.6.1 → 1.7.0

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.
@@ -0,0 +1,57 @@
1
+ /** Copy using the browser API, or the legacy path when that API is unavailable. */
2
+ export async function copyText(text: string): Promise<void> {
3
+ if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
4
+ await navigator.clipboard.writeText(text)
5
+ return
6
+ }
7
+ if (
8
+ typeof document === 'undefined' ||
9
+ !document.body ||
10
+ typeof document.execCommand !== 'function'
11
+ ) {
12
+ throw new Error('Clipboard access is unavailable in this browser.')
13
+ }
14
+ const focused = document.activeElement
15
+ const selection = document.getSelection()
16
+ const ranges = selection
17
+ ? Array.from({ length: selection.rangeCount }, (_, index) =>
18
+ selection.getRangeAt(index).cloneRange(),
19
+ )
20
+ : []
21
+ const inputSelection =
22
+ focused instanceof HTMLInputElement || focused instanceof HTMLTextAreaElement
23
+ ? {
24
+ start: focused.selectionStart,
25
+ end: focused.selectionEnd,
26
+ direction: focused.selectionDirection,
27
+ }
28
+ : undefined
29
+ const field = document.createElement('textarea')
30
+ field.value = text
31
+ field.setAttribute('readonly', '')
32
+ field.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0'
33
+ document.body.appendChild(field)
34
+ try {
35
+ field.select()
36
+ if (!document.execCommand('copy')) throw new Error('The browser could not copy the text.')
37
+ } finally {
38
+ field.remove()
39
+ if (focused instanceof HTMLElement) focused.focus({ preventScroll: true })
40
+ if (selection) {
41
+ selection.removeAllRanges()
42
+ for (const range of ranges) selection.addRange(range)
43
+ }
44
+ if (
45
+ inputSelection &&
46
+ inputSelection.start !== null &&
47
+ inputSelection.end !== null &&
48
+ (focused instanceof HTMLInputElement || focused instanceof HTMLTextAreaElement)
49
+ ) {
50
+ focused.setSelectionRange(
51
+ inputSelection.start,
52
+ inputSelection.end,
53
+ inputSelection.direction ?? undefined,
54
+ )
55
+ }
56
+ }
57
+ }
@@ -0,0 +1,53 @@
1
+ export type FlowOrientation = 'horizontal' | 'vertical'
2
+ export type FlowTree =
3
+ | { kind: 'node'; id: string }
4
+ | { kind: 'sequence' | 'parallel'; children: FlowTree[] }
5
+ export interface FlowEdge {
6
+ from: string
7
+ to: string
8
+ }
9
+ export interface FlowPoint {
10
+ x: number
11
+ y: number
12
+ }
13
+
14
+ /** Branches connect only at their entry/exit; empty groups pass through. */
15
+ export function getFlowEdges(tree: FlowTree): FlowEdge[] {
16
+ const edges: FlowEdge[] = []
17
+ const visit = (entry: FlowTree): { starts: string[]; ends: string[] } => {
18
+ if (entry.kind === 'node') return { starts: [entry.id], ends: [entry.id] }
19
+ const children = entry.children.map(visit).filter((child) => child.starts.length > 0)
20
+ if (entry.kind === 'parallel')
21
+ return {
22
+ starts: children.flatMap((child) => child.starts),
23
+ ends: children.flatMap((child) => child.ends),
24
+ }
25
+ for (let index = 1; index < children.length; index++) {
26
+ for (const from of children[index - 1].ends)
27
+ for (const to of children[index].starts) edges.push({ from, to })
28
+ }
29
+ return { starts: children[0]?.starts ?? [], ends: children.at(-1)?.ends ?? [] }
30
+ }
31
+ visit(tree)
32
+ return edges
33
+ }
34
+
35
+ /** Orthogonal connector with small rounded bends; also supports right-to-left. */
36
+ export function getFlowPath(
37
+ start: FlowPoint,
38
+ end: FlowPoint,
39
+ orientation: FlowOrientation,
40
+ ): string {
41
+ const vertical = orientation === 'vertical'
42
+ const [a, b, c, d] = vertical
43
+ ? [start.y, start.x, end.y, end.x]
44
+ : [start.x, start.y, end.x, end.y]
45
+ const point = (axis: number, cross: number) =>
46
+ vertical ? `${cross} ${axis}` : `${axis} ${cross}`
47
+ if (b === d) return `M ${point(a, b)} L ${point(c, d)}`
48
+ const middle = (a + c) / 2
49
+ const direction = Math.sign(c - a) || 1
50
+ const turn = Math.sign(d - b)
51
+ const radius = Math.min(6, Math.abs(c - a) / 2, Math.abs(d - b) / 2)
52
+ return `M ${point(a, b)} L ${point(middle - direction * radius, b)} Q ${point(middle, b)} ${point(middle, b + turn * radius)} L ${point(middle, d - turn * radius)} Q ${point(middle, d)} ${point(middle + direction * radius, d)} L ${point(c, d)}`
53
+ }
@@ -0,0 +1,135 @@
1
+ import {
2
+ forwardRef,
3
+ useEffect,
4
+ useRef,
5
+ useState,
6
+ type ComponentPropsWithoutRef,
7
+ type ReactNode,
8
+ type ReactElement,
9
+ } from 'react'
10
+ import {
11
+ ClipboardTextRoot,
12
+ type ClipboardTextStatus,
13
+ type ClipboardTextSize,
14
+ } from '../_internal/clipboard-text'
15
+ import { Tooltip, TooltipContent, TooltipTrigger } from '../_internal/tooltip'
16
+ import { copyText } from '../lib/clipboard'
17
+
18
+ export interface ClipboardTextProps extends Omit<
19
+ ComponentPropsWithoutRef<'div'>,
20
+ 'onCopy' | 'children'
21
+ > {
22
+ text: string
23
+ /** The actual value to copy when the display is masked or shortened. */
24
+ textToCopy?: string
25
+ size?: ClipboardTextSize
26
+ disabled?: boolean
27
+ onCopy?: (value: string) => void
28
+ onCopyError?: (error: Error) => void
29
+ /** How long success/error feedback remains, in milliseconds. @default 1500 */
30
+ feedbackDuration?: number
31
+ tooltip?:
32
+ | boolean
33
+ | {
34
+ text?: ReactNode
35
+ copiedText?: ReactNode
36
+ errorText?: ReactNode
37
+ side?: 'top' | 'bottom' | 'left' | 'right'
38
+ }
39
+ labels?: { copyAction?: string; copied?: string; copyError?: string; text?: string }
40
+ }
41
+
42
+ export const ClipboardText = forwardRef<HTMLDivElement, ClipboardTextProps>(function ClipboardText(
43
+ {
44
+ text,
45
+ textToCopy,
46
+ size = 'default',
47
+ disabled,
48
+ onCopy,
49
+ onCopyError,
50
+ feedbackDuration = 1500,
51
+ tooltip = true,
52
+ labels,
53
+ ...props
54
+ },
55
+ ref,
56
+ ) {
57
+ const [status, setStatus] = useState<ClipboardTextStatus>('idle')
58
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
59
+ const operation = useRef(0)
60
+ const mounted = useRef(false)
61
+ useEffect(() => {
62
+ mounted.current = true
63
+ operation.current++
64
+ const clearFeedback = () => {
65
+ if (timer.current) clearTimeout(timer.current)
66
+ }
67
+ return () => {
68
+ mounted.current = false
69
+ clearFeedback()
70
+ }
71
+ }, [])
72
+ useEffect(() => {
73
+ operation.current++
74
+ if (timer.current) clearTimeout(timer.current)
75
+ setStatus('idle')
76
+ }, [text, textToCopy])
77
+ const copy = async () => {
78
+ if (disabled) return
79
+ const current = ++operation.current
80
+ const value = textToCopy ?? text
81
+ if (timer.current) clearTimeout(timer.current)
82
+ setStatus('copying')
83
+ let failure: Error | undefined
84
+ try {
85
+ await copyText(value)
86
+ } catch (error) {
87
+ failure = error instanceof Error ? error : new Error(String(error))
88
+ }
89
+ if (!mounted.current || operation.current !== current) return
90
+ setStatus(failure ? 'error' : 'copied')
91
+ timer.current = setTimeout(
92
+ () => {
93
+ setStatus('idle')
94
+ timer.current = null
95
+ },
96
+ Math.max(0, feedbackDuration),
97
+ )
98
+ if (failure) onCopyError?.(failure)
99
+ else onCopy?.(value)
100
+ }
101
+ const config = typeof tooltip === 'object' ? tooltip : {}
102
+ const copyLabel = labels?.copyAction ?? 'Copy to clipboard'
103
+ const copiedLabel = labels?.copied ?? 'Copied to clipboard'
104
+ const errorLabel = labels?.copyError ?? 'Could not copy. Select the text and copy it manually.'
105
+ const renderCopyButton = tooltip
106
+ ? (button: ReactElement) => (
107
+ <Tooltip>
108
+ <TooltipTrigger render={button} />
109
+ <TooltipContent side={config.side ?? 'top'}>
110
+ {status === 'copied'
111
+ ? (config.copiedText ?? 'Copied!')
112
+ : status === 'error'
113
+ ? (config.errorText ?? 'Unable to copy')
114
+ : (config.text ?? 'Copy')}
115
+ </TooltipContent>
116
+ </Tooltip>
117
+ )
118
+ : undefined
119
+ return (
120
+ <ClipboardTextRoot
121
+ ref={ref}
122
+ text={text}
123
+ size={size}
124
+ status={status}
125
+ disabled={disabled}
126
+ copyLabel={status === 'copied' ? copiedLabel : copyLabel}
127
+ textLabel={labels?.text ?? 'Text to copy'}
128
+ statusText={status === 'copied' ? copiedLabel : status === 'error' ? errorLabel : ''}
129
+ onCopyClick={copy}
130
+ renderCopyButton={renderCopyButton}
131
+ {...props}
132
+ />
133
+ )
134
+ })
135
+ export type { ClipboardTextSize, ClipboardTextStatus } from '../_internal/clipboard-text'
@@ -0,0 +1,74 @@
1
+ import { forwardRef, type ReactNode } from 'react'
2
+ import {
3
+ FlowRoot,
4
+ FlowNode,
5
+ FlowParallel,
6
+ FlowList,
7
+ FlowAnchor,
8
+ type FlowRootProps,
9
+ } from '../_internal/flow'
10
+
11
+ export interface FlowStep {
12
+ id: string
13
+ label: ReactNode
14
+ description?: ReactNode
15
+ icon?: ReactNode
16
+ disabled?: boolean
17
+ }
18
+ export interface FlowBranch {
19
+ id: string
20
+ /** Each branch is a sequence; branches run in parallel. */
21
+ branches: FlowItem[][]
22
+ }
23
+ export type FlowItem = FlowStep | FlowBranch
24
+ export interface FlowProps extends FlowRootProps {
25
+ /** Supply steps/branches for the easy API, or use the compound components. */
26
+ steps?: FlowItem[]
27
+ }
28
+ function renderSteps(steps: FlowItem[]): ReactNode {
29
+ return steps.map((step) =>
30
+ 'branches' in step ? (
31
+ <FlowParallel key={step.id}>
32
+ {step.branches.map((branch, index) => (
33
+ <FlowList key={index}>{renderSteps(branch)}</FlowList>
34
+ ))}
35
+ </FlowParallel>
36
+ ) : (
37
+ <FlowNode key={step.id} id={step.id} disabled={step.disabled}>
38
+ <div className="flex items-center gap-2">
39
+ {step.icon && (
40
+ <span aria-hidden="true" className="text-icon-secondary [&_svg]:size-4">
41
+ {step.icon}
42
+ </span>
43
+ )}
44
+ <div>
45
+ <div className="font-medium">{step.label}</div>
46
+ {step.description != null && (
47
+ <div className="mt-1 text-xs text-content-secondary">{step.description}</div>
48
+ )}
49
+ </div>
50
+ </div>
51
+ </FlowNode>
52
+ ),
53
+ )
54
+ }
55
+ const FlowComponent = forwardRef<HTMLDivElement, FlowProps>(function Flow(
56
+ { steps, children, ...props },
57
+ ref,
58
+ ) {
59
+ return (
60
+ <FlowRoot ref={ref} {...props}>
61
+ {steps ? renderSteps(steps) : children}
62
+ </FlowRoot>
63
+ )
64
+ })
65
+ export const Flow = Object.assign(FlowComponent, {
66
+ Root: FlowRoot,
67
+ Node: FlowNode,
68
+ Parallel: FlowParallel,
69
+ List: FlowList,
70
+ Anchor: FlowAnchor,
71
+ })
72
+ export { FlowRoot, FlowNode, FlowParallel, FlowList, FlowAnchor }
73
+ export type { FlowRootProps, FlowNodeProps, FlowAnchorProps, FlowAlign } from '../_internal/flow'
74
+ export type { FlowOrientation } from '../lib/flow'
@@ -0,0 +1,49 @@
1
+ import { forwardRef, type ReactNode } from 'react'
2
+ import {
3
+ LayerCardRoot,
4
+ LayerCardPrimary,
5
+ LayerCardSecondary,
6
+ type LayerCardRootProps,
7
+ } from '../_internal/layer-card'
8
+
9
+ export interface LayerCardProps extends Omit<LayerCardRootProps, 'title' | 'layered'> {
10
+ /** Content in the recessed upper layer. */
11
+ title?: ReactNode
12
+ /** Action beside the upper-layer title. */
13
+ action?: ReactNode
14
+ /** Optional recessed lower layer. */
15
+ footer?: ReactNode
16
+ }
17
+
18
+ const LayerCardComponent = forwardRef<HTMLDivElement, LayerCardProps>(function LayerCard(
19
+ { title, action, footer, children, ...props },
20
+ ref,
21
+ ) {
22
+ const header = title != null || action != null
23
+ const layered = header || footer != null
24
+ return (
25
+ <LayerCardRoot ref={ref} layered={layered} {...props}>
26
+ {header && (
27
+ <LayerCardSecondary>
28
+ <div className="min-w-0 flex-1">{title}</div>
29
+ {action}
30
+ </LayerCardSecondary>
31
+ )}
32
+ {layered ? (
33
+ <LayerCardPrimary>{children}</LayerCardPrimary>
34
+ ) : (
35
+ <div className="p-(--layer-card-padding)">{children}</div>
36
+ )}
37
+ {footer != null && <LayerCardSecondary>{footer}</LayerCardSecondary>}
38
+ </LayerCardRoot>
39
+ )
40
+ })
41
+
42
+ /** Recessed header/footer layers around a raised content surface. */
43
+ export const LayerCard = Object.assign(LayerCardComponent, {
44
+ Root: LayerCardRoot,
45
+ Primary: LayerCardPrimary,
46
+ Secondary: LayerCardSecondary,
47
+ })
48
+ export { LayerCardRoot, LayerCardPrimary, LayerCardSecondary }
49
+ export type { LayerCardRootProps, LayerCardSectionProps } from '../_internal/layer-card'
@@ -0,0 +1,121 @@
1
+ import {
2
+ forwardRef,
3
+ useState,
4
+ type ComponentPropsWithoutRef,
5
+ type ReactNode,
6
+ type MouseEvent,
7
+ } from 'react'
8
+ import {
9
+ TableOfContentsRoot,
10
+ TableOfContentsTitle,
11
+ TableOfContentsList,
12
+ TableOfContentsItem,
13
+ TableOfContentsGroup,
14
+ } from '../_internal/table-of-contents'
15
+ import { useTableOfContentsActiveId } from '../hooks/use-table-of-contents-active-id'
16
+
17
+ export interface TableOfContentsItemData {
18
+ /** Matching document section ID. */
19
+ id: string
20
+ label: ReactNode
21
+ /** Defaults to #id for leaves; group labels are plain text unless provided. */
22
+ href?: string
23
+ children?: TableOfContentsItemData[]
24
+ }
25
+ export interface TableOfContentsProps extends Omit<ComponentPropsWithoutRef<'nav'>, 'title'> {
26
+ items?: TableOfContentsItemData[]
27
+ title?: ReactNode
28
+ activeId?: string
29
+ defaultActiveId?: string
30
+ onActiveIdChange?: (id: string) => void
31
+ onItemClick?: (item: TableOfContentsItemData, event: MouseEvent<HTMLAnchorElement>) => void
32
+ /** Track document section positions automatically. @default false */
33
+ trackScroll?: boolean
34
+ scrollOffset?: number
35
+ }
36
+ function sectionIds(items: TableOfContentsItemData[]): string[] {
37
+ return items.flatMap((item) => [item.id, ...sectionIds(item.children ?? [])])
38
+ }
39
+ const TableOfContentsComponent = forwardRef<HTMLElement, TableOfContentsProps>(
40
+ function TableOfContents(
41
+ {
42
+ items,
43
+ title = 'On this page',
44
+ activeId,
45
+ defaultActiveId,
46
+ onActiveIdChange,
47
+ onItemClick,
48
+ trackScroll = false,
49
+ scrollOffset = 96,
50
+ children,
51
+ ...props
52
+ },
53
+ ref,
54
+ ) {
55
+ const [selected, setSelected] = useState(defaultActiveId)
56
+ const tracked = useTableOfContentsActiveId(sectionIds(items ?? []), {
57
+ offset: scrollOffset,
58
+ enabled: trackScroll && activeId === undefined,
59
+ })
60
+ const current = activeId ?? tracked ?? selected
61
+ const handleClick = (item: TableOfContentsItemData, event: MouseEvent<HTMLAnchorElement>) => {
62
+ onItemClick?.(item, event)
63
+ if (event.defaultPrevented) return
64
+ if (activeId === undefined) setSelected(item.id)
65
+ onActiveIdChange?.(item.id)
66
+ }
67
+ const renderItems = (entries: TableOfContentsItemData[]): ReactNode =>
68
+ entries.map((item) =>
69
+ item.children?.length ? (
70
+ <TableOfContentsGroup
71
+ key={item.id}
72
+ label={item.label}
73
+ href={item.href}
74
+ active={current === item.id}
75
+ onLabelClick={(event) => handleClick(item, event)}
76
+ >
77
+ {renderItems(item.children)}
78
+ </TableOfContentsGroup>
79
+ ) : (
80
+ <TableOfContentsItem
81
+ key={item.id}
82
+ href={item.href ?? `#${item.id}`}
83
+ active={current === item.id}
84
+ onClick={(event) => handleClick(item, event)}
85
+ >
86
+ {item.label}
87
+ </TableOfContentsItem>
88
+ ),
89
+ )
90
+ return (
91
+ <TableOfContentsRoot ref={ref} {...props}>
92
+ {items ? (
93
+ <>
94
+ {title != null && <TableOfContentsTitle>{title}</TableOfContentsTitle>}
95
+ <TableOfContentsList>{renderItems(items)}</TableOfContentsList>
96
+ </>
97
+ ) : (
98
+ children
99
+ )}
100
+ </TableOfContentsRoot>
101
+ )
102
+ },
103
+ )
104
+ export const TableOfContents = Object.assign(TableOfContentsComponent, {
105
+ Root: TableOfContentsRoot,
106
+ Title: TableOfContentsTitle,
107
+ List: TableOfContentsList,
108
+ Item: TableOfContentsItem,
109
+ Group: TableOfContentsGroup,
110
+ })
111
+ export {
112
+ TableOfContentsRoot,
113
+ TableOfContentsTitle,
114
+ TableOfContentsList,
115
+ TableOfContentsItem,
116
+ TableOfContentsGroup,
117
+ }
118
+ export type {
119
+ TableOfContentsItemProps,
120
+ TableOfContentsGroupProps,
121
+ } from '../_internal/table-of-contents'
@@ -182,6 +182,10 @@
182
182
  --button-gap: calc(var(--spacing) * 1.5);
183
183
  --button-brand-font-weight: 600;
184
184
  --button-brand-text-shadow: 0 1px 1px #00000059, 0 0 1px #00000040;
185
+ --layer-card-radius: var(--radius-lg);
186
+ --layer-card-shadow: 0 1px 2px #0000000d;
187
+ --flow-node-shadow: 0 1px 2px #0000000d;
188
+ --flow-canvas-background-image: radial-gradient(var(--border-disabled) 1px, transparent 1px);
185
189
  --button-secondary-border: var(--border-secondary);
186
190
  --button-secondary-hover-bg: var(--bg-surface-hover);
187
191
  --button-secondary-shadow: 0 1px 2px #0000000d;
@@ -495,6 +499,10 @@
495
499
  --button-brand-font-weight: 600;
496
500
  --button-brand-text-shadow: 0 1px 1px #00000059, 0 0 1px #00000040;
497
501
  --card-radius: var(--radius-xl);
502
+ --layer-card-radius: var(--radius-lg);
503
+ --layer-card-shadow: 0 1px 2px #0000000d;
504
+ --flow-node-shadow: 0 1px 2px #0000000d;
505
+ --flow-canvas-background-image: radial-gradient(var(--border-disabled) 1px, transparent 1px);
498
506
  --input-radius: var(--radius-lg);
499
507
  --input-height: calc(var(--spacing) * 9);
500
508
  --badge-radius: var(--radius-md);
@@ -88,6 +88,10 @@ const shape: Record<string, string> = {
88
88
  '--button-brand-font-weight': '600',
89
89
  '--button-brand-text-shadow': '0 1px 1px #00000059, 0 0 1px #00000040',
90
90
  '--card-radius': 'var(--radius-xl)',
91
+ '--layer-card-radius': 'var(--radius-lg)',
92
+ '--layer-card-shadow': '0 1px 2px #0000000D',
93
+ '--flow-node-shadow': '0 1px 2px #0000000D',
94
+ '--flow-canvas-background-image': 'radial-gradient(var(--border-disabled) 1px, transparent 1px)',
91
95
  '--input-radius': 'var(--radius-lg)',
92
96
  '--input-height': 'calc(var(--spacing) * 9)',
93
97
  '--badge-radius': 'var(--radius-md)',
@@ -103,6 +103,24 @@
103
103
  --button-brand-5-hover-background-image: none;
104
104
  --button-brand-5-shadow: none;
105
105
  --button-brand-5-hover-shadow: initial;
106
+ /* Layered content surfaces, flow diagrams, and copy fields. */
107
+ --layer-card-radius: var(--card-radius);
108
+ --layer-card-padding: var(--card-padding);
109
+ --layer-card-shadow: var(--shadow-sm);
110
+ --clipboard-text-radius: var(--input-radius);
111
+ --clipboard-text-height: var(--input-height);
112
+ --clipboard-text-height-sm: calc(var(--spacing) * 6.5);
113
+ --clipboard-text-height-lg: calc(var(--spacing) * 10);
114
+ --flow-gap: calc(var(--spacing) * 10);
115
+ --flow-branch-gap: calc(var(--spacing) * 4);
116
+ --flow-node-radius: var(--radius-md);
117
+ --flow-node-shadow: var(--shadow-sm);
118
+ --flow-connector-color: initial;
119
+ --flow-canvas-radius: var(--radius-lg);
120
+ --flow-canvas-padding-x: calc(var(--spacing) * 4);
121
+ --flow-canvas-padding-y: calc(var(--spacing) * 12);
122
+ --flow-canvas-background-image: none;
123
+ --flow-canvas-background-size: calc(var(--spacing) * 4);
106
124
  --card-radius: var(--radius-lg);
107
125
  --card-padding: calc(var(--spacing) * 4);
108
126
  --input-radius: var(--radius-md);