Skip to content

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.

refactor(webv2): render the font library with the shared list

Josh Corbett968206b5ddbc
diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsx
index 2576df353a..5492433b32 100644
--- a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.browser.test.tsx
@@ -5,7 +5,7 @@ import { system } from '@theme/system';
import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { page } from 'vitest/browser';
+import { page, userEvent } from 'vitest/browser';
const dependencies = vi.hoisted(() => ({
canManageSharedFonts: false,
@@ -60,6 +60,9 @@ const font = {
let host: HTMLDivElement;
let root: Root;
+
+const pagerButton = (text: string): HTMLButtonElement | null =>
+ [...host.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent === text) ?? null;
let queryClient: QueryClient;
const renderPage = async (): Promise<void> => {
@@ -115,16 +118,17 @@ describe('FontsPage', () => {
await renderPage();
await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));
await vi.waitFor(() => expect(dependencies.ensure).toHaveBeenCalledOnce());
- const row = host.querySelector<HTMLElement>('[role="button"][aria-pressed="false"]');
+ const row = host.querySelector<HTMLButtonElement>('[role="listitem"] [data-list-primary]:not([aria-current])');
expect(row).not.toBeNull();
expect(row!.textContent).toContain('Aa');
expect(dependencies.retain).not.toHaveBeenCalled();
await act(() => {
row!.focus();
- row!.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' }));
});
+ expect(document.activeElement).toBe(row);
+ await userEvent.keyboard('{Enter}');
await vi.waitFor(() => expect(dependencies.ensure).toHaveBeenCalledTimes(2));
- expect(row!.getAttribute('aria-pressed')).toBe('true');
+ expect(row!.getAttribute('aria-current')).toBe('true');
expect(dependencies.retain).toHaveBeenCalledOnce();
expect(host.querySelector('h3')?.textContent).toBe('Example Sans Regular');
expect(host.textContent).toContain('fonts.previewText');
@@ -178,7 +182,7 @@ describe('FontsPage', () => {
await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));
expect(requestedOffsets).toEqual([0]);
- const nextPageButton = host.querySelector<HTMLButtonElement>('button[aria-label="common.nextPage"]');
+ const nextPageButton = pagerButton('common.nextPage');
expect(nextPageButton).not.toBeNull();
await act(() => nextPageButton!.click());
await vi.waitFor(() => expect(host.textContent).toContain('Second Page Font'));
@@ -203,15 +207,15 @@ describe('FontsPage', () => {
await renderPage();
await vi.waitFor(() => expect(host.textContent).toContain('Example Sans Regular'));
- const nextPageButton = host.querySelector<HTMLButtonElement>('button[aria-label="common.nextPage"]');
+ const nextPageButton = pagerButton('common.nextPage');
expect(nextPageButton).not.toBeNull();
await act(() => nextPageButton!.click());
await vi.waitFor(() => expect(host.textContent).toContain('fonts.emptyTitle'));
- const previousPageButton = host.querySelector<HTMLButtonElement>('button[aria-label="common.previousPage"]');
+ const previousPageButton = pagerButton('common.previousPage');
expect(previousPageButton).not.toBeNull();
- expect(previousPageButton).toBeEnabled();
+ expect(previousPageButton!.getAttribute('aria-disabled')).toBe('false');
expect(requestedOffsets).toEqual([0, 100]);
});
@@ -229,16 +233,21 @@ describe('FontsPage', () => {
await renderPage();
await vi.waitFor(() => expect(host.querySelector('[data-index="0"]')).not.toBeNull());
queryClient.setQueryData(['fonts', { limit: 100, scope: 'private', search: '' }], data);
- const viewport = host.querySelector<HTMLElement>('[aria-label="fonts.library"]')!;
+ const viewport = () => host.querySelector<HTMLElement>('[data-list-viewport]')!;
await act(() => {
- viewport.scrollTop = 800;
- viewport.dispatchEvent(new Event('scroll'));
+ viewport().scrollTop = 800;
+ viewport().dispatchEvent(new Event('scroll'));
});
- await vi.waitFor(() => expect(viewport.scrollTop).toBe(800));
+ await vi.waitFor(() => expect(viewport().scrollTop).toBe(800));
await page.getByRole('button', { name: 'fonts.filterMenu', exact: true }).click();
await page.getByRole('menuitemradio', { name: 'fonts.filters.my', exact: true }).click();
- await vi.waitFor(() => expect(viewport.scrollTop).toBe(0));
- expect(host.querySelector('[data-index="0"]')).not.toBeNull();
+ // The filtered list is a fresh viewport at the top, with its first row directly under the pinned chrome.
+ await vi.waitFor(() => {
+ expect(viewport().scrollTop).toBe(0);
+ const firstRow = host.querySelector<HTMLElement>('[data-index="0"]');
+ expect(firstRow).not.toBeNull();
+ expect(firstRow!.getBoundingClientRect().top).toBeCloseTo(viewport().getBoundingClientRect().top, 0);
+ });
});
it('keeps the library rows directly below search after the page is hidden and shown', async () => {
@@ -253,7 +262,7 @@ describe('FontsPage', () => {
queryKey: ['fonts', params],
}));
await renderPage();
- const firstRow = () => host.querySelector<HTMLElement>('[data-index="0"] [role="button"]');
+ const firstRow = () => host.querySelector<HTMLElement>('[data-index="0"] [data-list-primary]');
await vi.waitFor(() => expect(firstRow()).not.toBeNull());
const search = host.querySelector<HTMLInputElement>('input[aria-label="fonts.searchLabel"]')!;
for (let index = 0; index < 3; index += 1) {
diff --git a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx
index fb4b902a1b..47b089410f 100644
--- a/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx
+++ b/invokeai/frontend/webv2/src/features/fonts/ui/FontsPage.tsx
@@ -1,10 +1,10 @@
-/* eslint-disable react-perf/jsx-no-new-function-as-prop */
+/* eslint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop */
+import type { ListRowProps } from '@platform/ui/list/List';
import type { ChangeEvent } from 'react';
import {
Badge,
Box,
- Center,
Flex,
HStack,
Icon,
@@ -38,11 +38,14 @@ import {
isAccountScopeCurrent,
} from '@platform/state/accountLifecycle';
import { getApiErrorMessage } from '@platform/transport/http';
-import { Button, ConfirmDialog, IconButton, Row, Scrollable, SegmentedControl, Tabs } from '@platform/ui';
+import { Button, ConfirmDialog, IconButton, Scrollable, SegmentedControl, Tabs } from '@platform/ui';
import { EmptyState } from '@platform/ui/EmptyState';
+import { List } from '@platform/ui/list/List';
+import { ListItem } from '@platform/ui/list/ListItem';
+import { ListPager } from '@platform/ui/list/ListPager';
+import { listRowsFromItems } from '@platform/ui/list/listRows';
import { MenuContent } from '@platform/ui/Menu';
import { useQuery, useQueryClient } from '@tanstack/react-query';
-import { useVirtualizer } from '@tanstack/react-virtual';
import {
ArrowRightIcon,
CircleAlertIcon,
@@ -60,7 +63,8 @@ import { useTranslation } from 'react-i18next';
const FONT_ACCEPT = '.ttf,.otf,.woff,.woff2,font/ttf,font/otf,font/woff,font/woff2';
const FONT_PAGE_SIZE = 100;
-const FONT_ROW_HEIGHT = 56;
+const NO_FONTS: readonly FontRecord[] = [];
+const getFontId = (font: FontRecord): string => font.id;
// Match the Models and Nodes manager columns without coupling feature owners.
const LIBRARY_WIDTH = 'clamp(22rem, 32vw, 28rem)';
const HEADER_MIN_HEIGHT = '2.75rem';
@@ -312,7 +316,6 @@ const FontLibrary = () => {
const [deleteTarget, setDeleteTarget] = useState<FontRecord | null>(null);
const [isRescanning, setIsRescanning] = useState(false);
const inputRef = useRef<HTMLInputElement | null>(null);
- const scrollRef = useRef<HTMLDivElement | null>(null);
const uploadChainRef = useRef<Promise<void>>(Promise.resolve());
const [offset, setOffset] = useState(0);
const params = useMemo<FontListParams>(
@@ -325,15 +328,11 @@ const FontLibrary = () => {
[filter, offset, search]
);
const query = useQuery(fontsQueryOptions(params));
- const fonts = query.data?.items ?? [];
- // eslint-disable-next-line react/incompatible-library -- TanStack Virtual exposes imperative functions that the compiler cannot memoize safely.
- const virtualizer = useVirtualizer({
- count: fonts.length,
- estimateSize: () => FONT_ROW_HEIGHT,
- getItemKey: (index) => fonts[index]?.id ?? index,
- getScrollElement: () => scrollRef.current,
- overscan: 4,
- });
+ const fonts = query.data?.items ?? NO_FONTS;
+ const rows = useMemo(() => listRowsFromItems(fonts, getFontId), [fonts]);
+ // A new page, filter or search replaces every row: remount the list so it starts from the top whether or not
+ // the query is cached.
+ const listKey = `${filter}:${offset}:${search}`;
const invalidateFonts = useCallback(() => queryClient.invalidateQueries({ queryKey: fontKeys.all }), [queryClient]);
const handleFiles = useCallback(
@@ -478,15 +477,13 @@ const FontLibrary = () => {
const hasPreviousPage = offset > 0;
const hasNextPage = query.data !== undefined && offset + fonts.length < query.data.total;
const handlePreviousPage = useCallback(() => {
- virtualizer.scrollToOffset(0);
setOffset((current) => Math.max(0, current - FONT_PAGE_SIZE));
- }, [virtualizer]);
+ }, []);
const handleNextPage = useCallback(() => {
if (hasNextPage) {
- virtualizer.scrollToOffset(0);
setOffset((current) => current + FONT_PAGE_SIZE);
}
- }, [hasNextPage, virtualizer]);
+ }, [hasNextPage]);
const showPagination = offset > 0 || (query.data?.total ?? 0) > FONT_PAGE_SIZE;
const canDelete = useCallback(
(font: FontRecord) => font.source === 'uploaded' && (font.scope === 'private' || canManageSharedFonts),
@@ -533,7 +530,6 @@ const FontLibrary = () => {
size="xs"
value={search}
onChange={(event) => {
- virtualizer.scrollToOffset(0);
setSearch(event.currentTarget.value);
setOffset(0);
}}
@@ -556,7 +552,6 @@ const FontLibrary = () => {
<Menu.RadioItemGroup
value={filter}
onValueChange={(event) => {
- virtualizer.scrollToOffset(0);
setFilter(event.value as FontFilter);
setOffset(0);
}}
@@ -576,138 +571,79 @@ const FontLibrary = () => {
</Portal>
</Menu.Root>
</HStack>
- {query.isPending ? (
- <Center flex="1" minH="32">
- <Spinner color="fg.muted" size="sm" />
- </Center>
- ) : query.isError ? (
- <EmptyState
- danger
- description={getApiErrorMessage(query.error, t('fonts.couldNotLoad'))}
- icon={ERROR_ICON}
- title={t('fonts.couldNotLoad')}
- >
- <Button size="xs" variant="outline" onClick={handleRetry}>
- {t('common.retry')}
- </Button>
- </EmptyState>
- ) : fonts.length === 0 ? (
- <EmptyState
- description={search.trim() ? t('fonts.noSearchMatchesDescription') : t('fonts.emptyDescription')}
- icon={search.trim() ? EMPTY_SEARCH_ICON : EMPTY_ICON}
- title={search.trim() ? t('fonts.noSearchMatches') : t('fonts.emptyTitle')}
- >
- {search.trim() ? (
- <Button
- size="xs"
- variant="outline"
- onClick={() => {
- virtualizer.scrollToOffset(0);
- setSearch('');
- setOffset(0);
- }}
- >
- {t('common.clearSearch')}
- </Button>
- ) : (
- <Button size="sm" onClick={() => setActiveTab('add')}>
- {t('fonts.addFonts')}
- <Icon as={ArrowRightIcon} />
- </Button>
- )}
- </EmptyState>
- ) : (
- <Scrollable flex="1" h="full" label={t('fonts.library')} minH="0" viewportRef={scrollRef}>
- <Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">
- {virtualizer.getVirtualItems().map((item) => {
- const font = fonts[item.index];
- if (!font) {
- return null;
- }
- return (
- <Box
- data-index={item.index}
- key={item.key}
- left="0"
- position="absolute"
- h={`${FONT_ROW_HEIGHT}px`}
- top="0"
- transform={`translateY(${item.start}px)`}
- w="full"
- >
- <Box h="full" px="3" py="0.5">
- <Row
- active={selectedFont?.id === font.id ? 'accent' : 'none'}
- aria-pressed={selectedFont?.id === font.id}
- gap="2"
- h="full"
- minW="0"
- overflow="hidden"
- px="2"
- py="2"
- role="button"
- rounded="md"
- tabIndex={0}
- onClick={() => {
- setSelectedFont(font);
- setActiveTab('details');
- }}
- onKeyDown={(event) => {
- if (event.key === 'Enter' || event.key === ' ') {
- event.preventDefault();
- setSelectedFont(font);
- setActiveTab('details');
- }
- }}
- >
- <FontPreview
- compact
- key={`${font.id}:${font.contentHash}:${font.style}:${font.weight}`}
- font={font}
- />
- <Stack gap="0.5" minW="0" flex="1">
- <Text fontSize="xs" fontWeight="600" truncate>
- {font.label || font.family}
- </Text>
- <Text fontSize="2xs" opacity="0.75" truncate>
- {font.filename}
- </Text>
- </Stack>
- <Badge flexShrink={0} fontSize="2xs" variant="surface">
- {t(getScopeLabelKey(font.scope))}
- </Badge>
- </Row>
- </Box>
- </Box>
- );
- })}
- </Box>
- </Scrollable>
- )}
- {showPagination ? (
- <HStack justify="center" minH="8">
- <Button
- aria-label={t('common.previousPage')}
- disabled={!hasPreviousPage || query.isFetching}
- size="2xs"
- variant="ghost"
- onClick={handlePreviousPage}
+ <List
+ key={listKey}
+ activeKey={selectedFont?.id ?? null}
+ density="comfortable"
+ emptyState={
+ <EmptyState
+ description={search.trim() ? t('fonts.noSearchMatchesDescription') : t('fonts.emptyDescription')}
+ icon={search.trim() ? EMPTY_SEARCH_ICON : EMPTY_ICON}
+ title={search.trim() ? t('fonts.noSearchMatches') : t('fonts.emptyTitle')}
>
- {t('common.previousPage')}
- </Button>
- <Text aria-live="polite" color="fg.muted" fontSize="2xs">
- {t('common.pageNumber', { page: Math.floor(offset / FONT_PAGE_SIZE) + 1 })}
- </Text>
- <Button
- aria-label={t('common.nextPage')}
- disabled={!hasNextPage || query.isFetching}
- size="2xs"
- variant="ghost"
- onClick={handleNextPage}
+ {search.trim() ? (
+ <Button
+ size="xs"
+ variant="outline"
+ onClick={() => {
+ setSearch('');
+ setOffset(0);
+ }}
+ >
+ {t('common.clearSearch')}
+ </Button>
+ ) : (
+ <Button size="sm" onClick={() => setActiveTab('add')}>
+ {t('fonts.addFonts')}
+ <Icon as={ArrowRightIcon} />
+ </Button>
+ )}
+ </EmptyState>
+ }
+ errorState={
+ <EmptyState
+ danger
+ description={query.isError ? getApiErrorMessage(query.error, t('fonts.couldNotLoad')) : null}
+ icon={ERROR_ICON}
+ title={t('fonts.couldNotLoad')}
>
- {t('common.nextPage')}
- </Button>
- </HStack>
+ <Button size="xs" variant="outline" onClick={handleRetry}>
+ {t('common.retry')}
+ </Button>
+ </EmptyState>
+ }
+ label={t('fonts.library')}
+ renderItem={(font: FontRecord, rowProps: ListRowProps) => (
+ <ListItem
+ {...rowProps}
+ description={font.filename}
+ leading={
+ <FontPreview compact key={`${font.id}:${font.contentHash}:${font.style}:${font.weight}`} font={font} />
+ }
+ title={font.label || font.family}
+ trailing={
+ <Badge fontSize="2xs" variant="surface">
+ {t(getScopeLabelKey(font.scope))}
+ </Badge>
+ }
+ onPress={() => {
+ setSelectedFont(font);
+ setActiveTab('details');
+ }}
+ />
+ )}
+ rows={rows}
+ status={query.isPending ? 'loading' : query.isError ? 'error' : 'ready'}
+ />
+ {showPagination ? (
+ <ListPager
+ hasNext={hasNextPage}
+ hasPrevious={hasPreviousPage}
+ isBusy={query.isFetching}
+ page={Math.floor(offset / FONT_PAGE_SIZE) + 1}
+ onNext={handleNextPage}
+ onPrevious={handlePreviousPage}
+ />
) : null}
</Flex>
<Tabs.Root