Skip to content

feat(vapor): templateRef vdom interop #13323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: vapor
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ export function render(_ctx) {
}"
`;

exports[`compiler: template ref transform > static ref (inline mode) 1`] = `
"
const _setTemplateRef = _createTemplateRefSetter()
const n0 = t0()
_setTemplateRef(n0, foo, null, null, "foo")
return n0
"
`;

exports[`compiler: template ref transform > static ref 1`] = `
"import { createTemplateRefSetter as _createTemplateRefSetter, template as _template } from 'vue';
const t0 = _template("<div></div>", true)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { BindingTypes } from '@vue/compiler-dom'
import {
DynamicFlag,
type ForIRNode,
Expand Down Expand Up @@ -48,6 +49,16 @@ describe('compiler: template ref transform', () => {
expect(code).contains('_setTemplateRef(n0, "foo")')
})

test('static ref (inline mode)', () => {
const { code } = compileWithTransformRef(`<div ref="foo" />`, {
inline: true,
bindingMetadata: { foo: BindingTypes.SETUP_REF },
})
expect(code).matchSnapshot()
// pass the actual ref and ref key
expect(code).contains('_setTemplateRef(n0, foo, null, null, "foo")')
})

test('dynamic ref', () => {
const { ir, code } = compileWithTransformRef(`<div :ref="foo" />`)

Expand Down
22 changes: 21 additions & 1 deletion packages/compiler-vapor/src/generators/templateRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,46 @@ import { genExpression } from './expression'
import type { CodegenContext } from '../generate'
import type { DeclareOldRefIRNode, SetTemplateRefIRNode } from '../ir'
import { type CodeFragment, NEWLINE, genCall } from './utils'
import { BindingTypes, type SimpleExpressionNode } from '@vue/compiler-dom'

export const setTemplateRefIdent = `_setTemplateRef`

export function genSetTemplateRef(
oper: SetTemplateRefIRNode,
context: CodegenContext,
): CodeFragment[] {
const [refValue, refKey] = genRefValue(oper.value, context)
return [
NEWLINE,
oper.effect && `r${oper.element} = `,
...genCall(
setTemplateRefIdent, // will be generated in root scope
`n${oper.element}`,
genExpression(oper.value, context),
refValue,
oper.effect ? `r${oper.element}` : oper.refFor ? 'void 0' : undefined,
oper.refFor && 'true',
refKey,
),
]
}

export function genDeclareOldRef(oper: DeclareOldRefIRNode): CodeFragment[] {
return [NEWLINE, `let r${oper.id}`]
}

function genRefValue(value: SimpleExpressionNode, context: CodegenContext) {
// in inline mode there is no setupState object, so we can't use string
// keys to set the ref. Instead, we need to transform it to pass the
// actual ref instead.
if (!__BROWSER__ && value && context.options.inline) {
const binding = context.options.bindingMetadata[value.content]
if (
binding === BindingTypes.SETUP_LET ||
binding === BindingTypes.SETUP_REF ||
binding === BindingTypes.SETUP_MAYBE_REF
) {
return [[value.content], JSON.stringify(value.content)]
}
}
return [genExpression(value, context)]
}
8 changes: 8 additions & 0 deletions packages/runtime-core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -557,3 +557,11 @@ export { startMeasure, endMeasure } from './profiling'
* @internal
*/
export { initFeatureFlags } from './featureFlags'
/**
* @internal
*/
export { setRef } from './rendererTemplateRef'
/**
* @internal
*/
export { type VNodeNormalizedRef, normalizeRef } from './vnode'
2 changes: 1 addition & 1 deletion packages/runtime-core/src/rendererTemplateRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export function setRef(
const setupState = owner.setupState
const rawSetupState = toRaw(setupState)
const canSetSetupRef =
setupState === EMPTY_OBJ
setupState === undefined || setupState === EMPTY_OBJ
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is no setupState on vapor component instance

? () => false
: (key: string) => {
if (__DEV__) {
Expand Down
11 changes: 5 additions & 6 deletions packages/runtime-core/src/vnode.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,18 +454,17 @@ const createVNodeWithArgsTransform = (
const normalizeKey = ({ key }: VNodeProps): VNode['key'] =>
key != null ? key : null

const normalizeRef = ({
ref,
ref_key,
ref_for,
}: VNodeProps): VNodeNormalizedRefAtom | null => {
export const normalizeRef = (
{ ref, ref_key, ref_for }: VNodeProps,
i: ComponentInternalInstance = currentRenderingInstance!,
): VNodeNormalizedRefAtom | null => {
if (typeof ref === 'number') {
ref = '' + ref
}
return (
ref != null
? isString(ref) || isRef(ref) || isFunction(ref)
? { i: currentRenderingInstance, r: ref, k: ref_key, f: !!ref_for }
? { i, r: ref, k: ref_key, f: !!ref_for }
: ref
: null
) as any
Expand Down
51 changes: 51 additions & 0 deletions packages/runtime-vapor/__tests__/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { createVaporApp } from '../src'
import type { App } from '@vue/runtime-dom'
import type { VaporComponent, VaporComponentInstance } from '../src/component'
import type { RawProps } from '../src/componentProps'
import { compileScript, parse } from '@vue/compiler-sfc'
import * as runtimeVapor from '../src'
import * as runtimeDom from '@vue/runtime-dom'
import * as VueServerRenderer from '@vue/server-renderer'

export interface RenderContext {
component: VaporComponent
Expand Down Expand Up @@ -82,3 +86,50 @@ export function makeRender<C = VaporComponent>(

return define
}

export { runtimeDom, runtimeVapor, VueServerRenderer }
export function compile(
sfc: string,
data: runtimeDom.Ref<any>,
components: Record<string, any> = {},
{
vapor = true,
ssr = false,
}: {
vapor?: boolean | undefined
ssr?: boolean | undefined
} = {},
): any {
if (!sfc.includes(`<script`)) {
sfc =
`<script vapor>const data = _data; const components = _components;</script>` +
sfc
}
const descriptor = parse(sfc).descriptor

const script = compileScript(descriptor, {
id: 'x',
isProd: true,
inlineTemplate: true,
genDefaultAs: '__sfc__',
vapor,
templateOptions: {
ssr,
},
})

const code =
script.content
.replace(/\bimport {/g, 'const {')
.replace(/ as _/g, ': _')
.replace(/} from ['"]vue['"]/g, `} = Vue`)
.replace(/} from "vue\/server-renderer"/g, '} = VueServerRenderer') +
'\nreturn __sfc__'

return new Function('Vue', 'VueServerRenderer', '_data', '_components', code)(
{ ...runtimeDom, ...runtimeVapor },
VueServerRenderer,
data,
components,
)
}
Loading