/
stylable-value-parsers.ts
434 lines (392 loc) · 13.2 KB
/
stylable-value-parsers.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
import type * as postcss from 'postcss';
import postcssValueParser, {
ParsedValue as PostCSSParsedValue,
FunctionNode,
WordNode,
Node as ValueNode,
} from 'postcss-value-parser';
import type { Diagnostics } from './diagnostics';
import { processPseudoStates } from './pseudo-states';
import { parseSelector } from './selector-utils';
import type { ParsedValue, StateParsedValue } from './types';
export const valueParserWarnings = {
VALUE_CANNOT_BE_STRING() {
return 'value can not be a string (remove quotes?)';
},
CSS_MIXIN_FORCE_NAMED_PARAMS() {
return 'CSS mixins must use named parameters (e.g. "func(name value, [name value, ...])")';
},
INVALID_NAMED_IMPORT_AS(name: string) {
return `Invalid named import "as" with name "${name}"`;
},
INVALID_NESTED_KEYFRAMES(name: string) {
return `Invalid nested keyframes import "${name}"`;
},
};
export interface MappedStates {
[s: string]: StateParsedValue | string | null;
}
// TODO: remove
export interface TypedClass {
'-st-root'?: boolean;
'-st-states'?: string[] | MappedStates;
'-st-extends'?: string;
}
export interface MixinValue {
type: string;
options: Array<{ value: string }> | Record<string, string>;
partial?: boolean;
valueNode?: FunctionNode | WordNode;
originDecl?: postcss.Declaration;
}
export interface ArgValue {
type: string;
value: string;
}
export interface ExtendsValue {
symbolName: string;
args: ArgValue[][] | null;
}
export type ReportWarning = (message: string, options?: { word: string }) => void;
export const rootValueMapping = {
vars: ':vars' as const,
import: ':import' as const,
stScope: 'st-scope' as const,
namespace: 'namespace' as const,
};
export const valueMapping = {
from: '-st-from' as const,
named: '-st-named' as const,
default: '-st-default' as const,
root: '-st-root' as const,
states: '-st-states' as const,
extends: '-st-extends' as const,
mixin: '-st-mixin' as const,
partialMixin: '-st-partial-mixin' as const,
global: '-st-global' as const,
};
export const paramMapping = {
global: 'st-global' as const,
};
export const mixinDeclRegExp = new RegExp(`(${valueMapping.mixin})|(${valueMapping.partialMixin})`);
export type stKeys = keyof typeof valueMapping;
export const stValues: string[] = Object.keys(valueMapping).map(
(key) => valueMapping[key as stKeys]
);
export const animationPropRegExp = /animation$|animation-name$/;
export const globalValueRegExp = new RegExp(`^${paramMapping.global}\\((.*?)\\)$`);
export const stValuesMap: Record<string, boolean> = Object.keys(valueMapping).reduce((acc, key) => {
acc[valueMapping[key as stKeys]] = true;
return acc;
}, {} as Record<string, boolean>);
export const STYLABLE_VALUE_MATCHER = /^-st-/;
export const STYLABLE_NAMED_MATCHER = new RegExp(`^${valueMapping.named}-(.+)`);
export const SBTypesParsers = {
'-st-root'(value: string) {
return value === 'false' ? false : true;
},
'-st-global'(decl: postcss.Declaration, _diagnostics: Diagnostics) {
// Experimental
const selector: any = parseSelector(decl.value.replace(/^['"]/, '').replace(/['"]$/, ''));
return selector.nodes[0].nodes;
},
'-st-states'(value: string, decl: postcss.Declaration, diagnostics: Diagnostics) {
if (!value) {
return {};
}
return processPseudoStates(value, decl, diagnostics);
},
'-st-extends'(value: string) {
const ast = postcssValueParser(value);
const types: ExtendsValue[] = [];
ast.walk((node: any) => {
if (node.type === 'function') {
const args = getNamedArgs(node);
types.push({
symbolName: node.value,
args,
});
return false;
} else if (node.type === 'word') {
types.push({
symbolName: node.value,
args: null,
});
}
return undefined;
}, false);
return {
ast,
types,
};
},
'-st-named'(
value: string,
node: postcss.Declaration | postcss.AtRule,
diagnostics: Diagnostics
) {
const namedMap: Record<string, string> = {};
const keyframesMap: Record<string, string> = {};
if (value) {
handleNamedTokens(
postcssValueParser(value),
{ namedMap, keyframesMap },
'namedMap',
node,
diagnostics
);
}
return { namedMap, keyframesMap };
},
'-st-mixin'(
mixinNode: postcss.Declaration,
strategy: (type: string) => 'named' | 'args',
diagnostics?: Diagnostics,
emitStrategyDiagnostics = true
) {
const ast = postcssValueParser(mixinNode.value);
const mixins: Array<MixinValue> = [];
function reportWarning(message: string, options?: { word: string }) {
if (emitStrategyDiagnostics) {
diagnostics?.warn(mixinNode, message, options);
}
}
ast.nodes.forEach((node) => {
if (node.type === 'function') {
mixins.push({
type: node.value,
options: strategies[strategy(node.value)](node, reportWarning),
valueNode: node,
originDecl: mixinNode,
});
} else if (node.type === 'word') {
mixins.push({
type: node.value,
options: strategy(node.value) === 'named' ? {} : [],
valueNode: node,
originDecl: mixinNode,
});
} else if (node.type === 'string') {
diagnostics?.error(mixinNode, valueParserWarnings.VALUE_CANNOT_BE_STRING(), {
word: mixinNode.value,
});
}
});
return mixins;
},
'-st-partial-mixin'(
mixinNode: postcss.Declaration,
strategy: (type: string) => 'named' | 'args',
diagnostics?: Diagnostics
) {
return SBTypesParsers['-st-mixin'](mixinNode, strategy, diagnostics).map((mixin) => {
mixin.partial = true;
return mixin;
});
},
};
function handleNamedTokens(
tokens: PostCSSParsedValue | FunctionNode,
buckets: { namedMap: Record<string, string>; keyframesMap: Record<string, string> },
key: keyof typeof buckets = 'namedMap',
node: postcss.Declaration | postcss.AtRule,
diagnostics: Diagnostics
) {
const { nodes } = tokens;
for (let i = 0; i < nodes.length; i++) {
const token = nodes[i];
if (token.type === 'word') {
const space = nodes[i + 1];
const as = nodes[i + 2];
const spaceAfter = nodes[i + 3];
const asName = nodes[i + 4];
if (isImportAs(space, as)) {
if (spaceAfter?.type === 'space' && asName?.type === 'word') {
buckets[key][asName.value] = token.value;
i += 4; //ignore next 4 tokens
} else {
i += !asName ? 3 : 2;
diagnostics.warn(
node,
valueParserWarnings.INVALID_NAMED_IMPORT_AS(token.value)
);
continue;
}
} else {
buckets[key][token.value] = token.value;
}
} else if (token.type === 'function' && token.value === 'keyframes') {
if (key === 'keyframesMap') {
diagnostics.warn(
node,
valueParserWarnings.INVALID_NESTED_KEYFRAMES(
postcssValueParser.stringify(token)
)
);
}
handleNamedTokens(token, buckets, 'keyframesMap', node, diagnostics);
}
}
}
function isImportAs(space: ParsedValue, as: ParsedValue) {
return space?.type === 'space' && as?.type === 'word' && as?.value === 'as';
}
export function getNamedArgs(node: ParsedValue) {
const args: ParsedValue[][] = [];
if (node.nodes.length) {
args.push([]);
node.nodes.forEach((node: any) => {
if (node.type === 'div') {
args.push([]);
} else {
const { sourceIndex: _sourceIndex, ...clone } = node;
args[args.length - 1].push(clone);
}
});
}
// handle trailing comma
return args.length && args[args.length - 1].length === 0 ? args.slice(0, -1) : args;
}
export function getFormatterArgs(
node: ParsedValue,
allowComments = false,
reportWarning?: ReportWarning,
preserveQuotes = false
) {
const argsResult = [];
let currentArg = '';
let argIndex = 0;
for (const currentNode of node.nodes) {
if (currentNode.type === 'div' && currentNode.value === ',') {
checkEmptyArg();
argIndex++;
argsResult.push(currentArg.trim());
currentArg = '';
} else if (currentNode.type === 'comment') {
if (allowComments) {
currentArg +=
currentNode.resolvedValue || postcssValueParser.stringify(currentNode);
}
} else if (currentNode.type === 'string') {
currentArg += preserveQuotes
? postcssValueParser.stringify(currentNode)
: currentNode.value;
} else {
currentArg += currentNode.resolvedValue || postcssValueParser.stringify(currentNode);
}
}
checkEmptyArg();
argsResult.push(currentArg.trim());
let i = argsResult.length;
while (i--) {
if (argsResult[i] === '') {
argsResult.pop();
} else {
return argsResult;
}
}
return argsResult;
function checkEmptyArg() {
if (reportWarning && currentArg.trim() === '') {
reportWarning(
`${postcssValueParser.stringify(
node as postcssValueParser.Node
)}: argument at index ${argIndex} is empty`
);
}
}
}
export function getStringValue(nodes: ParsedValue | ParsedValue[]): string {
return postcssValueParser.stringify(nodes as postcssValueParser.Node, (node) => {
if ((node as ParsedValue).resolvedValue !== undefined) {
return (node as ParsedValue).resolvedValue as string | undefined;
} else {
// TODO: warn
return undefined;
}
});
}
export function groupValues(nodes: ValueNode[], divType = 'div') {
const grouped: ValueNode[][] = [];
let current: ValueNode[] = [];
nodes.forEach((n: any) => {
if (n.type === divType) {
grouped.push(current);
current = [];
} else {
current.push(n);
}
});
const last = grouped[grouped.length - 1];
if ((last && last !== current && current.length) || (!last && current.length)) {
grouped.push(current);
}
return grouped;
}
export const strategies = {
named: (node: any, reportWarning?: ReportWarning) => {
const named: Record<string, string> = {};
getNamedArgs(node).forEach((mixinArgsGroup) => {
const argsDivider = mixinArgsGroup[1];
if (mixinArgsGroup.length < 3 || (argsDivider && argsDivider.type !== 'space')) {
if (reportWarning) {
const argValue = mixinArgsGroup[0];
reportWarning(valueParserWarnings.CSS_MIXIN_FORCE_NAMED_PARAMS(), {
word: argValue.value,
});
}
return;
}
named[mixinArgsGroup[0].value] = stringifyParam(mixinArgsGroup.slice(2));
});
return named;
},
args: (node: any, reportWarning?: ReportWarning) => {
return getFormatterArgs(node, true, reportWarning).map((value) => ({ value }));
},
};
function stringifyParam(nodes: any) {
return postcssValueParser.stringify(nodes, (n: any) => {
if (n.type === 'function') {
return postcssValueParser.stringify(n);
} else if (n.type === 'div') {
return null;
} else if (n.type === 'string') {
return n.value;
} else {
return undefined;
}
});
}
export function listOptions(node: any) {
return groupValues(node.nodes)
.map((nodes: any) =>
postcssValueParser.stringify(nodes, (n: any) => {
if (n.type === 'div') {
return null;
} else if (n.type === 'string') {
return n.value;
} else {
return undefined;
}
})
)
.filter((x: string) => typeof x === 'string');
}
export function validateAllowedNodesUntil(
node: ParsedValue,
i: number,
untilType = 'div',
allowed = ['comment']
) {
i = 1;
let current = node.nodes[i];
while (current && current.type !== untilType) {
if (!allowed.includes(current.type)) {
return false;
}
i++;
current = node.nodes[i];
}
return true;
}