-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.es.js
625 lines (557 loc) · 15.1 KB
/
index.es.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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/*
* @Author: daycool
* @Date: 2018-04-10 12:12:03
* @Last Modified by: daycool
* @Last Modified time: 2019-02-28 18:37:23
*/
const nunjucks = require('nunjucks')
const fs = require('fs')
const path = require('path')
const prettier = require('prettier')
const mkdirp = require('mkdirp')
const _ = require('lodash')
const glob = require('glob')
const { HjsonData, hjsonStrToObj } = require('hjson2')
let appPath = ''
nunjucks.configure({
autoescape: false,
tags: {
blockStart: '<%',
blockEnd: '%>',
variableStart: '<$',
variableEnd: '$>',
commentStart: '<#',
commentEnd: '#>'
}
})
async function outputPage (
pageData,
appData,
scaffoldData,
interData,
templateData,
componentsData,
scaffoldDir
) {
appPath = path.join(scaffoldDir, scaffoldData.name)
if (!appPath) {
console.log('appPath不存在')
return
}
let pageId = ''
let pagePath = pageData.path
// let templateId = getTemplateId(pageData)
let appId = pageData.app_id
let service = getServiceInfo(pageData, interData)
pageData.service = service
appData.page.forEach(item => {
item.service = getServiceInfo(item, interData)
})
let renderTemplateOption = {
// templateId: templateId,
// appId: appId,
// pageId: pageId,
appData: appData,
scaffold: scaffoldData,
pageData: pageData,
interData: interData,
service: service,
templateData,
componentsData
}
// if(!pageId){
// renderTemplateOption.pageData = pageData;
// }
// let appData = await getAppData.bind(this)(appId);
// let scaffoldData = await getScaffoldData.bind(this)(appData.scaffold_id);
let previewFile = getPreviewFile(pagePath, scaffoldData)
let outputRenderTemplate = await renderTemplate(renderTemplateOption)
let previewTemplate = prettierTemplate(outputRenderTemplate)
await buildPreviewFile(previewFile, previewTemplate)
let previewUrl = getPreviewurl(pagePath, scaffoldData)
return previewUrl
}
async function outputConfigFile (
pageData,
appData,
scaffoldData,
interData,
scaffoldDir
) {
let renderData = {
pageData: pageData,
appData: appData,
scaffoldData: scaffoldData,
interData: interData
}
const promises = scaffoldData.extra_template.map(async item => {
let extraTemplateFile = getExtraTemplateFile(item, renderData)
let renderExtraTemplate = renderCommonTempate(item.template, renderData)
await buildTemplateFile(extraTemplateFile, renderExtraTemplate)
})
await Promise.all(promises)
}
function getExtraTemplateFile (extraTemplate, renderData) {
// let renderExtraTemplate = renderCommonTempate();
var name = nunjucks.renderString(extraTemplate.name, renderData)
var extraTemplateFile = path.join(appPath, extraTemplate.dir, name)
return extraTemplateFile
}
function getPreviewFile (path, scaffoldData) {
var dirname = appPath
var scaffoldDir = dirname + '/' + scaffoldData.name
var previewFile = appPath + scaffoldData.page_dir + path + '.js'
return previewFile
}
function getPreviewurl (path, scaffoldData) {
return '/scaffold/' + scaffoldData.name + '/#' + path
}
const getComment = (hjson, paths, ref) => {
const key = paths[paths.length - 1]
const value = ref[key]
const comment = hjson.getCommentJson(paths)
comment.ui &&
comment.ui.forEach((component, index) => {
comment.ui[index] = {
...component
}
})
const newComment = {
...getDefaultComponent(),
name: key,
value: value,
defaultValue: value,
label: '',
placeholder: '',
mock: '',
...comment
}
if (!newComment.type) {
newComment.type = getVarType(value)
}
return newComment
}
const getDefaultComponent = () => {
return {
key: 'component' + uuid(),
name: '',
value: '',
defaultValue: '',
// label: '',
// placeholder: '',
mock: ''
}
}
const getVarType = val => {
const type = Object.prototype.toString.call(val)
if (type === '[object String]') {
return 'string'
} else if (type === '[object Number]') {
return 'number'
} else if (type === '[object Boolean]') {
return 'boolean'
} else if (type === '[object Integer]') {
return 'integer'
} else if (type === '[object Object]') {
return 'object'
} else if (type === '[object Array]') {
return 'array'
}
}
function uuid () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0
var v = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
function toTreeData (
templateHjson,
reqHjson,
resHjson,
componentsData,
templateData
) {
// 模版
// const templateComments = templateHjson.getRootCommentJson()
const template = templateData
let data = {
...template,
fieldName: 'template',
children: []
}
const reqRootComponent = getRootData(reqHjson, componentsData)
const resRootComponent = getRootData(resHjson, componentsData)
data.children = [reqRootComponent, resRootComponent]
return data
}
function getRootData (hjson, componentsData) {
// 根组件
const rootComponentComments = hjson.getRootCommentJson()
const component = getComponentData(rootComponentComments, componentsData)
const rootComponent = {
...component,
fieldName: 'rootComponent',
children: []
}
const rootComponentChildren = rootComponent.children
getChildData(hjson, hjson.obj, [], componentsData, rootComponentChildren)
return rootComponent
}
function getChildData (hjson, value, paths, componentsData, parentChildren) {
// 子孙组件
// const value = hjson.getVar(paths)
Object.keys(value).forEach(fieldName => {
const newPaths = paths.concat(fieldName)
const newValue = hjson.getVar(newPaths)
const fieldComments = hjson.getCommentJson(newPaths)
const newComponent = getComponentData(fieldComments, componentsData)
const children = []
parentChildren.push({
...newComponent,
...fieldComments,
fieldName: fieldName,
children
})
if (typeof newValue === 'object') {
getChildData(hjson, newValue, newPaths, componentsData, children)
}
})
}
function getComponentData (comments, componentsData, uiType = 'ui') {
const ui = comments[uiType]
if (ui) {
const componentName = ui.__componentName
const componentCustomExtraField = ui
const component = getComponentByName(componentName, componentsData)
Object.keys(componentCustomExtraField).forEach(extraFieldName => {
component.extra_field.forEach(extraField => {
if (extraFieldName === extraField.name) {
extraField.value =
componentCustomExtraField[extraFieldName] ||
comments[extraFieldName]
}
})
})
return component
} else {
return {}
}
}
const renderObject = (obj, paths, comments, data, hjson, componentsData) => {
comments = comments.x || comments
const keys = comments.o
if (_.isPlainObject(obj)) {
keys.map(key => {
const newPaths = paths.concat(key)
const comments = getComment(hjson, newPaths, obj)
const componentCustom = comments.ui[0]
const componentName = componentCustom.__componentName
const component = getComponentByName(componentName, componentsData)
Object.keys(componentCustom).forEach(extraFieldName => {
component.extra_field.forEach(extraField => {
if (extraFieldName === extraField.name) {
extraField.value = componentCustom[extraFieldName]
}
})
})
const item = { fieldName: key, component, children: [] }
if (typeof obj[key] === 'objects') {
// renderObject(obj[key], paths)
}
data.push(item)
})
} else if (_.isArray(obj)) {
obj.forEach((item, index) => {
const newPaths = paths.concat(index)
renderObject(item, newPaths, comments, data, hjson, componentsData)
})
}
}
/**
* 页面预览可能没有页面id所以需要传pageData
*/
async function renderTemplate (options) {
// 修改content为tree 组件模式,有子组件render
// let data = options.pageData.page_template[0].content
let appData = options.appData
let service = options.service
let scaffold = options.scaffold
let interData = options.interData
let templateData = options.templateData
let componentsData = options.componentsData
let templateHjson = new HjsonData().parse(options.interData.comments)
let reqHjson = new HjsonData().parse(options.interData.req)
let resHjson = new HjsonData().parse(options.interData.res)
let data = toTreeData(
templateHjson,
reqHjson,
resHjson,
componentsData,
templateData
)
let outputTemplate = render(
data,
null,
null,
appData,
scaffold,
interData,
service,
templateData,
componentsData
)
return outputTemplate
}
function getServiceInfo (pageData, interData) {
// let tempalte = pageData.page_template[0]
let service = {
name: pageData.path.replace(/^\/+/, '').replace(/\//g, '_'),
url: interData.url,
reqData: interData.req,
resData: interData.res,
reqDataData: JSON.stringify(hjsonStrToObj(interData.req)),
resDataData: JSON.stringify(hjsonStrToObj(interData.res).data),
method: interData.method,
label: interData.label
}
return service
}
function renderCommonTempate (tmpl, data) {
let template = nunjucks.renderString(tmpl, data)
return template
}
function getComponentByName (name, componentList) {
let component = componentList.find(item => item.name == name)
if (component) {
return _.cloneDeep(component)
}
console.error('没有此组件:', name)
return {}
}
async function buildPreviewFile (filePath, template) {
let dir = path.dirname(filePath)
return new Promise((resolve, reject) => {
mkdirp(dir, function (err) {
if (err) console.error(err)
resolve()
fs.writeFileSync(filePath, template)
})
})
}
async function buildTemplateFile (filePath, template) {
let dir = path.dirname(filePath)
return new Promise((resolve, reject) => {
mkdirp(dir, function (err) {
if (err) console.error(err)
fs.writeFileSync(filePath, template)
resolve()
})
})
}
function prettierTemplate (template) {
let prettierTemplate = ''
try {
prettierTemplate = prettier.format(template, {
semi: true,
jsxBracketSameLine: true
})
} catch (e) {
prettierTemplate = template
console.error(e)
}
return prettierTemplate
}
function arrToMap (arr, key) {
var map = {}
key = key || 'id'
arr.forEach(item => {
map[item[key]] = item
})
return map
}
function render (
data,
parentData,
parentsData,
appData,
scaffold,
interData,
service,
templateData,
componentsData
) {
parentData = parentData || data
parentsData = parentsData || [data]
if (data.extra_field) {
data.extraField = arrToMap(data.extra_field, 'name') // 扩展字段
}
let outputTemplate = ''
if (data.template) {
outputTemplate = nunjucks.renderString(data.template, {
appData: appData,
scaffold: scaffold,
interData: interData,
service: service,
data: data,
extraField: data.extraField,
extraFieldMap: data.extraFieldMap,
parentData: parentData,
parentsData: parentsData,
templateData,
componentsData,
renderComponent: () => {
let outputTemplate = ''
// data.children &&
data.children.forEach(item => {
outputTemplate += render(
item,
data,
parentsData.concat(item),
appData,
scaffold,
interData,
service
)
})
return outputTemplate
},
renderExtraField: renderExtraField(data, item => {
const outputTemplate = render(
item,
data,
parentsData.concat(item),
appData,
scaffold,
interData,
service
)
return outputTemplate
}),
renderValid: function (validName) {
let template = ''
data.rules.forEach(item => {
template += `{pattern: ${item.rule}, message: "${item.error_msg}"},`
})
return template
}
})
} else {
data.children &&
data.children.forEach(item => {
outputTemplate += render(
item,
parentData,
parentsData,
appData,
scaffold,
interData,
service,
templateData,
componentsData
)
})
}
// console.log(outputTemplate)
return outputTemplate
}
function renderExtraField (data, render) {
return (extraFieldName, excludeExtraFiledName) => {
let template = ``
let extraField = null
let realExtraFieldData = data.extra_field
if (extraFieldName) {
const extraField = data.extra_field.find(
item => item.name === extraFieldName
)
realExtraFieldData = [extraField]
}
if (excludeExtraFiledName) {
const extraField = data.extra_field.find(
item => item.name === excludeExtraFiledName
)
_.remove(data.extra_field, item => item.name === excludeExtraFiledName)
realExtraFieldData = data.extra_field
}
realExtraFieldData.forEach(item => {
let valueStartSymbol = '{'
let valueEndSymbol = '}'
let value = ''
if (item.value_type == 'string') {
valueStartSymbol = '"'
valueEndSymbol = '"'
} else if (item.value_type == 'reactnode') {
valueStartSymbol = '{('
valueEndSymbol = ')}'
}
if (typeof item.value === 'undefined') {
value = item.default_value
} else {
value = item.value
}
template +=
' ' + item.name + '=' + valueStartSymbol + value + valueEndSymbol
})
return render({ template })
}
}
async function dirTree (dir, cwd, cb) {
const options = {
cwd: cwd,
matchBase: true,
ignore: ['.', '**/node_modules/**/*.*']
}
return new Promise((resolve, reject) => {
glob(dir, options, function (er, files) {
resolve(files)
if (cb) {
cb(files)
}
})
})
}
function getDirFiles (cwd, dir, cb, ignore) {
dir = dir || ''
let dirPath = path.join(cwd, dir)
return new Promise((resolve, reject) => {
fs.readdir(dirPath, function (err, files) {
if (!err) {
let filesArr = []
files.forEach(item => {
let fileInfo = {}
fileInfo.name = item
fileInfo.fullName = path.join(dir, item)
let realFilePath = path.join(dirPath, item)
fileInfo.realFilePath = realFilePath
fileInfo.isFile = fs.statSync(realFilePath).isFile()
filesArr.push(fileInfo)
// console.log(fs.statSync(item))
})
// console.log(filesArr)
resolve(filesArr)
if (cb) {
cb(filesArr)
}
} else {
reject(err)
}
})
})
}
async function getFileContent (file, cb) {
return new Promise((resolve, reject) => {
fs.readFile(file, 'utf8', function (er, content) {
resolve(content)
if (cb) {
cb(content)
}
})
})
}
module.exports = {
outputPage: outputPage,
outputConfigFile: outputConfigFile,
getDirFiles: getDirFiles,
dirTree: dirTree,
getFileContent: getFileContent
}