forked from HcySunYang/code-for-vue-3-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode-16-1.1.html
372 lines (315 loc) · 9.09 KB
/
code-16-1.1.html
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
<body>
<div>
<p>text 1</p>
<p>text 2</p>
</div>
</body>
<div id="foo">+--<p>Text1</p>+--<p>Text2</p>+</div>
<div><span></div></span>
<div>� asdf</div>
<script>
const TextModes = {
DATA: 'DATA',
RCDATA: 'RCDATA',
RAWTEXT: 'RAWTEXT',
CDATA: 'CDATA'
}
function parse(str) {
const context = {
source: str,
mode: TextModes.DATA,
advanceBy(num) {
context.source = context.source.slice(num)
},
advanceSpaces() {
const match = /^[\t\r\n\f ]+/.exec(context.source)
if (match) {
context.advanceBy(match[0].length)
}
}
}
const nodes = parseChildren(context, [])
return {
type: 'Root',
children: nodes
}
}
function parseChildren(context, ancestors) {
let nodes = []
const { mode } = context
while(!isEnd(context, ancestors)) {
let node
if (mode === TextModes.DATA || mode === TextModes.RCDATA) {
if (mode === TextModes.DATA && context.source[0] === '<') {
if (context.source[1] === '!') {
if (context.source.startsWith('<!--')) {
// 注释
node = parseComment(context)
} else if (context.source.startsWith('<![CDATA[')) {
// CDATA
node = parseCDATA(context, ancestors)
}
} else if (context.source[1] === '/') {
// 结束标签
} else if (/[a-z]/i.test(context.source[1])) {
// 标签
node = parseElement(context, ancestors)
}
} else if (context.source.startsWith('{{')) {
// 解析插值
node = parseInterpolation(context)
}
}
if (!node) {
node = parseText(context)
}
nodes.push(node)
}
return nodes
}
function parseElement(context, ancestors) {
const element = parseTag(context)
if (element.isSelfClosing) return element
ancestors.push(element)
if (element.tag === 'textarea' || element.tag === 'title') {
context.mode = TextModes.RCDATA
} else if (/style|xmp|iframe|noembed|noframes|noscript/.test(element.tag)) {
context.mode = TextModes.RAWTEXT
} else {
context.mode = TextModes.DATA
}
element.children = parseChildren(context, ancestors)
ancestors.pop()
if (context.source.startsWith(`</${element.tag}`)) {
parseTag(context, 'end')
} else {
console.error(`${element.tag} 标签缺少闭合标签`)
}
return element
}
function parseTag(context, type = 'start') {
const { advanceBy, advanceSpaces } = context
const match = type === 'start'
? /^<([a-z][^\t\r\n\f />]*)/i.exec(context.source)
: /^<\/([a-z][^\t\r\n\f />]*)/i.exec(context.source)
const tag = match[1]
advanceBy(match[0].length)
advanceSpaces()
const props = parseAttributes(context)
const isSelfClosing = context.source.startsWith('/>')
advanceBy(isSelfClosing ? 2 : 1)
return {
type: 'Element',
tag,
props,
children: [],
isSelfClosing
}
}
function parseAttributes(context) {
const { advanceBy, advanceSpaces } = context
const props = []
while (
!context.source.startsWith('>') &&
!context.source.startsWith('/>')
) {
const match = /^[^\t\r\n\f />][^\t\r\n\f />=]*/.exec(context.source)
const name = match[0]
advanceBy(name.length)
advanceSpaces()
advanceBy(1)
advanceSpaces()
let value = ''
const quote = context.source[0]
const isQuoted = quote === '"' || quote === "'"
if (isQuoted) {
advanceBy(1)
const endQuoteIndex = context.source.indexOf(quote)
if (endQuoteIndex > -1) {
value = context.source.slice(0, endQuoteIndex)
advanceBy(value.length)
advanceBy(1)
} else {
console.error('缺少引号')
}
} else {
const match = /^[^\t\r\n\f >]+/.exec(context.source)
value = match[0]
advanceBy(value.length)
}
advanceSpaces()
props.push({
type: 'Attribute',
name,
value
})
}
return props
}
function parseText(context) {
let endIndex = context.source.length
const ltIndex = context.source.indexOf('<')
const delimiterIndex = context.source.indexOf('{{')
if (ltIndex > -1 && ltIndex < endIndex) {
endIndex = ltIndex
}
if (delimiterIndex > -1 && delimiterIndex < endIndex) {
endIndex = delimiterIndex
}
const content = context.source.slice(0, endIndex)
context.advanceBy(content.length)
return {
type: 'Text',
content: decodeHtml(content)
}
}
function isEnd(context, ancestors) {
if (!context.source) return true
// 与节点栈内全部的节点比较
for (let i = ancestors.length - 1; i >= 0; --i) {
if (context.source.startsWith(`</${ancestors[i].tag}`)) {
return true
}
}
}
const namedCharacterReferences = {
"gt": ">",
"gt;": ">",
"lt": "<",
"lt;": "<",
"ltcc;": "⪦"
}
function decodeHtml(rawText, asAttr = false) {
let offset = 0
const end = rawText.length
let decodedText = ''
let maxCRNameLength = 0
function advance(length) {
offset += length
rawText = rawText.slice(length)
}
while (offset < end) {
const head = /&(?:#x?)?/i.exec(rawText)
if (!head) {
const remaining = end - offset
decodedText += rawText.slice(0, remaining)
advance(remaining)
break
}
// Advance to the "&".
decodedText += rawText.slice(0, head.index)
advance(head.index)
if (head[0] === '&') {
// Named character reference.
let name = ''
let value
if (/[0-9a-z]/i.test(rawText[1])) {
if (!maxCRNameLength) {
maxCRNameLength = Object.keys(namedCharacterReferences).reduce(
(max, name) => Math.max(max, name.length),
0
)
}
for (let length = maxCRNameLength; !value && length > 0; --length) {
name = rawText.substr(1, length)
value = (namedCharacterReferences)[name]
}
if (value) {
const semi = name.endsWith(';')
if (
asAttr &&
!semi &&
/[=a-z0-9]/i.test(rawText[name.length + 1] || '')
) {
decodedText += '&' + name
advance(1 + name.length)
} else {
decodedText += value
advance(1 + name.length)
}
} else {
decodedText += '&' + name
advance(1 + name.length)
}
} else {
decodedText += '&'
advance(1)
}
} else {
// 判断是十进制表示还是十六进制表示
const hex = head[0] === '&#x'
// 根据不同进制表示法,选用不同的正则
const pattern = hex ? /^&#x([0-9a-f]+);?/i : /^&#([0-9]+);?/
// 最终,body[1] 的值就是 Unicode 码点
const body = pattern.exec(rawText)
// 如果匹配成功,则调用 String.fromCodePoint 函数进行解码
if (body) {
// 将码点字符串转为十进制数字
const cp = Number.parseInt(body[1], hex ? 16 : 10)
// 码点的合法性检查
if (cp === 0) {
// 如果码点值为 0x00,替换为 0xfffd
cp = 0xfffd
} else if (cp > 0x10ffff) {
// 如果码点值超过了 Unicode 的最大值,替换为 0xfffd
cp = 0xfffd
} else if (cp >= 0xd800 && cp <= 0xdfff) {
// 如果码点值处于 surrogate pair 范围,替换为 0xfffd
cp = 0xfffd
} else if ((cp >= 0xfdd0 && cp <= 0xfdef) || (cp & 0xfffe) === 0xfffe) {
// 如果码点值处于 `noncharacter` 范围,则什么都不做,交给平台处理
// noop
} else if (
// 控制字符集的范围是:[0x01, 0x1f] 加上 [0x7f, 0x9f]
// 却掉 ASICC 空白符:0x09(TAB)、0x0A(LF)、0x0C(FF)
// 0x0D(CR) 虽然也是 ASICC 空白符,但需要包含
(cp >= 0x01 && cp <= 0x08) ||
cp === 0x0b ||
(cp >= 0x0d && cp <= 0x1f) ||
(cp >= 0x7f && cp <= 0x9f)
) {
// 在 CCR_REPLACEMENTS 表中查找替换码点,如果找不到则使用原码点
cp = CCR_REPLACEMENTS[cp] || cp
}
// 解码后追加到 decodedText 上
decodedText += String.fromCodePoint(cp)
// 消费掉整个数字字符引用的内容
advance(body[0].length)
} else {
// 如果没有匹配,则不进行解码操作,只是把 head[0] 追加到 decodedText 并消费掉
decodedText += head[0]
advance(head[0].length)
}
}
}
return decodedText
}
function parseInterpolation(context) {
context.advanceBy('{{'.length)
closeIndex = context.source.indexOf('}}')
const content = context.source.slice(0, closeIndex)
context.advanceBy(content.length)
context.advanceBy('}}'.length)
return {
type: 'Interpolation',
content: {
type: 'Expression',
content: decodeHtml(content)
}
}
}
function parseComment(context) {
context.advanceBy('<!--'.length)
closeIndex = context.source.indexOf('-->')
const content = context.source.slice(0, closeIndex)
context.advanceBy(content.length)
context.advanceBy('-->'.length)
return {
type: 'Comment',
content
}
}
const s = `<div><!-- comments --></div>`
const ast = parse(s)
console.log(ast)
</script>