Compare commits

...

11 Commits

Author SHA1 Message Date
Peng Xiao
42756045bb fix: failed to load blobs in electron (#1927) 2023-04-13 15:14:46 +00:00
Peng Xiao
934e242116 fix: electron sourcemap issues (#1919) 2023-04-13 08:37:50 -05:00
Qi
6571ec2df6 fix: pinboard operation menu disappear inexplicably when hover to menu from button, fixed #1898 (#1922) 2023-04-13 07:58:22 -05:00
Qi
7d64815aca feat: add navigation path in quick search (#1920) 2023-04-13 16:31:28 +08:00
Himself65
f20a151e57 fix(y-indexeddb): migration in firefox (#1904) 2023-04-12 22:42:17 -05:00
Himself65
6180a4c3cb fix: wrap React.lazy with Suspense (#1915) 2023-04-12 22:33:31 -05:00
Himself65
2bcda973d3 build: support sourcemap in sentry (#1910) 2023-04-12 21:26:06 -05:00
Himself65
1162bffb30 build: support sentry replay (#1908) 2023-04-12 21:18:41 -05:00
Himself65
2a2d682211 fix: cannot update a component while rendering a different component (#1907) 2023-04-12 16:46:29 -05:00
Sirocco
8f53043100 fix: improve UX of dropdown (#1905)
Removed the logic of onMouseLeave. The logic of clicking to open and clicking to close is clearer.

Fixes: #1898
2023-04-12 15:35:41 -05:00
Himself65
6d5b101bb3 fix: use startTransition (#1903) 2023-04-12 12:06:22 -05:00
42 changed files with 857 additions and 262 deletions

View File

@@ -1,16 +1,10 @@
import type { RequestInit } from 'undici';
import { fetch, ProxyAgent } from 'undici';
const redirectUri = 'https://affine.pro/client/auth-callback';
export const oauthEndpoint = `https://accounts.google.com/o/oauth2/v2/auth?client_id=${process.env.AFFINE_GOOGLE_CLIENT_ID}&redirect_uri=${redirectUri}&response_type=code&scope=openid https://www.googleapis.com/auth/userinfo.email profile&access_type=offline&customParameters={"prompt":"select_account"}`;
const tokenEndpoint = 'https://oauth2.googleapis.com/token';
export const exchangeToken = async (code: string) => {
const httpProxy = process.env.HTTP_PROXY || process.env.http_proxy;
const proxyAgent = httpProxy ? new ProxyAgent(httpProxy) : undefined;
export const getExchangeTokenParams = (code: string) => {
const postData = {
code,
client_id: process.env.AFFINE_GOOGLE_CLIENT_ID || '',
@@ -18,15 +12,12 @@ export const exchangeToken = async (code: string) => {
redirect_uri: redirectUri,
grant_type: 'authorization_code',
};
const requestOptions: RequestInit = {
const requestInit: RequestInit = {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(postData).toString(),
dispatcher: proxyAgent,
};
return fetch(tokenEndpoint, requestOptions).then(response => {
return response.json();
});
return { requestInit, url: tokenEndpoint };
};

View File

@@ -7,7 +7,7 @@ import { BrowserWindow, ipcMain, nativeTheme } from 'electron';
import fs from 'fs-extra';
import { parse } from 'url';
import { exchangeToken, oauthEndpoint } from './google-auth';
import { getExchangeTokenParams, oauthEndpoint } from './google-auth';
const AFFINE_ROOT = path.join(os.homedir(), '.affine');
@@ -40,23 +40,24 @@ export const registerHandlers = () => {
logger.info('sidebar visibility change', visible);
});
ipcMain.handle('ui:google-sign-in', async () => {
ipcMain.handle('ui:get-google-oauth-code', async () => {
logger.info('starting google sign in ...');
shell.openExternal(oauthEndpoint);
return new Promise<string>((resolve, reject) => {
return new Promise((resolve, reject) => {
const handleOpenUrl = async (_: any, url: string) => {
const mainWindow = BrowserWindow.getAllWindows().find(
w => !w.isDestroyed()
);
const urlObj = parse(url.replace('??', '?'), true);
if (!mainWindow || !url.startsWith('affine://')) return;
const token = (await exchangeToken(urlObj.query['code'] as string)) as {
id_token: string;
};
if (!mainWindow || !url.startsWith('affine://auth-callback')) return;
const code = urlObj.query['code'] as string;
if (!code) return;
logger.info('google sign in code received from callback', code);
app.removeListener('open-url', handleOpenUrl);
resolve(token.id_token);
logger.info('google sign in successful', token);
resolve(getExchangeTokenParams(code));
};
app.on('open-url', handleOpenUrl);
@@ -64,7 +65,7 @@ export const registerHandlers = () => {
setTimeout(() => {
reject(new Error('Timed out'));
app.removeListener('open-url', handleOpenUrl);
}, 60000);
}, 30000);
});
});

View File

@@ -1,23 +1,50 @@
import { protocol, session } from 'electron';
import { join } from 'path';
protocol.registerSchemesAsPrivileged([
{
scheme: 'assets',
privileges: {
secure: false,
corsEnabled: true,
supportFetchAPI: true,
standard: true,
bypassCSP: true,
},
},
]);
function toAbsolutePath(url: string) {
let realpath = decodeURIComponent(url);
const webStaticDir = join(__dirname, '../../../resources/web-static');
if (url.startsWith('./')) {
// if is a file type, load the file in resources
if (url.split('/').at(-1)?.includes('.')) {
realpath = join(webStaticDir, decodeURIComponent(url));
} else {
// else, fallback to load the index.html instead
realpath = join(webStaticDir, 'index.html');
}
}
return realpath;
}
export function registerProtocol() {
if (process.env.NODE_ENV === 'production') {
protocol.interceptFileProtocol('file', (request, callback) => {
const url = request.url.replace(/^file:\/\//, '');
const webStaticDir = join(__dirname, '../../../resources/web-static');
if (url.startsWith('./')) {
// if is a file type, load the file in resources
if (url.split('/').at(-1)?.includes('.')) {
const realpath = join(webStaticDir, decodeURIComponent(url));
callback(realpath);
} else {
// else, fallback to load the index.html instead
const realpath = join(webStaticDir, 'index.html');
console.log(realpath, 'realpath', url, 'url');
callback(realpath);
}
}
const realpath = toAbsolutePath(url);
// console.log('realpath', realpath, 'for', url);
callback(realpath);
return true;
});
protocol.registerFileProtocol('assets', (request, callback) => {
const url = request.url.replace(/^assets:\/\//, '');
const realpath = toAbsolutePath(url);
// console.log('realpath', realpath, 'for', url);
callback(realpath);
return true;
});
}

View File

@@ -7,6 +7,6 @@ interface Window {
*
* @see https://github.com/cawa-93/dts-for-context-bridge
*/
readonly apis: { workspaceSync: (id: string) => Promise<any>; onThemeChange: (theme: string) => Promise<any>; onSidebarVisibilityChange: (visible: boolean) => Promise<any>; googleSignIn: () => Promise<string>; updateEnv: (env: string, value: string) => void; };
readonly apis: { workspaceSync: (id: string) => Promise<any>; onThemeChange: (theme: string) => Promise<any>; onSidebarVisibilityChange: (visible: boolean) => Promise<any>; getGoogleOauthCode: () => Promise<{ requestInit: RequestInit; url: string; }>; updateEnv: (env: string, value: string) => void; };
readonly appInfo: { electron: boolean; isMacOS: boolean; };
}

View File

@@ -31,9 +31,11 @@ contextBridge.exposeInMainWorld('apis', {
ipcRenderer.invoke('ui:sidebar-visibility-change', visible),
/**
* Try sign in using Google and return a Google IDToken
* Try sign in using Google and return a request object to exchange the code for a token
* Not exchange in Node side because it is easier to do it in the renderer with VPN
*/
googleSignIn: (): Promise<string> => ipcRenderer.invoke('ui:google-sign-in'),
getGoogleOauthCode: (): Promise<{ requestInit: RequestInit; url: string }> =>
ipcRenderer.invoke('ui:get-google-oauth-code'),
/**
* Secret backdoor to update environment variables in main process

View File

@@ -34,6 +34,22 @@ cd(repoRootDir);
await $`yarn add`;
await $`yarn build`;
await $`yarn export`;
// step 1.5: amend sourceMappingURL to allow debugging in devtools
await glob('**/*.{js,css}', { cwd: affineWebOutDir }).then(files => {
return files.map(async file => {
const dir = path.dirname(file);
const fullpath = path.join(affineWebOutDir, file);
let content = await fs.readFile(fullpath, 'utf-8');
// replace # sourceMappingURL=76-6370cd185962bc89.js.map
// to # sourceMappingURL=assets://./{dir}/76-6370cd185962bc89.js.map
content = content.replace(/# sourceMappingURL=(.*)\.map/g, (_, p1) => {
return `# sourceMappingURL=assets://./${dir}/${p1}.map`;
});
await fs.writeFile(fullpath, content);
});
});
await fs.move(affineWebOutDir, publicAffineOutDir, { overwrite: true });
// step 2: build electron resources

View File

@@ -20,4 +20,6 @@ ENABLE_CHANGELOG=1
# Sentry
SENTRY_AUTH_TOKEN=
SENTRY_ORG=
SENTRY_PROJECT=
NEXT_PUBLIC_SENTRY_DSN=

View File

@@ -4,6 +4,7 @@ import path from 'node:path';
import { PerfseePlugin } from '@perfsee/webpack';
import { withSentryConfig } from '@sentry/nextjs';
import SentryWebpackPlugin from '@sentry/webpack-plugin';
import debugLocal from 'next-debug-local';
import preset from './preset.config.mjs';
@@ -113,6 +114,19 @@ const nextConfig = {
config.plugins = [perfsee];
}
}
if (
process.env.SENTRY_AUTH_TOKEN &&
process.env.SENTRY_ORG &&
process.env.SENTRY_PROJECT
) {
config.plugins.push(
new SentryWebpackPlugin({
include: '.next',
ignore: ['node_modules', 'cypress', 'test'],
urlPrefix: '~/_next',
})
);
}
return config;
},
@@ -124,6 +138,7 @@ const nextConfig = {
return profile;
},
basePath: process.env.NEXT_BASE_PATH,
assetPrefix: process.env.NEXT_ASSET_PREFIX,
pageExtensions: [...(preset.enableDebugPage ? ['tsx', 'dev.tsx'] : ['tsx'])],
};

View File

@@ -50,6 +50,7 @@
"@perfsee/webpack": "^1.5.0",
"@redux-devtools/extension": "^3.2.5",
"@rich-data/viewer": "^2.15.6",
"@sentry/webpack-plugin": "^1.20.0",
"@swc-jotai/debug-label": "^0.0.9",
"@swc-jotai/react-refresh": "^0.0.7",
"@types/react": "=18.0.31",

View File

@@ -5,4 +5,7 @@ const SENTRY_DSN = process.env.NEXT_PUBLIC_SENTRY_DSN;
Sentry.init({
dsn: SENTRY_DSN,
tracesSampleRate: 1.0,
replaysSessionSampleRate: 0.1,
replaysOnErrorSampleRate: 1.0,
integrations: [new Sentry.Replay()],
});

View File

@@ -8,7 +8,7 @@ import {
} from '@blocksuite/icons';
import type { PageMeta } from '@blocksuite/store';
import { useTheme } from '@mui/material';
import { useMemo, useState } from 'react';
import { useMemo, useRef, useState } from 'react';
import { useMetaHelper } from '../../../../hooks/affine/use-meta-helper';
import type { BlockSuiteWorkspace } from '../../../../shared';
@@ -44,6 +44,7 @@ export const OperationButton = ({
} = useTheme();
const { t } = useTranslation();
const timer = useRef<ReturnType<typeof setTimeout>>();
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const [operationMenuOpen, setOperationMenuOpen] = useState(false);
const [pinboardMenuOpen, setPinboardMenuOpen] = useState(false);
@@ -63,8 +64,13 @@ export const OperationButton = ({
e.stopPropagation();
}}
onMouseLeave={() => {
setOperationMenuOpen(false);
setPinboardMenuOpen(false);
timer.current = setTimeout(() => {
setOperationMenuOpen(false);
setPinboardMenuOpen(false);
}, 150);
}}
onMouseEnter={() => {
clearTimeout(timer.current);
}}
>
<StyledOperationButton

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

@@ -5,7 +5,7 @@ import { useBlockSuiteWorkspacePageTitle } from '@toeverything/hooks/use-blocksu
import { useAtomValue, useSetAtom } from 'jotai';
import Head from 'next/head';
import type React from 'react';
import { lazy, useCallback } from 'react';
import { lazy, startTransition, Suspense, useCallback } from 'react';
import { currentEditorAtom, workspacePreferredModeAtom } from '../atoms';
import { usePageMeta } from '../hooks/use-page-meta';
@@ -64,28 +64,34 @@ export const PageDetailEditor: React.FC<PageDetailEditorProps> = ({
>
{header}
</WorkspaceHeader>
<Editor
style={{
height: 'calc(100% - 52px)',
}}
key={pageId}
mode={isPublic ? 'page' : currentMode}
page={page}
onInit={useCallback(
(page: Page, editor: Readonly<EditorContainer>) => {
setEditor(editor);
onInit(page, editor);
},
[onInit, setEditor]
)}
onLoad={useCallback(
(page: Page, editor: EditorContainer) => {
setEditor(editor);
onLoad?.(page, editor);
},
[onLoad, setEditor]
)}
/>
<Suspense>
<Editor
style={{
height: 'calc(100% - 52px)',
}}
key={pageId}
mode={isPublic ? 'page' : currentMode}
page={page}
onInit={useCallback(
(page: Page, editor: Readonly<EditorContainer>) => {
startTransition(() => {
setEditor(editor);
});
onInit(page, editor);
},
[onInit, setEditor]
)}
onLoad={useCallback(
(page: Page, editor: EditorContainer) => {
startTransition(() => {
setEditor(editor);
});
onLoad?.(page, editor);
},
[onLoad, setEditor]
)}
/>
</Suspense>
</>
);
};

View File

@@ -2,7 +2,7 @@ import { MuiFade, Tooltip } from '@affine/component';
import { config } from '@affine/env';
import { useTranslation } from '@affine/i18n';
import { CloseIcon, NewIcon } from '@blocksuite/icons';
import { lazy, useState } from 'react';
import { lazy, Suspense, useState } from 'react';
import { ShortcutsModal } from '../shortcuts-modal';
import { ContactIcon, HelpIcon, KeyboardIcon } from './Icons';
@@ -113,11 +113,13 @@ export const HelpIsland = ({
</StyledTriggerWrapper>
</MuiFade>
</StyledIsland>
<ContactModal
open={open}
onClose={() => setOpen(false)}
logoSrc="/imgs/affine-text-logo.png"
/>
<Suspense>
<ContactModal
open={open}
onClose={() => setOpen(false)}
logoSrc="/imgs/affine-text-logo.png"
/>
</Suspense>
<ShortcutsModal
open={openShortCut}
onClose={() => setOpenShortCut(false)}

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

@@ -69,12 +69,14 @@ export const PublicQuickSearch: FC = () => {
openQuickSearchModalAtom
);
return (
<QuickSearchModal
blockSuiteWorkspace={publicWorkspace.blockSuiteWorkspace}
open={openQuickSearchModal}
setOpen={setOpenQuickSearchModalAtom}
router={router}
/>
<Suspense>
<QuickSearchModal
blockSuiteWorkspace={publicWorkspace.blockSuiteWorkspace}
open={openQuickSearchModal}
setOpen={setOpenQuickSearchModalAtom}
router={router}
/>
</Suspense>
);
};

View File

@@ -28,12 +28,14 @@ export const PublicQuickSearch: React.FC = () => {
openQuickSearchModalAtom
);
return (
<QuickSearchModal
blockSuiteWorkspace={publicWorkspace.blockSuiteWorkspace}
open={openQuickSearchModal}
setOpen={setOpenQuickSearchModalAtom}
router={router}
/>
<Suspense>
<QuickSearchModal
blockSuiteWorkspace={publicWorkspace.blockSuiteWorkspace}
open={openQuickSearchModal}
setOpen={setOpenQuickSearchModalAtom}
router={router}
/>
</Suspense>
);
};

View File

@@ -1,6 +1,6 @@
import { NoSsr } from '@mui/material';
import { useRouter } from 'next/router';
import { lazy } from 'react';
import { lazy, Suspense } from 'react';
import { StyledPage, StyledWrapper } from '../../layouts/styles';
import type { NextPageWithLayout } from '../../shared';
@@ -26,7 +26,9 @@ const InitPagePage: NextPageWithLayout = () => {
return (
<StyledPage>
<StyledWrapper>
<Editor onInit={initPage} testType={testType} />
<Suspense>
<Editor onInit={initPage} testType={testType} />
</Suspense>
<div id="toolWrapper" />
</StyledWrapper>
</StyledPage>

View File

@@ -11,7 +11,7 @@ import {
} from '@affine/workspace/affine/login';
import { useAtom } from 'jotai';
import type { NextPage } from 'next';
import { lazy, useMemo } from 'react';
import { lazy, Suspense, useMemo } from 'react';
import { toast } from '../../utils';
@@ -91,10 +91,12 @@ const LoginDevPage: NextPage = () => {
>
Check Permission
</Button>
<Viewer
theme={useTheme().resolvedTheme === 'light' ? 'light' : 'dark'}
value={user}
/>
<Suspense>
<Viewer
theme={useTheme().resolvedTheme === 'light' ? 'light' : 'dark'}
value={user}
/>
</Suspense>
</StyledWrapper>
</StyledPage>
);

View File

@@ -71,10 +71,12 @@ const ListPageInner: React.FC<{
<SearchIcon />
</IconButton>
</NavContainer>
<BlockSuitePublicPageList
onOpenPage={handleClickPage}
blockSuiteWorkspace={blockSuiteWorkspace}
/>
<Suspense>
<BlockSuitePublicPageList
onOpenPage={handleClickPage}
blockSuiteWorkspace={blockSuiteWorkspace}
/>
</Suspense>
</>
);
};

View File

@@ -52,7 +52,10 @@ const getPersistenceAllWorkspace = () => {
item.id,
(k: string) =>
// fixme: token could be expired
({ api: '/api/workspace', token: getLoginStorage()?.token }[k])
({
api: prefixUrl + 'api/workspace',
token: getLoginStorage()?.token,
}[k])
);
const affineWorkspace: AffineWorkspace = {
...item,

View File

@@ -3,7 +3,7 @@ import { arrayMove } from '@dnd-kit/sortable';
import { useAtom, useAtomValue, useSetAtom } from 'jotai';
import { useRouter } from 'next/router';
import type React from 'react';
import { lazy, useCallback, useTransition } from 'react';
import { lazy, Suspense, useCallback, useTransition } from 'react';
import {
currentWorkspaceIdAtom,
@@ -49,71 +49,75 @@ export function Modals() {
return (
<>
<WorkspaceListModal
disabled={transitioning}
user={user}
workspaces={workspaces}
currentWorkspaceId={currentWorkspaceId}
open={openWorkspacesModal || workspaces.length === 0}
onClose={useCallback(() => {
setOpenWorkspacesModal(false);
}, [setOpenWorkspacesModal])}
onMoveWorkspace={useCallback(
(activeId, overId) => {
const oldIndex = workspaces.findIndex(w => w.id === activeId);
const newIndex = workspaces.findIndex(w => w.id === overId);
transition(() =>
setWorkspaces(workspaces =>
arrayMove(workspaces, oldIndex, newIndex)
)
);
},
[setWorkspaces, workspaces]
)}
onClickWorkspace={useCallback(
workspace => {
<Suspense>
<WorkspaceListModal
disabled={transitioning}
user={user}
workspaces={workspaces}
currentWorkspaceId={currentWorkspaceId}
open={openWorkspacesModal || workspaces.length === 0}
onClose={useCallback(() => {
setOpenWorkspacesModal(false);
setCurrentWorkspace(workspace.id);
jumpToSubPath(workspace.id, WorkspaceSubPath.ALL);
},
[jumpToSubPath, setCurrentWorkspace, setOpenWorkspacesModal]
)}
onClickWorkspaceSetting={useCallback(
workspace => {
setOpenWorkspacesModal(false);
setCurrentWorkspace(workspace.id);
jumpToSubPath(workspace.id, WorkspaceSubPath.SETTING);
},
[jumpToSubPath, setCurrentWorkspace, setOpenWorkspacesModal]
)}
onClickLogin={useAffineLogIn()}
onClickLogout={useAffineLogOut()}
onCreateWorkspace={useCallback(() => {
setOpenCreateWorkspaceModal(true);
}, [setOpenCreateWorkspaceModal])}
/>
<CreateWorkspaceModal
open={openCreateWorkspaceModal}
onClose={useCallback(() => {
setOpenCreateWorkspaceModal(false);
}, [setOpenCreateWorkspaceModal])}
onCreate={useCallback(
async name => {
const id = await createLocalWorkspace(name);
}, [setOpenWorkspacesModal])}
onMoveWorkspace={useCallback(
(activeId, overId) => {
const oldIndex = workspaces.findIndex(w => w.id === activeId);
const newIndex = workspaces.findIndex(w => w.id === overId);
transition(() =>
setWorkspaces(workspaces =>
arrayMove(workspaces, oldIndex, newIndex)
)
);
},
[setWorkspaces, workspaces]
)}
onClickWorkspace={useCallback(
workspace => {
setOpenWorkspacesModal(false);
setCurrentWorkspace(workspace.id);
jumpToSubPath(workspace.id, WorkspaceSubPath.ALL);
},
[jumpToSubPath, setCurrentWorkspace, setOpenWorkspacesModal]
)}
onClickWorkspaceSetting={useCallback(
workspace => {
setOpenWorkspacesModal(false);
setCurrentWorkspace(workspace.id);
jumpToSubPath(workspace.id, WorkspaceSubPath.SETTING);
},
[jumpToSubPath, setCurrentWorkspace, setOpenWorkspacesModal]
)}
onClickLogin={useAffineLogIn()}
onClickLogout={useAffineLogOut()}
onCreateWorkspace={useCallback(() => {
setOpenCreateWorkspaceModal(true);
}, [setOpenCreateWorkspaceModal])}
/>
</Suspense>
<Suspense>
<CreateWorkspaceModal
open={openCreateWorkspaceModal}
onClose={useCallback(() => {
setOpenCreateWorkspaceModal(false);
setOpenWorkspacesModal(false);
setCurrentWorkspace(id);
return jumpToSubPath(id, WorkspaceSubPath.ALL);
},
[
createLocalWorkspace,
jumpToSubPath,
setCurrentWorkspace,
setOpenCreateWorkspaceModal,
setOpenWorkspacesModal,
]
)}
/>
}, [setOpenCreateWorkspaceModal])}
onCreate={useCallback(
async name => {
const id = await createLocalWorkspace(name);
setOpenCreateWorkspaceModal(false);
setOpenWorkspacesModal(false);
setCurrentWorkspace(id);
return jumpToSubPath(id, WorkspaceSubPath.ALL);
},
[
createLocalWorkspace,
jumpToSubPath,
setCurrentWorkspace,
setOpenCreateWorkspaceModal,
setOpenWorkspacesModal,
]
)}
/>
</Suspense>
</>
);
}

View File

@@ -41,13 +41,17 @@ const BlockSuiteEditorImpl = (props: EditorProps): ReactElement => {
if (editor.mode !== props.mode) {
editor.mode = props.mode;
}
if (editor.page !== props.page) {
editor.page = props.page;
if (page.root === null) {
props.onInit(page, editor);
useEffect(() => {
if (editor.page !== props.page) {
editor.page = props.page;
if (page.root === null) {
props.onInit(page, editor);
}
props.onLoad?.(page, editor);
}
props.onLoad?.(page, editor);
}
}, [props.page, props.onInit, props.onLoad]);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {

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

@@ -67,10 +67,13 @@ export const setLoginStorage = (login: LoginResponse) => {
};
const signInWithElectron = async (firebaseAuth: FirebaseAuth) => {
const code = await window.apis?.googleSignIn();
const credential = GoogleAuthProvider.credential(code);
const user = await signInWithCredential(firebaseAuth, credential);
return await user.user.getIdToken();
if (window.apis) {
const { url, requestInit } = await window.apis.getGoogleOauthCode();
const { id_token } = await fetch(url, requestInit).then(res => res.json());
const credential = GoogleAuthProvider.credential(id_token);
const user = await signInWithCredential(firebaseAuth, credential);
return await user.user.getIdToken();
}
};
export const clearLoginStorage = () => {

View File

@@ -7,6 +7,7 @@ import { __unstableSchemas, AffineSchemas } from '@blocksuite/blocks/models';
import { assertExists, uuidv4, Workspace } from '@blocksuite/store';
import { openDB } from 'idb';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { IndexeddbPersistence } from 'y-indexeddb';
import { applyUpdate, Doc, encodeStateAsUpdate } from 'yjs';
import type { WorkspacePersist } from '../index';
@@ -45,6 +46,7 @@ beforeEach(() => {
afterEach(() => {
indexedDB.deleteDatabase('affine-local');
localStorage.clear();
});
describe('indexeddb provider', () => {
@@ -196,6 +198,38 @@ describe('indexeddb provider', () => {
});
}
});
test('migration', async () => {
{
const yDoc = new Doc();
yDoc.getMap().set('foo', 'bar');
const persistence = new IndexeddbPersistence('test', yDoc);
await persistence.whenSynced;
persistence.destroy();
}
{
const yDoc = new Doc();
const provider = createIndexedDBProvider('test', yDoc);
provider.connect();
await provider.whenSynced;
await new Promise(resolve => setTimeout(resolve, 0));
expect(yDoc.getMap().get('foo')).toBe('bar');
}
localStorage.clear();
{
indexedDB.databases = vi.fn(async () => {
throw new Error('not supported');
});
expect(indexedDB.databases).rejects.toThrow('not supported');
const yDoc = new Doc();
expect(indexedDB.databases).toBeCalledTimes(1);
const provider = createIndexedDBProvider('test', yDoc);
provider.connect();
await provider.whenSynced;
expect(indexedDB.databases).toBeCalledTimes(2);
expect(yDoc.getMap().get('foo')).toBe('bar');
}
});
});
describe('milestone', () => {

View File

@@ -15,6 +15,23 @@ const snapshotOrigin = Symbol('snapshot-origin');
let mergeCount = 500;
async function databaseExists(name: string): Promise<boolean> {
return new Promise(resolve => {
const req = indexedDB.open(name);
let existed = true;
req.onsuccess = function () {
req.result.close();
if (!existed) {
indexedDB.deleteDatabase(name);
}
resolve(existed);
};
req.onupgradeneeded = function () {
existed = false;
};
});
}
export function revertUpdate(
doc: Doc,
snapshotUpdate: Uint8Array,
@@ -158,12 +175,13 @@ export const getMilestones = async (
return milestone.milestone;
};
let allDb: IDBDatabaseInfo[];
export const createIndexedDBProvider = (
id: string,
doc: Doc,
dbName = 'affine-local'
): IndexedDBProvider => {
let allDb: IDBDatabaseInfo[];
let resolve: () => void;
let reject: (reason?: unknown) => void;
let early = true;
@@ -238,53 +256,96 @@ export const createIndexedDBProvider = (
doc.on('destroy', handleDestroy);
// only run promise below, otherwise the logic is incorrect
const db = await dbPromise;
if (!allDb || localStorage.getItem(`${dbName}-migration`) !== 'true') {
allDb = await indexedDB.databases();
// run the migration
await Promise.all(
allDb.map(meta => {
if (meta.name && meta.version === 1) {
const name = meta.name;
const version = meta.version;
return openDB<IDBPDatabase<OldYjsDB>>(name, version).then(
async oldDB => {
if (!oldDB.objectStoreNames.contains('updates')) {
return;
}
const t = oldDB
.transaction('updates', 'readonly')
.objectStore('updates');
const updates = await t.getAll();
if (
!Array.isArray(updates) ||
!updates.every(update => update instanceof Uint8Array)
) {
return;
}
const update = mergeUpdates(updates);
const workspaceTransaction = db
.transaction('workspace', 'readwrite')
.objectStore('workspace');
const data = await workspaceTransaction.get(name);
if (!data) {
console.log('upgrading the database');
await workspaceTransaction.put({
id: name,
updates: [
{
timestamp: Date.now(),
update,
},
],
});
}
do {
if (!allDb || localStorage.getItem(`${dbName}-migration`) !== 'true') {
try {
allDb = await indexedDB.databases();
} catch {
// in firefox, `indexedDB.databases` is not exist
if (await databaseExists(id)) {
await openDB<IDBPDatabase<OldYjsDB>>(id, 1).then(async oldDB => {
if (!oldDB.objectStoreNames.contains('updates')) {
return;
}
);
const t = oldDB
.transaction('updates', 'readonly')
.objectStore('updates');
const updates = await t.getAll();
if (
!Array.isArray(updates) ||
!updates.every(update => update instanceof Uint8Array)
) {
return;
}
const update = mergeUpdates(updates);
const workspaceTransaction = db
.transaction('workspace', 'readwrite')
.objectStore('workspace');
const data = await workspaceTransaction.get(id);
if (!data) {
console.log('upgrading the database');
await workspaceTransaction.put({
id,
updates: [
{
timestamp: Date.now(),
update,
},
],
});
}
});
break;
}
})
);
localStorage.setItem(`${dbName}-migration`, 'true');
}
}
// run the migration
await Promise.all(
allDb.map(meta => {
if (meta.name && meta.version === 1) {
const name = meta.name;
const version = meta.version;
return openDB<IDBPDatabase<OldYjsDB>>(name, version).then(
async oldDB => {
if (!oldDB.objectStoreNames.contains('updates')) {
return;
}
const t = oldDB
.transaction('updates', 'readonly')
.objectStore('updates');
const updates = await t.getAll();
if (
!Array.isArray(updates) ||
!updates.every(update => update instanceof Uint8Array)
) {
return;
}
const update = mergeUpdates(updates);
const workspaceTransaction = db
.transaction('workspace', 'readwrite')
.objectStore('workspace');
const data = await workspaceTransaction.get(name);
if (!data) {
console.log('upgrading the database');
await workspaceTransaction.put({
id: name,
updates: [
{
timestamp: Date.now(),
update,
},
],
});
}
}
);
}
})
);
localStorage.setItem(`${dbName}-migration`, 'true');
break;
}
// eslint-disable-next-line no-constant-condition
} while (false);
const store = db
.transaction('workspace', 'readwrite')
.objectStore('workspace');

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');
});
});

View File

@@ -198,6 +198,7 @@ __metadata:
"@redux-devtools/extension": ^3.2.5
"@rich-data/viewer": ^2.15.6
"@sentry/nextjs": ^7.47.0
"@sentry/webpack-plugin": ^1.20.0
"@swc-jotai/debug-label": ^0.0.9
"@swc-jotai/react-refresh": ^0.0.7
"@toeverything/hooks": "workspace:*"
@@ -4950,7 +4951,7 @@ __metadata:
languageName: node
linkType: hard
"@sentry/webpack-plugin@npm:1.20.0":
"@sentry/webpack-plugin@npm:1.20.0, @sentry/webpack-plugin@npm:^1.20.0":
version: 1.20.0
resolution: "@sentry/webpack-plugin@npm:1.20.0"
dependencies: