Skip to content

Commit 0984ff4

Browse files
authored
fix(runtime): support root checks in Vue text v-model (#19589)
1 parent fa80561 commit 0984ff4

10 files changed

Lines changed: 250 additions & 1 deletion

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { createEvent, document } from '@tarojs/runtime'
2+
import { afterEach, describe, expect, test } from 'vitest'
3+
import { createApp, h, nextTick, ref, vModelText, withDirectives } from 'vue'
4+
5+
import type { FormElement } from '@tarojs/runtime'
6+
import type { App } from 'vue'
7+
8+
describe('text v-model on mini program nodes', () => {
9+
let app: App | undefined
10+
let container: ReturnType<typeof document.createElement> | undefined
11+
12+
afterEach(() => {
13+
app?.unmount()
14+
container?.remove()
15+
app = undefined
16+
container = undefined
17+
})
18+
19+
function mount (tag: string, modifiers = {}, connected = true) {
20+
const value = ref<string | number>('initial')
21+
container = document.createElement('view')
22+
if (connected) document.body.appendChild(container)
23+
app = createApp({
24+
render: () => withDirectives(h(tag, {
25+
'onUpdate:modelValue': next => { value.value = next }
26+
}), [[vModelText, value.value, undefined, modifiers]])
27+
})
28+
app.mount(container as unknown as Element)
29+
return { value, input: container.firstChild as FormElement & { composing?: boolean } }
30+
}
31+
32+
for (const tag of ['input', 'textarea']) {
33+
test.each([{}, { trim: true }, { number: true }, { lazy: true }])(`${tag} updates from the model with %j`, async modifiers => {
34+
const { value, input } = mount(tag, modifiers)
35+
expect(input.value).toBe('initial')
36+
value.value = 'replacement'
37+
await nextTick()
38+
expect(input.value).toBe('replacement')
39+
value.value = ''
40+
await nextTick()
41+
expect(input.value).toBe('')
42+
})
43+
44+
test(`${tag} updates inside a detached container`, async () => {
45+
const { value, input } = mount(tag, {}, false)
46+
value.value = 'detached update'
47+
await nextTick()
48+
expect(input.value).toBe('detached update')
49+
expect(input.getRootNode()).toBe(container)
50+
})
51+
}
52+
53+
test('preserves composing text until composition ends', async () => {
54+
const { value, input } = mount('input')
55+
input.composing = true
56+
value.value = 'pending'
57+
await nextTick()
58+
expect(input.value).toBe('initial')
59+
input.composing = false
60+
value.value = 'confirmed'
61+
await nextTick()
62+
expect(input.value).toBe('confirmed')
63+
})
64+
65+
test.each([
66+
[{ trim: true, lazy: true }, '42'],
67+
[{ number: true, lazy: true }, 42]
68+
])('propagates change events back to the model with %j', async (modifiers, expected) => {
69+
const { value, input } = mount('input', modifiers)
70+
input.value = ' 42 '
71+
input.dispatchEvent(createEvent({ type: 'change', detail: { value: ' 42 ' } }, input))
72+
await nextTick()
73+
expect(value.value).toBe(expected)
74+
})
75+
})
Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1-
import { document, navigator, SVGElement, TaroElement, window } from '@tarojs/runtime'
1+
import { document, navigator, ShadowRoot, SVGElement, TaroDocument, TaroElement, window } from '@tarojs/runtime'
22
import { vi } from 'vitest'
33

44
// 设置全局对象
55
vi.stubGlobal('document', document)
66
vi.stubGlobal('window', window)
77
vi.stubGlobal('navigator', navigator)
88
vi.stubGlobal('Element', TaroElement)
9+
vi.stubGlobal('Document', TaroDocument)
10+
vi.stubGlobal('ShadowRoot', ShadowRoot)
911
vi.stubGlobal('SVGElement', SVGElement)

‎packages/taro-runtime/src/dom/node.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,15 @@ export class TaroNode extends TaroEventTarget {
124124
return childNodes[childNodes.length - 1] || null
125125
}
126126

127+
public getRootNode (_options?: { composed?: boolean }): TaroNode {
128+
// Mini programs have no shadow trees, so composed does not change the root.
129+
let root: TaroNode = this
130+
while (root.parentNode) {
131+
root = root.parentNode
132+
}
133+
return root
134+
}
135+
127136
/**
128137
* @textContent 目前只能置空子元素
129138
* @TODO 等待完整 innerHTML 实现
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import { TaroElement } from './element'
2+
3+
// For Vue's instanceof checks only; mini programs do not support shadow DOM.
4+
export class ShadowRoot extends TaroElement {}

‎packages/taro-runtime/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,14 @@ export { parseUrl, TaroURLProvider as URL } from './bom/URL'
1616
export { URLSearchParams } from './bom/URLSearchParams'
1717
export { taroHistoryProvider as history, taroLocationProvider as location, taroWindowProvider as window } from './bom/window'
1818
// dom
19+
export { TaroDocument } from './dom/document'
1920
export { TaroElement } from './dom/element'
2021
export { createEvent, eventHandler, eventHandlerTTDom, TaroEvent } from './dom/event'
2122
export { FormElement } from './dom/form'
2223
export { bumpNearestCtxEpochForRoot, getNearestCtx, isNearestCtxEnv } from './dom/nearest-ctx'
2324
export { TaroNode } from './dom/node'
2425
export { TaroRootElement } from './dom/root'
26+
export { ShadowRoot } from './dom/shadow-root'
2527
export { Style } from './dom/style'
2628
export { SVGElement } from './dom/svg'
2729
export { TaroText } from './dom/text'
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import { describe, expect, test } from 'vitest'
2+
3+
import { document, DOCUMENT_FRAGMENT, ShadowRoot, TaroDocument } from '../src/index'
4+
5+
describe('getRootNode', () => {
6+
test('returns a detached node itself rather than its ownerDocument', () => {
7+
const node = document.createElement('input')
8+
expect(node.ownerDocument).toBe(document)
9+
expect(node.getRootNode()).toBe(node)
10+
})
11+
12+
test('returns the topmost ancestor of a detached subtree', () => {
13+
const parent = document.createElement('view')
14+
const child = document.createElement('input')
15+
parent.appendChild(child)
16+
expect(child.getRootNode()).toBe(parent)
17+
})
18+
19+
test('returns the document for connected nodes', () => {
20+
const parent = document.createElement('view')
21+
const child = document.createElement('input')
22+
parent.appendChild(child)
23+
document.body.appendChild(parent)
24+
try {
25+
expect(child.getRootNode()).toBe(document)
26+
expect(document.getRootNode()).toBe(document)
27+
} finally {
28+
parent.remove()
29+
}
30+
})
31+
32+
test('reflects removal and reparenting without a stale root', () => {
33+
const first = document.createElement('view')
34+
const second = document.createElement('view')
35+
const child = document.createElement('input')
36+
first.appendChild(child)
37+
expect(child.getRootNode()).toBe(first)
38+
second.appendChild(child)
39+
expect(child.getRootNode()).toBe(second)
40+
child.remove()
41+
expect(child.getRootNode()).toBe(child)
42+
})
43+
44+
test('supports text and comment nodes', () => {
45+
const parent = document.createElement('view')
46+
const text = document.createTextNode('text')
47+
const comment = document.createComment()
48+
parent.appendChild(text)
49+
parent.appendChild(comment)
50+
expect(text.getRootNode()).toBe(parent)
51+
expect(comment.getRootNode()).toBe(parent)
52+
})
53+
54+
test('returns a fragment until its children are inserted', () => {
55+
const fragment = document.createElement(DOCUMENT_FRAGMENT)
56+
const child = document.createElement('input')
57+
const parent = document.createElement('view')
58+
fragment.appendChild(child)
59+
expect(child.getRootNode()).toBe(fragment)
60+
parent.appendChild(fragment)
61+
expect(child.getRootNode()).toBe(parent)
62+
expect(fragment.getRootNode()).toBe(fragment)
63+
})
64+
65+
test.each([undefined, {}, { composed: false }, { composed: true }])('accepts root options %j', options => {
66+
const parent = document.createElement('view')
67+
const child = document.createElement('input')
68+
parent.appendChild(child)
69+
expect(child.getRootNode(options)).toBe(parent)
70+
})
71+
72+
test('exposes distinct constructors for Vue document and shadow root checks', () => {
73+
const node = document.createElement('input')
74+
expect(document).toBeInstanceOf(TaroDocument)
75+
expect(document).not.toBeInstanceOf(ShadowRoot)
76+
expect(node).not.toBeInstanceOf(TaroDocument)
77+
expect(node).not.toBeInstanceOf(ShadowRoot)
78+
})
79+
})

‎packages/taro-vite-runner/src/mini/config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ export default function (viteCompilerContext: ViteMiniCompilerContext): PluginOp
8787
requestAnimationFrame: ['@tarojs/runtime', 'requestAnimationFrame'],
8888
cancelAnimationFrame: ['@tarojs/runtime', 'cancelAnimationFrame'],
8989
Element: ['@tarojs/runtime', 'TaroElement'],
90+
Document: ['@tarojs/runtime', 'TaroDocument'],
91+
ShadowRoot: ['@tarojs/runtime', 'ShadowRoot'],
9092
SVGElement: ['@tarojs/runtime', 'SVGElement'],
9193
MutationObserver: ['@tarojs/runtime', 'MutationObserver'],
9294
history: ['@tarojs/runtime', 'history'],
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
2+
import { tmpdir } from 'node:os'
3+
import path from 'node:path'
4+
import vm from 'node:vm'
5+
6+
import { build } from 'vite'
7+
import { expect, test } from 'vitest'
8+
9+
import miniConfig from '../../src/mini/config'
10+
11+
import type { ViteMiniCompilerContext } from '@tarojs/taro/types/compile/viteCompilerContext'
12+
import type { RollupOutput } from 'rollup'
13+
import type { Plugin, UserConfig } from 'vite'
14+
15+
test('mini builds provide document constructors without native DOM globals', async () => {
16+
const root = realpathSync(mkdtempSync(path.join(tmpdir(), 'taro-dom-globals-')))
17+
try {
18+
const entry = path.join(root, 'entry.js')
19+
writeFileSync(entry, `
20+
import { document } from '@tarojs/runtime'
21+
export function probe(connected) {
22+
const parent = document.createElement('view')
23+
const input = document.createElement('input')
24+
parent.appendChild(input)
25+
if (connected) document.body.appendChild(parent)
26+
const root = input.getRootNode()
27+
const result = [root instanceof Document, root instanceof ShadowRoot, root === document]
28+
parent.remove()
29+
return result
30+
}
31+
`)
32+
const plugin = miniConfig({
33+
cwd: root,
34+
sourceDir: root,
35+
taroConfig: {
36+
framework: 'vue3',
37+
template: { isSupportRecursive: true },
38+
entry: { app: entry },
39+
output: { chunkFileNames: '[name].js' },
40+
fileType: { script: '.js' },
41+
postcss: { pxtransform: { config: {} } }
42+
}
43+
} as unknown as ViteMiniCompilerContext) as Plugin
44+
const config = await (plugin.config as () => Promise<UserConfig>)()
45+
const result = await build({
46+
configFile: false,
47+
root,
48+
logLevel: 'silent',
49+
define: { ...config.define, 'process.env.TARO_PLATFORM': JSON.stringify('mini') },
50+
resolve: {
51+
alias: { '@tarojs/runtime': path.resolve(__dirname, '../../../taro-runtime/src/index.ts') }
52+
},
53+
build: {
54+
write: false,
55+
minify: false,
56+
lib: { entry, formats: ['cjs'] },
57+
rollupOptions: { plugins: [config.build!.rollupOptions!.plugins![0]] }
58+
}
59+
}) as RollupOutput | RollupOutput[]
60+
const output = Array.isArray(result) ? result[0] : result
61+
const chunk = output.output.find(output => output.type === 'chunk')!
62+
const sandbox = { exports: {}, console } as Record<string, any>
63+
sandbox.global = sandbox
64+
vm.runInNewContext(chunk.code, sandbox)
65+
expect(Array.from(sandbox.exports.probe(true))).toEqual([true, false, true])
66+
expect(Array.from(sandbox.exports.probe(false))).toEqual([false, false, false])
67+
expect(sandbox.Document).toBeUndefined()
68+
expect(sandbox.ShadowRoot).toBeUndefined()
69+
} finally {
70+
rmSync(root, { recursive: true, force: true })
71+
}
72+
})

‎packages/taro-webpack5-prebundle/src/mini.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,8 @@ export class MiniPrebundle extends BasePrebundle<IMiniPrebundleConfig> {
116116
requestAnimationFrame: [taroRuntimeBundlePath, '_raf'],
117117
cancelAnimationFrame: [taroRuntimeBundlePath, '_caf'],
118118
Element: [taroRuntimeBundlePath, 'TaroElement'],
119+
Document: [taroRuntimeBundlePath, 'TaroDocument'],
120+
ShadowRoot: [taroRuntimeBundlePath, 'ShadowRoot'],
119121
SVGElement: [taroRuntimeBundlePath, 'SVGElement'],
120122
MutationObserver: [taroRuntimeBundlePath, 'MutationObserver'],
121123
history: [taroRuntimeBundlePath, 'history'],

‎packages/taro-webpack5-runner/src/webpack/MiniWebpackPlugin.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,8 @@ export class MiniWebpackPlugin {
5555
requestAnimationFrame: ['@tarojs/runtime', 'requestAnimationFrame'],
5656
cancelAnimationFrame: ['@tarojs/runtime', 'cancelAnimationFrame'],
5757
Element: ['@tarojs/runtime', 'TaroElement'],
58+
Document: ['@tarojs/runtime', 'TaroDocument'],
59+
ShadowRoot: ['@tarojs/runtime', 'ShadowRoot'],
5860
SVGElement: ['@tarojs/runtime', 'SVGElement'],
5961
MutationObserver: ['@tarojs/runtime', 'MutationObserver'],
6062
history: ['@tarojs/runtime', 'history'],

0 commit comments

Comments
 (0)