Răsfoiți Sursa

feat(runtime-vapor): template

三咲智子 Kevin Deng 2 ani în urmă
părinte
comite
ef9628ce7f

+ 0 - 3
packages/runtime-vapor/__tests__/basic.spec.ts

@@ -1,3 +0,0 @@
-test('basic', () => {
-  //
-})

+ 17 - 0
packages/runtime-vapor/__tests__/template.spec.ts

@@ -0,0 +1,17 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import { template } from '../src'
+
+describe('api: template', () => {
+  test('create element', () => {
+    const t = template('<div>')
+    const div = t()
+    expect(div).toBeInstanceOf(HTMLDivElement)
+
+    const div2 = t()
+    expect(div2).toBeInstanceOf(HTMLDivElement)
+    expect(div2).not.toBe(div)
+  })
+})

+ 1 - 1
packages/runtime-vapor/src/index.ts

@@ -1 +1 @@
-export const foo = 'bar'
+export { template } from './template'

+ 20 - 0
packages/runtime-vapor/src/template.ts

@@ -0,0 +1,20 @@
+export const template = (str: string): (() => Node) => {
+  let cached = false
+  let node: Node
+  return () => {
+    if (!cached) {
+      cached = true
+      const t = document.createElement('template')
+      t.innerHTML = str
+      // first render: insert the node directly.
+      // this removes it from the template fragment to avoid keeping two copies
+      // of the inserted tree in memory, even if the template is used only once.
+      return (node = t.content.firstChild!)
+    } else {
+      // repeated renders: clone from cache. This is more performant and
+      // efficient when dealing with big lists where the template is repeated
+      // many times.
+      return node.cloneNode(true)
+    }
+  }
+}