Extend skooma.text function to support template strings

This commit is contained in:
Talia 2021-12-26 17:54:04 +01:00
parent 4a473df213
commit 47969d4c42
No known key found for this signature in database
GPG key ID: AD727AD22802D0D6
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 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
text(null)
// 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
This function offers a generic mechanism for binding elements to dynamic state.