diff --git a/runtime/slots/hooks.test.tsx b/runtime/slots/hooks.test.tsx new file mode 100644 index 00000000..e9d7a501 --- /dev/null +++ b/runtime/slots/hooks.test.tsx @@ -0,0 +1,46 @@ +import { renderHook } from '@testing-library/react'; +import { ReactNode } from 'react'; +import { getSiteConfig, setSiteConfig } from '../config'; +import { useSlotOperations } from './hooks'; +import SlotContext from './SlotContext'; +import { WidgetOperationTypes } from './widget'; + +const enclosingSlotId = 'enclosing-slot.ui'; +const otherSlotId = 'other-slot.ui'; + +function wrapper({ children }: { children: ReactNode }) { + return ( + Default content }}> + {children} + + ); +} + +describe('useSlotOperations', () => { + beforeEach(() => { + setSiteConfig({ + ...getSiteConfig(), + apps: [{ + appId: 'test-app', + slots: [ + { slotId: 'enclosing-alias.ui', op: WidgetOperationTypes.APPEND, id: 'alias-widget', element:
Alias
}, + { slotId: otherSlotId, op: WidgetOperationTypes.APPEND, id: 'other-widget', element:
Other
}, + ], + }], + }); + }); + + afterEach(() => { + setSiteConfig({ ...getSiteConfig(), apps: [] }); + }); + + it('includes the default content and aliases of the enclosing slot when asked for it', () => { + const { result } = renderHook(() => useSlotOperations(enclosingSlotId), { wrapper }); + expect(result.current.map(operation => 'id' in operation && operation.id)).toEqual(['defaultContent', 'alias-widget']); + }); + + it('ignores the default content and aliases of the enclosing slot when asked for another slot', () => { + const { result } = renderHook(() => useSlotOperations(otherSlotId), { wrapper }); + expect(result.current.map(operation => 'id' in operation && operation.id)).toEqual(['other-widget']); + }); +}); diff --git a/runtime/slots/hooks.ts b/runtime/slots/hooks.ts index 48cfddf9..bc5038a8 100644 --- a/runtime/slots/hooks.ts +++ b/runtime/slots/hooks.ts @@ -7,9 +7,15 @@ import { createWidgetAppendOperation } from './widget'; /** * Resolves the operations registered for a given slot id (plus any aliases), * prepended with a default-content operation built from the slot's children. + * + * Children and aliases come from the enclosing slot, so they only apply when + * that slot is the one being asked for. Read from outside, a slot has neither. */ export function useSlotOperations(id: string) { - const { children, idAliases } = useSlotContext(); + const slotContext = useSlotContext(); + const isEnclosingSlot = slotContext.id === id; + const children = isEnclosingSlot ? slotContext.children : undefined; + const idAliases = isEnclosingSlot ? slotContext.idAliases : undefined; return useMemo(() => { const defaultOperation = createWidgetAppendOperation('defaultContent', id, children);