-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
96 lines (71 loc) · 2.47 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
'use strict'
var INDENT = ' '
function inlineRule (objRule) {
var str = ''
objRule && Object.keys(objRule).forEach(function (rule) {
str += rule + ':' + objRule[rule] + ';'
})
return str
}
function Stylize (styleFile) {
function styleClass (cssClass) {
return 'class="' + cssClass + '"'
}
function styleInline (cssClass) {
return 'style="' + inlineRule(styleFile['.' + cssClass]) + '"'
}
if (!styleFile) return styleClass
return styleInline
}
function type (doc) {
if (doc === null) return 'null'
if (Array.isArray(doc)) return 'array'
if (typeof doc === 'string' && /^https?:/.test(doc)) return 'link'
if (typeof doc === 'object' && typeof doc.toISOString === 'function') return 'date'
return typeof doc
}
function escape (str) {
return str.replace(/</g, '<').replace(/>/g, '>')
}
module.exports = function (doc, styleFile) {
var indent = ''
var style = Stylize(styleFile)
var forEach = function (list, start, end, fn) {
if (!list.length) return start + ' ' + end
var out = start + '\n'
indent += INDENT
list.forEach(function (key, i) {
out += indent + fn(key) + (i < list.length - 1 ? ',' : '') + '\n'
})
indent = indent.slice(0, -INDENT.length)
return out + indent + end
}
function visit (obj) {
if (obj === undefined) return ''
switch (type(obj)) {
case 'boolean':
return '<span ' + style('json-markup-bool') + '>' + obj + '</span>'
case 'number':
return '<span ' + style('json-markup-number') + '>' + obj + '</span>'
case 'date':
return '<span class="json-markup-string">"' + escape(obj.toISOString()) + '"</span>'
case 'null':
return '<span ' + style('json-markup-null') + '>null</span>'
case 'string':
return '<span ' + style('json-markup-string') + '>"' + escape(obj.replace(/\n/g, '\n' + indent)) + '"</span>'
case 'link':
return '<span ' + style('json-markup-string') + '>"<a href="' + escape(obj) + '">' + escape(obj) + '</a>"</span>'
case 'array':
return forEach(obj, '[', ']', visit)
case 'object':
var keys = Object.keys(obj).filter(function (key) {
return obj[key] !== undefined
})
return forEach(keys, '{', '}', function (key) {
return '<span ' + style('json-markup-key') + '>"' + escape(key) + '":</span> ' + visit(obj[key])
})
}
return ''
}
return '<div ' + style('json-markup') + '>' + visit(doc) + '</div>'
}