]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(runtime-vapor): template
author三咲智子 Kevin Deng <sxzz@sxzz.moe>
Thu, 9 Nov 2023 09:54:31 +0000 (17:54 +0800)
committer三咲智子 Kevin Deng <sxzz@sxzz.moe>
Thu, 16 Nov 2023 19:01:53 +0000 (03:01 +0800)
packages/runtime-vapor/__tests__/basic.spec.ts [deleted file]
packages/runtime-vapor/__tests__/template.spec.ts [new file with mode: 0644]
packages/runtime-vapor/src/index.ts
packages/runtime-vapor/src/template.ts [new file with mode: 0644]

diff --git a/packages/runtime-vapor/__tests__/basic.spec.ts b/packages/runtime-vapor/__tests__/basic.spec.ts
deleted file mode 100644 (file)
index 730cbb1..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-test('basic', () => {
-  //
-})
diff --git a/packages/runtime-vapor/__tests__/template.spec.ts b/packages/runtime-vapor/__tests__/template.spec.ts
new file mode 100644 (file)
index 0000000..da471b4
--- /dev/null
@@ -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)
+  })
+})
index 21ec276fc7f825c0cab53a2ead78a84c97df45f3..305a75ddb426a0525f6354acf750f58867c493af 100644 (file)
@@ -1 +1 @@
-export const foo = 'bar'
+export { template } from './template'
diff --git a/packages/runtime-vapor/src/template.ts b/packages/runtime-vapor/src/template.ts
new file mode 100644 (file)
index 0000000..4f66b15
--- /dev/null
@@ -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)
+    }
+  }
+}