@cognitap/radiant 0.0.84 → 0.0.86

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 (55) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/library/components/CodeBlock/CodeBlock.d.ts.map +1 -1
  3. package/dist/library/components/CodeBlock/CodeBlock.js +3 -37
  4. package/dist/library/components/CodeBlock/CodeBlock.js.map +1 -1
  5. package/dist/library/components/Collapsible/Collapsible.d.ts +5 -1
  6. package/dist/library/components/Collapsible/Collapsible.d.ts.map +1 -1
  7. package/dist/library/components/Collapsible/Collapsible.js +13 -3
  8. package/dist/library/components/Collapsible/Collapsible.js.map +1 -1
  9. package/dist/library/components/CopyButton/CopyButton.d.ts +17 -0
  10. package/dist/library/components/CopyButton/CopyButton.d.ts.map +1 -0
  11. package/dist/library/components/CopyButton/CopyButton.js +22 -0
  12. package/dist/library/components/CopyButton/CopyButton.js.map +1 -0
  13. package/dist/library/components/Dropzone/Dropzone.d.ts +26 -0
  14. package/dist/library/components/Dropzone/Dropzone.d.ts.map +1 -0
  15. package/dist/library/components/Dropzone/Dropzone.js +119 -0
  16. package/dist/library/components/Dropzone/Dropzone.js.map +1 -0
  17. package/dist/library/components/Highlight/Highlight.d.ts +15 -0
  18. package/dist/library/components/Highlight/Highlight.d.ts.map +1 -0
  19. package/dist/library/components/Highlight/Highlight.js +69 -0
  20. package/dist/library/components/Highlight/Highlight.js.map +1 -0
  21. package/dist/library/components/Spoiler/Spoiler.d.ts +15 -0
  22. package/dist/library/components/Spoiler/Spoiler.d.ts.map +1 -0
  23. package/dist/library/components/Spoiler/Spoiler.js +34 -0
  24. package/dist/library/components/Spoiler/Spoiler.js.map +1 -0
  25. package/dist/library/components/Tour/Tour.d.ts +31 -0
  26. package/dist/library/components/Tour/Tour.d.ts.map +1 -0
  27. package/dist/library/components/Tour/Tour.js +145 -0
  28. package/dist/library/components/Tour/Tour.js.map +1 -0
  29. package/dist/library/index.d.ts +9 -0
  30. package/dist/library/index.d.ts.map +1 -1
  31. package/dist/library/index.js +5 -0
  32. package/dist/library/index.js.map +1 -1
  33. package/dist/library/motion/transitions.d.ts.map +1 -1
  34. package/dist/library/motion/transitions.js +8 -3
  35. package/dist/library/motion/transitions.js.map +1 -1
  36. package/dist/library/react/useClipboardCopy.d.ts +8 -0
  37. package/dist/library/react/useClipboardCopy.d.ts.map +1 -0
  38. package/dist/library/react/useClipboardCopy.js +49 -0
  39. package/dist/library/react/useClipboardCopy.js.map +1 -0
  40. package/dist/library/react/usePopoverSurface.d.ts.map +1 -1
  41. package/dist/library/react/usePopoverSurface.js +3 -2
  42. package/dist/library/react/usePopoverSurface.js.map +1 -1
  43. package/dist/library/styles.css +1 -1
  44. package/package.json +1 -1
  45. package/src/components/CodeBlock/CodeBlock.tsx +3 -45
  46. package/src/components/Collapsible/Collapsible.tsx +22 -4
  47. package/src/components/CopyButton/CopyButton.tsx +75 -0
  48. package/src/components/Dropzone/Dropzone.tsx +232 -0
  49. package/src/components/Highlight/Highlight.tsx +112 -0
  50. package/src/components/Spoiler/Spoiler.tsx +97 -0
  51. package/src/components/Tour/Tour.tsx +335 -0
  52. package/src/index.ts +15 -0
  53. package/src/motion/transitions.ts +8 -3
  54. package/src/react/useClipboardCopy.ts +54 -0
  55. package/src/react/usePopoverSurface.ts +3 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cognitap/radiant",
3
- "version": "0.0.84",
3
+ "version": "0.0.86",
4
4
  "description": "React interaction components and presentation primitives",
