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
2 changes: 1 addition & 1 deletion ai-docs/ai-migration-v14-v15.md
Original file line number Diff line number Diff line change
Expand Up @@ -853,7 +853,7 @@ The channel-detail "send direct message" member action and the pinned-message en

Nothing to wire. `ChatView` provides the navigation and binds what is opened into a layout slot. To customize it (for example, open beside the current channel on ⌘/ctrl-click), pass `deriveWorkspaceNavigation`, which receives the SDK-derived navigation and returns the members to override. It must be referentially stable.

The same holds for your own components. Anything that reads `useWorkspaceNavigation()` (an "in a call" panel, a header badge for the open channel) has to render inside `ChatView`. Pass it as a `ChatView` child in a `views` layout: children render inside the provider, before the active view, and stay mounted when the view switches. The built-in `layout="nav-rail-entity-list-workspace"` does not render `children`. `openChannels` lists the active view's channels, so it is empty while the threads view is shown.
The same holds for your own components. Anything that reads `useWorkspaceNavigation()` (an "in a call" panel, a header badge for the open channel) has to render inside `ChatView`. Pass it as a `ChatView` child, with `views` or with the built-in `layout="nav-rail-entity-list-workspace"`: children render inside the provider, before the active view or the layout, and stay mounted when the view switches. Children that render markup sit next to the view or layout in `ChatView`'s root, so position them with your own CSS. `openChannels` lists the active view's channels, so it is empty while the threads view is shown.

