budibase/packages/string-templates/src/helpers/index.js

94 lines
2.4 KiB
JavaScript
Raw Normal View History

const Helper = require("./Helper")
const { SafeString } = require("handlebars")
const externalHandlebars = require("./external")
2021-10-11 15:53:55 +02:00
const { processJS } = require("./javascript")
2021-01-26 13:43:26 +01:00
const {
HelperFunctionNames,
HelperFunctionBuiltin,
LITERAL_MARKER,
} = require("./constants")
const HTML_SWAPS = {
"<": "&lt;",
">": "&gt;",
}
2022-05-04 18:36:30 +02:00
function isObject(value) {
if (value == null || typeof value !== "object") {
return false
}
return (
value.toString() === "[object Object]" ||
(value.length > 0 && typeof value[0] === "object")
)
}
const HELPERS = [
// external helpers
2021-05-04 12:32:22 +02:00
new Helper(HelperFunctionNames.OBJECT, value => {
return new SafeString(JSON.stringify(value))
}),
2021-10-11 15:53:55 +02:00
// javascript helper
new Helper(HelperFunctionNames.JS, processJS, false),
// this help is applied to all statements
new Helper(HelperFunctionNames.ALL, (value, { __opts }) => {
2022-05-04 18:36:30 +02:00
if (isObject(value)) {
return new SafeString(JSON.stringify(value))
}
// null/undefined values produce bad results
if (value == null || typeof value !== "string") {
return value == null ? "" : value
}
if (value && value.string) {
value = value.string
}
let text = value
if (__opts && __opts.escapeNewlines) {
text = value.replace(/\n/g, "\\n")
}
text = new SafeString(text.replace(/&amp;/g, "&"))
if (text == null || typeof text !== "string") {
return text
}
2021-05-04 12:32:22 +02:00
return text.replace(/[<>]/g, tag => {
return HTML_SWAPS[tag] || tag
})
2021-01-21 12:32:26 +01:00
}),
// adds a note for post-processor
2021-05-04 12:32:22 +02:00
new Helper(HelperFunctionNames.LITERAL, value => {
if (value === undefined) {
return ""
}
2021-01-26 13:43:26 +01:00
const type = typeof value
const outputVal = type === "object" ? JSON.stringify(value) : value
return `{{${LITERAL_MARKER} ${type}-${outputVal}}}`
2021-01-26 13:43:26 +01:00
}),
]
module.exports.HelperNames = () => {
return Object.values(HelperFunctionNames).concat(
HelperFunctionBuiltin,
2021-01-21 18:30:51 +01:00
externalHandlebars.externalHelperNames
)
}
module.exports.registerMinimum = handlebars => {
for (let helper of HELPERS) {
helper.register(handlebars)
}
}
module.exports.registerAll = handlebars => {
module.exports.registerMinimum(handlebars)
// register imported helpers
externalHandlebars.registerAll(handlebars)
}
2021-05-04 12:32:22 +02:00
module.exports.unregisterAll = handlebars => {
for (let helper of HELPERS) {
helper.unregister(handlebars)
}
// unregister all imported helpers
externalHandlebars.unregisterAll(handlebars)
}