5
5
  "homepage": "https://radiant-docs.pages.dev",
6
6
  "bugs": {
@@ -1,14 +1,6 @@
1
1
  'use client'
2
2
 
3
- import {
4
- createContext,
5
- useContext,
6
- useEffect,
7
- useId,
8
- useRef,
9
- useState,
10
- type ComponentProps
11
- } from 'react'
3
+ import { createContext, useContext, useId, type ComponentProps } from 'react'
12
4
  import { Button, type ButtonProps, type ButtonRenderProps } from '../Button/Button.js'
13
5
  import { ScrollArea, type ScrollAreaProps } from '../ScrollArea/ScrollArea.js'
14
6
  import { cn } from 'cn'
@@ -16,10 +8,9 @@ import { joinIds } from '../../internal/ids.js'
16
8
  import { composeAction } from '../../internal/events.js'
17
9
  import type { DistributiveOmit, WithoutToggle } from '../../internal/types.js'
18
10
  import type { PartStyle } from '../../presentation.js'
11
+ import { useClipboardCopy } from '../../react/useClipboardCopy.js'
19
12
  import type { ThemeStyle } from '../../themes/defineTheme.js'
20
13
 
21
- type Phase = 'idle' | 'pending' | 'success' | 'error'
22
- type Feedback = { source: string; phase: Phase }
23
14
  type Native<Host extends 'div' | 'pre'> = Omit<ComponentProps<Host>, 'style'> & {
24
15
  style?: ThemeStyle
25
16
  'data-slot'?: string
@@ -68,41 +59,8 @@ export function CodeBlock({
68
59
  ...props
69
60
  }: CodeBlockProps) {
70
61
  if (typeof code !== 'string') throw new TypeError('CodeBlock code must be a string.')
71
- const [feedback, setFeedback] = useState<Feedback>({ source: code, phase: 'idle' })
72
- const [pending, setPending] = useState(false)
73
- const busy = useRef(false),
74
- mounted = useRef(true),
75
- operation = useRef(0)
76
62
  const statusId = useId()
77
- // Forget feedback for replaced source without cancelling an already requested browser write.
78
- if (feedback.source !== code) setFeedback({ source: code, phase: 'idle' })
79
- useEffect(() => {
80
- mounted.current = true
81
- return () => {
82
- mounted.current = false
83
- operation.current += 1
84
- }
85
- }, [])
86
- const copy = async (win: Window | null) => {
87
- if (busy.current) return
88
- const source = code,
89
- request = ++operation.current
90
- busy.current = true
91
- setPending(true)
92
- setFeedback({ source, phase: 'pending' })
93
- let phase: Phase = 'success'
94
- try {
95
- if (!win?.navigator.clipboard?.writeText) throw new Error('Clipboard writing is unavailable.')
96
- await win.navigator.clipboard.writeText(source)
97
- } catch {
98
- phase = 'error'
99
- }
100
- if (!mounted.current || request !== operation.current) return
101
- busy.current = false
102
- setPending(false)
103
- setFeedback(current => (current.source === source ? { source, phase } : current))
104
- }
105
- const phase = feedback.source === code ? feedback.phase : 'idle'
63
+ const { copy, pending, phase } = useClipboardCopy(code)
106
64
  const message =
107
65
  phase === 'pending'
108
66
  ? loadingText
@@ -28,11 +28,12 @@ const collapsibleVariants = cva([
28
28
  '[color:var(--rad-collapsible-color,var(--rad-color-foreground,oklch(0.21_0.006_286)))]',
29
29
  '[box-shadow:var(--rad-collapsible-shadow,var(--rad-surface-shadow,none))] [backdrop-filter:var(--rad-surface-backdrop-filter,none)]',
30
30
  '[&::details-content]:overflow-hidden',
31
+ '[--_rad-disclosure-preview:0px]',
31
32
  '[&::details-content]:[interpolate-size:allow-keywords]',
32
33
  '[&::details-content]:transition-[height]',
33
34
  '[&::details-content]:duration-[var(--rad-collapsible-duration,var(--rad-motion-disclosure-duration,150ms))]',
34
35
  '[&::details-content]:ease-out',
35
- '[&:not([open])::details-content]:h-0',
36
+ '[&:not([open])::details-content]:h-[var(--_rad-disclosure-preview,0px)]',
36
37
  'open:[&::details-content]:h-auto',
37
38
  'motion-reduce:[&::details-content]:transition-none',
38
39
  'forced-colors:border-[CanvasText] forced-colors:bg-[Canvas] forced-colors:text-[CanvasText]'
@@ -108,7 +109,12 @@ function useCollapsibleContext() {
108
109
  return collapsible
109
110
  }
110
111
 
111
- export function Collapsible({
112
+ export function Collapsible(props: CollapsibleProps) {
113
+ return <CollapsibleRoot {...props} />
114
+ }
115
+
116
+ /** Private collapsed preview seam for Spoiler. */
117
+ export function CollapsibleRoot({
112
118
  open,
113
119
  defaultOpen,
114
120
  motion = 'inherit',
@@ -117,8 +123,10 @@ export function Collapsible({
117
123
  onToggle,
118
124
  className,
119
125
  children,
126
+ previewHeight,
127
+ style,
120
128
  ...props
121
- }: CollapsibleProps) {
129
+ }: CollapsibleProps & { previewHeight?: number }) {
122
130
  const node = useRef<HTMLDetailsElement>(null)
123
131
  const nativeRef = useComposedRefs(node, ref)
124
132
  const transition = useTransitionHost<HTMLDetailsElement>(
@@ -160,11 +168,21 @@ export function Collapsible({
160
168
  collapsibleVariants(),
161
169
  transition.active &&
162
170
  transition.ready &&
163
- '[&::details-content]:[content-visibility:visible] [&::details-content]:transition-none [&:not([open])::details-content]:h-[var(--_rad-spring-details-height,0px)] open:[&::details-content]:h-[var(--_rad-spring-details-height,auto)]',
171
+ '[&::details-content]:[content-visibility:visible] [&::details-content]:transition-none [&:not([open])::details-content]:h-[var(--_rad-spring-details-height,var(--_rad-disclosure-preview,0px))] open:[&::details-content]:h-[var(--_rad-spring-details-height,auto)]',
172
+ previewHeight !== undefined && '[&::details-content]:[content-visibility:visible]',
164
173
  motionOff && '[&::details-content]:transition-none [&>summary>svg]:transition-none',
165
174
  className
166
175
  )}
167
176
  data-slot={joinIds('collapsible', props['data-slot'])}
177
+ data-rad-disclosure-preview={previewHeight}
178
+ style={
179
+ previewHeight === undefined
180
+ ? style
181
+ : {
182
+ ...style,
183
+ '--_rad-disclosure-preview': `${previewHeight}px`
184
+ }
185
+ }
168
186
  data-state={isOpen ? 'open' : 'closed'}
169
187
  open={isOpen}
170
188
  onToggle={event => {
@@ -0,0 +1,75 @@
1
+ 'use client'
2
+
3
+ import { useId } from 'react'
4
+ import { cn } from 'cn'
5
+ import { composeAction } from '../../internal/events.js'
6
+ import { joinIds } from '../../internal/ids.js'
7
+ import type { DistributiveOmit, WithoutToggle } from '../../internal/types.js'
8
+ import type { PartStyle } from '../../presentation.js'
9
+ import { useClipboardCopy } from '../../react/useClipboardCopy.js'
10
+ import { Button, type ButtonProps, type ButtonRenderProps } from '../Button/Button.js'
11
+
12
+ export type CopyButtonRenderProps = ButtonRenderProps
13
+ export type CopyButtonProps = WithoutToggle<DistributiveOmit<ButtonProps, 'type' | 'value'>> & {
14
+ /** The exact text to write. */
15
+ value: string
16
+ /** Milliseconds to show a successful write before clearing the confirmation. */
17
+ resetDelay?: number
18
+ copiedText?: string
19
+ errorText?: string
20
+ parts?: { status?: PartStyle }
21
+ }
22
+
23
+ export function CopyButton({
24
+ value,
25
+ resetDelay = 2000,
26
+ copiedText = 'Copied.',
27
+ errorText = 'Could not copy. Try again or copy the text manually.',
28
+ onClick,
29
+ children = 'Copy',
30
+ pending: externalPending,
31
+ parts,
32
+ ...props
33
+ }: CopyButtonProps) {
34
+ if (typeof value !== 'string') throw new TypeError('CopyButton value must be a string.')
35
+ if (!Number.isFinite(resetDelay) || resetDelay <= 0 || resetDelay > 2_147_483_647) {
36
+ throw new RangeError('CopyButton resetDelay must be a positive delay in milliseconds.')
37
+ }
38
+ const statusId = useId()
39
+ const { pending, phase, copy } = useClipboardCopy(value, resetDelay)
40
+ const message = phase === 'success' ? copiedText : phase === 'error' ? errorText : ''
41
+
42
+ return (
43
+ <>
44
+ <Button
45
+ {...props}
46
+ type="button"
47
+ pressed={undefined}
48
+ defaultPressed={undefined}
49
+ onPressedChange={undefined}
50
+ aria-pressed={undefined}
51
+ pending={externalPending || pending}
52
+ data-slot={joinIds('copy-button', props['data-slot'])}
53
+ aria-describedby={joinIds(props['aria-describedby'], statusId)}
54
+ onClick={composeAction(onClick, event => {
55
+ void copy(event.currentTarget.ownerDocument.defaultView)
56
+ })}
57
+ >
58
+ {children}
59
+ </Button>
60
+ <output
61
+ id={statusId}
62
+ data-slot="copy-button-status"
63
+ data-state={phase}
64
+ className={cn(
65
+ 'block min-w-0 text-sm [overflow-wrap:anywhere] empty:absolute empty:size-px empty:overflow-hidden',
66
+ phase === 'error' && '[color:var(--rad-color-invalid)]',
67
+ parts?.status?.className
68
+ )}
69
+ style={parts?.status?.style}
70
+ >
71
+ {message}
72
+ </output>
73
+ </>
74
+ )
75
+ }
@@ -0,0 +1,232 @@
1
+ 'use client'
2
+
3
+ /* oxlint-disable jsx-a11y/prefer-tag-over-role -- Native form reset must leave the React-managed status children in place. */
4
+ import { useId, useRef, useState, type DragEvent } from 'react'
5
+ import { cn } from 'cn'
6
+ import { joinIds } from '../../internal/ids.js'
7
+ import type { PartStyle } from '../../presentation.js'
8
+ import { useComposedRefs } from '../../react/useComposedRefs.js'
9
+ import { useFormReset } from '../../react/useFormReset.js'
10
+ import { useField } from '../Field/Field.js'
11
+ import { FileInput, type FileInputProps } from '../FileInput/FileInput.js'
12
+ import { focusWithinRingClass } from '../shared/focusStyles.js'
13
+
14
+ export type DropzoneRejection = {
15
+ file: File
16
+ reason: 'type' | 'size' | 'count'
17
+ }
18
+
19
+ export type DropzoneSelection = {
20
+ accepted: readonly File[]
21
+ rejected: readonly DropzoneRejection[]
22
+ }
23
+
24
+ export type DropzoneProps = Omit<
25
+ FileInputProps,
26
+ 'parts' | 'onChange' | 'onDrop' | 'onDragEnter' | 'onDragOver' | 'onDragLeave'
27
+ > & {
28
+ /** Per-file limit, in bytes. */
29
+ maxSize?: number
30
+ maxFiles?: number
31
+ description?: string
32
+ rejectionText?: (rejection: DropzoneRejection) => string
33
+ onFilesChange?: (selection: DropzoneSelection) => void
34
+ parts?: { label?: PartStyle; description?: PartStyle; status?: PartStyle }
35
+ }
36
+
37
+ const reasons = {
38
+ type: 'Unsupported file type',
39
+ size: 'File is too large',
40
+ count: 'Too many files'
41
+ }
42
+
43
+ function matchesAccept(file: File, tokens: string[]) {
44
+ if (!tokens.length) return true
45
+ const name = file.name.toLowerCase()
46
+ const type = file.type.toLowerCase()
47
+ return tokens.some(token =>
48
+ token.startsWith('.')
49
+ ? name.endsWith(token)
50
+ : token.endsWith('/*')
51
+ ? type.startsWith(token.slice(0, -1))
52
+ : type === token
53
+ )
54
+ }
55
+
56
+ /** A file input that accepts both file-picker and drop selections. */
57
+ export function Dropzone({
58
+ accept,
59
+ multiple,
60
+ maxSize,
61
+ maxFiles,
62
+ chooseLabel = multiple ? 'Choose files or drop them here' : 'Choose a file or drop it here',
63
+ description,
64
+ emptyText,
65
+ rejectionText = rejection => rejection.file.name + ' — ' + reasons[rejection.reason],
66
+ onFilesChange,
67
+ className,
68
+ style,
69
+ parts,
70
+ ref,
71
+ 'data-slot': slot,
72
+ 'aria-label': ariaLabel,
73
+ 'aria-labelledby': labelledBy,
74
+ 'aria-describedby': describedBy,
75
+ ...props
76
+ }: DropzoneProps) {
77
+ if (maxSize !== undefined && (!Number.isFinite(maxSize) || maxSize < 0)) {
78
+ throw new RangeError('Dropzone maxSize must be a nonnegative number of bytes.')
79
+ }
80
+ if (maxFiles !== undefined && (!Number.isSafeInteger(maxFiles) || maxFiles < 1)) {
81
+ throw new RangeError('Dropzone maxFiles must be a positive integer.')
82
+ }
83
+ const field = useField()
84
+ const input = useRef<HTMLInputElement>(null)
85
+ const inputRef = useComposedRefs(input, ref)
86
+ const labelId = useId()
87
+ const descriptionId = useId()
88
+ const depth = useRef(0)
89
+ const [dragOver, setDragOver] = useState(false)
90
+ const [selection, setSelection] = useState<DropzoneSelection | null>(null)
91
+ useFormReset(input, () => setSelection(null))
92
+ const disabled = props.disabled || field?.disabled
93
+ const tokens = (accept ?? '')
94
+ .toLowerCase()
95
+ .split(',')
96
+ .map(token => token.trim())
97
+ .filter(Boolean)
98
+
99
+ function select(node: HTMLInputElement, files: readonly File[], dropped = false) {
100
+ const accepted: File[] = []
101
+ const rejected: DropzoneRejection[] = []
102
+ for (const file of files) {
103
+ if (!matchesAccept(file, tokens)) rejected.push({ file, reason: 'type' })
104
+ else if (maxSize !== undefined && file.size > maxSize) rejected.push({ file, reason: 'size' })
105
+ else if (accepted.length >= (multiple ? (maxFiles ?? Infinity) : 1))
106
+ rejected.push({ file, reason: 'count' })
107
+ else accepted.push(file)
108
+ }
109
+ if (dropped || rejected.length) {
110
+ const view = node.ownerDocument.defaultView!
111
+ const transfer = new view.DataTransfer()
112
+ for (const file of accepted) transfer.items.add(file)
113
+ node.files = transfer.files
114
+ }
115
+ const result = { accepted, rejected }
116
+ setSelection(result)
117
+ onFilesChange?.(result)
118
+ }
119
+
120
+ function filesIn(event: DragEvent<HTMLDivElement>) {
121
+ return event.dataTransfer.types.includes('Files') || event.dataTransfer.files.length > 0
122
+ }
123
+ const active = !disabled && dragOver
124
+ const state = active
125
+ ? 'drag-over'
126
+ : selection?.rejected.length
127
+ ? 'rejected'
128
+ : selection?.accepted.length
129
+ ? 'accepted'
130
+ : 'idle'
131
+
132
+ return (
133
+ <div
134
+ data-slot={joinIds('dropzone', slot)}
135
+ data-state={state}
136
+ data-disabled={disabled ? '' : undefined}
137
+ className={cn(
138
+ 'relative grid min-w-0 w-full gap-1 rounded-[var(--rad-control-radius,0.5rem)] [corner-shape:var(--rad-control-corner-shape,round)] border-2 border-dashed border-[var(--rad-color-border)] bg-[var(--rad-color-surface)] px-4 py-5 text-center [color:var(--rad-color-foreground)]',
139
+ 'has-[input:enabled]:hover:bg-[var(--rad-color-neutral)] data-[state=drag-over]:border-[var(--rad-color-accent)] data-[state=drag-over]:bg-[var(--rad-color-neutral)] data-[state=rejected]:border-[var(--rad-color-invalid)] data-disabled:opacity-60 forced-colors:border-[CanvasText] forced-colors:data-[state=drag-over]:border-[Highlight]',
140
+ focusWithinRingClass,
141
+ className
142
+ )}
143
+ style={style}
144
+ onDragEnter={event => {
145
+ if (!filesIn(event)) return
146
+ event.preventDefault()
147
+ if (input.current?.matches(':enabled')) {
148
+ depth.current++
149
+ setDragOver(true)
150
+ }
151
+ }}
152
+ onDragOver={event => {
153
+ if (!filesIn(event)) return
154
+ event.preventDefault()
155
+ event.dataTransfer.dropEffect = input.current?.matches(':enabled') ? 'copy' : 'none'
156
+ }}
157
+ onDragLeave={() => {
158
+ depth.current = Math.max(0, depth.current - 1)
159
+ if (!depth.current) setDragOver(false)
160
+ }}
161
+ onDrop={event => {
162
+ depth.current = 0
163
+ setDragOver(false)
164
+ if (!filesIn(event)) return
165
+ event.preventDefault()
166
+ const node = input.current
167
+ if (node?.matches(':enabled')) select(node, Array.from(event.dataTransfer.files), true)
168
+ }}
169
+ >
170
+ <FileInput
171
+ {...props}
172
+ ref={inputRef}
173
+ multiple={multiple}
174
+ accept={accept}
175
+ aria-label={ariaLabel}
176
+ aria-labelledby={
177
+ labelledBy ??
178
+ (ariaLabel ? undefined : field?.layout === 'control' ? field.labelId : labelId)
179
+ }
180
+ aria-describedby={joinIds(describedBy, description ? descriptionId : undefined)}
181
+ onChange={event => select(event.currentTarget, Array.from(event.currentTarget.files ?? []))}
182
+ data-slot="dropzone-input"
183
+ className="disabled:cursor-not-allowed"
184
+ parts={{
185
+ wrapper: { className: 'absolute inset-0 z-10' },
186
+ trigger: { className: '[&[aria-hidden]]:hidden' },
187
+ files: { className: '[&[aria-hidden]]:hidden' }
188
+ }}
189
+ />
190
+ <span
191
+ id={labelId}
192
+ data-slot="dropzone-label"
193
+ className={cn('text-sm font-semibold', parts?.label?.className)}
194
+ style={parts?.label?.style}
195
+ >
196
+ {chooseLabel}
197
+ </span>
198
+ {description && (
199
+ <span
200
+ id={descriptionId}
201
+ data-slot="dropzone-description"
202
+ className={cn(
203
+ 'text-xs [color:var(--rad-color-muted-foreground)]',
204
+ parts?.description?.className
205
+ )}
206
+ style={parts?.description?.style}
207
+ >
208
+ {description}
209
+ </span>
210
+ )}
211
+ <div
212
+ role="status"
213
+ data-slot="dropzone-status"
214
+ className={cn('grid gap-1 text-xs [overflow-wrap:anywhere]', parts?.status?.className)}
215
+ style={parts?.status?.style}
216
+ >
217
+ {selection?.accepted.map((file, index) => (
218
+ <span key={index}>{file.name}</span>
219
+ ))}
220
+ {selection?.rejected.map((rejection, index) => (
221
+ <span
222
+ key={index}
223
+ className="[color:var(--rad-color-invalid)]"
224
+ >
225
+ {rejectionText(rejection)}
226
+ </span>
227
+ ))}
228
+ {!selection && emptyText}
229
+ </div>
230
+ </div>
231
+ )
232
+ }
@@ -0,0 +1,112 @@
1
+ 'use client'
2
+
3
+ import { useMemo, type ComponentProps, type ReactNode } from 'react'
4
+ import { cn } from 'cn'
5
+ import { joinIds } from '../../internal/ids.js'
6
+ import { supportedLocale } from '../../internal/locale.js'
7
+ import type { PartStyle } from '../../presentation.js'
8
+ import { useLocale } from '../../react/useLocale.js'
9
+
10
+ export type HighlightProps = Omit<ComponentProps<'span'>, 'children' | 'style'> & {
11
+ text: string
12
+ query: string
13
+ caseSensitive?: boolean
14
+ ignoreDiacritics?: boolean
15
+ parts?: { mark?: PartStyle }
16
+ style?: PartStyle['style']
17
+ 'data-slot'?: string
18
+ }
19
+
20
+ function findRanges(
21
+ text: string,
22
+ query: string,
23
+ segmenter: Intl.Segmenter,
24
+ caseSensitive: boolean,
25
+ ignoreDiacritics: boolean
26
+ ) {
27
+ const ranges: { start: number; end: number }[] = []
28
+ if (!query || !text) return ranges
29
+ const locale = segmenter.resolvedOptions().locale
30
+ function fold(segment: string) {
31
+ const composed = segment.normalize()
32
+ const cased = caseSensitive
33
+ ? composed
34
+ : composed.toLocaleLowerCase(locale).toLocaleUpperCase(locale)
35
+ const decomposed = cased.normalize('NFD')
36
+ return ignoreDiacritics ? decomposed.replace(/\p{Diacritic}/gu, '') : decomposed
37
+ }
38
+ const needle = Array.from(segmenter.segment(query), value => fold(value.segment)).join('')
39
+ if (!needle) return ranges
40
+
41
+ let folded = ''
42
+ const starts = new Map<number, number>()
43
+ const ends = new Map<number, number>()
44
+ for (const { index, segment } of segmenter.segment(text)) {
45
+ const key = fold(segment)
46
+ if (!key) continue
47
+ // Folding can change a grapheme's length. Both boundaries must map to the original text.
48
+ starts.set(folded.length, index)
49
+ folded += key
50
+ ends.set(folded.length, index + segment.length)
51
+ }
52
+ let cursor = 0
53
+ while (cursor < folded.length) {
54
+ const index = folded.indexOf(needle, cursor)
55
+ if (index < 0) break
56
+ const limit = index + needle.length
57
+ const start = starts.get(index)
58
+ const end = ends.get(limit)
59
+ if (start !== undefined && end !== undefined) {
60
+ ranges.push({ start, end })
61
+ cursor = limit
62
+ } else cursor = index + 1
63
+ }
64
+ return ranges
65
+ }
66
+
67
+ export function Highlight({
68
+ text,
69
+ query,
70
+ caseSensitive = false,
71
+ ignoreDiacritics = false,
72
+ parts,
73
+ ...props
74
+ }: HighlightProps) {
75
+ const locale = useLocale()
76
+ const segmenter = useMemo(
77
+ () => new Intl.Segmenter(supportedLocale(Intl.Segmenter, locale)),
78
+ [locale]
79
+ )
80
+ const ranges = useMemo(
81
+ () => findRanges(text, query, segmenter, caseSensitive, ignoreDiacritics),
82
+ [text, query, segmenter, caseSensitive, ignoreDiacritics]
83
+ )
84
+ const content: ReactNode[] = []
85
+ let cursor = 0
86
+ for (const { start, end } of ranges) {
87
+ if (start > cursor) content.push(text.slice(cursor, start))
88
+ content.push(
89
+ <mark
90
+ key={start}
91
+ data-slot="highlight-mark"
92
+ className={cn(
93
+ 'rounded-[min(0.125rem,var(--rad-control-radius,0.125rem))] bg-[var(--rad-color-accent)] [color:var(--rad-color-accent-foreground)] [box-decoration-break:clone] forced-colors:bg-[Highlight] forced-colors:text-[HighlightText]',
94
+ parts?.mark?.className
95
+ )}
96
+ style={parts?.mark?.style}
97
+ >
98
+ {text.slice(start, end)}
99
+ </mark>
100
+ )
101
+ cursor = end
102
+ }
103
+ if (cursor < text.length) content.push(text.slice(cursor))
104
+ return (
105
+ <span
106
+ {...props}
107
+ data-slot={joinIds('highlight', props['data-slot'])}
108
+ >
109
+ {content}
110
+ </span>
111
+ )
112
+ }
@@ -0,0 +1,97 @@
1
+ 'use client'
2
+
3
+ import { useLayoutEffect, useRef, useState } from 'react'
4
+ import { cn } from 'cn'
5
+ import { joinIds } from '../../internal/ids.js'
6
+ import type { DistributiveOmit } from '../../internal/types.js'
7
+ import type { PartStyle } from '../../presentation.js'
8
+ import { useControllableState } from '../../react/useControllableState.js'
9
+ import {
10
+ CollapsibleContent,
11
+ CollapsibleRoot,
12
+ CollapsibleTrigger,
13
+ type CollapsibleProps
14
+ } from '../Collapsible/Collapsible.js'
15
+
16
+ export type SpoilerProps = DistributiveOmit<CollapsibleProps, 'name' | 'onToggle'> & {
17
+ /** Maximum height of the collapsed preview in CSS pixels. */
18
+ maxHeight?: number
19
+ showMoreLabel?: string
20
+ showLessLabel?: string
21
+ parts?: { trigger?: PartStyle; content?: PartStyle }
22
+ }
23
+
24
+ export function Spoiler({
25
+ maxHeight = 96,
26
+ open,
27
+ defaultOpen,
28
+ onOpenChange,
29
+ showMoreLabel = 'Show more',
30
+ showLessLabel = 'Show less',
31
+ motion,
32
+ className,
33
+ parts,
34
+ children,
35
+ ...props
36
+ }: SpoilerProps) {
37
+ if (!Number.isFinite(maxHeight) || maxHeight < 0) {
38
+ throw new RangeError('Spoiler maxHeight must be a nonnegative number of pixels.')
39
+ }
40
+ const state = useControllableState({
41
+ name: 'Spoiler',
42
+ value: open,
43
+ defaultValue: defaultOpen,
44
+ initialValue: false,
45
+ onChange: onOpenChange
46
+ })
47
+ const contentRef = useRef<HTMLDivElement>(null)
48
+ const [overflows, setOverflows] = useState<boolean | null>(null)
49
+ useLayoutEffect(() => {
50
+ const node = contentRef.current!
51
+ const win = node.ownerDocument.defaultView!
52
+ const measure = () => node.scrollHeight > maxHeight
53
+ // oxlint-disable-next-line react/set-state-in-effect -- Read external layout before showing a preview.
54
+ setOverflows(measure())
55
+ const observer = new win.ResizeObserver(() => setOverflows(measure()))
56
+ observer.observe(node)
57
+ return () => observer.disconnect()
58
+ }, [maxHeight])
59
+ const clipped = overflows === true && !state.value
60
+
61
+ return (
62
+ <CollapsibleRoot
63
+ {...props}
64
+ data-slot={joinIds('spoiler', props['data-slot'])}
65
+ className={cn('gap-0 [&::details-content]:row-start-1', className)}
66
+ open={!clipped}
67
+ onOpenChange={state.request}
68
+ motion={overflows === null ? 'off' : motion}
69
+ previewHeight={maxHeight}
70
+ >
71
+ <CollapsibleTrigger
72
+ data-slot="spoiler-trigger"
73
+ hidden={!overflows}
74
+ className={cn('row-start-2 py-2 [&[hidden]]:hidden', parts?.trigger?.className)}
75
+ style={parts?.trigger?.style}
76
+ >
77
+ {clipped ? showMoreLabel : showLessLabel}
78
+ </CollapsibleTrigger>
79
+ <CollapsibleContent
80
+ ref={contentRef}
81
+ data-slot="spoiler-content"
82
+ className={cn(
83
+ 'flow-root pt-[var(--rad-collapsible-content-padding,var(--rad-collapsible-padding,var(--rad-surface-padding,1.5rem)))]',
84
+ parts?.content?.className
85
+ )}
86
+ style={parts?.content?.style}
87
+ >
88
+ <div
89
+ inert={clipped}
90
+ aria-hidden={clipped || undefined}
91
+ >
92
+ {children}
93
+ </div>
94
+ </CollapsibleContent>
95
+ </CollapsibleRoot>
96
+ )
97
+ }