```tsx
// `CallControls` stands for a component of your own.
Expand Down
10 changes: 8 additions & 2 deletions src/plugins/SlotLayout/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,8 @@ export const ChatView = ({
[slotRenderers],
);

// Always-on `children` (e.g. sync helpers) render alongside the active view's content.
// Always-on `children` (e.g. sync helpers) render alongside the active view's content, in both the
// `views` mode and the built-in layout.
const activeViewContent = views?.[activeView];

const content = views ? (
Expand Down Expand Up @@ -369,7 +370,12 @@ export const ChatView = ({
return { fallback: Fallback ? <Fallback slot={slot} /> : undefined, slot };
});

return <WorkspaceLayout navRail={<ChatViewSelector />} slots={slots} />;
return (
<>
{children}
<WorkspaceLayout navRail={<ChatViewSelector />} slots={slots} />
</>
);
})()
) : (
children
Expand Down
45 changes: 30 additions & 15 deletions src/plugins/SlotLayout/ThreadListSlot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,32 +6,48 @@ import { useLayoutViewState } from './hooks/useLayoutViewState';
import { Slot } from './layout/Slot';

import type { PropsWithChildren, ReactNode } from 'react';
import type { SlotName } from './layoutController/layoutControllerTypes';
import type {
LayoutSlotBinding,
SlotName,
} from './layoutController/layoutControllerTypes';

export type ThreadListSlotProps = PropsWithChildren<{
/**
* Rendered while the slot holds no thread list: when the layout has no slot for it, and until
* the binding lands in a slot that does not hold one yet.
*/
fallback?: ReactNode;
/**
* The slot to bind the thread list to. Without it, or when the layout has no such slot: the slot
* already holding a thread list, else the first free slot, else the first slot, replacing what it
* holds. Moving the list to `slot` empties the slot it held.
*/
slot?: SlotName;
}>;

const LIST_BINDING_KEY = 'thread-list';
const LIST_ENTITY_KIND = 'threadList';

export const ThreadListSlot = ({
children,
fallback = null,
slot,
}: ThreadListSlotProps) => {
const isThreadListBinding = (binding?: LayoutSlotBinding) =>
getChatViewEntityBinding(binding)?.kind === LIST_ENTITY_KIND;

/**
* Binds a thread list into a layout slot and renders that slot. The slot shows `children` when
* given, and otherwise the renderer registered for the `threadList` kind (`<ThreadList/>` unless
* `ChatView`'s `slotRenderers` replace it).
*/
export const ThreadListSlot = ({ children, fallback, slot }: ThreadListSlotProps) => {
const { layoutController } = useChatViewContext();
const { availableSlots, slotBindings } = useLayoutViewState();

const requestedSlot = slot && availableSlots.includes(slot) ? slot : undefined;
const existingListSlot = availableSlots.find(
(candidate) =>
getChatViewEntityBinding(slotBindings[candidate])?.kind === LIST_ENTITY_KIND,
const existingListSlot = availableSlots.find((candidate) =>
isThreadListBinding(slotBindings[candidate]),
);
const firstFreeSlot = availableSlots.find((candidate) => !slotBindings[candidate]);
const listSlot =
requestedSlot ?? existingListSlot ?? firstFreeSlot ?? availableSlots[0];
const isListBound = !!listSlot && isThreadListBinding(slotBindings[listSlot]);

useEffect(() => {
if (!listSlot) return;
Expand All @@ -40,10 +56,7 @@ export const ThreadListSlot = ({
layoutController.release(existingListSlot);
}

const existingEntity = getChatViewEntityBinding(slotBindings[listSlot]);
if (existingEntity?.kind === LIST_ENTITY_KIND) {
return;
}
if (isListBound) return;

layoutController.bind(
listSlot,
Expand All @@ -53,9 +66,11 @@ export const ThreadListSlot = ({
source: {},
}),
);
}, [existingListSlot, layoutController, listSlot, requestedSlot, slotBindings]);
}, [existingListSlot, isListBound, layoutController, listSlot, requestedSlot]);

if (!listSlot) return <>{fallback}</>;

return <Slot slot={listSlot}>{children ?? fallback}</Slot>;
// `Slot` stays mounted while the list moves between slots. Until the list is bound, `false`
// stands in for a missing `fallback` so the slot does not render what it held before.
return <Slot slot={listSlot}>{isListBound ? children : (fallback ?? false)}</Slot>;
};
31 changes: 30 additions & 1 deletion src/plugins/SlotLayout/__tests__/ChatView.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
getTestClientWithUser,
mockTranslationContextValue,
} from '../../../mock-builders';
import { ChatView } from '../ChatView';
import { ChatView, useChatViewContext } from '../ChatView';
import { LayoutController } from '../layoutController/LayoutController';
import { createChatViewSlotBinding } from '../slotBinding';
import { useIsInThemeScope } from '../../../context/ThemeScopeContext';
Expand Down Expand Up @@ -341,4 +341,33 @@ describe('ChatView built-in workspace layout empty state', () => {
container.querySelector('.str-chat__chat-view__empty-placeholder'),
).not.toBeInTheDocument();
});

it('renders children alongside the layout, in the ChatView contexts', async () => {
const ChildProbe = () => (
<div data-active-view={useChatViewContext().activeView} data-testid='child' />
);
const { container } = await renderWorkspace({ children: <ChildProbe /> });

expect(screen.getByTestId('child')).toHaveAttribute('data-active-view', 'channels');
expect(
container.querySelector('.str-chat__chat-view__workspace-layout'),
).toBeInTheDocument();
});

it('keeps children mounted when the view switches', async () => {
const onUnmount = vi.fn();
const ChildProbe = () => {
React.useEffect(() => onUnmount, []);
return <div data-testid='child' />;
};
await renderWorkspace({ children: <ChildProbe /> });

fireEvent.click(screen.getByRole('button', { name: 'Open threads view' }));

expect(
await screen.findByRole('button', { current: true, name: 'Open threads view' }),
).toBeInTheDocument();
expect(screen.getByTestId('child')).toBeInTheDocument();
expect(onUnmount).not.toHaveBeenCalled();
});
});
205 changes: 205 additions & 0 deletions src/plugins/SlotLayout/__tests__/ThreadListSlot.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import React from 'react';
import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';

import { ChatProvider, TranslationProvider } from '../../../context';
import {
getTestClientWithUser,
mockTranslationContextValue,
} from '../../../mock-builders';
import { ChatView } from '../ChatView';
import { ThreadListSlot } from '../ThreadListSlot';
import { LayoutController } from '../layoutController/LayoutController';
import { createChatViewSlotBinding, getChatViewEntityBinding } from '../slotBinding';

import type { ComponentProps, ReactNode } from 'react';
import type { StreamChat } from 'stream-chat';

vi.mock('../../../components/Threads/ThreadList', () => ({
ThreadList: () => <div data-testid='thread-list' />,
}));

describe('ThreadListSlot', () => {
let client: StreamChat;

beforeEach(async () => {
client = await getTestClientWithUser();
});

afterEach(cleanup);

const renderTree = (
children: ReactNode,
chatViewProps: Partial<ComponentProps<typeof ChatView>> = {},
) => (
<ChatProvider
value={{
client,
getAppSettings: vi.fn(),
mutes: [],
searchController: fromPartial({}),
theme: 'messaging light',
useImageFlagEmojisOnWindows: false,
}}
>
<TranslationProvider value={mockTranslationContextValue()}>
<ChatView {...chatViewProps}>{children}</ChatView>
</TranslationProvider>
</ChatProvider>
);

const renderInChatView = (
children: ReactNode,
chatViewProps: Partial<ComponentProps<typeof ChatView>> = {},
) => render(renderTree(children, chatViewProps));

const createLayoutController = (availableSlots: string[]) =>
new LayoutController({ initialState: { availableSlots } });

const boundKind = (layoutController: LayoutController, slot: string) => {
const state = layoutController.state.getLatestValue();
return getChatViewEntityBinding(state.layouts?.[state.activeView]?.slotBindings[slot])
?.kind;
};

it('binds a thread list into the first free slot and renders <ThreadList/>', async () => {
const layoutController = createLayoutController(['slot1', 'slot2']);

renderInChatView(<ThreadListSlot />, { layoutController });

expect(await screen.findByTestId('thread-list')).toBeInTheDocument();
expect(boundKind(layoutController, 'slot1')).toBe('threadList');
});

it('renders the thread list, not `fallback`, once the list is bound', async () => {
const layoutController = createLayoutController(['slot1']);

renderInChatView(<ThreadListSlot fallback={<div data-testid='fallback' />} />, {
layoutController,
});

expect(await screen.findByTestId('thread-list')).toBeInTheDocument();
expect(screen.queryByTestId('fallback')).not.toBeInTheDocument();
});

it('renders `children` instead of the thread list', async () => {
const layoutController = createLayoutController(['slot1']);

renderInChatView(
<ThreadListSlot fallback={<div data-testid='fallback' />}>
<div data-testid='custom-list' />
</ThreadListSlot>,
{ layoutController },
);

expect(await screen.findByTestId('custom-list')).toBeInTheDocument();
expect(screen.queryByTestId('thread-list')).not.toBeInTheDocument();
expect(screen.queryByTestId('fallback')).not.toBeInTheDocument();
});

it("renders the app's `threadList` renderer from `slotRenderers`", async () => {
const layoutController = createLayoutController(['slot1']);

renderInChatView(<ThreadListSlot />, {
layoutController,
slotRenderers: { threadList: () => <div data-testid='app-thread-list' /> },
});

expect(await screen.findByTestId('app-thread-list')).toBeInTheDocument();
expect(screen.queryByTestId('thread-list')).not.toBeInTheDocument();
});

it('renders `fallback` while the layout has no slot for the list', () => {
const layoutController = createLayoutController([]);

renderInChatView(<ThreadListSlot fallback={<div data-testid='fallback' />} />, {
layoutController,
});

expect(screen.getByTestId('fallback')).toBeInTheDocument();
expect(screen.queryByTestId('thread-list')).not.toBeInTheDocument();
});

describe('before the binding lands', () => {
const bindChannel = (layoutController: LayoutController) => {
const channel = client.channel('messaging', 'general');
layoutController.bind(
'slot1',
createChatViewSlotBinding({ key: channel.cid, kind: 'channel', source: channel }),
);
// holds the thread list's binding back so the pre-bind render stays on screen
vi.spyOn(layoutController, 'bind').mockImplementation(() => undefined);
};
const slotRenderers = {
channel: () => <div data-testid='bound-channel' />,
};

it('shows nothing of what the slot held before', () => {
const layoutController = createLayoutController(['slot1']);
bindChannel(layoutController);

const { container } = renderInChatView(<ThreadListSlot />, {
layoutController,
slotRenderers,
});

expect(container.querySelector('section[data-slot="slot1"]')).toBeEmptyDOMElement();
expect(screen.queryByTestId('bound-channel')).not.toBeInTheDocument();
expect(screen.queryByTestId('thread-list')).not.toBeInTheDocument();
});

it('renders `fallback` inside the slot', () => {
const layoutController = createLayoutController(['slot1']);
bindChannel(layoutController);

const { container } = renderInChatView(
<ThreadListSlot fallback={<div data-testid='fallback' />} />,
{ layoutController, slotRenderers },
);

expect(
container.querySelector('section[data-slot="slot1"] [data-testid="fallback"]'),
).toBeInTheDocument();
expect(screen.queryByTestId('bound-channel')).not.toBeInTheDocument();
});
});

it('moves the thread list into the requested `slot`, releasing the slot it held', async () => {
const layoutController = createLayoutController(['slot1', 'slot2']);
const { rerender } = renderInChatView(<ThreadListSlot />, { layoutController });
await screen.findByTestId('thread-list');

rerender(renderTree(<ThreadListSlot slot='slot2' />, { layoutController }));

await waitFor(() => expect(boundKind(layoutController, 'slot2')).toBe('threadList'));
expect(boundKind(layoutController, 'slot1')).toBeUndefined();
expect(screen.getByTestId('thread-list')).toBeInTheDocument();
});

it('ignores a `slot` the layout does not have', async () => {
const layoutController = createLayoutController(['slot1']);

renderInChatView(<ThreadListSlot slot='missing' />, { layoutController });

expect(await screen.findByTestId('thread-list')).toBeInTheDocument();
expect(boundKind(layoutController, 'slot1')).toBe('threadList');
});

it('moves to a free slot when its slot is bound to another kind', async () => {
const layoutController = createLayoutController(['slot1', 'slot2']);
renderInChatView(<ThreadListSlot />, { layoutController });
await screen.findByTestId('thread-list');

const channel = client.channel('messaging', 'general');
act(() => {
layoutController.bind(
'slot1',
createChatViewSlotBinding({ key: channel.cid, kind: 'channel', source: channel }),
);
});

await waitFor(() => expect(boundKind(layoutController, 'slot2')).toBe('threadList'));
expect(boundKind(layoutController, 'slot1')).toBe('channel');
expect(screen.getByTestId('thread-list')).toBeInTheDocument();
});
});