Skip to content

Commit 3ad1f00

Browse files
committed
Refactor to improve bundle size
1 parent 5f4470e commit 3ad1f00

File tree

2 files changed

+31
-57
lines changed

2 files changed

+31
-57
lines changed

index.js

Lines changed: 20 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,84 +1,48 @@
11
'use strict'
22

3-
var eof = 0 // ''
4-
var lineFeed = 10 // '\n'
5-
var carriageReturn = 13 // '\r'
6-
73
module.exports = fromText
84

5+
var search = /\r?\n|\r/g
6+
97
// Implementation of the `innerText` setter:
108
// <https://html.spec.whatwg.org/#the-innertext-idl-attribute>
119
// Note that `innerText` only exists on element.
1210
// In this utility, we accept all parent nodes and handle them as elements, and
1311
// 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)
2314
var nodes = []
24-
var length = value.length
25-
var index = 0
2615
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
4718

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
5124

52-
break
53-
default:
54-
break
55-
}
56-
57-
index++
58-
59-
if (end !== -1) {
6025
if (end !== start) {
6126
nodes.push({type: 'text', value: value.slice(start, end)})
6227
}
6328

64-
if (br) {
65-
br = false
29+
start = end
30+
31+
if (match) {
32+
start += match[0].length
6633
nodes.push({
6734
type: 'element',
6835
tagName: 'br',
6936
properties: {},
7037
children: []
7138
})
7239
}
73-
74-
end = -1
75-
start = index
7640
}
77-
}
7841

79-
node.children = nodes
80-
}
42+
node.children = nodes
43+
} else {
44+
node.value = value
45+
}
8146

82-
function setLiteral(node, value) {
83-
node.value = value
47+
return node
8448
}

package.json

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,17 @@
6969
"esnext": false,
7070
"ignores": [
7171
"hast-util-from-text.js"
72-
]
72+
],
73+
"rules": {
74+
"eqeqeq": [
75+
"error",
76+
"always",
77+
{
78+
"null": "ignore"
79+
}
80+
],
81+
"no-eq-null": "off"
82+
}
7383
},
7484
"remarkConfig": {
7585
"plugins": [

0 commit comments

Comments
 (0)