Skip to content

Commit

Permalink
feat(runtime-vapor): the current instance should be kept in the slot
Browse files Browse the repository at this point in the history
  • Loading branch information
LittleSound committed Mar 26, 2024
1 parent ba17fb9 commit 100e3fd
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
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

0 comments on commit 100e3fd

Please sign in to comment.