-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathhuge-document.tsx
More file actions
547 lines (482 loc) · 14.3 KB
/
Copy pathhuge-document.tsx
File metadata and controls
547 lines (482 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import { faker } from '@faker-js/faker'
import React, {
CSSProperties,
Dispatch,
StrictMode,
useCallback,
useEffect,
useState,
} from 'react'
import { createEditor as slateCreateEditor, Descendant, Editor } from 'slate'
import {
Editable,
RenderElementProps,
RenderChunkProps,
Slate,
withReact,
useSelected,
} from 'slate-react'
import { HeadingElement, ParagraphElement } from './custom-types.d'
const SUPPORTS_EVENT_TIMING =
typeof window !== 'undefined' && 'PerformanceEventTiming' in window
const SUPPORTS_LOAF_TIMING =
typeof window !== 'undefined' &&
'PerformanceLongAnimationFrameTiming' in window
interface Config {
blocks: number
chunking: boolean
chunkSize: number
chunkDivs: boolean
chunkOutlines: boolean
contentVisibilityMode: 'none' | 'element' | 'chunk'
showSelectedHeadings: boolean
strictMode: boolean
}
const blocksOptions = [
2, 1000, 2500, 5000, 7500, 10000, 15000, 20000, 25000, 30000, 40000, 50000,
100000, 200000,
]
const chunkSizeOptions = [3, 10, 100, 1000]
const searchParams =
typeof document === 'undefined'
? null
: new URLSearchParams(document.location.search)
const parseNumber = (key: string, defaultValue: number) =>
parseInt(searchParams?.get(key) ?? '', 10) || defaultValue
const parseBoolean = (key: string, defaultValue: boolean) => {
const value = searchParams?.get(key)
if (value) return value === 'true'
return defaultValue
}
const parseEnum = <T extends string>(
key: string,
options: T[],
defaultValue: T
): T => {
const value = searchParams?.get(key) as T | null | undefined
if (value && options.includes(value)) return value
return defaultValue
}
const initialConfig: Config = {
blocks: parseNumber('blocks', 10000),
chunking: parseBoolean('chunking', true),
chunkSize: parseNumber('chunk_size', 1000),
chunkDivs: parseBoolean('chunk_divs', true),
chunkOutlines: parseBoolean('chunk_outlines', false),
contentVisibilityMode: parseEnum(
'content_visibility',
['none', 'element', 'chunk'],
'chunk'
),
showSelectedHeadings: parseBoolean('selected_headings', false),
strictMode: parseBoolean('strict', false),
}
const setSearchParams = (config: Config) => {
if (searchParams) {
searchParams.set('blocks', config.blocks.toString())
searchParams.set('chunking', config.chunking ? 'true' : 'false')
searchParams.set('chunk_size', config.chunkSize.toString())
searchParams.set('chunk_divs', config.chunkDivs ? 'true' : 'false')
searchParams.set('chunk_outlines', config.chunkOutlines ? 'true' : 'false')
searchParams.set('content_visibility', config.contentVisibilityMode)
searchParams.set(
'selected_headings',
config.showSelectedHeadings ? 'true' : 'false'
)
searchParams.set('strict', config.strictMode ? 'true' : 'false')
history.replaceState({}, '', `?${searchParams.toString()}`)
}
}
const cachedInitialValue: Descendant[] = []
const getInitialValue = (blocks: number) => {
if (cachedInitialValue.length >= blocks) {
return cachedInitialValue.slice(0, blocks)
}
faker.seed(1)
for (let i = cachedInitialValue.length; i < blocks; i++) {
if (i % 100 === 0) {
const heading: HeadingElement = {
type: 'heading-one',
children: [{ text: faker.lorem.sentence() }],
}
cachedInitialValue.push(heading)
} else {
const paragraph: ParagraphElement = {
type: 'paragraph',
children: [{ text: faker.lorem.paragraph() }],
}
cachedInitialValue.push(paragraph)
}
}
return cachedInitialValue.slice()
}
const initialInitialValue =
typeof window === 'undefined' ? [] : getInitialValue(initialConfig.blocks)
const createEditor = (config: Config) => {
const editor = withReact(slateCreateEditor())
editor.getChunkSize = node =>
config.chunking && node === editor ? config.chunkSize : null
return editor
}
const HugeDocumentExample = () => {
const [rendering, setRendering] = useState(false)
const [config, baseSetConfig] = useState<Config>(initialConfig)
const [initialValue, setInitialValue] = useState(initialInitialValue)
const [editor, setEditor] = useState(() => createEditor(config))
const [editorVersion, setEditorVersion] = useState(0)
const setConfig = useCallback(
(partialConfig: Partial<Config>) => {
const newConfig = { ...config, ...partialConfig }
setRendering(true)
baseSetConfig(newConfig)
setSearchParams(newConfig)
setTimeout(() => {
setRendering(false)
setInitialValue(getInitialValue(newConfig.blocks))
setEditor(createEditor(newConfig))
setEditorVersion(n => n + 1)
})
},
[config]
)
const renderElement = useCallback(
(props: RenderElementProps) => (
<Element
{...props}
contentVisibility={config.contentVisibilityMode === 'element'}
showSelectedHeadings={config.showSelectedHeadings}
/>
),
[config.contentVisibilityMode, config.showSelectedHeadings]
)
const renderChunk = useCallback(
(props: RenderChunkProps) => (
<Chunk
{...props}
contentVisibilityLowest={config.contentVisibilityMode === 'chunk'}
outline={config.chunkOutlines}
/>
),
[config.contentVisibilityMode, config.chunkOutlines]
)
const editable = rendering ? (
<div>Rendering…</div>
) : (
<Slate key={editorVersion} editor={editor} initialValue={initialValue}>
<Editable
placeholder="Enter some text…"
renderElement={renderElement}
renderChunk={config.chunkDivs ? renderChunk : undefined}
spellCheck
autoFocus
/>
</Slate>
)
const editableWithStrictMode = config.strictMode ? (
<StrictMode>{editable}</StrictMode>
) : (
editable
)
return (
<>
<PerformanceControls
editor={editor}
config={config}
setConfig={setConfig}
/>
{editableWithStrictMode}
</>
)
}
const Chunk = ({
attributes,
children,
lowest,
contentVisibilityLowest,
outline,
}: RenderChunkProps & {
contentVisibilityLowest: boolean
outline: boolean
}) => {
const style: CSSProperties = {
contentVisibility: contentVisibilityLowest && lowest ? 'auto' : undefined,
border: outline ? '1px solid red' : undefined,
padding: outline ? 20 : undefined,
marginBottom: outline ? 20 : undefined,
}
return (
<div {...attributes} style={style}>
{children}
</div>
)
}
const Heading = React.forwardRef<
HTMLHeadingElement,
React.ComponentProps<'h1'> & { showSelectedHeadings: boolean }
>(({ style: styleProp, showSelectedHeadings = false, ...props }, ref) => {
// Fine since the editor is remounted if the config changes
// eslint-disable-next-line react-hooks/rules-of-hooks
const selected = showSelectedHeadings ? useSelected() : false
const style = { ...styleProp, color: selected ? 'green' : undefined }
return <h1 ref={ref} {...props} aria-selected={selected} style={style} />
})
const Paragraph = 'p'
const Element = ({
attributes,
children,
element,
contentVisibility,
showSelectedHeadings,
}: RenderElementProps & {
contentVisibility: boolean
showSelectedHeadings: boolean
}) => {
const style: CSSProperties = {
contentVisibility: contentVisibility ? 'auto' : undefined,
}
switch (element.type) {
case 'heading-one':
return (
<Heading
{...attributes}
style={style}
showSelectedHeadings={showSelectedHeadings}
>
{children}
</Heading>
)
default:
return (
<Paragraph {...attributes} style={style}>
{children}
</Paragraph>
)
}
}
const PerformanceControls = ({
editor,
config,
setConfig,
}: {
editor: Editor
config: Config
setConfig: Dispatch<Partial<Config>>
}) => {
const [configurationOpen, setConfigurationOpen] = useState(true)
const [keyPressDurations, setKeyPressDurations] = useState<number[]>([])
const [lastLongAnimationFrameDuration, setLastLongAnimationFrameDuration] =
useState<number | null>(null)
const lastKeyPressDuration: number | null = keyPressDurations[0] ?? null
const averageKeyPressDuration =
keyPressDurations.length === 10
? Math.round(keyPressDurations.reduce((total, d) => total + d) / 10)
: null
useEffect(() => {
if (!SUPPORTS_EVENT_TIMING) return
const observer = new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
if (entry.name === 'keypress') {
const duration = Math.round(
// @ts-ignore Entry type is missing processingStart and processingEnd
entry.processingEnd - entry.processingStart
)
setKeyPressDurations(durations => [
duration,
...durations.slice(0, 9),
])
}
})
})
// @ts-ignore Options type is missing durationThreshold
observer.observe({ type: 'event', durationThreshold: 16 })
return () => observer.disconnect()
}, [])
useEffect(() => {
if (!SUPPORTS_LOAF_TIMING) return
const { apply } = editor
let afterOperation = false
editor.apply = operation => {
apply(operation)
afterOperation = true
}
const observer = new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
if (afterOperation) {
setLastLongAnimationFrameDuration(Math.round(entry.duration))
afterOperation = false
}
})
})
// Register the observer for events
observer.observe({ type: 'long-animation-frame' })
return () => observer.disconnect()
}, [editor])
return (
<div className="performance-controls">
<p>
<label>
Blocks:{' '}
<select
value={config.blocks}
onChange={event =>
setConfig({
blocks: parseInt(event.target.value, 10),
})
}
>
{blocksOptions.map(blocks => (
<option key={blocks} value={blocks}>
{blocks.toString().replace(/(\d{3})$/, ',$1')}
</option>
))}
</select>
</label>
</p>
<details
open={configurationOpen}
onToggle={event => setConfigurationOpen(event.currentTarget.open)}
>
<summary>Configuration</summary>
<p>
<label>
<input
type="checkbox"
checked={config.chunking}
onChange={event =>
setConfig({
chunking: event.target.checked,
})
}
/>{' '}
Chunking enabled
</label>
</p>
{config.chunking && (
<>
<p>
<label>
<input
type="checkbox"
checked={config.chunkDivs}
onChange={event =>
setConfig({
chunkDivs: event.target.checked,
})
}
/>{' '}
Render each chunk as a separate <code><div></code>
</label>
</p>
{config.chunkDivs && (
<p>
<label>
<input
type="checkbox"
checked={config.chunkOutlines}
onChange={event =>
setConfig({
chunkOutlines: event.target.checked,
})
}
/>{' '}
Outline each chunk
</label>
</p>
)}
<p>
<label>
Chunk size:{' '}
<select
value={config.chunkSize}
onChange={event =>
setConfig({
chunkSize: parseInt(event.target.value, 10),
})
}
>
{chunkSizeOptions.map(chunkSize => (
<option key={chunkSize} value={chunkSize}>
{chunkSize}
</option>
))}
</select>
</label>
</p>
</>
)}
<p>
<label>
Set <code>content-visibility: auto</code> on:{' '}
<select
value={config.contentVisibilityMode}
onChange={event =>
setConfig({
contentVisibilityMode: event.target.value as any,
})
}
>
<option value="none">None</option>
<option value="element">Elements</option>
{config.chunking && config.chunkDivs && (
<option value="chunk">Lowest chunks</option>
)}
</select>
</label>
</p>
<p>
<label>
<input
type="checkbox"
checked={config.showSelectedHeadings}
onChange={event =>
setConfig({
showSelectedHeadings: event.target.checked,
})
}
/>{' '}
Call <code>useSelected</code> in each heading
</label>
</p>
<p>
<label>
<input
type="checkbox"
checked={config.strictMode}
onChange={event =>
setConfig({
strictMode: event.target.checked,
})
}
/>{' '}
React strict mode (only works in localhost)
</label>
</p>
</details>
<details>
<summary>Statistics</summary>
<p>
Last keypress (ms):{' '}
{SUPPORTS_EVENT_TIMING
? lastKeyPressDuration ?? '-'
: 'Not supported'}
</p>
<p>
Average of last 10 keypresses (ms):{' '}
{SUPPORTS_EVENT_TIMING
? averageKeyPressDuration ?? '-'
: 'Not supported'}
</p>
<p>
Last long animation frame (ms):{' '}
{SUPPORTS_LOAF_TIMING
? lastLongAnimationFrameDuration ?? '-'
: 'Not supported'}
</p>
{SUPPORTS_EVENT_TIMING && lastKeyPressDuration === null && (
<p>Events shorter than 16ms may not be detected.</p>
)}
</details>
</div>
)
}
export default HugeDocumentExample