-
Notifications
You must be signed in to change notification settings - Fork 399
Expand file tree
/
Copy pathobject_factory.js
More file actions
462 lines (408 loc) · 15.5 KB
/
object_factory.js
File metadata and controls
462 lines (408 loc) · 15.5 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
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
'use strict';
const _ = require('lodash');
const path = require('path');
const logger = require('./log');
const patternEngines = require('./pattern_engines');
// prefixMatcher is intended to match the leading maybe-underscore,
// zero or more digits, and maybe-dash at the beginning of a pattern file name we can hack them
// off and get at the good part.
const prefixMatcher = /^_?(\d+-)?/;
const prefixMatcherDeprecationCheckOrder = /^(\d+-).+/;
const prefixMatcherDeprecationCheckHidden = /^_.+/;
/**
* Pattern constructor / Pattern properties
*
* Before changing functionalities of the pattern object please read the following pull requests
* to get more details about the behavior of the folder structure
* https://patternlab.io/docs/overview-of-patterns/#heading-deeper-nesting
* https://github.com/pattern-lab/patternlab-node/pull/992
* https://github.com/pattern-lab/patternlab-node/pull/1016
* https://github.com/pattern-lab/patternlab-node/pull/1143
*
* @param {string} relPath relative directory
* @param {Object} jsonFileData The JSON used to render values in the pattern.
* @param {Patternlab} patternlab The actual pattern lab instance
* @param {boolean} isPromoteToFlatPatternRun specifies if the pattern needs to be removed from its deep nesting folder
*/
const Pattern = function (
relPath,
jsonFileData,
patternlab,
isPromoteToFlatPatternRun
) {
this.relPath = path.normalize(relPath); // 'atoms/global/colors.mustache'
/**
* We expect relPath to be the path of the pattern template, relative to the
* root of the pattern tree. Parse out the path parts and save the useful ones.
*/
const pathObj = path.parse(this.relPath);
// We need to check for templates with a fileextension that contains multiple dots like e.g. .html.twig
if (
patternlab?.config?.patternExtension?.includes('.') &&
this.relPath.endsWith('.' + patternlab.config.patternExtension)
) {
this.fileExtension = '.' + patternlab.config.patternExtension; // e.g. '.html.twig'
this.fileName = path.basename(this.relPath, this.fileExtension); // e.g. 'colors'
} else {
this.fileExtension = pathObj.ext; // e.g. '.hbs'
this.fileName = pathObj.name; // e.g. 'colors'
}
this.subdir = pathObj.dir; // 'atoms/global'
const info = this.getPatternInfo(
pathObj,
patternlab,
isPromoteToFlatPatternRun ||
(patternlab &&
patternlab.config &&
patternlab.config.allPatternsAreDeeplyNested),
this.fileName
);
// TODO: Remove if block when dropping ordering by prefix and keep else code
// (When we drop the info about the old ordering is deprecated)
if (
(prefixMatcherDeprecationCheckOrder.test(this.getDirLevel(0, info)) ||
prefixMatcherDeprecationCheckOrder.test(this.getDirLevel(1, info)) ||
prefixMatcherDeprecationCheckOrder.test(this.fileName)) &&
patternlab &&
patternlab.config &&
!patternlab.config.disableDeprecationWarningForOrderPatterns
) {
logger.warning(
`${info.shortNotation}-${this.fileName} "Pattern", "Group" and "Subgroup" ordering by number prefix (##-) will be deprecated in the future.\n See https://patternlab.io/docs/reorganizing-patterns/`
);
}
if (
(prefixMatcherDeprecationCheckHidden.test(this.getDirLevel(0, info)) ||
prefixMatcherDeprecationCheckHidden.test(this.getDirLevel(1, info)) ||
prefixMatcherDeprecationCheckHidden.test(this.fileName)) &&
!info.isMetaPattern &&
patternlab &&
patternlab.config &&
!patternlab.config.disableDeprecationWarningForHiddenPatterns
) {
logger.warning(
`${info.shortNotation}/${this.fileName} "Pattern", "Group" and "Subgroup" hiding by underscore prefix (_*) will be deprecated in the future.\n See https://patternlab.io/docs/hiding-patterns-in-the-navigation/`
);
}
// TODO: Remove if when dropping ordering by prefix and keep else code
if (info.patternHasOwnDir) {
// Since there is still the requirement of having the numbers provided for sorting
// this will be required to keep the folder prefix and the variant name
// /00-atoms/00-global/00-colors/colors~variant.hbs
// -> 00-atoms-00-global-00-colors-variant
this.name = `${info.shortNotation}-${path.parse(pathObj.dir).base}${
this.fileName.indexOf('~') !== -1 ? '-' + this.fileName.split('~')[1] : ''
}`;
} else {
// this is the unique name, subDir + fileName (sans extension)
this.name = `${info.shortNotation}-${this.fileName.replace('~', '-')}`;
}
// the JSON used to render values in the pattern
this.jsonFileData = jsonFileData || {};
// flip tildes to dashes
this.patternBaseName = this.fileName
.replace(prefixMatcher, '')
.replace('~', '-'); // 'colors'
// Fancy name - Uppercase letters of pattern name partials.
// global-colors -> 'Global Colors'
// this is the display name for the ui. strip numeric + hyphen prefixes
this.patternName = _.startCase(this.patternBaseName);
// the top-level pattern group this pattern belongs to. 'atoms'
this.patternGroup = this.getDirLevel(0, info).replace(prefixMatcher, '');
// the sub-group this pattern belongs to.
this.patternSubgroup = this.getDirLevel(1, info).replace(prefixMatcher, ''); // 'global'
// the joined pattern group and subgroup directory
this.flatPatternPath = info.shortNotation; // 'atoms-global'
// Calculated path from the root of the public directory to the generated
// (rendered!) html file for this pattern, to be shown in the iframe
this.patternLink = patternlab
? this.getPatternLink(patternlab, 'rendered')
: null;
// The canonical "key" by which this pattern is known. This is the callable
// name of the pattern. UPDATE: this.key is now known as this.patternPartial
this.patternPartial = this.patternGroup + '-' + this.patternBaseName;
// Let's calculate the verbose name ahead of time! We don't use path.sep here
// on purpose. This isn't a file name!
this.verbosePartial = `${info.shortNotation}/${this.fileName}`;
/**
* Definition of flat pattern:
* The flat pattern is a high level pattern which is attached directly to
* the main root folder or to a root directory.
* --- This ---
* root
* flatPattern
* --- OR That ---
* root
* molecules
* flatPattern
*/
this.isFlatPattern =
this.patternGroup === this.patternSubgroup || !this.patternSubgroup;
this.isPattern = true;
this.patternState = '';
this.template = '';
this.patternPartialCode = '';
this.lineage = [];
this.lineageIndex = [];
this.lineageR = [];
this.lineageRIndex = [];
this.isPseudoPattern = false;
this.order = 0;
this.variantOrder = 0;
this.engine = patternEngines.getEngineForPattern(this);
// TODO: Remove the following when ordering by file prefix gets obsolete
this.patternGroupData = this.patternGroupData || {};
if (!this.patternGroupData.order && info.patternGroupOrder) {
this.patternGroupData.order = info.patternGroupOrder;
}
// TODO: Remove the following when ordering by file prefix gets obsolete
this.patternSubgroupData = this.patternSubgroupData || {};
if (!this.patternSubgroupData.order && info.patternSubgroupOrder) {
this.patternGroupData.order = info.patternSubgroupOrder;
}
// TODO: Remove the following when ordering by file prefix gets obsolete
if (prefixMatcherDeprecationCheckOrder.test(this.fileName)) {
if (this.fileName.indexOf('~') === -1) {
this.order = this.setPatternOrderDataForInfo(this.fileName);
} else {
this.variantOrder = this.setPatternOrderDataForInfo(this.fileName);
}
}
/**
* Determines if this pattern needs to be recompiled.
*
* @see {@link CompileState}*/
this.compileState = null;
/**
* Timestamp in milliseconds when the pattern template or auxiliary file (e.g. json) were modified.
* If multiple files are affected, this is the timestamp of the most recent change.
*
* @see {@link pattern}
*/
this.lastModified = null;
};
// Pattern methods
Pattern.prototype = {
// render function - acts as a proxy for the PatternEngine's
render: function (data, partials) {
if (!this.extendedTemplate) {
this.extendedTemplate = this.template;
}
if (this.engine) {
const promise = this.engine.renderPattern(
this,
data || this.jsonFileData,
partials
);
return promise
.then((results) => {
return results;
})
.catch((reason) => {
return Promise.reject(reason);
});
}
return Promise.reject('where is the engine?');
},
registerPartial: function () {
if (this.engine && typeof this.engine.registerPartial === 'function') {
this.engine.registerPartial(this);
}
},
/**
* calculated path from the root of the public directory to the generated html
* file for this pattern.
*
* Should look something like 'atoms-global-colors/atoms-global-colors.html'
*
* @param {Patternlab} patternlab Current patternlab instance
* @param {string} suffixType File suffix
* @param {string} customFileExtension Custom extension
*/
getPatternLink: function (patternlab, suffixType, customFileExtension) {
// if no suffixType is provided, we default to rendered
const suffixConfig = patternlab.config.outputFileSuffixes;
const suffix = suffixType
? suffixConfig[suffixType]
: suffixConfig.rendered;
if (suffixType === 'rawTemplate') {
return this.name + path.sep + this.name + suffix + this.fileExtension;
}
if (suffixType === 'custom') {
return this.name + path.sep + this.name + customFileExtension;
}
return this.name + path.sep + this.name + suffix + '.html';
},
/**
* The finders all delegate to the PatternEngine, which also
* encapsulates all appropriate regex's
*/
findPartials: function () {
return this.engine.findPartials(this);
},
findPartialsWithPatternParameters: function () {
return this.engine.findPartialsWithPatternParameters(this);
},
findListItems: function () {
return this.engine.findListItems(this);
},
findPartial: function (partialString) {
return this.engine.findPartial(partialString);
},
/**
* Get a directory on a specific level of the pattern path
*
* @param {Number} level Level of folder to get
* @param {Object} pInfo general information about the pattern
*/
getDirLevel: function (level, pInfo) {
const items = this.subdir.split(path.sep);
pInfo && pInfo.patternHasOwnDir && items.pop();
if (items[level]) {
return items[level];
} else if (level >= 1) {
return '';
} else {
// I'm not quite sure about that but its better than empty node
// TODO: verify
return 'root';
}
},
/**
* Reset the information that the pattern has it's own directory,
* so that this pattern will not be handled as flat pattern if it
* is located on a top level folder.
*
* @param {Patternlab} patternlab Current patternlab instance
*/
promoteFromDirectoryToFlatPattern: function (patternlab) {
const p = new Pattern(this.relPath, this.jsonFileData, patternlab, true);
// Only reset the specific fields, not everything
Object.assign(this, {
name: p.name,
patternLink: p.patternLink,
patternGroup: p.patternGroup,
patternSubgroup: p.patternSubgroup,
isFlatPattern: p.isFlatPattern,
flatPatternPath: p.flatPatternPath,
patternPartial: p.patternPartial,
verbosePartial: p.verbosePartial,
});
},
/**
* Retrieves the number prefix, which later is used for sorting.
* (Can be removed when sorting by number prefix becomes obsolete)
* @param {*} pathStr the path that needs to be checked for number prefixes
* @returns the order number or 0 when no prefix is available
*/
setPatternOrderDataForInfo: (pathStr) => {
const match = pathStr.match(prefixMatcherDeprecationCheckOrder);
return match && match.length >= 1
? pathStr.match(prefixMatcherDeprecationCheckOrder)[1].replace('-', '')
: 0;
},
/**
* The "info" object contains information about pattern structure if it is
* a nested pattern or if it just a sub folder structure. It's just used for
* internal purposes. Remember every pattern information based on "this.*"
* will be used by other functions
*
* @param pathObj path.parse() object containing useful path information
*/
getPatternInfo: (
pathObj,
patternlab,
isPromoteToFlatPatternRun,
filename
) => {
const info = {
// colors(.mustache) is deeply nested in atoms-/global/colors
patternlab: patternlab,
patternHasOwnDir: isPromoteToFlatPatternRun
? path.basename(pathObj.dir).replace(prefixMatcher, '') ===
filename.replace(prefixMatcher, '') ||
path.basename(pathObj.dir).replace(prefixMatcher, '') ===
filename.split('~')[0].replace(prefixMatcher, '')
: false,
};
info.dir = info.patternHasOwnDir ? pathObj.dir.split(path.sep).pop() : '';
info.dirLevel = pathObj.dir.split(path.sep).filter((s) => !!s).length;
// Only relevant for deprecation check and message
if (path.parse(pathObj.dir).base === '_meta') {
info.isMetaPattern = true;
}
if (info.dirLevel === 0 || (info.dirLevel === 1 && info.patternHasOwnDir)) {
// -> ./
info.shortNotation = 'root';
} else if (info.dirLevel === 2 && info.patternHasOwnDir) {
// -> ./folder
info.shortNotation = path.dirname(pathObj.dir).replace(prefixMatcher, '');
info.patternGroupOrder = Pattern.prototype.setPatternOrderDataForInfo(
path.dirname(pathObj.dir)
);
} else {
// -> ./folder/folder
info.shortNotation = pathObj.dir
.split(/\/|\\/, 2)
.map((o, i) => {
if (i === 0) {
// TODO: Remove when prefix gets deprecated
info.patternGroupOrder =
Pattern.prototype.setPatternOrderDataForInfo(o);
}
if (i === 1) {
// TODO: Remove when prefix gets deprecated
info.patternSubgroupOrder =
Pattern.prototype.setPatternOrderDataForInfo(o);
}
return o.replace(prefixMatcher, '');
})
.join('-')
.replace(new RegExp(`-${info.dir}$`), '');
info.verbosePartial = pathObj.dir
.split(/\/|\\/, 2)
.map((o) => o.replace(prefixMatcher, ''))
.join('/')
.replace(new RegExp(`-${info.dir}$`), '');
}
return info;
},
};
// Pattern static methods
/**
* factory: creates an empty Pattern for miscellaneous internal use, such as
* by list_item_hunter
*
* @param {Object} customProps Properties to apply to new pattern
* @param {Patternlab} patternlab Current patternlab instance
*/
Pattern.createEmpty = function (customProps, patternlab) {
let relPath = '';
if (customProps) {
if (customProps.relPath) {
relPath = customProps.relPath;
} else if (customProps.subdir && customProps.filename) {
relPath = path.join(customProps.subdir, customProps.filename);
}
}
const pattern = new Pattern(relPath, null, patternlab);
return Object.assign(pattern, customProps);
};
/**
* factory: creates a Pattern object on-demand from a hash; the hash accepts
* parameters that replace the positional parameters that the Pattern
* constructor takes.
*/
Pattern.create = function (relPath, data, customProps, patternlab) {
const newPattern = new Pattern(relPath || '', data || null, patternlab);
return Object.assign(newPattern, customProps);
};
const CompileState = {
NEEDS_REBUILD: 'needs rebuild',
BUILDING: 'building',
CLEAN: 'clean',
};
module.exports = {
Pattern: Pattern,
CompileState: CompileState,
};