-
Notifications
You must be signed in to change notification settings - Fork 514
/
Copy pathCSSSyntax.ejs
410 lines (374 loc) · 13.8 KB
/
CSSSyntax.ejs
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
<%
/*
* Displays the formal syntax for a CSS property, using the values found in
* the https://github.com/w3c/webref package.
*
* The property name is taken from the page slug.
*
* The syntax is pretty-printed and syntax-highlighted.
*/
const webRefData = require('@webref/css');
const { definitionSyntax } = require('css-tree');
const locale = env.locale;
// URL where we describe value definition syntax
const valueDefinitionUrl = `/${locale}/docs/Web/CSS/Value_definition_syntax`;
// CSS types for which we want to link to another page, and not expand the syntax
const typesToLink = ["<color>", "<gradient>"];
// Map item names onto slugs, in cases where the slug can't be derived from the name
const slugMap = {
"<color>": "color_value",
"<position>": "position_value"
}
// Descriptions used for building links and tooltips for parts of the value definition syntax
const syntaxDescriptions = {
'*': {
fragment: 'asterisk',
tooltip: mdn.localString({ 'en-US': 'Asterisk: the entity may occur zero, one or several times' })
},
'+': {
fragment: 'plus',
tooltip: mdn.localString({ 'en-US': 'Plus: the entity may occur one or several times' })
},
'?': {
fragment: 'question_mark',
tooltip: mdn.localString({ 'en-US': 'Question mark: the entity is optional' })
},
'{}': {
fragment: 'curly_braces',
tooltip: mdn.localString({ 'en-US': 'Curly braces: encloses two integers defining the minimal and maximal numbers of occurrences of the entity' })
},
'#': {
fragment: 'hash_mark',
tooltip: mdn.localString({ 'en-US': 'Hash mark: the entity is repeated one or several times, each occurence separated by a comma' })
},
'!': {
fragment: 'exclamation_point_!',
tooltip: mdn.localString({ 'en-US': 'Exclamation point: the group must produce at least one value' })
},
'[]': {
fragment: 'brackets',
tooltip: mdn.localString({ 'en-US': 'Brackets: enclose several entities, combinators, and multipliers to transform them as a single component' })
},
'|': {
fragment: 'single_bar',
tooltip: mdn.localString({ 'en-US': 'Single bar: exactly one of the entities must be present' })
},
'||': {
fragment: 'double_bar',
tooltip: mdn.localString({ 'en-US': 'Double bar: one or several of the entities must be present, in any order' })
},
'&&': {
fragment: 'double_ampersand',
tooltip: mdn.localString({ 'en-US': 'Double ampersand: all of the entities must be present, in any order' })
}
}
// get the contents of webref
const parsedWebRef = await webRefData.listAll();
// get all the value syntaxes
let valuespaces = {};
for (const spec of Object.values(parsedWebRef)) {
valuespaces = {...valuespaces, ...spec.valuespaces};
}
/**
* Get the formal syntax and properly formatted name for an item.
*/
function getNameAndSyntax() {
// get the item name from the page slug
let itemName = $0 || env.slug.split('/').pop().toLowerCase();
let itemSyntax;
if (env.tags.includes("CSS Property")) {
// get syntax for a CSS property
itemSyntax = getPropertySyntax(itemName, parsedWebRef);
} else if (env.tags.includes("CSS Data Type")) {
// get syntax for a CSS data type
// some CSS data type slugs have a `_value` suffix
if (itemName.endsWith("_value")) {
itemName = itemName.replace("_value", "");
}
itemName = `<${itemName}>`;
// not all types have an entry in the syntax
if (valuespaces[itemName]) {
itemSyntax = valuespaces[itemName].value;
}
} else if (env.tags.includes("CSS Function")) {
// get syntax for a CSS function
itemName = `<${itemName}()>`;
// not all types have an entry in the syntax
if (valuespaces[itemName]) {
itemSyntax = valuespaces[itemName].value;
}
}
return {
name: itemName,
syntax: itemSyntax
}
}
/**
* Get the formal syntax for a property from the webref data, given:
* @param {string} propertyName - the name of the property
*/
function getPropertySyntax(propertyName) {
// 1) get all specs which list this property
let specsForProp = [];
for (const [shortname, data] of Object.entries(parsedWebRef)) {
const propNames = Object.keys(data.properties);
if (propNames.includes(propertyName)) {
specsForProp.push(shortname);
}
}
// 2) If we have more than one spec, filter out specs that end "-n" where n is a number
if (specsForProp.length > 1) {
specsForProp = specsForProp.filter( specName => !(/-\d+$/.test(specName)) );
}
// 3) If we now have only one spec, return the syntax it lists
if (specsForProp.length === 1) {
return parsedWebRef[specsForProp[0]].properties[propertyName].value;
}
// 4) If we still have > 1 spec, assume that:
// - one of them is the base spec, which defines `values`,
// - the others define incremental additions as `newValues`
let syntax = '';
let newSyntaxes = '';
for (const specName of specsForProp) {
const baseValue = parsedWebRef[specName].properties[propertyName].value;
if (baseValue) {
syntax = baseValue;
}
const newValues = parsedWebRef[specName].properties[propertyName].newValues;
if (newValues) {
newSyntaxes += ` | ${newValues}`;
}
}
// Concatenate newValues onto values to return a single syntax string
if (newSyntaxes) {
syntax += newSyntaxes;
}
return syntax;
}
/**
* Get the markup for a multiplier, including links to the value definition syntax.
*/
function renderMultiplier(multiplierName) {
let key = multiplierName;
// remove number inside `{}` multiplier
if (multiplierName.startsWith('{')) {
key = '{}';
}
// these two multiplier combinations can appear, and in this case we want links to both parts
if (multiplierName === '+#' || multiplierName === '#?') {
const info1 = syntaxDescriptions[multiplierName[0]];
const info2 = syntaxDescriptions[multiplierName[1]];
const link1 = `<a href="${valueDefinitionUrl}#${info1.fragment}" title="${info1.tooltip}">${multiplierName[0]}</a>`;
const link2 = `<a href="${valueDefinitionUrl}#${info2.fragment}" title="${info2.tooltip}">${multiplierName[1]}</a>`;
return `${link1}${link2}`;
}
const info = syntaxDescriptions[key];
return `<a href="${valueDefinitionUrl}#${info.fragment}" title="${info.tooltip}">${multiplierName}</a>`;
}
/**
* Determines the markup to generate for a single node in the AST
* generated by css-tree.
*/
function renderNode(name, node) {
switch (node.type) {
case 'Property': {
return `<span class="token property">${name}</span>`;
}
case 'Type': {
// encode < and >
let encoded = name.replaceAll('<', '<');
encoded = encoded.replaceAll('>', '>');
// add CSS class: we use "property" because there isn't one for types
const span = `<span class="token property">${encoded}</span>`;
// If the type is not included in the syntax, or is in "typesToLink",
// link to its dedicated page (don't expand it)
if (valuespaces[name]?.value && !typesToLink.includes(name)) {
return span;
} else {
let slug;
// If the name is in slugMap, we can't derive the slug from the name
if (slugMap[name]) {
slug = slugMap[name];
} else {
// The slug should not include the angle brackets
slug = name.replaceAll('<', '');
slug = slug.replaceAll('>', '');
// The slug should not contain the range in square brackets, as in "<number [0,∞]>"
slug = slug.replace(/\[.*\]/, '');
}
return `<a href="/${locale}/docs/Web/CSS/${slug}">${span}</a>`;
}
}
case 'Multiplier': {
// link to the value definition syntax and provide a tooltip
return renderMultiplier(name);
}
case 'Keyword': {
return `<span class="token keyword">${name}</span>`;
}
case 'Function': {
return `<span class="token function">${name}</span>`;
}
case 'Token': {
if (name === ')') {
// this is a closing bracket
return `<span class="token function">${name}</span>`;
}
}
case 'Group': {
// link from brackets to the value definition syntax docs
const info = syntaxDescriptions['[]'];
name = name.replace(/^\[/, `<a href="${valueDefinitionUrl}#${info.fragment}" title="${info.tooltip}">[</a>`);
name = name.replace(/\]$/, `<a href="${valueDefinitionUrl}#${info.fragment}" title="${info.tooltip}">]</a>`);
// link from combinators (except " ") to the value definition syntax docs
if (node.combinator && (node.combinator !== ' ')) {
const info = syntaxDescriptions[node.combinator];
// note that we are replacing the combinator surrounded by spaces, like " | "
name = name.replaceAll(` ${node.combinator} `, ` <a href="${valueDefinitionUrl}#${info.fragment}" title="${info.tooltip}">${node.combinator}</a> `);
}
return name;
}
default:
return name;
}
}
/**
* Generate the markup for every term in a syntax definition,
* ensuring that the terms are visually aligned
*/
function renderTerms(terms, combinator) {
let output = '';
const renderedTerms = [];
for (const term of terms) {
// figure out the lengths of the translated terms, without markup
// this is just so we can align the terms properly
const termTextLength = definitionSyntax.generate(term).length;
// get the translated terms, with markup
const termText = definitionSyntax.generate(term, { decorate: renderNode});
renderedTerms.push({
text: termText,
length: termTextLength
});
}
// we will space-pad all terms to the length of the longest term,
// so that lines are aligned, but padding must not cause lines to wrap,
// so the target width is clamped to the line length.
const maxLineLength = 50;
let maxTermLength = Math.max(...renderedTerms.map(t => t.length));
maxTermLength = Math.min(maxTermLength, maxLineLength);
// write out the translated terms, padding with spaces for alignment
// and separating terms using their combinator symbol
for (let i = 0; i < renderedTerms.length; i++) {
const termText = renderedTerms[i].text;
const spaceCount = Math.max(2, (maxTermLength + 2) - renderedTerms[i].length);
let combinatorText = '';
if (combinator && combinator !== " ") {
const info = syntaxDescriptions[combinator];
// link from combinators (except " ") to the value definition syntax docs
combinatorText = `<a href="${valueDefinitionUrl}#${info.fragment}" title="${info.tooltip}">${combinator}</a>`;
}
// omit the combinator for the final term
combinatorText = (i < renderedTerms.length-1 ? combinatorText : '');
output += ` ${termText}${' '.repeat(spaceCount)}${combinatorText}<br/>`;
}
return output;
}
/**
* Render the syntax for a single type.
*/
function renderSyntax(type, syntax) {
// write out the name of this type
type = type.replaceAll('<', '<');
type = type.replaceAll('>', '>');
let output = `<span class="token property" id="${type}">${type} = </span><br/>`;
const ast = definitionSyntax.parse(syntax);
// if the combinator is ' ', write the complete type syntax in a single line
if (ast.combinator === ' ') {
output += renderTerms([ast], ast.combinator);
} else {
// otherwise write out each direct child in its own line
output += renderTerms(ast.terms, ast.combinator);
}
return output;
}
/**
* Get names of all the types in a given set of syntaxes
*/
function getTypesForSyntaxes(syntaxes, constituents) {
function processNode(node) {
// Ignore the constituent parts of "typesToLink" types
if (typesToLink.includes(`<${node.name}>`)) {
return;
}
if (node.type === 'Type' && !constituents.includes(node.name)) {
constituents.push(node.name);
}
}
for (const syntax of syntaxes) {
const ast = definitionSyntax.parse(syntax);
definitionSyntax.walk(ast, processNode);
}
}
/**
* Given an item (such as a CSS property), fetch all the types that participate
* in its formal syntax definition, either directly or transitively.
*/
function getConstituentTypes(itemSyntax) {
const allConstituents = [];
let oldConstituentsLength = 0;
// get all the types in the top-level syntax
let constituentSyntaxes = [itemSyntax];
// while an iteration added more types...
while (true) {
oldConstituentsLength = allConstituents.length;
getTypesForSyntaxes(constituentSyntaxes, allConstituents);
if (allConstituents.length <= oldConstituentsLength) {
break;
}
// get the syntaxes for all newly added constituents,
// and then get the types in those syntaxes
constituentSyntaxes = [];
for (const constituent of allConstituents.slice(oldConstituentsLength)) {
const constituentSyntaxEntry = valuespaces[`<${constituent}>`];
if (constituentSyntaxEntry?.value) {
constituentSyntaxes.push(constituentSyntaxEntry.value);
}
}
}
return allConstituents;
}
/**
* Write out the complete formal syntax for an item.
*
* This includes the item's own syntax, described in `itemSyntax`,
* and also the syntax for any types that participate in the definition of
* the item.
*/
function writeFormalSyntax(itemName, itemSyntax) {
let output = '';
output += '<pre>';
// write the syntax for the property
output += renderSyntax(itemName, itemSyntax);
output += '<br/>';
// collect all the constituent types for the property
const types = getConstituentTypes(itemSyntax);
// and write each one out
for (const type of types) {
if (valuespaces[`<${type}>`] && valuespaces[`<${type}>`].value) {
output += renderSyntax(`<${type}>`, valuespaces[`<${type}>`].value);
output += '<br/>';
}
}
output += '</pre>';
return output;
}
let output = '';
const {name, syntax} = getNameAndSyntax();
if (!syntax) {
output = 'Error: could not find syntax for this item';
} else {
// write it out
output = writeFormalSyntax(name, syntax);
}
%>
<%-output%>