-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
Copy pathtag.ts
468 lines (390 loc) · 10.6 KB
/
tag.ts
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import readExpression from '../read/expression';
import readScript from '../read/script';
import readStyle from '../read/style';
import { readDirective } from '../read/directives';
import { trimStart, trimEnd } from '../../utils/trim';
import { decodeCharacterReferences } from '../utils/html';
import isVoidElementName from '../../utils/isVoidElementName';
import { Parser } from '../index';
import { Node } from '../../interfaces';
const validTagName = /^\!?[a-zA-Z]{1,}:?[a-zA-Z0-9\-]*/;
const metaTags = new Map([
['svelte:window', 'Window'],
['svelte:head', 'Head']
]);
const specials = new Map([
[
'script',
{
read: readScript,
property: 'js',
},
],
[
'style',
{
read: readStyle,
property: 'css',
},
],
]);
const SELF = 'svelte:self';
const COMPONENT = 'svelte:component';
// based on http://developers.whatwg.org/syntax.html#syntax-tag-omission
const disallowedContents = new Map([
['li', new Set(['li'])],
['dt', new Set(['dt', 'dd'])],
['dd', new Set(['dt', 'dd'])],
[
'p',
new Set(
'address article aside blockquote div dl fieldset footer form h1 h2 h3 h4 h5 h6 header hgroup hr main menu nav ol p pre section table ul'.split(
' '
)
),
],
['rt', new Set(['rt', 'rp'])],
['rp', new Set(['rt', 'rp'])],
['optgroup', new Set(['optgroup'])],
['option', new Set(['option', 'optgroup'])],
['thead', new Set(['tbody', 'tfoot'])],
['tbody', new Set(['tbody', 'tfoot'])],
['tfoot', new Set(['tbody'])],
['tr', new Set(['tr', 'tbody'])],
['td', new Set(['td', 'th', 'tr'])],
['th', new Set(['td', 'th', 'tr'])],
]);
function parentIsHead(stack) {
let i = stack.length;
while (i--) {
const { type } = stack[i];
if (type === 'Head') return true;
if (type === 'Element' || type === 'Component') return false;
}
return false;
}
export default function tag(parser: Parser) {
const start = parser.index++;
let parent = parser.current();
if (parser.eat('!--')) {
const data = parser.readUntil(/-->/);
parser.eat('-->', true, 'comment was left open, expected -->');
parser.current().children.push({
start,
end: parser.index,
type: 'Comment',
data,
});
return;
}
const isClosingTag = parser.eat('/');
const name = readTagName(parser);
if (metaTags.has(name)) {
const slug = metaTags.get(name).toLowerCase();
if (isClosingTag) {
if (name === 'svelte:window' && parser.current().children.length) {
parser.error({
code: `invalid-window-content`,
message: `<${name}> cannot have children`
}, parser.current().children[0].start);
}
} else {
if (name in parser.metaTags) {
parser.error({
code: `duplicate-${slug}`,
message: `A component can only have one <${name}> tag`
}, start);
}
if (parser.stack.length > 1) {
parser.error({
code: `invalid-${slug}-placement`,
message: `<${name}> tags cannot be inside elements or blocks`
}, start);
}
parser.metaTags[name] = true;
}
}
const type = metaTags.has(name)
? metaTags.get(name)
: (/[A-Z]/.test(name[0]) || name === 'svelte:self' || name === 'svelte:component') ? 'Component'
: name === 'title' && parentIsHead(parser.stack) ? 'Title'
: name === 'slot' && !parser.customElement ? 'Slot' : 'Element';
const element: Node = {
start,
end: null, // filled in later
type,
name,
attributes: [],
children: [],
};
parser.allowWhitespace();
if (isClosingTag) {
if (isVoidElementName(name)) {
parser.error({
code: `invalid-void-content`,
message: `<${name}> is a void element and cannot have children, or a closing tag`
}, start);
}
parser.eat('>', true);
// close any elements that don't have their own closing tags, e.g. <div><p></div>
while (parent.name !== name) {
if (parent.type !== 'Element')
parser.error({
code: `invalid-closing-tag`,
message: `</${name}> attempted to close an element that was not open`
}, start);
parent.end = start;
parser.stack.pop();
parent = parser.current();
}
parent.end = parser.index;
parser.stack.pop();
return;
} else if (disallowedContents.has(parent.name)) {
// can this be a child of the parent element, or does it implicitly
// close it, like `<li>one<li>two`?
if (disallowedContents.get(parent.name).has(name)) {
parent.end = start;
parser.stack.pop();
}
}
if (name === 'slot') {
let i = parser.stack.length;
while (i--) {
const item = parser.stack[i];
if (item.type === 'EachBlock') {
parser.error({
code: `invalid-slot-placement`,
message: `<slot> cannot be a child of an each-block`
}, start);
}
}
}
const uniqueNames = new Set();
let attribute;
while ((attribute = readAttribute(parser, uniqueNames))) {
if (attribute.type === 'Binding' && !parser.allowBindings) {
parser.error({
code: `binding-disabled`,
message: `Two-way binding is disabled`
}, attribute.start);
}
element.attributes.push(attribute);
parser.allowWhitespace();
}
if (name === 'svelte:component') {
// TODO post v2, treat this just as any other attribute
const index = element.attributes.findIndex(attr => attr.name === 'this');
if (!~index) {
parser.error({
code: `missing-component-definition`,
message: `<svelte:component> must have a 'this' attribute`
}, start);
}
const definition = element.attributes.splice(index, 1)[0];
if (definition.value === true || definition.value.length !== 1 || definition.value[0].type === 'Text') {
parser.error({
code: `invalid-component-definition`,
message: `invalid component definition`
}, definition.start);
}
element.expression = definition.value[0].expression;
}
// special cases – top-level <script> and <style>
if (specials.has(name) && parser.stack.length === 1) {
const special = specials.get(name);
if (parser[special.property]) {
parser.index = start;
parser.error({
code: `duplicate-${name}`,
message: `You can only have one top-level <${name}> tag per component`
});
}
parser.eat('>', true);
parser[special.property] = special.read(parser, start, element.attributes);
return;
}
parser.current().children.push(element);
const selfClosing = parser.eat('/') || isVoidElementName(name);
parser.eat('>', true);
if (selfClosing) {
// don't push self-closing elements onto the stack
element.end = parser.index;
} else if (name === 'textarea') {
// special case
element.children = readSequence(
parser,
() =>
parser.template.slice(parser.index, parser.index + 11) === '</textarea>'
);
parser.read(/<\/textarea>/);
element.end = parser.index;
} else if (name === 'script') {
// special case
const start = parser.index;
const data = parser.readUntil(/<\/script>/);
const end = parser.index;
element.children.push({ start, end, type: 'Text', data });
parser.eat('</script>', true);
element.end = parser.index;
} else if (name === 'style') {
// special case
const start = parser.index;
const data = parser.readUntil(/<\/style>/);
const end = parser.index;
element.children.push({ start, end, type: 'Text', data });
parser.eat('</style>', true);
} else {
parser.stack.push(element);
}
}
function readTagName(parser: Parser) {
const start = parser.index;
if (parser.eat(SELF)) {
// check we're inside a block, otherwise this
// will cause infinite recursion
let i = parser.stack.length;
let legal = false;
while (i--) {
const fragment = parser.stack[i];
if (fragment.type === 'IfBlock' || fragment.type === 'EachBlock') {
legal = true;
break;
}
}
if (!legal) {
parser.error({
code: `invalid-self-placement`,
message: `<${SELF}> components can only exist inside if-blocks or each-blocks`
}, start);
}
return SELF;
}
if (parser.eat(COMPONENT)) return COMPONENT;
const name = parser.readUntil(/(\s|\/|>)/);
if (metaTags.has(name)) return name;
if (!validTagName.test(name)) {
parser.error({
code: `invalid-tag-name`,
message: `Expected valid tag name`
}, start);
}
return name;
}
function readAttribute(parser: Parser, uniqueNames: Set<string>) {
const start = parser.index;
if (parser.eat('{')) {
parser.allowWhitespace();
if (parser.eat('...')) {
const expression = readExpression(parser);
parser.allowWhitespace();
parser.eat('}', true);
return {
start,
end: parser.index,
type: 'Spread',
expression
};
} else {
const valueStart = parser.index;
const name = parser.readIdentifier();
parser.allowWhitespace();
parser.eat('}', true);
return {
start,
end: parser.index,
type: 'Attribute',
name,
value: [{
start: valueStart,
end: valueStart + name.length,
type: 'AttributeShorthand',
expression: {
start: valueStart,
end: valueStart + name.length,
type: 'Identifier',
name
}
}]
};
}
}
let name = parser.readUntil(/(\s|=|\/|>)/);
if (!name) return null;
if (uniqueNames.has(name)) {
parser.error({
code: `duplicate-attribute`,
message: 'Attributes need to be unique'
}, start);
}
uniqueNames.add(name);
parser.allowWhitespace();
const directive = readDirective(parser, start, name);
if (directive) return directive;
let value = parser.eat('=') ? readAttributeValue(parser) : true;
return {
start,
end: parser.index,
type: 'Attribute',
name,
value,
};
}
function readAttributeValue(parser: Parser) {
const quoteMark = parser.eat(`'`) ? `'` : parser.eat(`"`) ? `"` : null;
const regex = quoteMark === `'`
? /'/
: quoteMark === `"` ? /"/ : /[\s"'=<>\/`]/;
const value = readSequence(parser, () =>
regex.test(parser.template[parser.index])
);
if (quoteMark) parser.index += 1;
return value;
}
function readSequence(parser: Parser, done: () => boolean) {
let currentChunk: Node = {
start: parser.index,
end: null,
type: 'Text',
data: '',
};
const chunks = [];
while (parser.index < parser.template.length) {
const index = parser.index;
if (done()) {
currentChunk.end = parser.index;
if (currentChunk.data) chunks.push(currentChunk);
chunks.forEach(chunk => {
if (chunk.type === 'Text')
chunk.data = decodeCharacterReferences(chunk.data);
});
return chunks;
} else if (parser.eat('{')) {
if (currentChunk.data) {
currentChunk.end = index;
chunks.push(currentChunk);
}
const expression = readExpression(parser);
parser.allowWhitespace();
parser.eat('}', true);
chunks.push({
start: index,
end: parser.index,
type: 'MustacheTag',
expression,
});
currentChunk = {
start: parser.index,
end: null,
type: 'Text',
data: '',
};
} else {
currentChunk.data += parser.template[parser.index++];
}
}
parser.error({
code: `unexpected-eof`,
message: `Unexpected end of input`
});
}