-
-
Notifications
You must be signed in to change notification settings - Fork 518
/
html.ts
308 lines (254 loc) · 10.3 KB
/
html.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
import type { Abbreviation, AbbreviationNode, AbbreviationAttribute, Value } from '@emmetio/abbreviation';
import { pushNewline, pushString, tagName, selfClose, attrName, isBooleanAttribute, attrQuote, isInline, expressionStart, expressionEnd } from '../../output-stream.js';
import walk, { type WalkState, createWalkState } from './walk.js';
import { caret, isInlineElement, isSnippet, isField, pushTokens, shouldOutputAttribute } from './utils.js';
import { commentNodeBefore, commentNodeAfter, type CommentWalkState, createCommentState } from './comment.js';
import type { Config } from '../../config.js';
type WalkNext = (node: AbbreviationNode, index: number, items: AbbreviationNode[]) => void;
export interface HTMLWalkState extends WalkState {
comment: CommentWalkState;
}
const htmlTagRegex = /^<([\w\-:]+)[\s>]/;
const reservedKeywords = new Set([
'for', 'while', 'of', 'async', 'await', 'const', 'let', 'var', 'continue',
'break', 'debugger', 'do', 'export', 'import', 'in', 'instanceof', 'new', 'return',
'switch', 'this', 'throw', 'try', 'catch', 'typeof', 'void', 'with', 'yield'
]);
export default function html(abbr: Abbreviation, config: Config): string {
const state = createWalkState(config) as HTMLWalkState;
state.comment = createCommentState(config);
walk(abbr, element, state);
return state.out.value;
}
/**
* Outputs `node` content to output stream of `state`
* @param node Context node
* @param index Index of `node` in `items`
* @param items List of `node`’s siblings
* @param state Current walk state
*/
function element(node: AbbreviationNode, index: number, items: AbbreviationNode[], state: HTMLWalkState, next: WalkNext) {
const { out, config } = state;
const format = shouldFormat(node, index, items, state);
// Pick offset level for current node
const level = getIndent(state);
out.level += level;
format && pushNewline(out, true);
if (node.name) {
const name = tagName(node.name, config);
commentNodeBefore(node, state);
pushString(out, `<${name}`);
if (node.attributes) {
for (const attr of node.attributes) {
if (shouldOutputAttribute(attr)) {
pushAttribute(attr, state);
}
}
}
if (node.selfClosing && !node.children.length && !node.value) {
pushString(out, `${selfClose(config)}>`);
} else {
pushString(out, '>');
if (!pushSnippet(node, state, next)) {
if (node.value) {
const innerFormat = node.value.some(hasNewline) || startsWithBlockTag(node.value, config);
innerFormat && pushNewline(state.out, ++out.level);
pushTokens(node.value, state);
innerFormat && pushNewline(state.out, --out.level);
}
node.children.forEach(next);
if (!node.value && !node.children.length) {
const innerFormat = config.options['output.formatLeafNode']
|| config.options['output.formatForce'].includes(node.name);
innerFormat && pushNewline(state.out, ++out.level);
pushTokens(caret, state);
innerFormat && pushNewline(state.out, --out.level);
}
}
pushString(out, `</${name}>`);
commentNodeAfter(node, state);
}
} else if (!pushSnippet(node, state, next) && node.value) {
// A text-only node (snippet)
pushTokens(node.value, state);
node.children.forEach(next);
}
if (format && index === items.length - 1 && state.parent) {
const offset = isSnippet(state.parent) ? 0 : 1;
pushNewline(out, out.level - offset);
}
out.level -= level;
}
/**
* Outputs given attribute’s content into output stream
*/
function pushAttribute(attr: AbbreviationAttribute, state: WalkState) {
const { out, config } = state;
if (attr.name) {
const attributes = config.options['markup.attributes'];
const valuePrefix = config.options['markup.valuePrefix'];
let { name, value } = attr;
let lQuote = attrQuote(attr, config, true);
let rQuote = attrQuote(attr, config);
if (attributes) {
name = getMultiValue(name, attributes, attr.multiple) || name;
}
name = attrName(name, config);
if (config.options['jsx.enabled'] && attr.multiple) {
lQuote = expressionStart;
rQuote = expressionEnd;
}
const prefix = valuePrefix
? getMultiValue(attr.name, valuePrefix, attr.multiple)
: null;
if (prefix && value?.length === 1 && typeof value[0] === 'string') {
// Add given prefix in object notation
const val = value[0] as string;
value = [isPropKey(val) ? `${prefix}.${val}` : `${prefix}['${val}']`];
if (config.options['jsx.enabled']) {
lQuote = expressionStart;
rQuote = expressionEnd;
}
}
if (isBooleanAttribute(attr, config) && !value) {
// If attribute value is omitted and it’s a boolean value, check for
// `compactBoolean` option: if it’s disabled, set value to attribute name
// (XML style)
if (!config.options['output.compactBoolean']) {
value = [name];
}
} else if (!value) {
value = caret;
}
pushString(out, ' ' + name);
if (value) {
pushString(out, '=' + lQuote);
pushTokens(value, state);
pushString(out, rQuote);
} else if (config.options['output.selfClosingStyle'] !== 'html') {
pushString(out, '=' + lQuote + rQuote);
}
}
}
export function pushSnippet(node: AbbreviationNode, state: WalkState, next: WalkNext): boolean {
if (node.value && node.children.length) {
// We have a value and child nodes. In case if value contains fields,
// we should output children as a content of first field
const fieldIx = node.value.findIndex(isField);
if (fieldIx !== -1) {
pushTokens(node.value.slice(0, fieldIx), state);
const line = state.out.line;
let pos = fieldIx + 1;
node.children.forEach(next);
// If there was a line change, trim leading whitespace for better result
if (state.out.line !== line && typeof node.value[pos] === 'string') {
pushString(state.out, (node.value[pos++] as string).trimLeft());
}
pushTokens(node.value.slice(pos), state);
return true;
}
}
return false;
}
/**
* Check if given node should be formatted in its parent context
*/
function shouldFormat(node: AbbreviationNode, index: number, items: AbbreviationNode[], state: WalkState): boolean {
const { config, parent } = state;
if (!config.options['output.format']) {
return false;
}
if (index === 0 && !parent) {
// Do not format very first node
return false;
}
// Do not format single child of snippet
if (parent && isSnippet(parent) && items.length === 1) {
return false;
}
/**
* Adjacent text-only/snippet nodes
*/
if (isSnippet(node)) {
// Adjacent text-only/snippet nodes
const format = isSnippet(items[index - 1]) || isSnippet(items[index + 1])
// Has newlines: looks like wrapping code fragment
|| node.value!.some(hasNewline)
// Format as wrapper: contains children which will be outputted as field content
|| (node.value!.some(isField) && node.children.length);
if (format) {
return true;
}
}
if (isInline(node, config)) {
// Check if inline node is the next sibling of block-level node
if (index === 0) {
// First node in parent: format if it’s followed by a block-level element
for (let i = 0; i < items.length; i++) {
if (!isInline(items[i], config)) {
return true;
}
}
} else if (!isInline(items[index - 1], config)) {
// Node is right after block-level element
return true;
}
if (config.options['output.inlineBreak']) {
// check for adjacent inline elements before and after current element
let adjacentInline = 1;
let before = index;
let after = index;
while (isInlineElement(items[--before], config)) {
adjacentInline++;
}
while (isInlineElement(items[++after], config)) {
adjacentInline++;
}
if (adjacentInline >= config.options['output.inlineBreak']) {
return true;
}
}
// Edge case: inline node contains node that should receive formatting
for (let i = 0, il = node.children.length; i < il; i++) {
if (shouldFormat(node.children[i], i, node.children, state)) {
return true;
}
}
return false;
}
return true;
}
/**
* Returns indentation offset for given node
*/
function getIndent(state: WalkState): number {
const { config, parent } = state;
if (!parent || isSnippet(parent) || (parent.name && config.options['output.formatSkip'].includes(parent.name))) {
return 0;
}
return 1;
}
/**
* Check if given node value contains newlines
*/
function hasNewline(value: Value): boolean {
return typeof value === 'string' && /\r|\n/.test(value);
}
/**
* Check if given node value starts with block-level tag
*/
function startsWithBlockTag(value: Value[], config: Config): boolean {
if (value.length && typeof value[0] === 'string') {
const matches = htmlTagRegex.exec(value[0]);
if (matches?.length && !config.options['inlineElements'].includes(matches[1].toLowerCase())) {
return true;
}
}
return false;
}
function getMultiValue(key: string, data: Record<string, string>, multiple?: boolean): string | undefined {
return (multiple && data[`${key}*`]) || data[key];
}
function isPropKey(name: string): boolean {
return !reservedKeywords.has(name) && /^[a-zA-Z_$][\w_$]*$/.test(name);
}