fx/print.js

105 lines
2.6 KiB
JavaScript
Raw Normal View History

'use strict'
const indent = require('indent-string')
const config = require('./config')
2018-12-01 17:29:44 +00:00
function print(input, options = {}) {
2018-12-14 18:13:39 +00:00
const {expanded, highlight, currentPath} = options
const index = new Map()
let row = 0
2018-12-14 18:13:39 +00:00
function format(text, style, path) {
2018-12-15 05:48:37 +00:00
text = JSON.stringify(text)
2018-12-14 17:48:29 +00:00
if (!highlight) {
return style(text)
}
2018-12-14 18:13:39 +00:00
const highlightStyle = (currentPath === path) ? config.highlightCurrent : config.highlight
2018-12-14 17:48:29 +00:00
return text
.replace(highlight, s => '<fx>' + s + '<fx>')
.split(/<fx>/g)
2018-12-14 18:13:39 +00:00
.map((s, i) => i % 2 !== 0 ? highlightStyle(s) : style(s))
2018-12-14 17:48:29 +00:00
.join('')
}
function doPrint(v, path = '') {
index.set(row, path)
const eol = () => {
row++
return '\n'
}
if (typeof v === 'undefined') {
return void 0
}
if (v === null) {
2018-12-15 05:48:37 +00:00
return format(v, config.null, path)
}
if (typeof v === 'number' && Number.isFinite(v)) {
2018-12-15 05:48:37 +00:00
return format(v, config.number, path)
}
if (typeof v === 'boolean') {
2018-12-15 05:48:37 +00:00
return format(v, config.boolean, path)
}
if (typeof v === 'string') {
2018-12-15 05:48:37 +00:00
return format(v, config.string, path)
}
if (Array.isArray(v)) {
2018-12-07 15:51:10 +00:00
let output = config.bracket('[')
const len = v.length
2018-12-07 15:51:10 +00:00
if (len > 0) {
if (expanded && !expanded.has(path)) {
output += '\u2026'
} else {
output += eol()
let i = 0
for (let item of v) {
const value = typeof item === 'undefined' ? null : item // JSON.stringify compatibility
output += indent(doPrint(value, path + '[' + i + ']'), config.space)
output += i++ < len - 1 ? config.comma(',') : ''
output += eol()
}
}
}
return output + config.bracket(']')
}
if (typeof v === 'object' && v.constructor === Object) {
2018-12-07 15:51:10 +00:00
let output = config.bracket('{')
2018-12-07 15:51:10 +00:00
const entries = Object.entries(v).filter(([key, value]) => typeof value !== 'undefined') // JSON.stringify compatibility
const len = entries.length
2018-12-07 15:51:10 +00:00
if (len > 0) {
if (expanded && !expanded.has(path)) {
output += '\u2026'
} else {
output += eol()
let i = 0
for (let [key, value] of entries) {
2018-12-15 05:48:37 +00:00
const part = format(key, config.key, path + '.' + key) + config.colon(':') + ' ' + doPrint(value, path + '.' + key)
2018-12-07 15:51:10 +00:00
output += indent(part, config.space)
output += i++ < len - 1 ? config.comma(',') : ''
output += eol()
}
}
}
return output + config.bracket('}')
}
2018-12-07 15:51:10 +00:00
return JSON.stringify(v, null, config.space)
}
return [doPrint(input), index]
}
module.exports = print