Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
import type { GalleryItemKey } from '@features/gallery/core/items';
import type { GalleryBoardSectionId } from '@features/gallery/core/settings';
import type { GalleryBoard } from '@features/gallery/core/types';
import { Box, HStack, Icon, ScrollArea, Stack, Text } from '@chakra-ui/react';
import { useDndContext, useDroppable } from '@dnd-kit/core';
import { getGalleryBoardLabel } from '@features/gallery/core/boardLabels';
import { toGalleryItemKey } from '@features/gallery/core/items';
import {
isGalleryBoardSectionOpen,
toggleGalleryBoardSection,
toggleGalleryProjectGroup,
} from '@features/gallery/core/settings';
import { usePreservedScrollOffset } from '@platform/react/usePreservedScrollOffset';
import { IconButton } from '@platform/ui/Button';
import { RenameDialog } from '@platform/ui/RenameDialog';
import { Tooltip } from '@platform/ui/Tooltip';
import { PlusIcon } from 'lucide-react';
import { Fragment, use, useCallback, useMemo, useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { BoardCoverIcon } from './GalleryBoardCover';
import { GalleryBoardFilters } from './GalleryBoardFilters';
import { getGalleryBoardGroups, isMovableGalleryBoard } from './galleryBoardGroups';
import { GalleryBoardMenu, type GalleryBoardMenuTarget } from './GalleryBoardMenu';
import { GalleryBoardRow } from './GalleryBoardRow';
import { GalleryBoardRowShell } from './GalleryBoardRowShell';
import { GalleryBoardSection } from './GalleryBoardSection';
import {
acceptsGalleryBoardMove,
GalleryDragScope,
getGalleryBoardTierDropData,
getGalleryBoardTierDropId,
} from './galleryDnd';
import { focusVisibleOperable, GalleryLoadNotice } from './GalleryLoadError';
import { GalleryProjectGroup } from './GalleryProjectGroup';
import { useOptionalGalleryUi } from './GalleryUiContext';
import { useGalleryWidget } from './GalleryWidgetContext';
import { useGalleryDestination } from './useGalleryDestination';
const SCROLL_CONTENT_PROPS = { py: '1' } as const;
const CREATE_ROW_COVER = <BoardCoverIcon icon={PlusIcon} />;
type CreateTier = 'library' | 'project';
export const GalleryBoardsPanel = () => {
const { t } = useTranslation();
const { actions, boardsState, gallery, projectId, projectName, projectNames, region } = useGalleryWidget();
// Board drags work only inside the workbench's drag context; elsewhere, use the menu.
const canDragBoards = use(GalleryDragScope);
const [searchTerm, setSearchTerm] = useState('');
const [createDialogTier, setCreateDialogTier] = useState<CreateTier | null>(null);
const [boardMenuTarget, setBoardMenuTarget] = useState<GalleryBoardMenuTarget | null>(null);
const boardsViewportRef = useRef<HTMLDivElement>(null);
// The shell keeps the gallery mounted across layouts; a container that stops rendering loses its offset.
usePreservedScrollOffset(boardsViewportRef);
const { showArchivedBoards, showDateBoards, showOtherProjectBoards } = gallery.settings;
const groups = useMemo(
() =>
getGalleryBoardGroups({
boards: gallery.boards,
projectBoardId: gallery.projectBoardId,
projectId,
projectNames,
searchTerm,
showArchived: showArchivedBoards,
showDates: showDateBoards,
showOtherProjects: showOtherProjectBoards,
t,
}),
[
gallery.boards,
gallery.projectBoardId,
projectId,
projectNames,
searchTerm,
showArchivedBoards,
showDateBoards,
showOtherProjectBoards,
t,
]
);
const loadedItemBoardIds = useMemo(
() => new Map<GalleryItemKey, string>(gallery.items.map((item) => [toGalleryItemKey(item), item.boardId])),
[gallery.items]
);
const trimmedSearchTerm = searchTerm.trim();
const tierLabel = useCallback(
(tier: CreateTier) => (tier === 'project' ? projectName : t('widgets.gallery.boardGroups.library')),
[projectName, t]
);
const createBoardIn = useCallback(
(name: string, tier: CreateTier) => actions.createBoard(name, tier === 'project' ? projectId : null),
[actions, projectId]
);
// The row goes away as soon as it is taken, so a slow create cannot be taken twice.
const createBoardFromSearch = useCallback(
(tier: CreateTier) => {
if (groups.canCreateFromSearch) {
setSearchTerm('');
void createBoardIn(trimmedSearchTerm, tier);
}
},
[createBoardIn, groups.canCreateFromSearch, trimmedSearchTerm]
);
// Enter creates only with no matches, avoiding accidental near-duplicates.
const handleSubmitSearch = useCallback(() => {
if (!groups.hasAnyMatch) {
createBoardFromSearch('project');
}
}, [createBoardFromSearch, groups.hasAnyMatch]);
const handleAddProjectBoard = useCallback(() => setCreateDialogTier('project'), []);
const handleAddLibraryBoard = useCallback(() => setCreateDialogTier('library'), []);
const closeCreateDialog = useCallback(() => setCreateDialogTier(null), []);
// The search is cleared only once the board exists; a reported failure keeps the typed name.
const handleCreateDialogSubmit = useCallback(
async (name: string) => {
if (!(await createBoardIn(name, createDialogTier ?? 'project'))) {
throw new Error('The board was not created.');
}
setSearchTerm('');
},
[createBoardIn, createDialogTier]
);
const addProjectBoardAction = useMemo(
() => <AddBoardButton label={t('widgets.gallery.createBoardInProject')} onClick={handleAddProjectBoard} />,
[handleAddProjectBoard, t]
);
const addLibraryBoardAction = useMemo(
() => <AddBoardButton label={t('widgets.gallery.createBoardInLibrary')} onClick={handleAddLibraryBoard} />,
[handleAddLibraryBoard, t]
);
const createProjectBoardFromSearch = useCallback(() => createBoardFromSearch('project'), [createBoardFromSearch]);
const createLibraryBoardFromSearch = useCallback(() => createBoardFromSearch('library'), [createBoardFromSearch]);
const noteBoardBrowsed = useOptionalGalleryUi()?.noteBoardBrowsed;
const handleSelectBoard = useCallback(
(boardId: string) => {
setSearchTerm('');
actions.selectBoard(boardId);
noteBoardBrowsed?.(boardId);
},
[actions, noteBoardBrowsed]
);
const openBoardMenu = useCallback((board: GalleryBoard, x: number, y: number) => {
setBoardMenuTarget({ board, x, y });
}, []);
const handleToggleSection = useCallback(
(sectionId: GalleryBoardSectionId, isOpen: boolean) =>
actions.updateSettings(toggleGalleryBoardSection(gallery.settings, sectionId, isOpen)),
[actions, gallery.settings]
);
const isSectionOpen = (sectionId: GalleryBoardSectionId) => isGalleryBoardSectionOpen(gallery.settings, sectionId);
const collapsedProjectGroupIds = useMemo(
() => new Set(gallery.settings.collapsedProjectGroupIds),
[gallery.settings.collapsedProjectGroupIds]
);
const handleToggleProjectGroup = useCallback(
(groupProjectId: string, isOpen: boolean) =>
actions.updateSettings(toggleGalleryProjectGroup(gallery.settings, groupProjectId, isOpen)),
[actions, gallery.settings]
);
// Without the backend's list the fixed rows would read as empty tiers, so the failure takes their place.
const isBoardListUnavailable = boardsState.status === 'error';
const isBoardListSettled = boardsState.status !== 'loading' && !isBoardListUnavailable;
const focusBoardList = useCallback(() => focusVisibleOperable(boardsViewportRef.current), []);
const focusBoardRow = useCallback(
(boardId: string) => {
const row = boardsViewportRef.current?.querySelector<HTMLElement>(
`[data-board-row="${CSS.escape(boardId)}"] button[type="button"]:not(.board-row-actions)`
);
if (row) {
row.focus();
} else {
focusBoardList();
}
},
[focusBoardList]
);
// A move or archive takes the row away with the menu's focus target; focus then goes to the row wherever it now is.
const relocatingBoardIdRef = useRef<string | null>(null);
const handleBoardRelocated = useCallback((boardId: string) => {
relocatingBoardIdRef.current = boardId;
}, []);
const handleBoardMenuClose = useCallback(() => {
const menuBoardId = boardMenuTarget?.board.id ?? null;
setBoardMenuTarget(null);
const relocatedBoardId = relocatingBoardIdRef.current;
relocatingBoardIdRef.current = null;
if (!document.activeElement?.closest('[data-scope="menu"]')) {
return;
}
if (relocatedBoardId !== null) {
focusBoardRow(relocatedBoardId);
return;
}
// The menu has no trigger of its own, so focus returns to the row's ⋮.
const actionsButton =
menuBoardId === null
? null
: boardsViewportRef.current?.querySelector<HTMLElement>(
`[data-board-row="${CSS.escape(menuBoardId)}"] .board-row-actions`
);
if (actionsButton) {
actionsButton.focus();
} else if (menuBoardId !== null) {
focusBoardRow(menuBoardId);
}
}, [boardMenuTarget, focusBoardRow]);
// A board that refuses results sends them to the inbox, whose row says so.
const destination = useGalleryDestination(gallery);
const refusedBoard =
destination.refusedBoardId === null ? undefined : destination.getBoard(destination.refusedBoardId);
const renderRow = (board: GalleryBoard, accessibleName?: string) => (
<GalleryBoardRow
key={board.id}
accessibleName={accessibleName}
autoAddRedirectedFrom={
destination.refusedBoardId !== null && destination.boardId === board.id
? refusedBoard
? getGalleryBoardLabel(refusedBoard, t)
: t('widgets.gallery.unknownBoard')
: undefined
}
board={board}
dragScope={canDragBoards && isMovableGalleryBoard(board, gallery.projectBoardId) ? region : undefined}
isAutoAddTarget={board.id === destination.boardId}
isMenuOpen={boardMenuTarget?.board.id === board.id}
isSelected={board.id === gallery.selectedBoardId}
loadedItemBoardIds={loadedItemBoardIds}
onFocusLost={focusBoardRow}
onOpenMenu={openBoardMenu}
onSelectBoard={handleSelectBoard}
/>
);
const renderCreateRow = (tier: CreateTier) =>
groups.canCreateFromSearch ? (
<GalleryBoardRowShell
cover={CREATE_ROW_COVER}
label={t('widgets.gallery.createBoardNamedIn', { destination: tierLabel(tier), name: trimmedSearchTerm })}
labelWeight="600"
onSelect={tier === 'project' ? createProjectBoardFromSearch : createLibraryBoardFromSearch}
/>
) : null;
// Every tier is the caller's own: other people's boards are listed apart.
const renderDropTier = (tierProjectId: string | null, label: string, content: ReactNode) =>
canDragBoards ? (
<GalleryBoardTierDropZone dropScope={region} label={label} projectId={tierProjectId}>
{content}
</GalleryBoardTierDropZone>
) : (
content
);
const renderHint = (text: string) =>
trimmedSearchTerm ? null : (
<Text color="fg.muted" fontSize="xs" pe="2" ps="2" py="1">
{text}
</Text>
);
const projectBoards = isBoardListUnavailable ? [] : groups.projectBoards;
const libraryBoards = isBoardListUnavailable ? [] : groups.libraryBoards;
// Uncategorized is where media on no board shows, not a board.
const countBoards = (boards: GalleryBoard[]) => boards.filter((board) => board.kind === 'board').length;
return (
<Stack flex="1" gap="1" minH="0" minW="0">
<GalleryBoardFilters searchTerm={searchTerm} onSearchChange={setSearchTerm} onSubmitSearch={handleSubmitSearch} />
<ScrollArea.Root flex="1" minH="0" variant="hover" w="full">
<ScrollArea.Viewport ref={boardsViewportRef} h="full" w="full">
<ScrollArea.Content {...SCROLL_CONTENT_PROPS}>
{renderDropTier(
projectId,
projectName,
<GalleryBoardSection
action={addProjectBoardAction}
count={countBoards(projectBoards)}
isOpen={isSectionOpen('project')}
label={projectName}
sectionId="project"
onToggle={handleToggleSection}
>
{boardsState.status === 'error' || boardsState.status === 'stale-error' ? (
<GalleryLoadNotice
message={t(
isBoardListUnavailable
? 'widgets.gallery.boardsLoadFailed'
: 'widgets.gallery.boardsRefreshFailed'
)}
pe="1"
ps="2"
read={boardsState}
retryLabel={t('widgets.gallery.retryLoadingBoards')}
onFocusLost={focusBoardList}
/>
) : null}
{projectBoards.map((board) => renderRow(board))}
{renderCreateRow('project')}
{isBoardListSettled && projectBoards.every((board) => board.isInbox)
? renderHint(t('widgets.gallery.projectBoardsHint'))
: null}
</GalleryBoardSection>
)}
{renderDropTier(
null,
t('widgets.gallery.boardGroups.library'),
<GalleryBoardSection
action={addLibraryBoardAction}
count={countBoards(libraryBoards)}
isOpen={isSectionOpen('library')}
label={t('widgets.gallery.boardGroups.library')}
sectionId="library"
onToggle={handleToggleSection}
>
{libraryBoards.map((board) => renderRow(board))}
{renderCreateRow('library')}
{isBoardListSettled && libraryBoards.every((board) => board.kind === 'uncategorized')
? renderHint(t('widgets.gallery.libraryBoardsHint'))
: null}
</GalleryBoardSection>
)}
{!isBoardListUnavailable && groups.sharedBoards.length > 0 ? (
<GalleryBoardSection
count={groups.sharedBoards.length}
isOpen={isSectionOpen('shared')}
label={t('widgets.gallery.boardGroups.shared')}
sectionId="shared"
onToggle={handleToggleSection}
>
{groups.sharedBoards.map((board) => renderRow(board))}
</GalleryBoardSection>
) : null}
{!isBoardListUnavailable && groups.otherUsersBoards.length > 0 ? (
<GalleryBoardSection
count={groups.otherUsersBoards.length}
isOpen={isSectionOpen('other-users')}
label={t('widgets.gallery.boardGroups.otherUsers')}
sectionId="other-users"
onToggle={handleToggleSection}
>
{groups.otherUsersBoards.map((board) => renderRow(board))}
</GalleryBoardSection>
) : null}
{!isBoardListUnavailable && groups.otherProjects.length > 0 ? (
<GalleryBoardSection
count={groups.otherProjects.length}
isOpen={isSectionOpen('other-projects')}
label={t('widgets.gallery.boardGroups.otherProjects')}
sectionId="other-projects"
onToggle={handleToggleSection}
>
{groups.otherProjects.map((group) => (
<Fragment key={group.projectId}>
{renderDropTier(
group.projectId,
group.label,
<GalleryProjectGroup
isCollapsed={collapsedProjectGroupIds.has(group.projectId)}
isSearching={trimmedSearchTerm !== ''}
label={group.label}
projectId={group.projectId}
onToggle={handleToggleProjectGroup}
>
{group.boards.map((board) =>
// Every other project's inbox is "Inbox"; assistive tech needs the project in the name.
renderRow(
board,
board.isInbox ? t('widgets.gallery.inboxOf', { project: group.label }) : undefined
)
)}
</GalleryProjectGroup>
)}
</Fragment>
))}
</GalleryBoardSection>
) : null}
{!isBoardListUnavailable && groups.dateBoards.length > 0 ? (
<GalleryBoardSection
isOpen={isSectionOpen('dates')}
label={t('widgets.gallery.boardGroups.byDate')}
sectionId="dates"
onToggle={handleToggleSection}
>
{groups.dateBoards.map((board) => (
<GalleryBoardRow
key={board.id}
board={board}
isMenuOpen={boardMenuTarget?.board.id === board.id}
isSelected={board.id === gallery.selectedBoardId}
loadedItemBoardIds={loadedItemBoardIds}
onSelectBoard={handleSelectBoard}
/>
))}
</GalleryBoardSection>
) : null}
{!isBoardListUnavailable && groups.archivedBoards.length > 0 ? (
<GalleryBoardSection
isOpen={isSectionOpen('archived')}
label={t('common.archived')}
sectionId="archived"
onToggle={handleToggleSection}
>
{groups.archivedBoards.map((board) => renderRow(board))}
</GalleryBoardSection>
) : null}
{!isBoardListUnavailable && !groups.hasAnyMatch && !groups.canCreateFromSearch ? (
<HStack justify="center" py="3">
<Text color="fg.muted" fontSize="xs">
{t('widgets.gallery.noBoardsMatchSearch')}
</Text>
</HStack>
) : null}
</ScrollArea.Content>
</ScrollArea.Viewport>
<ScrollArea.Scrollbar>
<ScrollArea.Thumb />
</ScrollArea.Scrollbar>
</ScrollArea.Root>
<GalleryBoardMenu
target={boardMenuTarget}
onBoardRelocated={handleBoardRelocated}
onClose={handleBoardMenuClose}
/>
<RenameDialog
cancelLabel={t('common.cancel')}
initialName={trimmedSearchTerm}
isOpen={createDialogTier !== null}
label={t('widgets.gallery.boardName')}
submitLabel={t('widgets.gallery.createBoard')}
submitUnchanged
title={t('widgets.gallery.createBoardIn', { destination: tierLabel(createDialogTier ?? 'project') })}
onClose={closeCreateDialog}
onSubmit={handleCreateDialogSubmit}
/>
</Stack>
);
};
/** Anywhere on the tier takes the drop, so a collapsed section still does. */
const GalleryBoardTierDropZone = ({
children,
dropScope,
label,
projectId,
}: {
children: ReactNode;
/** Another gallery's dragged boards neither land on it nor see it highlighted. */
dropScope: string;
label: string;
projectId: string | null;
}) => {
const { active } = useDndContext();
const canDrop = acceptsGalleryBoardMove(active?.data.current, projectId, dropScope);
const { isOver, setNodeRef } = useDroppable({
data: getGalleryBoardTierDropData(projectId, label, dropScope),
disabled: !canDrop,
id: getGalleryBoardTierDropId(projectId, dropScope),
});
return (
<Box
ref={setNodeRef}
// Outlines, so the highlight cannot reflow the list under the pointer.
bg={canDrop && isOver ? 'accent.muted' : undefined}
outline={canDrop ? (isOver ? '2px solid' : '1px dashed') : undefined}
outlineColor={canDrop ? 'accent.solid' : undefined}
outlineOffset="-2px"
rounded="sm"
transition="background var(--wb-motion-duration-fast) ease"
>
{children}
</Box>
);
};
const AddBoardButton = ({ label, onClick }: { label: string; onClick: () => void }): ReactNode => (
<Tooltip content={label}>
<IconButton aria-haspopup="dialog" aria-label={label} color="fg.muted" size="sm" variant="ghost" onClick={onClick}>
<Icon as={PlusIcon} boxSize="3.5" />
</IconButton>
</Tooltip>
);