Extend skooma.text function to support template strings

This commit is contained in:
Talia 2021-12-26 17:54:04 +01:00
parent 694b4da6a4
commit e8d18ae19a
Signed by: darkwiiplayer
GPG key ID: 7808674088232B3E
2 changed files with 23 additions and 1 deletions

View file

@ -99,4 +99,17 @@ export const handle = fn => event => { event.preventDefault(); return fn(event)
export const html = nameSpacedProxy({nameFilter: name => name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()}) export const html = nameSpacedProxy({nameFilter: name => name.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase()})
export const svg = nameSpacedProxy({xmlns: "http://www.w3.org/2000/svg"}) export const svg = nameSpacedProxy({xmlns: "http://www.w3.org/2000/svg"})
export const text = (data="") => document.createTextNode(data) const textFromTemplate = (literals, items) => {
const fragment = new DocumentFragment()
for (const key in items) {
fragment.append(document.createTextNode(literals[key]))
fragment.append(items[key])
}
fragment.append(document.createTextNode(literals.at(-1)))
return fragment
}
export const text = (data="", ...items) =>
typeof data == "string"
? document.createTextNode(data)
: textFromTemplate(data, items)

View file

@ -48,8 +48,17 @@ text()
// Defaults to empty string instead of erroring // Defaults to empty string instead of erroring
text(null) text(null)
// Non-string arguments still error // Non-string arguments still error
text`Hello, World!`
// returns a new document fragment containing the text node "Hello, World!"
text`Hello, ${user}!`
// returns a document fragment containing 3 nodes:
// "Hello, ", the interpolated value of `user` and "!"
``` ```
When used with templates, `text` tries to append any interpolated values into
the document fragment as is and without checking them.
## bind ## bind
This function offers a generic mechanism for binding elements to dynamic state. This function offers a generic mechanism for binding elements to dynamic state.