forked from ianstormtaylor/slate
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch-highlighting.js
More file actions
106 lines (96 loc) · 2.55 KB
/
search-highlighting.js
File metadata and controls
106 lines (96 loc) · 2.55 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
import React, { useState, useCallback, useMemo } from 'react'
import { Slate, Editable, withReact } from 'slate-react'
import { Text, createEditor } from 'slate'
import { css } from 'emotion'
import { withHistory } from 'slate-history'
import { Icon, Toolbar } from '../components'
const SearchHighlightingExample = () => {
const [value, setValue] = useState(initialValue)
const [search, setSearch] = useState()
const editor = useMemo(() => withHistory(withReact(createEditor())), [])
const decorate = useCallback(
([node, path]) => {
const ranges = []
if (search && Text.isText(node)) {
const { text } = node
const parts = text.split(search)
let offset = 0
parts.forEach((part, i) => {
if (i !== 0) {
ranges.push({
anchor: { path, offset: offset - search.length },
focus: { path, offset },
highlight: true,
})
}
offset = offset + part.length + search.length
})
}
return ranges
},
[search]
)
return (
<Slate editor={editor} value={value} onChange={value => setValue(value)}>
<Toolbar>
<div
className={css`
position: relative;
`}
>
<Icon
className={css`
position: absolute;
top: 0.5em;
left: 0.5em;
color: #ccc;
`}
>
search
</Icon>
<input
type="search"
placeholder="Search the text..."
onChange={e => setSearch(e.target.value)}
className={css`
padding-left: 2em;
width: 100%;
`}
/>
</div>
</Toolbar>
<Editable decorate={decorate} renderLeaf={props => <Leaf {...props} />} />
</Slate>
)
}
const Leaf = ({ attributes, children, leaf }) => {
return (
<span
{...attributes}
className={css`
font-weight: ${leaf.bold && 'bold'};
background-color: ${leaf.highlight && '#ffeeba'};
`}
>
{children}
</span>
)
}
const initialValue = [
{
children: [
{
text:
'This is editable text that you can search. As you search, it looks for matching strings of text, and adds ',
},
{ text: 'decorations', bold: true },
{ text: ' to them in realtime.' },
],
},
{
children: [
{ text: 'Try it out for yourself by typing in the search box above!' },
],
},
]
export default SearchHighlightingExample