forked from tollwerk/fractal-typo3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
376 lines (338 loc) · 11.8 KB
/
index.js
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
/* eslint-disable global-require, import/no-dynamic-require, no-console, no-underscore-dangle */
const { Adapter } = require('@frctl/fractal');
const path = require('path');
const fs = require('fs');
const dashify = require('dashify');
const mkdirp = require('mkdirp').sync;
const chalk = require('chalk');
const deleteEmpty = require('delete-empty');
const url = require('url');
const request = require('request-promise');
const files = [];
let typo3url = null;
let typo3dev = 0;
let app;
let logger;
let componentCache;
/**
* Write a file to disc
*
* @param {String} file File path
* @param {String} content File content
*/
function writeFile(file, content) {
fs.writeFileSync(file, content);
files.push(path.relative(app.components.get('path'), file));
}
/**
* Configure a component
*
* @param {String} configPath Component configuration path
* @param {Object} component Component properties
* @param {String} componentPath Component path
*/
function configureComponent(configPath, component, componentPath) {
let config;
if (configPath in componentCache) {
config = componentCache[configPath];
// If this is the default variant
if (!component.variant) {
config.title = component.name;
config.status = component.status;
config.context = config.context || {};
config.context.type = component.type;
}
config.variants = config.variants || [];
} else {
config = {
title: component.name,
status: component.status,
context: {
type: component.type,
component: component.class,
config: component.config,
resources: component.resources || [],
},
variants: [],
};
}
// Register the preview component
if (component.preview) {
config.preview = `@${[...componentPath, dashify(component.name), 'preview'].join('-')}`;
}
// Remove the variant if already present
const variant = component.variant || 'default';
config.variants = config.variants.filter((vt) => vt.name !== variant);
// Register the variant
config.variants.push({
name: variant,
label: component.label || ((variant === 'default') ? component.name : variant),
context: {
config: component.config,
parameters: component.parameters || {},
request: component.request,
component: component.class,
},
});
config.variants = config.variants.sort((a, b) => {
const aName = a.label.toLowerCase();
const bName = b.label.toLowerCase();
if (aName > bName) {
return 1;
}
return (aName < bName) ? -1 : 0;
});
config.variants.forEach((v, i) => {
config.variants[i].order = i;
});
// Write the configuration file
writeFile(configPath, JSON.stringify(config, null, 4));
componentCache[configPath] = config;
// If there's a component note
if ((variant === 'default') && component.notice) {
const readme = path.join(path.dirname(configPath), 'README.md');
writeFile(readme, component.notice);
}
}
/**
* Create and pre-configure a directory
*
* @param {String} dirPrefix Path prefix
* @param {Array} dirPath Directory path
* @param {Array} dirConfigs Local directory configurations
* @return {boolean} Directory been created and pre-configured
*/
function createCollection(dirPrefix, dirPath, dirConfigs) {
const dir = dirPath.shift();
const dirConfig = dirConfigs.shift() || {};
const absDir = path.join(dirPrefix, dir);
// Create the collection directory
try {
if (!fs.statSync(absDir).isDirectory()) {
throw new Error('1');
}
} catch (e) {
try {
if (!mkdirp(absDir)) {
throw new Error('2');
}
} catch (f) {
return false;
}
}
// Configure the collection prefix
const configPath = path.join(absDir, `${dir.replace(/^\d{2}-/, '')}.config.json`);
const prefix = path.relative(app.components.get('path'), absDir).split(path.sep).map((p) => p.replace(/^\d{2}-/, '')).join('-');
let config;
try {
config = require(configPath);
config.prefix = prefix;
} catch (e) {
config = { prefix };
}
['label'].forEach((c) => {
if (c in dirConfig) {
config[c] = dirConfig[c];
}
});
writeFile(configPath, JSON.stringify(config, null, 4));
// Recurse
return dirPath.length ? createCollection(absDir, dirPath, dirConfigs) : true;
}
/**
* Register a component
*
* @param {Object} component Component
*/
function registerComponent(component) {
const componentName = dashify(component.name);
const componentLocalConfig = (component.local instanceof Array) ? component.local : [];
while (componentLocalConfig.length < component.path.length) {
componentLocalConfig.push([]);
}
const componentPath = component.path.slice(0).map((p) => dashify(p));
const componentRealPath = componentPath.map((p, i) => (componentLocalConfig[i].dirsort
? `${String.prototype.padStart.apply(componentLocalConfig[i].dirsort, [2, '0'])}-${p}` : p));
const componentParent = path.join(app.components.get('path'), ...componentRealPath);
const componentDirectory = path.join(componentParent, componentName);
// Create the component directory
if (!createCollection(app.components.get('path'), [...componentRealPath, componentName], componentLocalConfig)) {
throw new Error(`Could not create component directory ${componentDirectory}`);
}
// Write out the template file
const componentVariantName = componentName + (component.variant ? `--${dashify(component.variant)}` : '');
const componentTemplate = path.join(componentDirectory, `${componentVariantName}.${component.extension}`);
writeFile(componentTemplate, component.template);
// Write out the preview template
if (component.preview) {
writeFile(path.join(componentParent, `_${componentName}-preview.t3s`), component.preview);
}
// Configure the component
configureComponent(path.join(componentDirectory, `${componentName}.config.json`), component, componentPath);
}
/**
* Process a component
*
* @param {Object} component Component
*/
function processComponent(component) {
let { name } = component;
if (component.variant) {
name += ` (${component.variant})`;
}
const pathName = component.path.slice(0);
pathName.push(name);
// If the component is invalid
if (!component.valid) {
logger.log(`${chalk.bold.red('X')} ${pathName.join('/')} (failed)`);
return;
}
logger.log(`${chalk.green('√')} ${pathName.join('/')} (succeeded)`);
registerComponent(component);
}
/**
* Update the components by extracting them from a TYPO3 instance
*
* @return {Promise} Promise
*/
const update = function update() {
app = this.fractal;
componentCache = {};
return request({
uri: typo3url,
qs: { type: 2402, tx_twcomponentlibrary_component: { dev: typo3dev } },
json: true,
}).then((components) => {
for (const component of components) {
processComponent(component);
}
// Write the general shared context
const context = { context: { typo3: typo3url } };
writeFile(path.resolve(app.components.get('path'), 'components.config.json'), JSON.stringify(context, null, 4));
// See if there's a component file manifest
const manifest = path.resolve(app.components.get('path'), 'components.files.json');
try {
if (fs.statSync(manifest).isFile()) {
const currentFiles = new Set(files);
const prevFiles = new Set(JSON.parse(fs.readFileSync(manifest)));
// Delete all redundant files
[...prevFiles].filter((f) => !currentFiles.has(f)).forEach((f) => fs.unlinkSync(path.resolve(app.components.get('path'), f)));
}
} catch (e) {
// Ignore errors
} finally {
writeFile(manifest, JSON.stringify(files));
deleteEmpty.sync(app.components.get('path'));
}
}).catch((err) => {
logger.log(err);
process.exit(1);
});
};
/**
* Encode an object as URI parameters
*
* @param {Object} params Parameter object
* @param {String} prefix Parameter prefix
* @return {Array} Encoded URI parameters
*/
const encodeURIParams = function encodeURIParams(params, prefix) {
let parts = [];
for (const name in params) {
if (Object.prototype.hasOwnProperty.call(params, name)) {
const paramName = prefix ? (`${prefix}[${encodeURIComponent(name)}]`) : encodeURIComponent(name);
if (typeof params[name] === 'object') {
parts = Array.prototype.concat.apply(parts,
encodeURIParams(params[name], paramName));
} else {
parts.push(`${paramName}=${encodeURIComponent(params[name])}`);
}
}
}
return parts;
};
/**
* Create and return the graph URL for a particular component
*
* @param {Component} component Component
*/
const componentGraphUrl = function componentGraphUrl(component) {
const context = ('variants' in component) ? component.variants().default().context : component.context;
const graphUrl = url.parse(context.typo3);
graphUrl.search = `?${encodeURIParams(Object.assign(context.request.arguments, {
tx_twcomponentlibrary_component: { component: context.component },
type: 2401,
})).join('&')}`;
return url.format(graphUrl);
};
/**
* Configure the TYPO3 connection
*
* @param {String} t3url TYPO3 base URL
* @param {Boolean} t3dev Include development components
* @param {Theme} t3theme TYPO3 theme
* @param {Object} customLogger Customer logger
*/
const configure = function configure(t3url, t3dev, t3theme, customLogger) {
typo3url = t3url;
typo3dev = t3dev ? 1 : 0;
logger = customLogger || console;
if (!logger.log) {
throw new Error('Make sure the logger has a log() method');
}
// If a Fractal theme is given
if ((typeof t3theme === 'object') && (typeof t3theme.options === 'function')) {
t3theme.addLoadPath(path.resolve(__dirname, 'lib', 'views'));
// Add the graph panel
const options = t3theme.options();
if (options.panels.indexOf('graph') < 0) {
options.panels.push('graph');
}
t3theme.options(options);
t3theme.addListener('init', (engine) => {
engine._engine.addFilter('componentGraphUrl', componentGraphUrl);
});
}
};
/**
* TYPO3 template rendering engine
*/
class TYPO3Adapter extends Adapter {
/**
* Render a component
*
* @param {String} componentPath Component path
* @param {String} str Template string
* @param {Object} context Rendering context
* @return {Promise} Rendering promise
*/
render(componentPath, str, context) { // , meta
if (context.component) {
const views = {};
this.views.forEach((view) => {
views[view.handle] = view.content;
});
return this.engine.compile(str, context, views);
}
return this.engine.handlebars.render(null, str, context);
}
}
/**
* TYPO3 template engine
*/
const engine = function engine() {
return {
register(source, gapp) {
const typo3Engine = require('./lib/typo3.js');
const handlebars = require('@frctl/handlebars');
typo3Engine.handlebars = handlebars({}).register(source, gapp);
typo3Engine.handlebars.load();
return new TYPO3Adapter(typo3Engine, source); // , gapp
},
};
};
module.exports = {
update,
engine,
configure,
};