forked from sveltejs/language-tools
/
Element.ts
363 lines (340 loc) · 14.5 KB
/
Element.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
import MagicString from 'magic-string';
import { BaseDirective, BaseNode } from '../../interfaces';
import { surroundWithIgnoreComments } from '../../utils/ignore';
import {
transform,
TransformationArray,
sanitizePropName,
surroundWith,
getDirectiveNameStartEndIdx,
rangeWithTrailingPropertyAccess
} from '../utils/node-utils';
const voidTags = 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr'.split(',');
/**
* Handles HTML elements as well as svelte:options, svelte:head, svelte:window, svelte:body, svelte:element
*
* Children of this element should call the methods on this class to add themselves to the correct
* position within the transformation.
*
* The transformation result does not have anything to do with HTMLx, it instead uses plan JS,
* leveraging scoped blocks (`{ ... }`). Each element is transformed to something that is
* contained in such a block. This ensures we can declare variables inside that do not leak
* to the outside while preserving TypeScript's control flow.
*
* A transformation reads for example like this:
* ```
* // before
* <div class={foo} />
* // after
* { const $$_div = __sveltets_2_createElement("div", {"class": foo,}); }
* ```
*/
export class Element {
private startEndTransformation: TransformationArray = ['});'];
private attrsTransformation: TransformationArray = [];
private slotLetsTransformation?: [TransformationArray, TransformationArray];
private actionsTransformation: TransformationArray = [];
private actionIdentifiers: string[] = [];
private endTransformation: TransformationArray = [];
private startTagStart: number;
private startTagEnd: number;
private isSelfclosing: boolean;
public tagName: string;
public child?: any;
// Add const $$xxx = ... only if the variable name is actually used
// in order to prevent "$$xxx is defined but never used" TS hints
private referencedName = false;
private _name: string;
public get name(): string {
this.referencedName = true;
return this._name;
}
/**
* @param str The MagicString instance used to manipulate the text
* @param node The Svelte AST node that represents this element
* @param typingsNamespace Determines which namespace to use for the createElement function
* @param parent The Svelte AST parent node
*/
constructor(
private str: MagicString,
private node: BaseNode,
public typingsNamespace: string,
public parent?: any
) {
if (parent) {
parent.child = this;
}
this.tagName = this.node.name === 'svelte:body' ? 'body' : this.node.name;
this.isSelfclosing = this.computeIsSelfclosing();
this.startTagStart = this.node.start;
this.startTagEnd = this.computeStartTagEnd();
const tagEnd = this.startTagStart + this.node.name.length + 1;
// Ensure deleted characters are mapped to the attributes object so we
// get autocompletion when triggering it on a whitespace.
if (/\s/.test(str.original.charAt(tagEnd))) {
this.attrsTransformation.push(tagEnd);
this.attrsTransformation.push([tagEnd, tagEnd + 1]);
// Overwrite necessary or else we get really weird mappings
this.str.overwrite(tagEnd, tagEnd + 1, '', { contentOnly: true });
}
switch (this.node.name) {
// Although not everything that is possible to add to Element
// is valid on the special svelte elements,
// we still also handle them here and let the Svelte parser handle invalid
// cases. For us it doesn't make a difference to a normal HTML element.
case 'svelte:options':
case 'svelte:head':
case 'svelte:window':
case 'svelte:body':
case 'svelte:fragment': {
// remove the colon: svelte:xxx -> sveltexxx
const nodeName = `svelte${this.node.name.substring(7)}`;
this._name = '$$_' + nodeName + this.computeDepth();
break;
}
case 'svelte:element': {
this._name = '$$_svelteelement' + this.computeDepth();
break;
}
case 'slot': {
// If the element is a <slot> tag, create the element with the createSlot-function
// which is created inside createRenderFunction.ts to check that the name and attributes
// of the slot tag are correct. The check will error if the user defined $$Slots
// and the slot definition or its attributes contradict that type definition.
this._name = '$$_slot' + this.computeDepth();
break;
}
default: {
this._name = '$$_' + sanitizePropName(this.node.name) + this.computeDepth();
break;
}
}
}
/**
* attribute={foo} --> "attribute": foo,
* @param name Attribute name
* @param value Attribute value, if present. If not present, this is treated as a shorthand attribute
*/
addAttribute(name: TransformationArray, value?: TransformationArray): void {
if (value) {
this.attrsTransformation.push(...name, ':', ...value, ',');
} else {
this.attrsTransformation.push(...name, ',');
}
}
/**
* Handle the slot of `<... slot=".." />`
* @param transformation Slot name transformation
*/
addSlotName(transformation: TransformationArray): void {
this.slotLetsTransformation = this.slotLetsTransformation || [[], []];
this.slotLetsTransformation[0] = transformation;
}
/**
* Handle the let: of `<... let:xx={yy} />`
* @param transformation Let transformation
*/
addSlotLet(transformation: TransformationArray): void {
this.slotLetsTransformation = this.slotLetsTransformation || [['default'], []];
this.slotLetsTransformation[1].push(...transformation, ',');
}
addAction(attr: BaseDirective) {
const id = `$$action_${this.actionIdentifiers.length}`;
this.actionIdentifiers.push(id);
if (!this.actionsTransformation.length) {
this.actionsTransformation.push('{');
}
this.actionsTransformation.push(
`const ${id} = __sveltets_2_ensureAction(`,
getDirectiveNameStartEndIdx(this.str, attr),
`(${this.typingsNamespace}.mapElementTag('${this.tagName}')`
);
if (attr.expression) {
this.actionsTransformation.push(
',(',
rangeWithTrailingPropertyAccess(this.str.original, attr.expression),
')'
);
}
this.actionsTransformation.push('));');
}
/**
* Add something right after the start tag end.
*/
appendToStartEnd(value: TransformationArray): void {
this.startEndTransformation.push(...value);
}
performTransformation(): void {
this.endTransformation.push('}');
const slotLetTransformation: TransformationArray = [];
if (this.slotLetsTransformation) {
if (this.slotLetsTransformation[0][0] === 'default') {
slotLetTransformation.push(
// add dummy destructuring parameter because if all parameters are unused,
// the mapping will be confusing, because TS will highlight the whole destructuring
`{const {${surroundWithIgnoreComments('$$_$$')},`,
...this.slotLetsTransformation[1],
`} = ${this.parent.name}.$$slot_def.default;$$_$$;`
);
} else {
slotLetTransformation.push(
// See comment above
`{const {${surroundWithIgnoreComments('$$_$$')},`,
...this.slotLetsTransformation[1],
`} = ${this.parent.name}.$$slot_def["`,
...this.slotLetsTransformation[0],
'"];$$_$$;'
);
}
this.endTransformation.push('}');
}
if (this.actionIdentifiers.length) {
this.endTransformation.push('}');
}
if (this.isSelfclosing) {
transform(this.str, this.startTagStart, this.startTagEnd, this.startTagEnd, [
// Named slot transformations go first inside a outer block scope because
// <div let:xx {x} /> means "use the x of let:x", and without a separate
// block scope this would give a "used before defined" error
...slotLetTransformation,
...this.actionsTransformation,
...this.getStartTransformation(),
...this.attrsTransformation,
...this.startEndTransformation,
...this.endTransformation
]);
} else {
transform(this.str, this.startTagStart, this.startTagEnd, this.startTagEnd, [
...slotLetTransformation,
...this.actionsTransformation,
...this.getStartTransformation(),
...this.attrsTransformation,
...this.startEndTransformation
]);
const tagEndIdx = this.str.original
.substring(this.node.start, this.node.end)
.lastIndexOf(`</${this.node.name}`);
// tagEndIdx === -1 happens in situations of unclosed tags like `<p>fooo <p>anothertag</p>`
const endStart = tagEndIdx === -1 ? this.node.end : tagEndIdx + this.node.start;
transform(this.str, endStart, this.node.end, this.node.end, this.endTransformation);
}
}
private getStartTransformation(): TransformationArray {
const createElement = `${this.typingsNamespace}.createElement`;
const addActions = () => {
if (this.actionIdentifiers.length) {
return `, __sveltets_2_union(${this.actionIdentifiers.join(',')})`;
} else {
return '';
}
};
switch (this.node.name) {
// Although not everything that is possible to add to Element
// is valid on the special svelte elements,
// we still also handle them here and let the Svelte parser handle invalid
// cases. For us it doesn't make a difference to a normal HTML element.
case 'svelte:options':
case 'svelte:head':
case 'svelte:window':
case 'svelte:body':
case 'svelte:fragment': {
if (!this.referencedName) {
return [`{ ${createElement}("${this.node.name}"${addActions()}, {`];
} else {
return [
`{ const ${this._name} = ${createElement}("${
this.node.name
}"${addActions()}, {`
];
}
}
case 'svelte:element': {
const nodeName = this.node.tag
? typeof this.node.tag !== 'string'
? ([this.node.tag.start, this.node.tag.end] as [number, number])
: `"${this.node.tag}"`
: '""';
if (!this.referencedName) {
return [`{ ${createElement}(`, nodeName, `${addActions()}, {`];
} else {
return [
`{ const ${this._name} = ${createElement}(`,
nodeName,
`${addActions()}, {`
];
}
}
case 'slot': {
// If the element is a <slot> tag, create the element with the createSlot-function
// which is created inside createRenderFunction.ts to check that the name and attributes
// of the slot tag are correct. The check will error if the user defined $$Slots
// and the slot definition or its attributes contradict that type definition.
const slotName =
this.node.attributes?.find((a: BaseNode) => a.name === 'name')?.value[0] ||
'default';
if (!this.referencedName) {
return [
'{ __sveltets_createSlot(',
typeof slotName === 'string'
? `"${slotName}"`
: surroundWith(this.str, [slotName.start, slotName.end], '"', '"'),
', {'
];
} else {
return [
`{ const ${this._name} = __sveltets_createSlot(`,
typeof slotName === 'string'
? `"${slotName}"`
: surroundWith(this.str, [slotName.start, slotName.end], '"', '"'),
', {'
];
}
}
default: {
if (!this.referencedName) {
return [
`{ ${createElement}("`,
[this.node.start + 1, this.node.start + 1 + this.node.name.length],
`"${addActions()}, {`
];
} else {
return [
`{ const ${this._name} = ${createElement}("`,
[this.node.start + 1, this.node.start + 1 + this.node.name.length],
`"${addActions()}, {`
];
}
}
}
}
private computeStartTagEnd() {
if (this.node.children?.length) {
return this.node.children[0].start;
}
return this.isSelfclosing
? this.node.end
: this.str.original.lastIndexOf('>', this.node.end - 2) + 1;
}
private computeIsSelfclosing() {
if (this.str.original[this.node.end - 2] === '/' || voidTags.includes(this.node.name)) {
return true;
}
return (
!this.node.children?.length &&
// Paranoid check because theoretically there could be other void
// tags in different namespaces other than HTML
!this.str.original
.substring(this.node.start, this.node.end)
.match(new RegExp(`</${this.node.name}\\s*>$`))
);
}
private computeDepth() {
let idx = 0;
let parent = this.parent;
while (parent) {
parent = parent.parent;
idx++;
}
return idx;
}
}