1
0
Fork 0
mirror of synced 2024-06-27 02:20:35 +12:00
budibase/packages/string-templates/src/helpers/index.js

80 lines
2.1 KiB
JavaScript
Raw Normal View History

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