forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.tsx
86 lines (77 loc) · 2.1 KB
/
text.tsx
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
import React, { useRef } from 'react'
import { Range, Element, Text as SlateText } from 'slate'
import Leaf from './leaf'
import { ReactEditor, useSlateStatic } from '..'
import { RenderLeafProps, RenderPlaceholderProps } from './editable'
import { useIsomorphicLayoutEffect } from '../hooks/use-isomorphic-layout-effect'
import {
KEY_TO_ELEMENT,
NODE_TO_ELEMENT,
ELEMENT_TO_NODE,
} from '../utils/weak-maps'
import { isDecoratorRangeListEqual } from '../utils/range-list'
/**
* Text.
*/
const Text = (props: {
decorations: Range[]
isLast: boolean
parent: Element
renderPlaceholder: (props: RenderPlaceholderProps) => JSX.Element
renderLeaf?: (props: RenderLeafProps) => JSX.Element
text: SlateText
}) => {
const {
decorations,
isLast,
parent,
renderPlaceholder,
renderLeaf,
text,
} = props
const editor = useSlateStatic()
const ref = useRef<HTMLSpanElement>(null)
const leaves = SlateText.decorations(text, decorations)
const key = ReactEditor.findKey(editor, text)
const children = []
for (let i = 0; i < leaves.length; i++) {
const leaf = leaves[i]
children.push(
<Leaf
isLast={isLast && i === leaves.length - 1}
key={`${key.id}-${i}`}
renderPlaceholder={renderPlaceholder}
leaf={leaf}
text={text}
parent={parent}
renderLeaf={renderLeaf}
/>
)
}
// Update element-related weak maps with the DOM element ref.
useIsomorphicLayoutEffect(() => {
if (ref.current) {
KEY_TO_ELEMENT.set(key, ref.current)
NODE_TO_ELEMENT.set(text, ref.current)
ELEMENT_TO_NODE.set(ref.current, text)
} else {
KEY_TO_ELEMENT.delete(key)
NODE_TO_ELEMENT.delete(text)
}
})
return (
<span data-slate-node="text" ref={ref}>
{children}
</span>
)
}
const MemoizedText = React.memo(Text, (prev, next) => {
return (
next.parent === prev.parent &&
next.isLast === prev.isLast &&
next.renderLeaf === prev.renderLeaf &&
next.text === prev.text &&
isDecoratorRangeListEqual(next.decorations, prev.decorations)
)
})
export default MemoizedText