|
1 | 1 | 'use strict'
|
2 | 2 |
|
3 |
| -var eof = 0 // '' |
4 |
| -var lineFeed = 10 // '\n' |
5 |
| -var carriageReturn = 13 // '\r' |
6 |
| - |
7 | 3 | module.exports = fromText
|
8 | 4 |
|
| 5 | +var search = /\r?\n|\r/g |
| 6 | + |
9 | 7 | // Implementation of the `innerText` setter:
|
10 | 8 | // <https://html.spec.whatwg.org/#the-innertext-idl-attribute>
|
11 | 9 | // Note that `innerText` only exists on element.
|
12 | 10 | // In this utility, we accept all parent nodes and handle them as elements, and
|
13 | 11 | // for all literals we set the `value` of the given node the the given value.
|
14 |
| -function fromText(node, value) { |
15 |
| - var fn = 'children' in node ? setParent : setLiteral |
16 |
| - |
17 |
| - fn(node, value === null || value === undefined ? '' : String(value)) |
18 |
| - |
19 |
| - return node |
20 |
| -} |
21 |
| - |
22 |
| -function setParent(node, value) { |
| 12 | +function fromText(node, content) { |
| 13 | + var value = content == null ? '' : String(content) |
23 | 14 | var nodes = []
|
24 |
| - var length = value.length |
25 |
| - var index = 0 |
26 | 15 | var start = 0
|
27 |
| - var end = -1 |
28 |
| - var char = 0 |
29 |
| - var br = false |
30 |
| - |
31 |
| - node.children = [] |
32 |
| - |
33 |
| - while (index <= length) { |
34 |
| - char = index === length ? 0 : value.charCodeAt(index) |
35 |
| - |
36 |
| - switch (char) { |
37 |
| - case eof: |
38 |
| - end = index |
39 |
| - break |
40 |
| - case lineFeed: |
41 |
| - end = index |
42 |
| - br = true |
43 |
| - break |
44 |
| - case carriageReturn: |
45 |
| - end = index |
46 |
| - br = true |
| 16 | + var match |
| 17 | + var end |
47 | 18 |
|
48 |
| - if (value.charCodeAt(index + 1) === lineFeed) { |
49 |
| - index++ |
50 |
| - } |
| 19 | + if ('children' in node) { |
| 20 | + while (start < value.length) { |
| 21 | + search.lastIndex = start |
| 22 | + match = search.exec(value) |
| 23 | + end = match ? match.index : value.length |
51 | 24 |
|
52 |
| - break |
53 |
| - default: |
54 |
| - break |
55 |
| - } |
56 |
| - |
57 |
| - index++ |
58 |
| - |
59 |
| - if (end !== -1) { |
60 | 25 | if (end !== start) {
|
61 | 26 | nodes.push({type: 'text', value: value.slice(start, end)})
|
62 | 27 | }
|
63 | 28 |
|
64 |
| - if (br) { |
65 |
| - br = false |
| 29 | + start = end |
| 30 | + |
| 31 | + if (match) { |
| 32 | + start += match[0].length |
66 | 33 | nodes.push({
|
67 | 34 | type: 'element',
|
68 | 35 | tagName: 'br',
|
69 | 36 | properties: {},
|
70 | 37 | children: []
|
71 | 38 | })
|
72 | 39 | }
|
73 |
| - |
74 |
| - end = -1 |
75 |
| - start = index |
76 | 40 | }
|
77 |
| - } |
78 | 41 |
|
79 |
| - node.children = nodes |
80 |
| -} |
| 42 | + node.children = nodes |
| 43 | + } else { |
| 44 | + node.value = value |
| 45 | + } |
81 | 46 |
|
82 |
| -function setLiteral(node, value) { |
83 |
| - node.value = value |
| 47 | + return node |
84 | 48 | }
|
0 commit comments