Skip to content
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

feat(runtime-vapor): attach current instance to render slot #168

Merged
merged 2 commits into from
Apr 6, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 30 additions & 0 deletions packages/runtime-vapor/__tests__/componentSlots.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
nextTick,
ref,
template,
withCtx,
} from '../src'
import { makeRender } from './_utils'

Expand Down Expand Up @@ -152,6 +153,35 @@ describe('component: slots', () => {
expect(instance.slots).toHaveProperty('footer')
})

test('the current instance should be kept in the slot', async () => {
let instanceInSlot: any

const Comp = defineComponent({
render() {
const instance = getCurrentInstance()
instance!.slots.default!()
return template('<div></div>')()
},
})

const { instance } = define({
render() {
return createComponent(
Comp,
{},
{
default: withCtx(() => {
instanceInSlot = getCurrentInstance()
return template('content')()
}),
},
)
},
}).render()

expect(instanceInSlot).toBe(instance)
})

test.todo('should respect $stable flag', async () => {
// TODO: $stable flag?
})
Expand Down
22 changes: 22 additions & 0 deletions packages/runtime-vapor/src/componentRenderContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import {
type ComponentInternalInstance,
currentInstance,
setCurrentInstance,
} from './component'

export function withCtx<T extends (...args: any) => any>(
fn: T,
instance: ComponentInternalInstance | null = currentInstance,
): T {
if (!instance) return fn

const fnWithCtx = ((...args: any[]) => {
const reset = setCurrentInstance(instance)
try {
return fn(...args)
} finally {
reset()
}
}) as T
return fnWithCtx
}
1 change: 1 addition & 0 deletions packages/runtime-vapor/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export {
type FunctionalComponent,
type SetupFn,
} from './component'
export { withCtx } from './componentRenderContext'
export { renderEffect } from './renderEffect'
export {
watch,
Expand Down
Loading