Skip to content
Merged
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
62 changes: 61 additions & 1 deletion runtime/slots/Slot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useLayoutForSlotId } from './layout/hooks';
import Slot from './Slot';
import SlotContext from './SlotContext';
import { getSiteConfig, setSiteConfig } from '../config';
import { WidgetOperationTypes } from '.';
import { SlotOperation, useWidgetOptions, WidgetOperationTypes } from '.';

jest.mock('./layout/hooks');

Expand Down Expand Up @@ -70,3 +70,63 @@ describe('Slot component with site config operations', () => {
await findByText('Alias Widget');
});
});

function AliasedWidget() {
const { label } = useWidgetOptions();
return <div>{typeof label === 'string' ? label : 'Aliased'}</div>;
}

describe('Slot component with operations targeting a widget id alias', () => {
const slotId = 'new-slot.ui';
const widgets: SlotOperation[] = [
{ slotId, op: WidgetOperationTypes.APPEND, id: 'aliased-widget', idAliases: ['widget-alias'], component: AliasedWidget },
{ slotId, op: WidgetOperationTypes.APPEND, id: 'other-widget', element: <div>Other</div> },
];

beforeEach(() => {
(useLayoutForSlotId as jest.Mock).mockReturnValue(null);
});

afterEach(() => {
setSiteConfig({ ...getSiteConfig(), apps: [] });
});

async function renderSlotWith(operation: SlotOperation) {
setSiteConfig({
...getSiteConfig(),
apps: [{ appId: 'test-app', slots: [...widgets, operation] }],
});
const { container, findByText } = render(<MemoryRouter><TestSlot /></MemoryRouter>);
await findByText('Other');
return container;
}

function renderedWidgetTexts(container: HTMLElement) {
return Array.from(container.querySelectorAll('div')).map(div => div.textContent);
}

it('INSERT_AFTER places the widget after the aliased widget', async () => {
const container = await renderSlotWith({ slotId, op: WidgetOperationTypes.INSERT_AFTER, id: 'inserted', relatedId: 'widget-alias', element: <div>Inserted</div> });
expect(renderedWidgetTexts(container)).toEqual(['Aliased', 'Inserted', 'Other']);
});

it('INSERT_BEFORE places the widget before the aliased widget', async () => {
const container = await renderSlotWith({ slotId, op: WidgetOperationTypes.INSERT_BEFORE, id: 'inserted', relatedId: 'widget-alias', element: <div>Inserted</div> });
expect(renderedWidgetTexts(container)).toEqual(['Inserted', 'Aliased', 'Other']);
});

it('REPLACE renders the widget in place of the aliased widget', async () => {
const container = await renderSlotWith({ slotId, op: WidgetOperationTypes.REPLACE, id: 'replacement', relatedId: 'widget-alias', element: <div>Replacement</div> });
expect(renderedWidgetTexts(container)).toEqual(['Replacement', 'Other']);
});

it('REMOVE drops the aliased widget', async () => {
const container = await renderSlotWith({ slotId, op: WidgetOperationTypes.REMOVE, relatedId: 'widget-alias' });
expect(renderedWidgetTexts(container)).toEqual(['Other']);
});

it('OPTIONS reaches the aliased widget through useWidgetOptions', async () => {
const container = await renderSlotWith({ slotId, op: WidgetOperationTypes.OPTIONS, relatedId: 'widget-alias', options: { label: 'From alias' } });
expect(renderedWidgetTexts(container)).toEqual(['From alias', 'Other']);
});
});
2 changes: 1 addition & 1 deletion runtime/slots/widget/WidgetContext.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createContext } from 'react';

