-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
293 lines (268 loc) · 8.87 KB
/
main.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
/**
* twbschema
* @author E-Com Club <[email protected]>
* @license MIT
*/
window.twbschema = (function () {
'use strict'
// regex to find object properties on text
var propertyRegex = /([[(]?([\w-]+)?(_|\*)([\w-]+)?[\])]?)/g
// count rows to create IDs
var counter = 0
// control row colors
var rowBgClass = ''
// handle schema definitions
var defs
var gen = function (json, dotNotation) {
var i
// generate docs HTML
// preset empty string
var html = ''
// if root object
var root
// object path
if (!dotNotation) {
root = true
dotNotation = ''
// check definitions on root object
if (json.definitions) {
defs = json.definitions
}
}
// start treating schema
// Ref.: http://json-schema.org/specification.html
// array of required fields
var req = json.required
// merge all object properties
var props = Object.assign({}, json.properties, json.patternProperties)
// check each object property
// first row without border
var rowBorderClass = ''
for (var field in props) {
if (props.hasOwnProperty(field)) {
// path for nested objects if any
var childDotNotation = dotNotation + field
// new field ID for HTML elements
var id = 'schema-field-' + counter
counter++
// mark required fields
var labelRequired = ''
if (Array.isArray(req)) {
for (i = 0; i < req.length; i++) {
if (field === req[i]) {
// field is requred
labelRequired = '<span class="text-danger ml-2">required</span>'
break
}
}
}
var prop = props[field]
if (!prop.hasOwnProperty('type')) {
// try schema definitions
if (defs && typeof prop.$ref === 'string') {
var model = prop.$ref.replace('#/definitions/', '')
if (defs.hasOwnProperty(model)) {
// merge definition model to prop object
prop = Object.assign({}, defs[model], prop)
}
}
}
var type = prop.type
if (Array.isArray(type)) {
// use first (most important ?) type
type = type[0]
}
var description
if (prop.description) {
// mark other refered fields on description
description = prop.description.replace(propertyRegex, '<samp class="text-info">$1</samp>')
} else {
description = ''
}
// render optional list of field specifications
var specsList = ''
var addSpec = function (name, val) {
// populate specs list
if (val === undefined) {
// specification value is required
return
}
// eg.: minimum number, string max length...
// samp tag HTML
var samp
if (Array.isArray(val) && typeof val[0] !== 'object') {
// array of strings or numbers
samp = ''
for (var i = 0; i < val.length; i++) {
if (i > 0) {
// not first value
samp += '<span class="text-muted mx-1"> · </span>'
}
samp += '<samp>' + val[i] + '</samp>'
}
} else {
switch (typeof val) {
case 'string':
case 'number':
samp = val
break
default:
// object, boolean or null
samp = JSON.stringify(val)
}
// single value
samp = '<samp>' + samp + '</samp>'
}
// HTML for field spec rows
// add li element to specs list
specsList += '<li><span class="text-muted mr-1">' + name + ': </span>' + samp + '</li>'
}
if (prop.hasOwnProperty('default')) {
// mark default value
addSpec('Default', prop['default'])
}
if (prop['enum']) {
// array of possible values
addSpec('Possible values', prop['enum'])
}
// details inside collapsible div
// https://getbootstrap.com/docs/4.1/components/collapse/
var objectContent = ''
var typeLink = function () {
// parse type string to HTML link
// open collapse div
type = '<a class="dropdown-toggle" data-toggle="collapse" href="#' + id + '" ' +
'aria-expanded="false" aria-controls="' + id + '">' + type + '</a>'
}
// try to handle specs for each field type
switch (type) {
case 'number':
addSpec('Minimun', prop.minimum)
addSpec('Maximum', prop.maximum)
addSpec('Max precision', prop.multipleOf)
break
case 'integer':
addSpec('Minimun', prop.min)
addSpec('Maximum', prop.max)
break
case 'string':
addSpec('Min length', prop.minLength)
addSpec('Max length', prop.maxLength)
addSpec('Format', prop.format)
addSpec('RegEx', prop.pattern)
break
case 'object':
// link to current object properties
typeLink()
// render current object doc reference
// recursive call
// pass dot notation param
childDotNotation += '.'
objectContent = gen(prop, childDotNotation)
addSpec('Min properties', prop.minProperties)
addSpec('Max properties', prop.maxProperties)
break
case 'array':
// also shows array element type
type = type + '[' + prop.items.type + ']'
typeLink()
if (prop.items.type === 'object') {
// array of nested objects
// recursive call
// pass dot notation param with [] indicating array
childDotNotation += '[].'
objectContent = gen(prop.items, childDotNotation)
} else {
// array of numbers or strings
// simulate an object schema with properties
var obj = {
'properties': {
'[]': prop.items
}
}
// recursive call
objectContent = gen(obj, childDotNotation)
}
addSpec('Min elements', prop.minItems)
addSpec('Max elements', prop.maxItems)
break
}
if (specsList !== '') {
// has specification(s)
// setup ul element HTML
specsList = '<ul class="small list-unstyled mt-3 mb-0">' + specsList + '</ul>'
}
// render row HTML
html += '<div class="px-3 pb-3' + rowBorderClass + rowBgClass + '">' +
'<div class="row align-items-center">' +
'<div class="col-sm-7">' +
'<div class="mt-3">' +
'<code><span class="text-secondary">' + dotNotation + '</span>' + field + '</code>' +
'<code class="text-muted small"><br>' + type + labelRequired + '</code>' +
'<div class="small">' + description + '</div>' +
'</div>' +
'</div>' +
'<div class="col">' +
specsList +
'</div>' +
'</div>' +
'</div>' +
'<div class="collapse border-top" id="' + id + '">' +
objectContent +
'</div>'
if (root) {
// stripped rows on root level
// next row class
if (rowBgClass !== '') {
rowBgClass = ''
} else {
// https://getbootstrap.com/docs/4.0/utilities/colors/
rowBgClass = ' bg-light'
}
}
// only first row has no border
if (rowBorderClass === '') {
rowBorderClass = ' border-top'
}
}
}
// returns rendered HTML
return html
}
var doc = function (el, schema) {
// main function
// receives DOM element and JSON Schema
// parse object first
var json, err
if (typeof schema === 'string') {
try {
json = JSON.parse(schema)
} catch (e) {
err = e
}
} else if (typeof schema === 'object' && schema !== null) {
json = schema
} else {
err = new Error('Schema must be a valid JSON object or string')
}
if (err) {
console.error('[twbschema fatal error (invalid schema)]', err)
} else {
// valid
// convert JSON Schema to docs UI
var html = gen(json)
if (typeof el === 'object' && el !== null && el.innerHTML) {
el.innerHTML = html
} else {
// not a DOM element
// just return HTML string
return html
}
}
}
// return methods
return {
'doc': doc
}
}())
// Sample: https://jsfiddle.net/8rzyboan/119/