/
htmlxtojsx.ts
237 lines (214 loc) · 9.29 KB
/
htmlxtojsx.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
import MagicString from 'magic-string';
import { walk, Node } from 'estree-walker';
import { parseHtmlx } from './parser';
export function convertHtmlxToJsx(str: MagicString, ast: Node) {
let htmlx = str.original;
str.prepend("<>");
str.append("</>");
const handleRaw = (rawBlock: Node) => {
let tokenStart = htmlx.indexOf("@html", rawBlock.start);
str.remove(tokenStart, "@html".length + 1);
};
const handleDebug = (debugBlock: Node) => {
let tokenStart = htmlx.indexOf("@debug", debugBlock.start);
str.remove(tokenStart, "@debug".length + 1);
};
const handleElementEventHandler = (attr: Node) => {
let jsxEventName = `on${attr.name[0].toUpperCase() + attr.name.substr(1)}`
if (attr.expression) {
let endAttr = htmlx.indexOf("=", attr.start)
str.overwrite(attr.start, endAttr, jsxEventName)
} else {
str.overwrite(attr.start, attr.end, `${jsxEventName}={null}`)
}
}
const handleClassDirective = (attr: Node) => {
let needCurly = (attr.expression.start == attr.start + "class:".length);
str.overwrite(attr.start, attr.expression.start, `{...__sveltets_ensureType(Boolean, `)
str.appendLeft(attr.expression.end, `)${ needCurly ? "}" : "" }`)
}
const handleActionDirective = (attr: Node) => {
str.overwrite(attr.start, attr.start + "use:".length, "{...__sveltets_ensureAction(")
if (!attr.expression) {
str.appendLeft(attr.end, ")}");
return;
}
str.overwrite(attr.start + `use:${attr.name}`.length, attr.expression.start, ",")
str.appendLeft(attr.expression.end, ")");
}
const handleBinding = (attr: Node, el: Node) => {
//bind group on input
if (attr.name == "group" && el.name == "input") {
str.remove(attr.start, attr.start+"bind:group=".length);
str.prependRight(attr.expression.start,"...__sveltets_ensureType(String, ")
str.appendLeft(attr.expression.end,")")
return;
}
//bind this on element
if (attr.name == "this" && el.type == "Element") {
str.remove(attr.start, attr.start + "bind:this=".length)
str.prependRight(attr.expression.start, "...__sveltets_ensureType(HTMLElement, ");
str.appendLeft(attr.expression.end, ")");
return;
}
//bind this on component
if (attr.name == "this" && el.type == "InlineComponent") {
str.remove(attr.start, attr.start + "bind:this=".length)
str.prependRight(attr.expression.start, `...__sveltets_ensureType(${el.name}, `);
str.appendLeft(attr.expression.end, ")");
return;
}
str.remove(attr.start,attr.start+"bind:".length);
if (attr.expression.start == attr.start + "bind:".length) {
str.appendLeft(attr.end, `={${attr.name}}`);
}
}
const handleComponentEventHandler = (attr: Node) => {
if (attr.expression) {
//for handler assignment, we changeIt to call to our __sveltets_ensureFunction
let endAttr = htmlx.indexOf("=", attr.start)+1
str.remove(attr.start, endAttr)
str.prependRight(attr.expression.start, "...__sveltets_ensureFunction((")
str.appendLeft(attr.expression.end, "))");
} else {
//for passthrough handlers, we just remove
str.remove(attr.start, attr.end)
}
}
const handleIf = (ifBlock: Node) => {
// {#if expr} ->
// {() => { if (expr) { <>
str.overwrite(ifBlock.start, ifBlock.expression.start, "{() => {if (");
let end = htmlx.indexOf("}", ifBlock.expression.end);
str.appendLeft(ifBlock.expression.end, ")");
str.overwrite(end, end + 1, "{<>");
// {:else} -> </>} else {<>
if (ifBlock.else) {
let elseEnd = htmlx.lastIndexOf("}", ifBlock.else.start);
let elseStart = htmlx.lastIndexOf("{", elseEnd);
str.overwrite(elseStart, elseStart + 1, "</>}");
str.overwrite(elseEnd, elseEnd + 1, "{<>");
let colon = htmlx.indexOf(":", elseStart);
str.remove(colon, colon + 1);
}
// {/if} -> </>}}}</>
let endif = htmlx.lastIndexOf("{", ifBlock.end);
str.overwrite(endif, ifBlock.end, "</>}}}");
};
const handleEach = (eachBlock: Node) => {
// {#each items as item,i (key)} ->
// {(items).map((item,i) => (key) && <>
str.overwrite(eachBlock.start, eachBlock.expression.start, "{(");
str.overwrite(eachBlock.expression.end, eachBlock.context.start, ").map((");
let contextEnd = eachBlock.context.end;
if (eachBlock.index) {
let idxLoc = htmlx.indexOf(eachBlock.index, contextEnd);
contextEnd = idxLoc + eachBlock.index.length;
}
str.prependLeft(contextEnd, ") =>");
if (eachBlock.key) {
let endEachStart = htmlx.indexOf("}", eachBlock.key.end);
str.overwrite(endEachStart, endEachStart + 1, " && <>");
}
else {
let endEachStart = htmlx.indexOf("}", contextEnd);
str.overwrite(endEachStart, endEachStart + 1, " <>");
}
let endEach = htmlx.lastIndexOf("{", eachBlock.end);
// {/each} -> </>)} or {:else} -> </>)}
if (eachBlock.else) {
let elseEnd = htmlx.lastIndexOf("}", eachBlock.else.start);
let elseStart = htmlx.lastIndexOf("{", elseEnd);
str.overwrite(elseStart, elseEnd + 1, "</>)}");
str.remove(endEach, eachBlock.end);
}
else {
str.overwrite(endEach, eachBlock.end, "</>)}");
}
};
// {#await somePromise then value} ->
// {() => {let _$$p = (somePromise);
const handleAwait = (awaitBlock: Node) => {
str.overwrite(awaitBlock.start, awaitBlock.expression.start, "{() => {let _$$p = (");
str.prependLeft(awaitBlock.expression.end, ");");
// then value } | {:then value} ->
// _$$p.then((value) => {<>
let thenStart: number;
let thenEnd: number;
if (!awaitBlock.pending.skip) {
//thenBlock seems to include the {:then} tag
thenStart = awaitBlock.then.start;
thenEnd = htmlx.indexOf("}", thenStart) + 1;
str.prependLeft(thenStart, "</>; ");
// add the start tag too
let awaitEnd = htmlx.indexOf("}", awaitBlock.expression.end);
str.remove(awaitEnd, awaitEnd + 1);
str.appendRight(awaitEnd, " <>");
}
else {
thenEnd = htmlx.lastIndexOf("}", awaitBlock.then.start) + 1;
thenStart = htmlx.indexOf("then", awaitBlock.expression.end);
}
// console.log("overwriting",thenStart, thenEnd);
str.overwrite(thenStart, thenEnd, "_$$p.then((" + awaitBlock.value + ") => {<>");
//{:catch error} ->
//</>}).catch((error) => {<>
if (!awaitBlock.catch.skip) {
//catch block includes the {:catch}
let catchStart = awaitBlock.catch.start;
let catchSymbolEnd = htmlx.indexOf(":catch", catchStart) + ":catch".length;
let errorStart = awaitBlock.error ? htmlx.indexOf(awaitBlock.error, catchSymbolEnd) : catchSymbolEnd;
let errorEnd = awaitBlock.error ? errorStart + awaitBlock.error.length : errorStart;
let catchEnd = htmlx.indexOf("}", awaitBlock.catch.start) + 1;
str.overwrite(catchStart, errorStart, "</>}).catch((");
str.overwrite(errorEnd, catchEnd, ") => {<>");
}
// {/await} ->
// <>})}
let awaitEndStart = htmlx.lastIndexOf("{", awaitBlock.end);
str.overwrite(awaitEndStart, awaitBlock.end, "</>})}}");
};
walk(ast, {
enter: (node: Node, parent, prop, index) => {
if (node.type == "IfBlock")
handleIf(node);
if (node.type == "EachBlock")
handleEach(node);
if (node.type == "AwaitBlock")
handleAwait(node);
if (node.type == "RawMustacheTag")
handleRaw(node);
if (node.type == "DebugTag")
handleDebug(node);
if (node.type == "Element" || node.type == "InlineComponent") {
for(let attr of node.attributes) {
if (attr.type == "EventHandler") {
if (node.type == "Element") {
handleElementEventHandler(attr);
} else {
handleComponentEventHandler(attr);
}
}
if (attr.type == "Binding") {
handleBinding(attr, node);
}
if (attr.type == "Class") {
handleClassDirective(attr);
}
if (attr.type == "Action") {
handleActionDirective(attr);
}
}
}
}
});
}
export function htmlx2jsx(htmlx: string) {
let ast = parseHtmlx(htmlx);
let str = new MagicString(htmlx)
convertHtmlxToJsx(str, ast);
return {
map: str.generateMap({ hires: true }),
code: str.toString(),
}
}