forked from rollup/rollup
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSXIdentifier.ts
More file actions
74 lines (67 loc) · 2.01 KB
/
JSXIdentifier.ts
File metadata and controls
74 lines (67 loc) · 2.01 KB
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
import type MagicString from 'magic-string';
import type { NormalizedJsxOptions } from '../../rollup/types';
import type { RenderOptions } from '../../utils/renderHelpers';
import type JSXMemberExpression from './JSXMemberExpression';
import type * as NodeType from './NodeType';
import IdentifierBase from './shared/IdentifierBase';
const enum IdentifierType {
Reference,
NativeElementName,
Other
}
export default class JSXIdentifier extends IdentifierBase {
type!: NodeType.tJSXIdentifier;
name!: string;
private isNativeElement = false;
bind(): void {
const type = this.getType();
if (type === IdentifierType.Reference) {
this.variable = this.scope.findVariable(this.name);
this.variable.addReference(this);
} else if (type === IdentifierType.NativeElementName) {
this.isNativeElement = true;
}
}
render(
code: MagicString,
{ snippets: { getPropertyAccess }, useOriginalName }: RenderOptions
): void {
if (this.variable) {
const name = this.variable.getName(getPropertyAccess, useOriginalName);
if (name !== this.name) {
code.overwrite(this.start, this.end, name, {
contentOnly: true,
storeName: true
});
}
} else if (
this.isNativeElement &&
(this.scope.context.options.jsx as NormalizedJsxOptions).mode !== 'preserve'
) {
code.update(this.start, this.end, JSON.stringify(this.name));
}
}
private getType(): IdentifierType {
switch (this.parent.type) {
case 'JSXOpeningElement':
case 'JSXClosingElement': {
return this.name.startsWith(this.name.charAt(0).toUpperCase())
? IdentifierType.Reference
: IdentifierType.NativeElementName;
}
case 'JSXMemberExpression': {
return (this.parent as JSXMemberExpression).object === this
? IdentifierType.Reference
: IdentifierType.Other;
}
case 'JSXAttribute':
case 'JSXNamespacedName': {
return IdentifierType.Other;
}
default: {
/* istanbul ignore next */
throw new Error(`Unexpected parent node type for JSXIdentifier: ${this.parent.type}`);
}
}
}
}