const WidgetContext = createContext<{ slotId: string; widgetId: string; role?: string }>({
const WidgetContext = createContext<{ slotId: string; widgetId: string; widgetIdAliases?: string[]; role?: string }>({
slotId: '',
widgetId: '',
role: undefined,
Expand Down
5 changes: 3 additions & 2 deletions runtime/slots/widget/WidgetProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@ interface WidgetProviderProps {
children: ReactNode;
slotId: string;
widgetId: string;
widgetIdAliases?: string[];
role?: string;
}

export default function WidgetProvider({ children, slotId, widgetId, role }: WidgetProviderProps) {
export default function WidgetProvider({ children, slotId, widgetId, widgetIdAliases, role }: WidgetProviderProps) {
useEffect(() => {
if (role !== undefined) {
addActiveWidgetRole(role);
Expand All @@ -23,7 +24,7 @@ export default function WidgetProvider({ children, slotId, widgetId, role }: Wid
}, [role]);

return (
<WidgetContext.Provider value={{ slotId, widgetId, role }}>
<WidgetContext.Provider value={{ slotId, widgetId, widgetIdAliases, role }}>
{children}
</WidgetContext.Provider>
);
Expand Down
75 changes: 75 additions & 0 deletions runtime/slots/widget/hooks.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { renderHook } from '@testing-library/react';
import { ReactNode } from 'react';
import * as slotHooks from '../hooks';
import { useSortedWidgetOperations, useWidgetOptions, useWidgetOptionsForId } from './hooks';
import { WidgetInsertAfterOperation, WidgetInsertBeforeOperation, WidgetOperationTypes, WidgetOptionsOperation } from './types';
import WidgetContext from './WidgetContext';

jest.mock('../hooks'); // mocks the useSlotOperations hook

const slotId = 'test-slot.ui';

describe('useSortedWidgetOperations', () => {
// The widget is declared under its new id with the old id as an alias.
const declaresWidget: WidgetInsertAfterOperation = {
slotId,
op: WidgetOperationTypes.INSERT_AFTER,
id: 'new-widget',
idAliases: ['old-widget'],
relatedId: 'anchor',
element: <div>New</div>,
};
const insertAfterAlias: WidgetInsertAfterOperation = { slotId, op: WidgetOperationTypes.INSERT_AFTER, id: 'after-alias', relatedId: 'old-widget', element: <div /> };
const insertBeforeAlias: WidgetInsertBeforeOperation = { slotId, op: WidgetOperationTypes.INSERT_BEFORE, id: 'before-alias', relatedId: 'old-widget', element: <div /> };
const insertAfterId: WidgetInsertAfterOperation = { slotId, op: WidgetOperationTypes.INSERT_AFTER, id: 'after-id', relatedId: 'new-widget', element: <div /> };
const insertBeforeId: WidgetInsertBeforeOperation = { slotId, op: WidgetOperationTypes.INSERT_BEFORE, id: 'before-id', relatedId: 'new-widget', element: <div /> };
const targetingWidget = [insertAfterAlias, insertBeforeAlias, insertAfterId, insertBeforeId];

it('sorts INSERT_AFTER and INSERT_BEFORE targeting the alias or the id after the operation declaring the widget', () => {
(slotHooks.useSlotOperations as jest.Mock).mockReturnValue([...targetingWidget, declaresWidget]);
const { result } = renderHook(() => useSortedWidgetOperations(slotId));
expect(result.current).toEqual([declaresWidget, ...targetingWidget]);
});

it('keeps declaration order among operations targeting the alias and the id, as with one shared relatedId', () => {
const reversed = [...targetingWidget].reverse();
(slotHooks.useSlotOperations as jest.Mock).mockReturnValue([...reversed, declaresWidget]);
const { result } = renderHook(() => useSortedWidgetOperations(slotId));
expect(result.current).toEqual([declaresWidget, ...reversed]);
});
});

describe('useWidgetOptionsForId', () => {
const forAlias: WidgetOptionsOperation = { slotId, op: WidgetOperationTypes.OPTIONS, relatedId: 'old-widget', options: { fromAlias: true } };
const forId: WidgetOptionsOperation = { slotId, op: WidgetOperationTypes.OPTIONS, relatedId: 'new-widget', options: { fromId: true } };
const forOther: WidgetOptionsOperation = { slotId, op: WidgetOperationTypes.OPTIONS, relatedId: 'other-widget', options: { fromOther: true } };

beforeEach(() => {
(slotHooks.useSlotOperations as jest.Mock).mockReturnValue([forAlias, forId, forOther]);
});

it('merges OPTIONS declared against the id and against an alias', () => {
const { result } = renderHook(() => useWidgetOptionsForId(slotId, 'new-widget', ['old-widget']));
expect(result.current).toEqual({ fromAlias: true, fromId: true });
});

it('merges only OPTIONS declared against the id when there are no aliases', () => {
const { result } = renderHook(() => useWidgetOptionsForId(slotId, 'new-widget'));
expect(result.current).toEqual({ fromId: true });
});
});

describe('useWidgetOptions', () => {
it('merges OPTIONS against the widget id and the aliases read from WidgetContext', () => {
const forAlias: WidgetOptionsOperation = { slotId, op: WidgetOperationTypes.OPTIONS, relatedId: 'old-widget', options: { fromAlias: true } };
const forId: WidgetOptionsOperation = { slotId, op: WidgetOperationTypes.OPTIONS, relatedId: 'new-widget', options: { fromId: true } };
(slotHooks.useSlotOperations as jest.Mock).mockReturnValue([forAlias, forId]);
const wrapper = ({ children }: { children: ReactNode }) => (
<WidgetContext.Provider value={{ slotId, widgetId: 'new-widget', widgetIdAliases: ['old-widget'] }}>
{children}
</WidgetContext.Provider>
);
const { result } = renderHook(() => useWidgetOptions(), { wrapper });
expect(result.current).toEqual({ fromAlias: true, fromId: true });
});
});
17 changes: 9 additions & 8 deletions runtime/slots/widget/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import useActiveRoles from '../../react/hooks/useActiveRoles';
import { useSlotContext, useSlotOperations } from '../hooks';
import { isSlotOperationConditionSatisfied } from '../utils';
import { WidgetList, WidgetOperation } from './types';
import { createWidgets, isWidgetAbsoluteOperation, isWidgetOperation, isWidgetOptionsOperation, isWidgetRelativeOperation } from './utils';
import { createWidgets, isWidgetAbsoluteOperation, isWidgetOperation, isWidgetOptionsOperation, isWidgetRelativeOperation, matchesWidgetId } from './utils';
import WidgetContext from './WidgetContext';

export function useWidgets(): WidgetList {
Expand Down Expand Up @@ -48,9 +48,9 @@ export function useSortedWidgetOperations(id: string) {
} else if (bAbsolute) {
return 1;
} else if (isWidgetRelativeOperation(a) && isWidgetRelativeOperation(b)) {
if (a.id === b.relatedId) {
if (matchesWidgetId(a, b.relatedId)) {
return -1;
} else if (b.id === a.relatedId) {
} else if (matchesWidgetId(b, a.relatedId)) {
return 1;
}
}
Expand All @@ -65,20 +65,21 @@ export function useSortedWidgetOperations(id: string) {
* operations are merged in declaration order, meaning last one in wins.
*/
export function useWidgetOptions() {
const { slotId, widgetId } = useContext(WidgetContext);
return useWidgetOptionsForId(slotId, widgetId);
const { slotId, widgetId, widgetIdAliases } = useContext(WidgetContext);
return useWidgetOptionsForId(slotId, widgetId, widgetIdAliases);
}

export function useWidgetOptionsForId(slotId: string, widgetId: string) {
export function useWidgetOptionsForId(slotId: string, widgetId: string, widgetIdAliases?: string[]) {
const operations = useWidgetOperations(slotId);

return useMemo(() => {
const identity = { id: widgetId, idAliases: widgetIdAliases };
let options: Record<string, unknown> = {};
for (const operation of operations) {
if (isWidgetOptionsOperation(operation) && operation.relatedId === widgetId) {
if (isWidgetOptionsOperation(operation) && matchesWidgetId(identity, operation.relatedId)) {
options = { ...options, ...operation.options };
}
}
return options;
}, [widgetId, operations]);
}, [widgetId, widgetIdAliases, operations]);
}
5 changes: 5 additions & 0 deletions runtime/slots/widget/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,10 @@ export type WidgetRendererProps = (
export interface WidgetIdentityProps {
id: string;
role?: string;
/**
* Other IDs this widget answers to. A relative operation (INSERT_AFTER, INSERT_BEFORE, REPLACE, REMOVE, OPTIONS) whose relatedId names one of them applies as if it named `id`. When a widget ID is renamed, keep the old ID here for at least one release so site configs that target it keep working.
*/
idAliases?: string[];
}

export interface WidgetRelationshipProps {
Expand Down Expand Up @@ -131,6 +135,7 @@ export type WidgetOperation = WidgetAbsoluteOperation | WidgetRelativeOperation;
export interface IdentifiedWidget {
id: string;
role?: string;
idAliases?: string[];
node: ReactNode;
}

Expand Down
74 changes: 73 additions & 1 deletion runtime/slots/widget/utils.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react';
import { WidgetOperationTypes } from './types';
import { WidgetAppendOperation, WidgetList, WidgetOperation, WidgetOperationTypes } from './types';
import { createWidgets } from './utils';

// Mock WidgetProvider to just render children, avoiding context dependencies.
Expand All @@ -10,6 +10,10 @@ jest.mock('./WidgetProvider', () => ({

const slotId = 'test-slot';

function identifiedIds(widgets: WidgetList) {
return widgets.identified.map(w => w.id);
}

function makeAppendOp(id: string, label: string, role?: string) {
return {
slotId,
Expand Down Expand Up @@ -129,4 +133,72 @@ describe('createWidgets', () => {
expect(widgets.withoutRole('sidebar')).toHaveLength(1);
});
});

describe('operations targeting a widget id alias', () => {
const aliasedWidget: WidgetAppendOperation = { slotId, op: WidgetOperationTypes.APPEND, id: 'aliased-widget', idAliases: ['widget-alias'], element: <div>Aliased</div> };
const otherWidget: WidgetAppendOperation = { slotId, op: WidgetOperationTypes.APPEND, id: 'other-widget', element: <div>Other</div> };

function applyToAliasedWidgets(operation: WidgetOperation) {
return createWidgets([aliasedWidget, otherWidget, operation]);
}

it('INSERT_AFTER places the widget after the aliased widget', () => {
const widgets = applyToAliasedWidgets({ slotId, op: WidgetOperationTypes.INSERT_AFTER, id: 'inserted', relatedId: 'widget-alias', element: <div /> });
expect(identifiedIds(widgets)).toEqual(['aliased-widget', 'inserted', 'other-widget']);
});

it('INSERT_BEFORE places the widget before the aliased widget', () => {
const widgets = applyToAliasedWidgets({ slotId, op: WidgetOperationTypes.INSERT_BEFORE, id: 'inserted', relatedId: 'widget-alias', element: <div /> });
expect(identifiedIds(widgets)).toEqual(['inserted', 'aliased-widget', 'other-widget']);
});

it('REPLACE puts the widget in place of the aliased widget', () => {
const widgets = applyToAliasedWidgets({ slotId, op: WidgetOperationTypes.REPLACE, id: 'replacement', relatedId: 'widget-alias', element: <div /> });
expect(identifiedIds(widgets)).toEqual(['replacement', 'other-widget']);
});

it('REMOVE drops the aliased widget', () => {
const widgets = applyToAliasedWidgets({ slotId, op: WidgetOperationTypes.REMOVE, relatedId: 'widget-alias' });
expect(identifiedIds(widgets)).toEqual(['other-widget']);
});

it('REMOVE targeting the current id still drops the aliased widget', () => {
const widgets = applyToAliasedWidgets({ slotId, op: WidgetOperationTypes.REMOVE, relatedId: 'aliased-widget' });
expect(identifiedIds(widgets)).toEqual(['other-widget']);
});

it('INSERT_AFTER targeting neither the id nor the alias adds nothing', () => {
const widgets = applyToAliasedWidgets({ slotId, op: WidgetOperationTypes.INSERT_AFTER, id: 'inserted', relatedId: 'unknown-widget', element: <div /> });
expect(identifiedIds(widgets)).toEqual(['aliased-widget', 'other-widget']);
});

it('byId and withoutId match the alias', () => {
const widgets = createWidgets([aliasedWidget, otherWidget]);
expect(widgets.byId('widget-alias')).toHaveLength(1);
expect(widgets.withoutId('widget-alias')).toHaveLength(1);
});

it('exposes idAliases on the identified widget', () => {
const widgets = createWidgets([aliasedWidget, otherWidget]);
expect(widgets.identified[0]).toEqual(
expect.objectContaining({ id: 'aliased-widget', idAliases: ['widget-alias'] })
);
});
});

describe('an id and an alias matching the same relatedId', () => {
const widgetWithId: WidgetAppendOperation = { slotId, op: WidgetOperationTypes.APPEND, id: 'shared', element: <div>Id</div> };
const widgetWithAlias: WidgetAppendOperation = { slotId, op: WidgetOperationTypes.APPEND, id: 'aliased', idAliases: ['shared'], element: <div>Alias</div> };
const removeShared: WidgetOperation = { slotId, op: WidgetOperationTypes.REMOVE, relatedId: 'shared' };

it('REMOVE drops the widget with the id when it is listed first', () => {
const widgets = createWidgets([widgetWithId, widgetWithAlias, removeShared]);
expect(identifiedIds(widgets)).toEqual(['aliased']);
});

it('REMOVE drops the widget with the alias when it is listed first', () => {
const widgets = createWidgets([widgetWithAlias, widgetWithId, removeShared]);
expect(identifiedIds(widgets)).toEqual(['shared']);
});
});
});
17 changes: 11 additions & 6 deletions runtime/slots/widget/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export function isWidgetIdentityRoleOperation(operation: SlotOperation): operati
return isWidgetIdentityOperation(operation) && hasWidgetIdentityRoleProps(operation);
}

export function matchesWidgetId(identity: Pick<WidgetIdentityProps, 'id' | 'idAliases'>, id: string) {
return identity.id === id || (identity.idAliases?.includes(id) ?? false);
}

export function createWidgetAppendOperation(id: string, slotId: string, element: ReactNode) {
let operation: WidgetOperation | undefined = undefined;
if (element) {
Expand Down Expand Up @@ -101,7 +105,7 @@ function hasWidgetIdentityRoleProps(operation: WidgetOperation): operation is (W
*/
function createIdentifiedWidget(operation: WidgetRendererOperation, componentProps?: Record<string, unknown>) {
let widget: ReactNode = null;
const { id } = operation;
const { id, idAliases, role, slotId } = operation;
if (hasWidgetComponentProps(operation)) {
widget = (
<operation.component {...componentProps} />
Expand All @@ -116,9 +120,10 @@ function createIdentifiedWidget(operation: WidgetRendererOperation, componentPro

return {
id,
role: operation.role,
role,
idAliases,
node: (
<WidgetProvider key={id} slotId={operation.slotId} widgetId={operation.id} role={operation.role}>
<WidgetProvider key={id} slotId={slotId} widgetId={id} widgetIdAliases={idAliases} role={role}>
{widget}
</WidgetProvider>
),
Expand All @@ -127,7 +132,7 @@ function createIdentifiedWidget(operation: WidgetRendererOperation, componentPro

function findRelatedWidgetIndex(id: string, widgets: IdentifiedWidget[]) {
for (const candidateRelatedWidget of widgets) {
if (candidateRelatedWidget.id === id) {
if (matchesWidgetId(candidateRelatedWidget, id)) {
return widgets.indexOf(candidateRelatedWidget);
}
}
Expand Down Expand Up @@ -182,11 +187,11 @@ function createWidgetList(identifiedWidgets: IdentifiedWidget[]): WidgetList {
widgetList.identified = identifiedWidgets;

widgetList.byId = (id: string): ReactNode[] => {
return identifiedWidgets.filter(w => w.id === id).map(w => w.node);
return identifiedWidgets.filter(w => matchesWidgetId(w, id)).map(w => w.node);
};

widgetList.withoutId = (id: string): ReactNode[] => {
return identifiedWidgets.filter(w => w.id !== id).map(w => w.node);
return identifiedWidgets.filter(w => !matchesWidgetId(w, id)).map(w => w.node);
};

widgetList.byRole = (role: string): ReactNode[] => {
Expand Down
Loading