feat: add navigation path in quick search (#1920)

This commit is contained in:
Qi 2023-04-13 16:31:28 +08:00 committed by GitHub
parent f20a151e57
commit 7d64815aca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
17 changed files with 450 additions and 47 deletions

View File

@ -2,6 +2,7 @@ import { Input } from '@affine/component';
import {
ArrowDownSmallIcon,
EdgelessIcon,
LevelIcon,
PageIcon,
PivotsIcon,
} from '@blocksuite/icons';
@ -19,17 +20,25 @@ import { OperationButton } from './OperationButton';
const getIcon = (type: 'root' | 'edgeless' | 'page') => {
switch (type) {
case 'root':
return <PivotsIcon />;
return <PivotsIcon className="mode-icon" />;
case 'edgeless':
return <EdgelessIcon />;
return <EdgelessIcon className="mode-icon" />;
default:
return <PageIcon />;
return <PageIcon className="mode-icon" />;
}
};
export const PinboardRender: PinboardNode['render'] = (
node,
{ isOver, onAdd, onDelete, collapsed, setCollapsed, isSelected },
{
isOver,
onAdd,
onDelete,
collapsed,
setCollapsed,
isSelected,
disableCollapse,
},
renderProps
) => {
const {
@ -38,6 +47,7 @@ export const PinboardRender: PinboardNode['render'] = (
currentMeta,
metas = [],
blockSuiteWorkspace,
asPath,
} = renderProps!;
const record = useAtomValue(workspacePreferredModeAtom);
const { setPageTitle } = usePageMetaHelper(blockSuiteWorkspace);
@ -60,17 +70,22 @@ export const PinboardRender: PinboardNode['render'] = (
onMouseLeave={() => setIsHover(false)}
isOver={isOver || isSelected}
active={active}
disableCollapse={!!disableCollapse}
>
<StyledCollapsedButton
collapse={collapsed}
show={!!node.children?.length}
onClick={e => {
e.stopPropagation();
setCollapsed(node.id, !collapsed);
}}
>
<ArrowDownSmallIcon />
</StyledCollapsedButton>
{!disableCollapse && (
<StyledCollapsedButton
collapse={collapsed}
show={!!node.children?.length}
onClick={e => {
e.stopPropagation();
setCollapsed(node.id, !collapsed);
}}
>
<ArrowDownSmallIcon />
</StyledCollapsedButton>
)}
{asPath && !isRoot ? <LevelIcon className="path-icon" /> : null}
{getIcon(isRoot ? 'root' : record[node.id])}
{showRename ? (

View File

@ -32,13 +32,14 @@ export const StyledPinboard = styled('div')<{
disable?: boolean;
active?: boolean;
isOver?: boolean;
}>(({ disable = false, active = false, theme, isOver }) => {
disableCollapse?: boolean;
}>(({ disableCollapse, disable = false, active = false, theme, isOver }) => {
return {
width: '100%',
height: '32px',
borderRadius: '8px',
...displayFlex('flex-start', 'center'),
padding: '0 2px 0 16px',
padding: disableCollapse ? '0 5px' : '0 2px 0 16px',
position: 'relative',
color: disable
? theme.colors.disableColor
@ -54,7 +55,11 @@ export const StyledPinboard = styled('div')<{
textAlign: 'left',
...textEllipsis(1),
},
'> svg': {
'.path-icon': {
fontSize: '16px',
transform: 'translateY(-4px)',
},
'.mode-icon': {
fontSize: '20px',
marginRight: '8px',
flexShrink: '0',

View File

@ -15,6 +15,7 @@ import {
import type { BlockSuiteWorkspace } from '../../../shared';
import { Footer } from './Footer';
import { NavigationPath } from './navigation-path';
import { PublishedResults } from './PublishedResults';
import { Results } from './Results';
import { SearchInput } from './SearchInput';
@ -106,8 +107,15 @@ export const QuickSearchModal: React.FC<QuickSearchModalProps> = ({
maxHeight: '80vh',
minHeight: isPublicAndNoQuery() ? '72px' : '412px',
top: '80px',
overflow: 'hidden',
}}
>
<NavigationPath
blockSuiteWorkspace={blockSuiteWorkspace}
onJumpToPage={() => {
setOpen(false);
}}
/>
<Command
shouldFilter={false}
//Handle KeyboardEvent conflicts with blocksuite

View File

@ -0,0 +1,166 @@
import { IconButton, Tooltip, TreeView } from '@affine/component';
import { useTranslation } from '@affine/i18n';
import {
ArrowRightSmallIcon,
CollapseIcon,
ExpandIcon,
MoreHorizontalIcon,
} from '@blocksuite/icons';
import type { PageMeta } from '@blocksuite/store';
import { useRouter } from 'next/router';
import type { MouseEvent } from 'react';
import { Fragment, useCallback, useMemo, useState } from 'react';
import { usePageMeta } from '../../../../hooks/use-page-meta';
import type { PinboardNode } from '../../../../hooks/use-pinboard-data';
import { usePinboardData } from '../../../../hooks/use-pinboard-data';
import { useRouterHelper } from '../../../../hooks/use-router-helper';
import type { BlockSuiteWorkspace } from '../../../../shared';
import { PinboardRender } from '../../../affine/pinboard';
import {
StyledNavigationPathContainer,
StyledNavPathExtendContainer,
StyledNavPathLink,
} from './styles';
import { calcHowManyPathShouldBeShown, findPath } from './utils';
export const NavigationPath = ({
blockSuiteWorkspace,
pageId: propsPageId,
onJumpToPage,
}: {
blockSuiteWorkspace: BlockSuiteWorkspace;
pageId?: string;
onJumpToPage?: (pageId: string) => void;
}) => {
const metas = usePageMeta(blockSuiteWorkspace);
const router = useRouter();
const { t } = useTranslation();
const [openExtend, setOpenExtend] = useState(false);
const pageId = propsPageId ?? router.query.pageId;
const { jumpToPage } = useRouterHelper(router);
const pathData = useMemo(() => {
const meta = metas.find(m => m.id === pageId);
const path = meta ? findPath(metas, meta) : [];
const actualPath = calcHowManyPathShouldBeShown(path);
return {
hasEllipsis: path.length !== actualPath.length,
path: actualPath,
};
}, [metas, pageId]);
if (pathData.path.length < 2) {
// Means there is no parent page
return null;
}
return (
<>
<StyledNavigationPathContainer data-testid="navigation-path">
{openExtend ? (
<span>{t('Navigation Path')}</span>
) : (
pathData.path.map((meta, index) => {
const isLast = index === pathData.path.length - 1;
const showEllipsis = pathData.hasEllipsis && index === 1;
return (
<Fragment key={meta.id}>
{showEllipsis && (
<>
<IconButton
size="small"
onClick={() => setOpenExtend(true)}
>
<MoreHorizontalIcon />
</IconButton>
<ArrowRightSmallIcon className="path-arrow" />
</>
)}
<StyledNavPathLink
data-testid="navigation-path-link"
active={isLast}
onClick={() => {
if (isLast) return;
jumpToPage(blockSuiteWorkspace.id, meta.id);
onJumpToPage?.(meta.id);
}}
title={meta.title}
>
{meta.title}
</StyledNavPathLink>
{!isLast && <ArrowRightSmallIcon className="path-arrow" />}
</Fragment>
);
})
)}
<Tooltip
content={
openExtend ? t('Back to Quick Search') : t('View Navigation Path')
}
placement="top"
disablePortal={true}
>
<IconButton
data-testid="navigation-path-expand-btn"
size="middle"
className="collapse-btn"
onClick={() => {
setOpenExtend(!openExtend);
}}
>
{openExtend ? <CollapseIcon /> : <ExpandIcon />}
</IconButton>
</Tooltip>
</StyledNavigationPathContainer>
<NavigationPathExtendPanel
open={openExtend}
blockSuiteWorkspace={blockSuiteWorkspace}
metas={metas}
onJumpToPage={onJumpToPage}
/>
</>
);
};
const NavigationPathExtendPanel = ({
open,
metas,
blockSuiteWorkspace,
onJumpToPage,
}: {
open: boolean;
metas: PageMeta[];
blockSuiteWorkspace: BlockSuiteWorkspace;
onJumpToPage?: (pageId: string) => void;
}) => {
const router = useRouter();
const { jumpToPage } = useRouterHelper(router);
const handlePinboardClick = useCallback(
(e: MouseEvent<HTMLDivElement>, node: PinboardNode) => {
jumpToPage(blockSuiteWorkspace.id, node.id);
onJumpToPage?.(node.id);
},
[blockSuiteWorkspace.id, jumpToPage, onJumpToPage]
);
const { data } = usePinboardData({
metas,
pinboardRender: PinboardRender,
blockSuiteWorkspace: blockSuiteWorkspace,
onClick: handlePinboardClick,
asPath: true,
});
return (
<StyledNavPathExtendContainer
show={open}
data-testid="navigation-path-expand-panel"
>
<div className="tree-container">
<TreeView data={data} indent={10} disableCollapse={true} />
</div>
</StyledNavPathExtendContainer>
);
};

View File

@ -0,0 +1,66 @@
import { displayFlex, styled, textEllipsis } from '@affine/component';
export const StyledNavigationPathContainer = styled('div')(({ theme }) => {
return {
height: '46px',
...displayFlex('flex-start', 'center'),
background: theme.colors.hubBackground,
padding: '0 40px 0 20px',
position: 'relative',
fontSize: theme.font.sm,
zIndex: 2,
'.collapse-btn': {
position: 'absolute',
right: '12px',
top: 0,
bottom: 0,
margin: 'auto',
},
'.path-arrow': {
fontSize: '16px',
color: theme.colors.iconColor,
},
};
});
export const StyledNavPathLink = styled('div')<{ active?: boolean }>(
({ theme, active }) => {
return {
color: active ? theme.colors.textColor : theme.colors.secondaryTextColor,
cursor: active ? 'auto' : 'pointer',
maxWidth: '160px',
...textEllipsis(1),
padding: '0 4px',
transition: 'background .15s',
':hover': active
? {}
: {
background: theme.colors.hoverBackground,
borderRadius: '4px',
},
};
}
);
export const StyledNavPathExtendContainer = styled('div')<{ show: boolean }>(
({ show, theme }) => {
return {
position: 'absolute',
left: '0',
top: show ? '0' : '-100%',
zIndex: '1',
height: '100%',
width: '100%',
background: theme.colors.hubBackground,
transition: 'top .15s',
fontSize: theme.font.sm,
color: theme.colors.secondaryTextColor,
paddingTop: '46px',
paddingRight: '12px',
'.tree-container': {
padding: '0 12px 0 15px',
},
};
}
);

View File

@ -0,0 +1,60 @@
import type { PageMeta } from '@blocksuite/store';
export function findPath(metas: PageMeta[], meta: PageMeta): PageMeta[] {
function helper(group: PageMeta[]): PageMeta[] {
const last = group[group.length - 1];
const parent = metas.find(m => m.subpageIds.includes(last.id));
if (parent) {
return helper([...group, parent]);
}
return group;
}
return helper([meta]).reverse();
}
function getPathItemWidth(content: string) {
// padding is 8px, arrow is 16px, and each char is 10px
// the max width is 160px
const charWidth = 10;
const w = content.length * charWidth + 8 + 16;
return w > 160 ? 160 : w;
}
// XXX: this is a static way to calculate the path width, not get the real width
export function calcHowManyPathShouldBeShown(path: PageMeta[]): PageMeta[] {
if (path.length === 0) {
return [];
}
const first = path[0];
const last = path[path.length - 1];
// 20 is the ellipsis icon width
const maxWidth = 550 - 20;
if (first.id === last.id) {
return [first];
}
function getMiddlePath(restWidth: number, restPath: PageMeta[]): PageMeta[] {
if (restPath.length === 0) {
return [];
}
const last = restPath[restPath.length - 1];
const w = getPathItemWidth(last.title);
if (restWidth - w > 80) {
return [
...getMiddlePath(restWidth - w, restPath.slice(0, restPath.length - 1)),
last,
];
}
return [];
}
return [
first,
...getMiddlePath(
maxWidth - getPathItemWidth(first.title),
path.slice(1, -1)
),
last,
];
}

View File

@ -114,9 +114,7 @@ export const StyledModalDivider = styled('div')(({ theme }) => {
width: 'auto',
height: '0',
margin: '6px 16px',
position: 'relative',
borderTop: `0.5px solid ${theme.colors.borderColor}`,
transition: 'all 0.15s',
};
});

View File

@ -9,6 +9,8 @@ export type RenderProps = {
blockSuiteWorkspace: BlockSuiteWorkspace;
onClick?: (e: MouseEvent<HTMLDivElement>, node: PinboardNode) => void;
showOperationButton?: boolean;
// If true, the node will be rendered with path icon at start
asPath?: boolean;
};
export type NodeRenderProps = RenderProps & {
@ -57,6 +59,7 @@ export function usePinboardData({
blockSuiteWorkspace,
onClick,
showOperationButton,
asPath,
}: {
metas: PageMeta[];
pinboardRender: PinboardNode['render'];
@ -67,8 +70,16 @@ export function usePinboardData({
blockSuiteWorkspace,
onClick,
showOperationButton,
asPath,
}),
[blockSuiteWorkspace, metas, onClick, pinboardRender, showOperationButton]
[
asPath,
blockSuiteWorkspace,
metas,
onClick,
pinboardRender,
showOperationButton,
]
);
return {

View File

@ -12,8 +12,8 @@ const SIZE_CONFIG = {
areaSize: 20,
},
[SIZE_MIDDLE]: {
iconSize: 20,
areaSize: 28,
iconSize: 16,
areaSize: 24,
},
[SIZE_NORMAL]: {
iconSize: 24,

View File

@ -105,6 +105,7 @@ const TreeNodeItem = <RenderProps,>({
onAdd,
onDelete,
dropRef,
disableCollapse,
}: TreeNodeItemProps<RenderProps>) => {
return (
<div ref={dropRef}>
@ -115,6 +116,7 @@ const TreeNodeItem = <RenderProps,>({
collapsed,
setCollapsed,
isSelected: selectedId === node.id,
disableCollapse,
})}
</div>
);

View File

@ -12,6 +12,7 @@ export const TreeView = <RenderProps,>({
onSelect,
enableDnd = true,
initialCollapsedIds = [],
disableCollapse,
...otherProps
}: TreeViewProps<RenderProps>) => {
const [selectedId, setSelectedId] = useState<string>();
@ -62,6 +63,9 @@ export const TreeView = <RenderProps,>({
}, [data, selectedId]);
const setCollapsed: TreeNodeProps['setCollapsed'] = (id, collapsed) => {
if (disableCollapse) {
return;
}
if (collapsed) {
setCollapsedIds(ids => [...ids, id]);
} else {
@ -81,6 +85,7 @@ export const TreeView = <RenderProps,>({
node={node}
selectedId={selectedId}
enableDnd={enableDnd}
disableCollapse={disableCollapse}
{...otherProps}
/>
))}
@ -99,6 +104,7 @@ export const TreeView = <RenderProps,>({
node={node}
selectedId={selectedId}
enableDnd={enableDnd}
disableCollapse={disableCollapse}
{...otherProps}
/>
))}

View File

@ -23,6 +23,7 @@ export type Node<RenderProps = unknown> = {
collapsed: boolean;
setCollapsed: (id: string, collapsed: boolean) => void;
isSelected: boolean;
disableCollapse?: ReactNode;
},
renderProps?: RenderProps
) => ReactNode;
@ -39,6 +40,7 @@ type CommonProps<RenderProps = unknown> = {
onDrop?: OnDrop;
// Only trigger when the enableKeyboardSelection is true
onSelect?: (id: string) => void;
disableCollapse?: ReactNode;
};
export type TreeNodeProps<RenderProps = unknown> = {
@ -65,6 +67,7 @@ export type TreeNodeItemProps<RenderProps = unknown> = {
export type TreeViewProps<RenderProps = unknown> = {
data: Node<RenderProps>[];
initialCollapsedIds?: string[];
disableCollapse?: boolean;
} & CommonProps<RenderProps>;
export type NodeLIneProps<RenderProps = unknown> = {

View File

@ -201,5 +201,8 @@
"Move page to...": "Move page to...",
"Remove from Pivots": "Remove from Pivots",
"RFP": "Pages can be freely added/removed from pivots, remaining accessible from \"All Pages\".",
"Discover what's new!": "Discover what's new!"
"Discover what's new!": "Discover what's new!",
"Navigation Path": "Navigation Path",
"View Navigation Path": "View Navigation Path",
"Back to Quick Search": "Back to Quick Search"
}

View File

@ -1,6 +1,14 @@
import type { Page } from '@playwright/test';
import { getMetas } from './utils';
export async function openHomePage(page: Page) {
await page.goto('http://localhost:8080');
await page.waitForSelector('#__next');
}
export async function initHomePageWithPinboard(page: Page) {
await openHomePage(page);
await page.waitForSelector('[data-testid="sidebar-pinboard-container"]');
return (await getMetas(page)).find(m => m.isRootPinboard);
}

View File

@ -27,3 +27,21 @@ export async function clickPageMoreActions(page: Page) {
.getByTestId('editor-option-menu')
.click();
}
export async function createPinboardPage(
page: Page,
parentId: string,
title: string
) {
await newPage(page);
await page.focus('.affine-default-page-block-title');
await page.type('.affine-default-page-block-title', title, {
delay: 100,
});
await clickPageMoreActions(page);
await page.getByTestId('move-to-menu-item').click();
await page
.getByTestId('pinboard-menu')
.getByTestId(`pinboard-${parentId}`)
.click();
}

View File

@ -1,31 +1,11 @@
import type { Page } from '@playwright/test';
import { expect } from '@playwright/test';
import { openHomePage } from '../libs/load-page';
import { clickPageMoreActions, newPage } from '../libs/page-logic';
import { initHomePageWithPinboard } from '../libs/load-page';
import { createPinboardPage } from '../libs/page-logic';
import { test } from '../libs/playwright';
import { getMetas } from '../libs/utils';
async function createPinboardPage(page: Page, parentId: string, title: string) {
await newPage(page);
await page.focus('.affine-default-page-block-title');
await page.type('.affine-default-page-block-title', title, {
delay: 100,
});
await clickPageMoreActions(page);
await page.getByTestId('move-to-menu-item').click();
await page
.getByTestId('pinboard-menu')
.getByTestId(`pinboard-${parentId}`)
.click();
}
async function initHomePageWithPinboard(page: Page) {
await openHomePage(page);
await page.waitForSelector('[data-testid="sidebar-pinboard-container"]');
return (await getMetas(page)).find(m => m.isRootPinboard);
}
async function openPinboardPageOperationMenu(page: Page, id: string) {
const node = await page
.getByTestId('sidebar-pinboard-container')

View File

@ -1,8 +1,12 @@
import { expect, type Page } from '@playwright/test';
import { withCtrlOrMeta } from '../libs/keyboard';
import { openHomePage } from '../libs/load-page';
import { newPage, waitMarkdownImported } from '../libs/page-logic';
import { initHomePageWithPinboard, openHomePage } from '../libs/load-page';
import {
createPinboardPage,
newPage,
waitMarkdownImported,
} from '../libs/page-logic';
import { test } from '../libs/playwright';
const openQuickSearchByShortcut = async (page: Page) =>
@ -204,4 +208,54 @@ test.describe('Novice guidance for quick search', () => {
await page.getByTestId('sliderBar-arrowButton-collapse').click();
await expect(quickSearchTips).not.toBeVisible();
});
test('Show navigation path if page is a subpage', async ({ page }) => {
const rootPinboardMeta = await initHomePageWithPinboard(page);
await createPinboardPage(page, rootPinboardMeta?.id ?? '', 'test1');
await openQuickSearchByShortcut(page);
expect(await page.getByTestId('navigation-path').count()).toBe(1);
});
test('Not show navigation path if page is not a subpage or current page is not in editor', async ({
page,
}) => {
await openHomePage(page);
await waitMarkdownImported(page);
await openQuickSearchByShortcut(page);
expect(await page.getByTestId('navigation-path').count()).toBe(0);
});
test('Navigation path item click will jump to page, but not current active item', async ({
page,
}) => {
const rootPinboardMeta = await initHomePageWithPinboard(page);
await createPinboardPage(page, rootPinboardMeta?.id ?? '', 'test1');
await openQuickSearchByShortcut(page);
const oldUrl = page.url();
expect(
await page.locator('[data-testid="navigation-path-link"]').count()
).toBe(2);
await page.locator('[data-testid="navigation-path-link"]').nth(1).click();
expect(page.url()).toBe(oldUrl);
await page.locator('[data-testid="navigation-path-link"]').nth(0).click();
expect(page.url()).not.toBe(oldUrl);
});
test('Navigation path expand', async ({ page }) => {
//
const rootPinboardMeta = await initHomePageWithPinboard(page);
await createPinboardPage(page, rootPinboardMeta?.id ?? '', 'test1');
await openQuickSearchByShortcut(page);
const top = await page
.getByTestId('navigation-path-expand-panel')
.evaluate(el => {
return window.getComputedStyle(el).getPropertyValue('top');
});
expect(parseInt(top)).toBeLessThan(0);
await page.getByTestId('navigation-path-expand-btn').click();
await page.waitForTimeout(500);
const expandTop = await page
.getByTestId('navigation-path-expand-panel')
.evaluate(el => {
return window.getComputedStyle(el).getPropertyValue('top');
});
expect(expandTop).toBe('0px');
});
});