Skip to content

Commit

Permalink
Merge pull request #65 from seanpdoyle/node-template-part
Browse files Browse the repository at this point in the history
Extend `processPropertyIdentity` to handle Element
  • Loading branch information
keithamus authored Jan 25, 2023
2 parents 001646f + f6ab0f3 commit 5c3e242
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/processors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export function createProcessor(processPart: PartProcessor): TemplateTypeInit {
}

export function processPropertyIdentity(part: TemplatePart, value: unknown): void {
part.value = String(value)
part.value = value instanceof Element ? value : String(value)
}

export function processBooleanAttribute(part: TemplatePart, value: unknown): boolean {
Expand Down
2 changes: 1 addition & 1 deletion src/template-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {propertyIdentity} from './processors.js'
import {TemplatePart, TemplateTypeInit} from './types.js'

function* collectParts(el: DocumentFragment): Generator<TemplatePart> {
const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, null, false)
const walker = el.ownerDocument.createTreeWalker(el, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, null)
let node
while ((node = walker.nextNode())) {
if (node instanceof Element && node.hasAttributes()) {
Expand Down
2 changes: 1 addition & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type {TemplateInstance} from './template-instance.js'

export interface TemplatePart {
expression: string
value: string | null
value: Element | string | null
}

type TemplateProcessCallback = (instance: TemplateInstance, parts: Iterable<TemplatePart>, params: unknown) => void
Expand Down
13 changes: 13 additions & 0 deletions test/template-instance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,19 @@ describe('template-instance', () => {
root.appendChild(instance)
expect(root.innerHTML).to.equal(`Hello world`)
})
it('applies data to templated element nodes', () => {
const template = document.createElement('template')
const element = Object.assign(document.createElement('div'), {
innerHTML: 'Hello world'
})
const originalHTML = `{{x}}`
template.innerHTML = originalHTML
const instance = new TemplateInstance(template, {x: element})
expect(template.innerHTML).to.equal(originalHTML)
const root = document.createElement('div')
root.appendChild(instance)
expect(root.innerHTML).to.equal(`<div>Hello world</div>`)
})
it('can render into partial text nodes', () => {
const template = document.createElement('template')
const originalHTML = `Hello {{x}}!`
Expand Down

0 comments on commit 5c3e242

Please sign in to comment.