Merge remote-tracking branch 'origin' into feat/cloud-sync-saika

This commit is contained in:
MingLiang Wang
2023-01-09 10:46:15 +08:00
43 changed files with 1092 additions and 404 deletions
+1 -1
View File
@@ -5,7 +5,7 @@
"fixed": [],
"linked": [],
"access": "restricted",
"baseBranch": "feat/cloud-sync",
"baseBranch": "feat/master",
"updateInternalDependencies": "patch",
"ignore": []
}
+2
View File
@@ -0,0 +1,2 @@
**/project.json @darkskygit
**/pnpm-lock.yaml @darkskygit
+1 -2
View File
@@ -1,8 +1,7 @@
name: Pathfinder changelog
on:
push:
branches: [feat/cloud-sync, master]
workflow_dispatch:
# Cancels all previous workflow runs for pull requests that have not completed.
# See https://docs.github.com/en/actions/using-jobs/using-concurrency
@@ -1,10 +1,7 @@
name: Pathfinder Check
name: Build Pathfinder Self-hosted
on:
push:
branches: [feat/cloud-sync]
pull_request:
branches: [feat/cloud-sync]
workflow_dispatch:
# Cancels all previous workflow runs for pull requests that have not completed.
# See https://docs.github.com/en/actions/using-jobs/using-concurrency
@@ -15,69 +12,12 @@ concurrency:
cancel-in-progress: true
jobs:
build:
name: Build on Pull Request
if: github.ref != 'refs/heads/master'
build-self-hosted:
name: Build Community
if: github.ref == 'refs/heads/master'
runs-on: self-hosted
environment: development
steps:
- uses: actions/checkout@v2
- uses: pnpm/action-setup@v2
with:
version: 'latest'
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: 18.x
registry-url: https://npm.pkg.github.com
scope: '@toeverything'
cache: 'pnpm'
- run: node scripts/module-resolve/ci.js
- name: Restore cache
uses: actions/cache@v3
with:
path: |
.next/cache
# Generate a new cache whenever packages or source files change.
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/pnpm-lock.yaml') }}-${{ hashFiles('**.[jt]s', '**.[jt]sx') }}
# If source files changed but packages didn't, rebuild from a prior cache.
restore-keys: |
${{ runner.os }}-nextjs-${{ hashFiles('**/pnpm-lock.yaml') }}-
- name: Install dependencies
run: pnpm install --no-frozen-lockfile
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_GITHUB_AUTH_TOKEN }}
- name: Build
run: pnpm build
env:
NEXT_PUBLIC_FIREBASE_API_KEY: ${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN: ${{ secrets.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN }}
NEXT_PUBLIC_FIREBASE_PROJECT_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_PROJECT_ID }}
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET: ${{ secrets.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET }}
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID }}
NEXT_PUBLIC_FIREBASE_APP_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_APP_ID }}
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID }}
- name: Export
run: pnpm export
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
path: ./packages/app/.next
lint:
name: Lint and E2E Test
runs-on: ubuntu-latest
environment: development
needs: build
steps:
- uses: actions/checkout@v2
- uses: pnpm/action-setup@v2
@@ -106,18 +46,8 @@ jobs:
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_GITHUB_AUTH_TOKEN }}
- name: Download artifact
uses: actions/download-artifact@v3
with:
name: artifact
path: packages/app/.next/
- name: Lint & E2E Test
run: |
pnpm lint --max-warnings=0
PLAYWRIGHT_BROWSERS_PATH=0 npx playwright install chromium
PLAYWRIGHT_BROWSERS_PATH=0 pnpm test
PLAYWRIGHT_BROWSERS_PATH=0 pnpm test:dc
- name: Build
run: pnpm build
env:
NEXT_PUBLIC_FIREBASE_API_KEY: ${{ secrets.NEXT_PUBLIC_FIREBASE_API_KEY }}
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN: ${{ secrets.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN }}
@@ -126,3 +56,59 @@ jobs:
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID }}
NEXT_PUBLIC_FIREBASE_APP_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_APP_ID }}
NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID: ${{ secrets.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID }}
- name: Export
run: pnpm export
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
path: ./packages/app/out
publish-self-hosted:
name: Push Community Image
if: github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
needs: build-self-hosted
permissions:
contents: read
packages: write
env:
REGISTRY: ghcr.io
IMAGE_NAME: 'toeverything/affine-static'
IMAGE_TAG_LATEST: abbey-wood
steps:
- name: Check out the repo
uses: actions/checkout@v2
- name: Download artifact
uses: actions/download-artifact@v3
with:
name: artifact
path: packages/app/out/
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: ${{ env.IMAGE_TAG_LATEST }}
- name: Build Docker image
uses: docker/build-push-action@v3
with:
context: .
push: true
file: ./.github/deployment/Dockerfile
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+8 -1
View File
@@ -3,5 +3,12 @@
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true,
"editor.formatOnSaveMode": "file",
"cSpell.words": ["blocksuite", "datacenter", "livedemo", "pnpm", "testid"]
"cSpell.words": [
"blocksuite",
"datacenter",
"livedemo",
"pnpm",
"selfhosted",
"testid"
]
}
+2 -1
View File
@@ -6,7 +6,8 @@
"license": "MPL-2.0",
"scripts": {
"dev": "pnpm --filter=!@affine/app build && pnpm --filter @affine/app dev",
"dev:ac": "pnpm --filter=!@affine/app build && pnpm --filter @affine/app dev:ac",
"dev:ac": "pnpm --filter=!@affine/app build && NODE_API_SERVER=ac pnpm --filter @affine/app dev",
"dev:local": "pnpm --filter=!@affine/app build && NODE_API_SERVER=local pnpm --filter @affine/app dev",
"build": " pnpm --filter=!@affine/app build && pnpm --filter!=@affine/datacenter -r build",
"export": "pnpm --filter @affine/app export",
"start": "pnpm --filter @affine/app start",
+47 -25
View File
@@ -4,6 +4,32 @@ const { dependencies } = require('./package.json');
const path = require('node:path');
const printer = require('./scripts/printer').printer;
const enableDebugLocal = path.isAbsolute(process.env.LOCAL_BLOCK_SUITE ?? '');
const EDITOR_VERSION = enableDebugLocal
? 'local-version'
: dependencies['@blocksuite/editor'];
const profileTarget = {
ac: '100.85.73.88:12001',
dev: '100.85.73.88:12001',
local: '127.0.0.1:3000',
};
const getRedirectConfig = profile => {
const target = profileTarget[profile || 'dev'] || profileTarget['dev'];
return [
[
{ source: '/api/:path*', destination: `http://${target}/api/:path*` },
{
source: '/collaboration/:path*',
destination: `http://${target}/collaboration/:path*`,
},
],
target,
];
};
/** @type {import('next').NextConfig} */
const nextConfig = {
productionBrowserSourceMaps: true,
@@ -16,7 +42,7 @@ const nextConfig = {
CI: process.env.CI || null,
VERSION: getGitVersion(),
COMMIT_HASH: getCommitHash(),
EDITOR_VERSION: dependencies['@blocksuite/editor'],
EDITOR_VERSION,
},
webpack: config => {
config.experiments = { ...config.experiments, topLevelAwait: true };
@@ -31,30 +57,12 @@ const nextConfig = {
images: {
unoptimized: true,
},
// XXX not test yet
rewrites: async () => {
if (process.env.NODE_API_SERVER === 'ac') {
let destinationAC = 'http://100.85.73.88:12001/api/:path*';
printer.info('API request proxy to [AC Server] ' + destinationAC);
return [
{
source: '/api/:path*',
destination: destinationAC,
},
];
} else {
let destinationStandard = 'http://100.77.180.48:11001/api/:path*';
printer.info(
'API request proxy to [Standard Server] ' + destinationStandard
);
return [
{
source: '/api/:path*',
destination: destinationStandard,
},
];
}
const [profile, desc] = getRedirectConfig(process.env.NODE_API_SERVER);
printer.info(
`API request proxy to [${process.env.NODE_API_SERVER} Server]: ` + desc
);
return profile;
},
basePath: process.env.BASE_PATH,
};
@@ -63,11 +71,25 @@ const baseDir = process.env.LOCAL_BLOCK_SUITE ?? '/';
const withDebugLocal = require('next-debug-local')(
{
'@blocksuite/editor': path.resolve(baseDir, 'packages', 'editor'),
'@blocksuite/blocks/models': path.resolve(
baseDir,
'packages',
'blocks',
'src',
'models'
),
'@blocksuite/blocks/std': path.resolve(
baseDir,
'packages',
'blocks',
'src',
'std'
),
'@blocksuite/blocks': path.resolve(baseDir, 'packages', 'blocks'),
'@blocksuite/store': path.resolve(baseDir, 'packages', 'store'),
},
{
enable: path.isAbsolute(process.env.LOCAL_BLOCK_SUITE ?? ''),
enable: enableDebugLocal,
}
);
+4 -5
View File
@@ -3,7 +3,6 @@
"version": "0.3.1",
"scripts": {
"dev": "next dev -p 8080",
"dev:ac": "NODE_API_SERVER=ac next dev -p 8080",
"build": "next build",
"export": "next export",
"start": "next start",
@@ -11,10 +10,10 @@
},
"dependencies": {
"@affine/datacenter": "workspace:*",
"@blocksuite/blocks": "0.3.1",
"@blocksuite/editor": "0.3.1",
"@blocksuite/blocks": "=0.3.1-20230106060050-1aad55d",
"@blocksuite/editor": "=0.3.1-20230106060050-1aad55d",
"@blocksuite/icons": "^2.0.2",
"@blocksuite/store": "0.3.1",
"@blocksuite/store": "=0.3.1-20230106060050-1aad55d",
"@emotion/css": "^11.10.0",
"@emotion/react": "^11.10.4",
"@emotion/server": "^11.10.0",
@@ -45,7 +44,7 @@
"@types/react": "18.0.20",
"@types/react-dom": "18.0.6",
"@types/wicg-file-system-access": "^2020.9.5",
"chalk-next": "^6.1.5",
"chalk": "^4.1.2",
"eslint": "8.22.0",
"eslint-config-next": "12.3.1",
"eslint-config-prettier": "^8.5.0",
+3 -2
View File
@@ -1,9 +1,10 @@
import { NotFoundTitle, PageContainer } from './styles';
import { useTranslation } from 'react-i18next';
export const NotfoundPage = () => {
const { t } = useTranslation();
return (
<PageContainer>
<NotFoundTitle>404 - Page Not Found</NotFoundTitle>
<NotFoundTitle>{t('404 - Page Not Found')}</NotFoundTitle>
</PageContainer>
);
};
@@ -23,7 +23,7 @@ import {
StyledModalFooter,
} from './style';
import bg from '@/components/contact-modal/bg.png';
import { useTranslation } from 'react-i18next';
const linkList = [
{
icon: <GithubIcon />,
@@ -51,27 +51,31 @@ const linkList = [
link: 'https://discord.gg/Arn7TqJBvG',
},
];
const rightLinkList = [
{
icon: <LogoIcon />,
title: 'Official Website ',
subTitle: 'AFFiNE.pro',
link: 'https://affine.pro',
},
{
icon: <DocIcon />,
title: 'AFFiNE Community',
subTitle: 'community.affine.pro',
link: 'https://community.affine.pro',
},
];
type TransitionsModalProps = {
open: boolean;
onClose: () => void;
};
export const ContactModal = ({ open, onClose }: TransitionsModalProps) => {
export const ContactModal = ({
open,
onClose,
}: TransitionsModalProps): JSX.Element => {
const { t } = useTranslation();
const rightLinkList = [
{
icon: <LogoIcon />,
title: t('Official Website'),
subTitle: 'AFFiNE.pro',
link: 'https://affine.pro',
},
{
icon: <DocIcon />,
title: t('AFFiNE Community'),
subTitle: 'community.affine.pro',
link: 'https://community.affine.pro',
},
];
return (
<Modal open={open} onClose={onClose} data-testid="contact-us-modal-content">
<ModalWrapper
@@ -109,7 +113,7 @@ export const ContactModal = ({ open, onClose }: TransitionsModalProps) => {
})}
</StyledLeftContainer>
<StyledRightContainer>
<StyledSubTitle>Get in touch!</StyledSubTitle>
<StyledSubTitle>{t('Get in touch!')}</StyledSubTitle>
{linkList.map(({ icon, title, link }) => {
return (
<StyledSmallLink key={title} href={link} target="_blank">
@@ -128,7 +132,7 @@ export const ContactModal = ({ open, onClose }: TransitionsModalProps) => {
target="_blank"
rel="noreferrer"
>
How is AFFiNE Alpha different
{t('How is AFFiNE Alpha different?')}
</a>
</p>
<p>Copyright &copy; 2022 Toeverything</p>
@@ -15,7 +15,7 @@ import { useTheme } from '@/providers/themeProvider';
import { EdgelessIcon, PaperIcon } from './icons';
import useCurrentPageMeta from '@/hooks/use-current-page-meta';
import { usePageHelper } from '@/hooks/use-page-helper';
import { useTranslation } from 'react-i18next';
const PaperItem = ({ active }: { active?: boolean }) => {
const {
theme: {
@@ -96,7 +96,7 @@ export const EditorModeSwitch = ({
setRadioItemStatus(modifyRadioItemStatus());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isHover, mode]);
const { t } = useTranslation();
return (
<StyledAnimateRadioContainer
data-testid="editor-mode-switcher"
@@ -106,7 +106,7 @@ export const EditorModeSwitch = ({
>
<AnimateRadioItem
isLeft={true}
label="Paper"
label={t('Paper')}
icon={<PaperItem />}
active={mode === 'page'}
status={radioItemStatus.left}
@@ -126,7 +126,7 @@ export const EditorModeSwitch = ({
<StyledMiddleLine hidden={!isHover} dark={themeMode === 'dark'} />
<AnimateRadioItem
isLeft={false}
label="Edgeless"
label={t('Edgeless')}
data-testid="switch-edgeless-item"
icon={<EdgelessItem />}
active={mode === 'edgeless'}
@@ -22,14 +22,14 @@ export const EditorHeader = () => {
useEffect(() => {
onPropsUpdated(editor => {
setTitle(editor.model?.title || 'Untitled');
setTitle(editor.pageBlockModel?.title || 'Untitled');
});
}, [onPropsUpdated]);
useEffect(() => {
setTimeout(() => {
// If first time in, need to wait for editor to be inserted into DOM
setTitle(editor?.model?.title || 'Untitled');
setTitle(editor?.pageBlockModel?.title || 'Untitled');
}, 300);
}, [editor]);
@@ -16,12 +16,13 @@ import { usePageHelper } from '@/hooks/use-page-helper';
import { useConfirm } from '@/providers/confirm-provider';
import useCurrentPageMeta from '@/hooks/use-current-page-meta';
import { toast } from '@/ui/toast';
import { useTranslation } from 'react-i18next';
const PopoverContent = () => {
const { editor } = useAppState();
const { toggleFavoritePage, toggleDeletePage } = usePageHelper();
const { changePageMode } = usePageHelper();
const { confirm } = useConfirm();
const { t } = useTranslation();
const {
mode = 'page',
id = '',
@@ -35,11 +36,13 @@ const PopoverContent = () => {
data-testid="editor-option-menu-favorite"
onClick={() => {
toggleFavoritePage(id);
toast(!favorite ? 'Removed to Favourites' : 'Added to Favourites');
toast(
favorite ? t('Removed from Favourites') : t('Added to Favourites')
);
}}
icon={favorite ? <FavouritedIcon /> : <FavouritesIcon />}
>
{favorite ? 'Remove' : 'Add'} to favourites
{favorite ? t('Remove from favourites') : t('Add to favourites')}
</MenuItem>
<MenuItem
icon={mode === 'page' ? <EdgelessIcon /> : <PaperIcon />}
@@ -48,7 +51,8 @@ const PopoverContent = () => {
changePageMode(id, mode === 'page' ? 'edgeless' : 'page');
}}
>
Convert to {mode === 'page' ? 'Edgeless' : 'Page'}
{t('Convert to ')}
{mode === 'page' ? t('Edgeless') : t('Page')}
</MenuItem>
<Menu
placement="left-start"
@@ -60,7 +64,7 @@ const PopoverContent = () => {
}}
icon={<ExportToHtmlIcon />}
>
Export to HTML
{t('Export to HTML')}
</MenuItem>
<MenuItem
onClick={() => {
@@ -68,31 +72,33 @@ const PopoverContent = () => {
}}
icon={<ExportToMarkdownIcon />}
>
Export to Markdown
{t('Export to Markdown')}
</MenuItem>
</>
}
>
<MenuItem icon={<ExportIcon />} isDir={true}>
Export
{t('Export')}
</MenuItem>
</Menu>
<MenuItem
data-testid="editor-option-menu-delete"
onClick={() => {
confirm({
title: 'Delete page?',
content: `${title || 'Untitled'} will be moved to Trash`,
confirmText: 'Delete',
title: t('Delete page?'),
content: t('will be moved to Trash', {
title: title || 'Untitled',
}),
confirmText: t('Delete'),
confirmType: 'danger',
}).then(confirm => {
confirm && toggleDeletePage(id);
confirm && toast('Moved to Trash');
confirm && toast(t('Moved to Trash'));
});
}}
icon={<TrashIcon />}
>
Delete
{t('Delete')}
</MenuItem>
</>
);
@@ -3,15 +3,15 @@ import { IconButton, IconButtonProps } from '@/ui/button';
import { Tooltip } from '@/ui/tooltip';
import { ArrowDownIcon } from '@blocksuite/icons';
import { useModal } from '@/providers/global-modal-provider';
import { useTranslation } from 'react-i18next';
export const QuickSearchButton = ({
onClick,
...props
}: Omit<IconButtonProps, 'children'>) => {
const { triggerQuickSearchModal } = useModal();
const { t } = useTranslation();
return (
<Tooltip content="Switch to" placement="bottom">
<Tooltip content={t('Switch to')} placement="bottom">
<IconButton
data-testid="header-quickSearchButton"
{...props}
@@ -8,6 +8,7 @@ import {
import { CloseIcon, ContactIcon, HelpIcon, KeyboardIcon } from './icons';
import Grow from '@mui/material/Grow';
import { Tooltip } from '@/ui/tooltip';
import { useTranslation } from 'react-i18next';
import { useModal } from '@/providers/global-modal-provider';
import { useTheme } from '@/providers/themeProvider';
import useCurrentPageMeta from '@/hooks/use-current-page-meta';
@@ -22,7 +23,7 @@ export const HelpIsland = ({
const { mode: editorMode } = useCurrentPageMeta() || {};
const { triggerShortcutsModal, triggerContactModal } = useModal();
const isEdgelessDark = mode === 'dark' && editorMode === 'edgeless';
const { t } = useTranslation();
return (
<>
<StyledIsland
@@ -37,7 +38,7 @@ export const HelpIsland = ({
<Grow in={showContent}>
<StyledIslandWrapper>
{showList.includes('contact') && (
<Tooltip content="Contact Us" placement="left-end">
<Tooltip content={t('Contact Us')} placement="left-end">
<StyledIconWrapper
data-testid="right-bottom-contact-us-icon"
isEdgelessDark={isEdgelessDark}
@@ -51,7 +52,7 @@ export const HelpIsland = ({
</Tooltip>
)}
{showList.includes('shortcuts') && (
<Tooltip content="Keyboard Shortcuts" placement="left-end">
<Tooltip content={t('Keyboard Shortcuts')} placement="left-end">
<StyledIconWrapper
data-testid="shortcuts-icon"
isEdgelessDark={isEdgelessDark}
+6 -3
View File
@@ -6,6 +6,7 @@ import Loading from '@/components/loading';
import { usePageHelper } from '@/hooks/use-page-helper';
import { useAppState } from '@/providers/app-state-provider/context';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
// import { Tooltip } from '@/ui/tooltip';
type ImportModalProps = {
open: boolean;
@@ -19,6 +20,7 @@ export const ImportModal = ({ open, onClose }: ImportModalProps) => {
const [status, setStatus] = useState<'unImported' | 'importing'>('importing');
const { openPage, createPage } = usePageHelper();
const { currentWorkspace } = useAppState();
const { t } = useTranslation();
const _applyTemplate = function (pageId: string, template: Template) {
const page = currentWorkspace?.getPage(pageId);
@@ -29,9 +31,10 @@ export const ImportModal = ({ open, onClose }: ImportModalProps) => {
setTimeout(() => {
const editor = document.querySelector('editor-container');
if (editor) {
const groupId = page.addBlock({ flavour: 'affine:group' }, pageId);
page.addBlock({ flavour: 'affine:surface' }, null);
const frameId = page.addBlock({ flavour: 'affine:frame' }, pageId);
// TODO blocksuite should offer a method to import markdown from store
editor.clipboard.importMarkdown(template.source, `${groupId}`);
editor.clipboard.importMarkdown(template.source, `${frameId}`);
page.resetHistory();
editor.requestUpdate();
}
@@ -84,7 +87,7 @@ export const ImportModal = ({ open, onClose }: ImportModalProps) => {
<Modal open={open} onClose={onClose}>
<ModalWrapper width={460} minHeight={240}>
<ModalCloseButton onClick={onClose} />
<StyledTitle>Import</StyledTitle>
<StyledTitle>{t('Import')}</StyledTitle>
{status === 'unImported' && (
<StyledButtonWrapper>
@@ -24,7 +24,7 @@ import { useAppState } from '@/providers/app-state-provider/context';
import { toast } from '@/ui/toast';
import { usePageHelper } from '@/hooks/use-page-helper';
import { useTheme } from '@/providers/themeProvider';
import { useTranslation } from 'react-i18next';
const FavoriteTag = ({
pageMeta: { favorite, id },
}: {
@@ -32,9 +32,10 @@ const FavoriteTag = ({
}) => {
const { toggleFavoritePage } = usePageHelper();
const { theme } = useTheme();
const { t } = useTranslation();
return (
<Tooltip
content={favorite ? 'Favourited' : 'Favourite'}
content={favorite ? t('Favourited') : t('Favourite')}
placement="top-start"
>
<IconButton
@@ -43,7 +44,9 @@ const FavoriteTag = ({
onClick={e => {
e.stopPropagation();
toggleFavoritePage(id);
toast(!favorite ? 'Removed to Favourites' : 'Added to Favourites');
toast(
favorite ? t('Removed from Favourites') : t('Added to Favourites')
);
}}
style={{
color: favorite ? theme.colors.primaryColor : theme.colors.iconColor,
@@ -71,6 +74,7 @@ export const PageList = ({
}) => {
const router = useRouter();
const { currentWorkspaceId } = useAppState();
const { t } = useTranslation();
if (pageList.length === 0) {
return <Empty />;
}
@@ -80,10 +84,10 @@ export const PageList = ({
<Table>
<TableHead>
<TableRow>
<TableCell proportion={0.5}>Title</TableCell>
<TableCell proportion={0.2}>Created</TableCell>
<TableCell proportion={0.5}>{t('Title')}</TableCell>
<TableCell proportion={0.2}>{t('Created')}</TableCell>
<TableCell proportion={0.2}>
{isTrash ? 'Moved to Trash' : 'Updated'}
{isTrash ? t('Moved to Trash') : t('Updated')}
</TableCell>
<TableCell proportion={0.1}></TableCell>
</TableRow>
@@ -108,7 +112,7 @@ export const PageList = ({
<PaperIcon />
)}
<Content ellipsis={true} color="inherit">
{pageMeta.title || 'Untitled'}
{pageMeta.title || t('Untitled')}
</Content>
</StyledTitleLink>
{showFavoriteTag && <FavoriteTag pageMeta={pageMeta} />}
@@ -14,23 +14,25 @@ import {
} from '@blocksuite/icons';
import { toast } from '@/ui/toast';
import { usePageHelper } from '@/hooks/use-page-helper';
import { useTranslation } from 'react-i18next';
export const OperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
const { id, favorite } = pageMeta;
const { openPage } = usePageHelper();
const { toggleFavoritePage, toggleDeletePage } = usePageHelper();
const { confirm } = useConfirm();
const { t } = useTranslation();
const OperationMenu = (
<>
<MenuItem
onClick={() => {
toggleFavoritePage(id);
toast(!favorite ? 'Removed to Favourites' : 'Added to Favourites');
toast(
favorite ? t('Removed from Favourites') : t('Added to Favourites')
);
}}
icon={favorite ? <FavouritedIcon /> : <FavouritesIcon />}
>
{favorite ? 'Remove' : 'Add'} to favourites
{favorite ? t('Remove from favourites') : t('Add to favourites')}
</MenuItem>
<MenuItem
onClick={() => {
@@ -38,23 +40,25 @@ export const OperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
}}
icon={<OpenInNewIcon />}
>
Open in new tab
{t('Open in new tab')}
</MenuItem>
<MenuItem
onClick={() => {
confirm({
title: 'Delete page?',
content: `${pageMeta.title || 'Untitled'} will be moved to Trash`,
confirmText: 'Delete',
title: t('Delete page?'),
content: t('will be moved to Trash', {
title: pageMeta.title || 'Untitled',
}),
confirmText: t('Delete'),
confirmType: 'danger',
}).then(confirm => {
confirm && toggleDeletePage(id);
toast('Moved to Trash');
toast(t('Moved to Trash'));
});
}}
icon={<TrashIcon />}
>
Delete
{t('Delete')}
</MenuItem>
</>
);
@@ -74,7 +78,7 @@ export const TrashOperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
const { openPage, getPageMeta } = usePageHelper();
const { toggleDeletePage, permanentlyDeletePage } = usePageHelper();
const { confirm } = useConfirm();
const { t } = useTranslation();
return (
<Wrapper>
<IconButton
@@ -82,7 +86,7 @@ export const TrashOperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
style={{ marginRight: '12px' }}
onClick={() => {
toggleDeletePage(id);
toast(`${getPageMeta(id)?.title || 'Untitled'} restored`);
toast(t('restored', { title: getPageMeta(id)?.title || 'Untitled' }));
openPage(id);
}}
>
@@ -92,13 +96,13 @@ export const TrashOperationCell = ({ pageMeta }: { pageMeta: PageMeta }) => {
darker={true}
onClick={() => {
confirm({
title: 'Delete permanently?',
content: "Once deleted, you can't undo this action.",
confirmText: 'Delete',
title: t('Delete permanently?'),
content: t("Once deleted, you can't undo this action."),
confirmText: t('Delete'),
confirmType: 'danger',
}).then(confirm => {
confirm && permanentlyDeletePage(id);
toast('Permanently deleted');
toast(t('Permanently deleted'));
});
}}
>
@@ -1,21 +1,29 @@
import { AllPagesIcon, FavouritesIcon, TrashIcon } from '@blocksuite/icons';
import { useTranslation } from 'react-i18next';
export const config = (currentWorkspaceId: string) => {
export const useSwitchToConfig = (
currentWorkspaceId: string
): {
title: string;
href: string;
icon: React.FC<React.SVGProps<SVGSVGElement>>;
}[] => {
const { t } = useTranslation();
const List = [
{
title: 'All pages',
title: t('All pages'),
href: currentWorkspaceId ? `/workspace/${currentWorkspaceId}/all` : '',
icon: AllPagesIcon,
},
{
title: 'Favourites',
title: t('Favourites'),
href: currentWorkspaceId
? `/workspace/${currentWorkspaceId}/favorite`
: '',
icon: FavouritesIcon,
},
{
title: 'Trash',
title: t('Trash'),
href: currentWorkspaceId ? `/workspace/${currentWorkspaceId}/trash` : '',
icon: TrashIcon,
},
@@ -4,10 +4,11 @@ import { StyledModalFooterContent } from './style';
import { useModal } from '@/providers/global-modal-provider';
import { Command } from 'cmdk';
import { usePageHelper } from '@/hooks/use-page-helper';
import { useTranslation } from 'react-i18next';
export const Footer = (props: { query: string }) => {
const { triggerQuickSearchModal } = useModal();
const { openPage, createPage } = usePageHelper();
const { t } = useTranslation();
const query = props.query;
return (
@@ -25,9 +26,9 @@ export const Footer = (props: { query: string }) => {
<StyledModalFooterContent>
<AddIcon />
{query ? (
<span>New &quot;{query}&quot; page</span>
<span>{t('New Keyword Page', { query: query })}</span>
) : (
<span>New page</span>
<span>{t('New Page')}</span>
)}
</StyledModalFooterContent>
</Command.Item>
@@ -5,8 +5,9 @@ import { PaperIcon, EdgelessIcon } from '@blocksuite/icons';
import { Dispatch, SetStateAction, useEffect, useState } from 'react';
import { useAppState } from '@/providers/app-state-provider';
import { useRouter } from 'next/router';
import { config } from './config';
import { useSwitchToConfig } from './config';
import { NoResultSVG } from './noResultSVG';
import { useTranslation } from 'react-i18next';
import usePageHelper from '@/hooks/use-page-helper';
import usePageMetaList from '@/hooks/use-page-meta-list';
export const Results = (props: {
@@ -25,8 +26,9 @@ export const Results = (props: {
const router = useRouter();
const { currentWorkspaceId } = useAppState();
const { search } = usePageHelper();
const List = config(currentWorkspaceId);
const List = useSwitchToConfig(currentWorkspaceId);
const [results, setResults] = useState(new Map<string, string | undefined>());
const { t } = useTranslation();
useEffect(() => {
setResults(search(query));
setLoading(false);
@@ -47,7 +49,9 @@ export const Results = (props: {
<>
{query ? (
resultsPageMeta.length ? (
<Command.Group heading={`Find ${resultsPageMeta.length} results`}>
<Command.Group
heading={t('Find results', { number: resultsPageMeta.length })}
>
{resultsPageMeta.map(result => {
return (
<Command.Item
@@ -72,12 +76,12 @@ export const Results = (props: {
</Command.Group>
) : (
<StyledNotFound>
<span>Find 0 result</span>
<span>{t('Find 0 result')}</span>
<NoResultSVG />
</StyledNotFound>
)
) : (
<Command.Group heading="Switch to">
<Command.Group heading={t('Switch to')}>
{List.map(link => {
return (
<Command.Item
@@ -1,71 +1,88 @@
export const macKeyboardShortcuts = {
Undo: '⌘+Z',
Redo: '⌘+⇧+Z',
Bold: '⌘+B',
Italic: '⌘+I',
Underline: '⌘+U',
Strikethrough: '⌘+⇧+S',
'Inline code': ' ⌘+E',
'Code block': '⌘+⌥+C',
Link: '⌘+K',
'Body text': '⌘+⌥+0',
'Heading 1': '⌘+⌥+1',
'Heading 2': '⌘+⌥+2',
'Heading 3': '⌘+⌥+3',
'Heading 4': '⌘+⌥+4',
'Heading 5': '⌘+⌥+5',
'Heading 6': '⌘+⌥+6',
'Increase indent': 'Tab',
'Reduce indent': '⇧+Tab',
import { useTranslation } from 'react-i18next';
interface ShortcutTip {
[x: string]: string;
}
export const useMacKeyboardShortcuts = (): ShortcutTip => {
const { t } = useTranslation();
return {
[t('Undo')]: '⌘+Z',
[t('Redo')]: '⌘+⇧+Z',
[t('Bold')]: '⌘+B',
[t('Italic')]: '⌘+I',
[t('Underline')]: '⌘+U',
[t('Strikethrough')]: '⌘+⇧+S',
[t('Inline code')]: ' ⌘+E',
[t('Code block')]: '⌘+⌥+C',
[t('Link')]: '⌘+K',
[t('Body text')]: '⌘+⌥+0',
[t('Heading', { number: '1' })]: '⌘+⌥+1',
[t('Heading', { number: '2' })]: '⌘+⌥+2',
[t('Heading', { number: '3' })]: '⌘+⌥+3',
[t('Heading', { number: '4' })]: '⌘+⌥+4',
[t('Heading', { number: '5' })]: '⌘+⌥+5',
[t('Heading', { number: '6' })]: '⌘+⌥+6',
[t('Increase indent')]: 'Tab',
[t('Reduce indent')]: '⇧+Tab',
};
};
export const macMarkdownShortcuts = {
Bold: '**Text** ',
Italic: '*Text* ',
Underline: '~Text~ ',
Strikethrough: '~~Text~~ ',
Divider: '***',
'Inline code': '`Text` ',
'Code block': '``` Space',
'Heading 1': '# Text',
'Heading 2': '## Text',
'Heading 3': '### Text',
'Heading 4': '#### Text',
'Heading 5': '##### Text',
'Heading 6': '###### Text',
export const useMacMarkdownShortcuts = (): ShortcutTip => {
const { t } = useTranslation();
return {
[t('Bold')]: '**Text** ',
[t('Italic')]: '*Text* ',
[t('Underline')]: '~Text~ ',
[t('Strikethrough')]: '~~Text~~ ',
[t('Divider')]: '***',
[t('Inline code')]: '`Text` ',
[t('Code block')]: '``` Space',
[t('Heading', { number: '1' })]: '# Text',
[t('Heading', { number: '2' })]: '## Text',
[t('Heading', { number: '3' })]: '### Text',
[t('Heading', { number: '4' })]: '#### Text',
[t('Heading', { number: '5' })]: '##### Text',
[t('Heading', { number: '6' })]: '###### Text',
};
};
export const windowsKeyboardShortcuts = {
Undo: 'Ctrl+Z',
Redo: 'Ctrl+Y',
Bold: 'Ctrl+B',
Italic: 'Ctrl+I',
Underline: 'Ctrl+U',
Strikethrough: 'Ctrl+Shift+S',
'Inline code': ' Ctrl+E',
'Code block': 'Ctrl+Alt+C',
Link: 'Ctrl+K',
'Body text': 'Ctrl+Shift+0',
'Heading 1': 'Ctrl+Shift+1',
'Heading 2': 'Ctrl+Shift+2',
'Heading 3': 'Ctrl+Shift+3',
'Heading 4': 'Ctrl+Shift+4',
'Heading 5': 'Ctrl+Shift+5',
'Heading 6': 'Ctrl+Shift+6',
'Increase indent': 'Tab',
'Reduce indent': 'Shift+Tab',
export const useWindowsKeyboardShortcuts = (): ShortcutTip => {
const { t } = useTranslation();
return {
[t('Undo')]: 'Ctrl+Z',
[t('Redo')]: 'Ctrl+Y',
[t('Bold')]: 'Ctrl+B',
[t('Italic')]: 'Ctrl+I',
[t('Underline')]: 'Ctrl+U',
[t('Strikethrough')]: 'Ctrl+Shift+S',
[t('Inline code')]: ' Ctrl+E',
[t('Code block')]: 'Ctrl+Alt+C',
[t('Link')]: 'Ctrl+K',
[t('Body text')]: 'Ctrl+Shift+0',
[t('Heading', { number: '1' })]: 'Ctrl+Shift+1',
[t('Heading', { number: '2' })]: 'Ctrl+Shift+2',
[t('Heading', { number: '3' })]: 'Ctrl+Shift+3',
[t('Heading', { number: '4' })]: 'Ctrl+Shift+4',
[t('Heading', { number: '5' })]: 'Ctrl+Shift+5',
[t('Heading', { number: '6' })]: 'Ctrl+Shift+6',
[t('Increase indent')]: 'Tab',
[t('Reduce indent')]: 'Shift+Tab',
};
};
export const winMarkdownShortcuts = {
Bold: '**Text** ',
Italic: '*Text* ',
Underline: '~Text~ ',
Strikethrough: '~~Text~~ ',
'Inline code': '`Text` ',
'Code block': '``` Text',
'Heading 1': '# Text',
'Heading 2': '## Text',
'Heading 3': '### Text',
'Heading 4': '#### Text',
'Heading 5': '##### Text',
'Heading 6': '###### Text',
export const useWinMarkdownShortcuts = (): ShortcutTip => {
const { t } = useTranslation();
return {
[t('Bold')]: '**Text** ',
[t('Italic')]: '*Text* ',
[t('Underline')]: '~Text~ ',
[t('Strikethrough')]: '~~Text~~ ',
[t('Divider')]: '***',
[t('Inline code')]: '`Text` ',
[t('Code block')]: '``` Text',
[t('Heading', { number: '1' })]: '# Text',
[t('Heading', { number: '2' })]: '## Text',
[t('Heading', { number: '3' })]: '### Text',
[t('Heading', { number: '4' })]: '#### Text',
[t('Heading', { number: '5' })]: '##### Text',
[t('Heading', { number: '6' })]: '###### Text',
};
};
@@ -8,14 +8,15 @@ import {
StyledTitle,
} from './style';
import {
macKeyboardShortcuts,
macMarkdownShortcuts,
windowsKeyboardShortcuts,
winMarkdownShortcuts,
useMacKeyboardShortcuts,
useMacMarkdownShortcuts,
useWindowsKeyboardShortcuts,
useWinMarkdownShortcuts,
} from '@/components/shortcuts-modal/config';
import Slide from '@mui/material/Slide';
import { ModalCloseButton } from '@/ui/modal';
import { getUaHelper } from '@/utils';
import { useTranslation } from 'react-i18next';
type ModalProps = {
open: boolean;
onClose: () => void;
@@ -26,12 +27,18 @@ const isMac = () => {
};
export const ShortcutsModal = ({ open, onClose }: ModalProps) => {
const { t } = useTranslation();
const macMarkdownShortcuts = useMacMarkdownShortcuts();
const winMarkdownShortcuts = useWinMarkdownShortcuts();
const macKeyboardShortcuts = useMacKeyboardShortcuts();
const windowsKeyboardShortcuts = useWindowsKeyboardShortcuts();
const markdownShortcuts = isMac()
? macMarkdownShortcuts
: winMarkdownShortcuts;
const keyboardShortcuts = isMac()
? macKeyboardShortcuts
: windowsKeyboardShortcuts;
return createPortal(
<Slide direction="left" in={open} mountOnEnter unmountOnExit>
<StyledShortcutsModal data-testid="shortcuts-modal">
@@ -39,7 +46,7 @@ export const ShortcutsModal = ({ open, onClose }: ModalProps) => {
<StyledModalHeader>
<StyledTitle>
<KeyboardIcon />
Shortcuts
{t('Shortcuts')}
</StyledTitle>
<ModalCloseButton
@@ -53,7 +60,7 @@ export const ShortcutsModal = ({ open, onClose }: ModalProps) => {
/>
</StyledModalHeader>
<StyledSubTitle style={{ marginTop: 0 }}>
Keyboard Shortcuts
{t('Keyboard Shortcuts')}
</StyledSubTitle>
{Object.entries(keyboardShortcuts).map(([title, shortcuts]) => {
return (
@@ -63,7 +70,7 @@ export const ShortcutsModal = ({ open, onClose }: ModalProps) => {
</StyledListItem>
);
})}
<StyledSubTitle>Markdown Syntax</StyledSubTitle>
<StyledSubTitle>{t('Markdown Syntax')}</StyledSubTitle>
{Object.entries(markdownShortcuts).map(([title, shortcuts]) => {
return (
<StyledListItem key={title}>
@@ -4,14 +4,14 @@ import {
StyledArrowButton,
StyledLink,
StyledListItem,
StyledListItemForWorkspace,
// StyledListItemForWorkspace,
StyledNewPageButton,
StyledSliderBar,
StyledSliderBarWrapper,
StyledSubListItem,
} from './style';
import { Arrow } from './icons';
import { WorkspaceSelector } from './WorkspaceSelector';
// import { WorkspaceSelector } from './WorkspaceSelector';
import Collapse from '@mui/material/Collapse';
import {
ArrowDownIcon,
@@ -26,17 +26,17 @@ import Link from 'next/link';
import { Tooltip } from '@/ui/tooltip';
import { useModal } from '@/providers/global-modal-provider';
import { useAppState } from '@/providers/app-state-provider/context';
import { IconButton } from '@/ui/button';
import useLocalStorage from '@/hooks/use-local-storage';
import usePageMetaList from '@/hooks/use-page-meta-list';
import { usePageHelper } from '@/hooks/use-page-helper';
import { useTranslation } from 'react-i18next';
const FavoriteList = ({ showList }: { showList: boolean }) => {
const { openPage } = usePageHelper();
const pageList = usePageMetaList();
const router = useRouter();
const { t } = useTranslation();
const favoriteList = pageList.filter(p => p.favorite && !p.trash);
return (
<Collapse in={showList}>
@@ -59,7 +59,7 @@ const FavoriteList = ({ showList }: { showList: boolean }) => {
);
})}
{favoriteList.length === 0 && (
<StyledSubListItem disable={true}>No item</StyledSubListItem>
<StyledSubListItem disable={true}>{t('No item')}</StyledSubListItem>
)}
</Collapse>
);
@@ -70,7 +70,7 @@ export const WorkSpaceSliderBar = () => {
const { currentWorkspaceId } = useAppState();
const { openPage, createPage } = usePageHelper();
const router = useRouter();
const { t } = useTranslation();
const [showTip, setShowTip] = useState(false);
const [show, setShow] = useLocalStorage('AFFiNE_SLIDE_BAR', false, true);
@@ -86,7 +86,7 @@ export const WorkSpaceSliderBar = () => {
<>
<StyledSliderBar show={show}>
<Tooltip
content={show ? 'Collapse sidebar' : 'Expand sidebar'}
content={show ? t('Collapse sidebar') : t('Expand sidebar')}
placement="right"
visible={showTip}
>
@@ -109,9 +109,9 @@ export const WorkSpaceSliderBar = () => {
</Tooltip>
<StyledSliderBarWrapper data-testid="sliderBar">
<StyledListItemForWorkspace>
{/* <StyledListItemForWorkspace>
<WorkspaceSelector />
</StyledListItemForWorkspace>
</StyledListItemForWorkspace> */}
<StyledListItem
data-testid="sliderBar-quickSearchButton"
style={{ cursor: 'pointer' }}
@@ -120,17 +120,17 @@ export const WorkSpaceSliderBar = () => {
}}
>
<SearchIcon />
Quick search
{t('Quick search')}
</StyledListItem>
<Link href={{ pathname: paths.all }}>
<StyledListItem active={router.asPath === paths.all}>
<AllPagesIcon /> <span>All pages</span>
<AllPagesIcon /> <span>{t('All pages')}</span>
</StyledListItem>
</Link>
<StyledListItem active={router.asPath === paths.favorite}>
<StyledLink href={{ pathname: paths.favorite }}>
<FavouritesIcon />
Favourites
{t('Favourites')}
</StyledLink>
<IconButton
darker={true}
@@ -152,12 +152,12 @@ export const WorkSpaceSliderBar = () => {
triggerImportModal();
}}
>
<ImportIcon /> Import
<ImportIcon /> {t('Import')}
</StyledListItem>
<Link href={{ pathname: paths.trash }}>
<StyledListItem active={router.asPath === paths.trash}>
<TrashIcon /> Trash
<TrashIcon /> {t('Trash')}
</StyledListItem>
</Link>
<StyledNewPageButton
@@ -168,7 +168,7 @@ export const WorkSpaceSliderBar = () => {
}
}}
>
<AddIcon /> New Page
<AddIcon /> {t('New Page')}
</StyledNewPageButton>
</StyledSliderBarWrapper>
</StyledSliderBar>
@@ -1,8 +1,8 @@
import { useState, useEffect } from 'react';
import { useAppState } from '@/providers/app-state-provider';
import { useRouter } from 'next/router';
const defaultOutLineWorkspaceId =
'local-first-' + '85b4ca0b9081421d903bbc2501ea280f';
const defaultOutLineWorkspaceId = 'affine';
// 'local-first-' + '85b4ca0b9081421d903bbc2501ea280f';
// It is a fully effective hook
// Cause it not just ensure workspace loaded, but also have router change.
export const useEnsureWorkspace = () => {
+2 -2
View File
@@ -17,7 +17,7 @@ export const usePropsUpdated: UsePropsUpdated = () => {
return;
}
setTimeout(() => {
editor.model?.propsUpdated.on(() => {
editor.pageBlockModel?.propsUpdated.on(() => {
callbackQueue.current.forEach(callback => {
callback(editor);
});
@@ -26,7 +26,7 @@ export const usePropsUpdated: UsePropsUpdated = () => {
return () => {
callbackQueue.current = [];
editor?.model?.propsUpdated.dispose();
editor?.pageBlockModel?.propsUpdated?.dispose();
};
}, [editor]);
+62 -25
View File
@@ -1,28 +1,65 @@
{
"Sync to Disk": "Sync to Disk",
"Share": "Share",
"WarningTips": {
"IsNotfsApiSupported": "Welcome to the AFFiNE demo. To begin saving changes you can SYNC DATA TO DISK with the latest version of Chromium based browser like Chrome/Edge",
"IsNotLocalWorkspace": "Welcome to the AFFiNE demo. To begin saving changes you can SYNC TO DISK.",
"DoNotStore": "AFFiNE is under active development and the current version is UNSTABLE. Please DO NOT store information or data"
},
"Layout": "Layout",
"Comment": "Comment",
"Settings": "Settings",
"ComingSoon": "Layout Settings Coming Soon...",
"Duplicate Page": "Duplicate Page",
"Copy Page Link": "Copy Page Link",
"Language": "Language",
"Clear Workspace": "Clear Workspace",
"Export As Markdown": "Export As Markdown",
"Export As HTML": "Export As HTML",
"Export As PDF (Unsupported)": "Export As PDF (Unsupported)",
"Import Workspace": "Import Workspace",
"Export Workspace": "Export Workspace",
"Last edited by": "Last edited by {{name}}",
"Logout": "Logout",
"Quick search": "Quick search",
"All pages": "All pages",
"Favourites": "Favourites",
"No item": "No item",
"Import": "Import",
"Trash": "Trash",
"New Page": "New Page",
"New Keyword Page": "New '{{query}}' page",
"Find 0 result": "Find 0 result",
"Find results": "Find {{number}} results",
"Collapse sidebar": "Collapse sidebar",
"Expand sidebar": "Expand sidebar",
"Removed from Favourites": "Removed from Favourites",
"Remove from favourites": "Remove from favourites",
"Added to Favourites": "Added to Favourites",
"Add to favourites": "Add to favourites",
"Paper": "Paper",
"Edgeless": "Edgeless",
"Switch to": "Switch to",
"Convert to ": "Convert to ",
"Page": "Page",
"Export": "Export",
"Export to HTML": "Export to HTML",
"Export to Markdown": "Export to Markdown",
"Delete": "Delete",
"Turn into": "Turn into",
"Add A Below Block": "Add A Below Block",
"Divide Here As A New Group": "Divide Here As A New Group"
"Title": "Title",
"Untitled": "Untitled",
"Created": "Created",
"Updated": "Updated",
"Open in new tab": "Open in new tab",
"Favourite": "Favourite",
"Favourited": "Favourited",
"Delete page?": "Delete page?",
"Delete permanently?": "Delete permanently?",
"will be moved to Trash": "{{title}} will be moved to Trash",
"Once deleted, you can't undo this action.": "Once deleted,you can't undo this action.",
"Moved to Trash": "Moved to Trash",
"Permanently deleted": "Permanently deleted",
"restored": "{{title}} restored",
"Cancel": "Cancel",
"Keyboard Shortcuts": "Keyboard Shortcuts",
"Contact Us": "Contact Us",
"Official Website": "Official Website",
"Get in touch!": "Get in touch!",
"AFFiNE Community": "AFFiNE Community",
"How is AFFiNE Alpha different?": "How is AFFiNE Alpha different?",
"Shortcuts": "Shortcuts",
"Undo": "Undo",
"Redo": "Redo",
"Bold": "Bold",
"Italic": "Italic",
"Underline": "Underline",
"Strikethrough": "Strikethrough",
"Inline code": "Inline code",
"Code block": "Code block",
"Link": "Link",
"Body text": "Body text",
"Heading": "Heading {{number}}",
"Increase indent": "Increase indent",
"Reduce indent": "Reduce indent",
"Markdown Syntax": "Markdown Syntax",
"Divider": "Divider",
"404 - Page Not Found": "404 - Page Not Found"
}
+1
View File
@@ -18,6 +18,7 @@ import { useEffect } from 'react';
import { useAppState } from '@/providers/app-state-provider';
import { PageLoading } from '@/components/loading';
import Head from 'next/head';
import '@/libs/i18n';
const ThemeProvider = dynamic(() => import('@/providers/themeProvider'), {
ssr: false,
@@ -43,12 +43,16 @@ const All = () => {
if (page) {
currentWorkspace?.setPageMeta(page.id, { title });
if (page && page.root === null) {
setTimeout(() => {
setTimeout(async () => {
const editor = document.querySelector('editor-container');
if (editor) {
const groupId = page.addBlock({ flavour: 'affine:group' }, pageId);
page.addBlock({ flavour: 'affine:surface' }, null);
const frameId = page.addBlock({ flavour: 'affine:frame' }, pageId);
// TODO blocksuite should offer a method to import markdown from store
editor.clipboard.importMarkdown(template.source, `${groupId}`);
await editor.clipboard.importMarkdown(
template.source,
`${frameId}`
);
page.resetHistory();
editor.requestUpdate();
}
@@ -1,10 +1,10 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import {
useRef,
useEffect,
useState,
ReactElement,
PropsWithChildren,
ReactElement,
useEffect,
useRef,
useState,
} from 'react';
import { styled } from '@/styles';
import { EditorHeader } from '@/components/header';
@@ -16,9 +16,11 @@ import type { NextPageWithLayout } from '../..//_app';
import WorkspaceLayout from '@/components/workspace-layout';
import { useRouter } from 'next/router';
import { usePageHelper } from '@/hooks/use-page-helper';
const StyledEditorContainer = styled('div')(() => {
return {
height: 'calc(100vh - 60px)',
padding: '0 32px',
};
});
@@ -54,15 +56,20 @@ const Page: NextPageWithLayout = () => {
flavour: 'affine:page',
title,
});
const groupId = currentPage!.addBlock(
{ flavour: 'affine:group' },
currentPage!.addBlock({ flavour: 'affine:surface' }, null);
const frameId = currentPage!.addBlock(
{ flavour: 'affine:frame' },
pageId
);
currentPage!.addBlock({ flavour: 'affine:group' }, pageId);
currentPage!.addBlock({ flavour: 'affine:frame' }, pageId);
// If this is a first page in workspace, init an introduction markdown
if (isFirstPage) {
editor.clipboard.importMarkdown(exampleMarkdown, `${groupId}`);
currentWorkspace!.setPageMeta(currentPage!.id, { title });
editor.clipboard
.importMarkdown(exampleMarkdown, `${frameId}`)
.then(() => {
currentWorkspace!.setPageMeta(currentPage!.id, { title });
currentPage!.resetHistory();
});
}
currentPage!.resetHistory();
}
@@ -4,13 +4,13 @@ import usePageMetaList from '@/hooks/use-page-meta-list';
import { PageListHeader } from '@/components/header';
import { ReactElement } from 'react';
import WorkspaceLayout from '@/components/workspace-layout';
import { useTranslation } from 'react-i18next';
const All = () => {
const pageMetaList = usePageMetaList();
const { t } = useTranslation();
return (
<>
<PageListHeader icon={<AllPagesIcon />}>All Page</PageListHeader>
<PageListHeader icon={<AllPagesIcon />}>{t('All pages')}</PageListHeader>
<PageList
pageList={pageMetaList.filter(p => !p.trash)}
showFavoriteTag={true}
@@ -4,12 +4,15 @@ import { FavouritesIcon } from '@blocksuite/icons';
import usePageMetaList from '@/hooks/use-page-meta-list';
import { ReactElement } from 'react';
import WorkspaceLayout from '@/components/workspace-layout';
import { useTranslation } from 'react-i18next';
export const Favorite = () => {
const pageMetaList = usePageMetaList();
const { t } = useTranslation();
return (
<>
<PageListHeader icon={<FavouritesIcon />}>Favourites</PageListHeader>
<PageListHeader icon={<FavouritesIcon />}>
{t('Favourites')}
</PageListHeader>
<PageList pageList={pageMetaList.filter(p => p.favorite && !p.trash)} />
</>
);
@@ -4,12 +4,13 @@ import { TrashIcon } from '@blocksuite/icons';
import usePageMetaList from '@/hooks/use-page-meta-list';
import { ReactElement } from 'react';
import WorkspaceLayout from '@/components/workspace-layout';
import { useTranslation } from 'react-i18next';
export const Trash = () => {
const pageMetaList = usePageMetaList();
const { t } = useTranslation();
return (
<>
<PageListHeader icon={<TrashIcon />}>Trash</PageListHeader>
<PageListHeader icon={<TrashIcon />}>{t('Trash')}</PageListHeader>
<PageList pageList={pageMetaList.filter(p => p.trash)} isTrash={true} />
</>
);
@@ -18,7 +18,7 @@ const DynamicBlocksuite = ({
const openWorkspace: LoadWorkspaceHandler = async (workspaceId: string) => {
if (workspaceId) {
const dc = await getDataCenter();
return dc.load(workspaceId, { providerId: 'affine' });
return dc.load(workspaceId, { providerId: 'selfhosted' });
} else {
return null;
}
@@ -10,6 +10,11 @@ Let us know what you think of this latest version.
2. More complete Markdown support and improved keyboard shortcuts;
3. New features such as dark mode; Switch between view styles using the ☀ and 🌙.
4. Clean and modern UI/UX design.
5. You can self-host locally with Docker.
```basic
docker run -d -v [YOUR_PATH]:/app/data -p 3000:3000 ghcr.io/toeverything/affine-self-hosted:alpha-abbey-wood
```
**Looking for Markdown syntax or keyboard shortcuts?**
@@ -23,15 +28,21 @@ Let us know what you think of this latest version.
- Copy and paste **images** into your pages, resize them and add captions
- Add horizontal line dividers to your text with `---` and `***`
- Changes are saved **locally**, but we still recommend you export your data to avoid data loss
- Insert code blocks with syntax highlighting support using ```
- Insert code blocks with syntax highlighting support using `````
### Playground:
[] Try a horiztaonl line: `---`
[] Try a horizontal line: `---`
[] What about a code block? ```
[] What about a code block? `````
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;console.log('Hello world');
```javascript
console.log('Hello world');
```
[] Can you resize this image?
![](https://cdn.affine.pro/694fdbab78e0da3ed7922eba7d506dcf12f57308e1904dd694f53eb2.jpg)
**How about page management?**
+3 -1
View File
@@ -7,6 +7,7 @@ import {
StyledModalWrapper,
} from '@/ui/confirm/styles';
import { Button } from '@/ui/button';
import { useTranslation } from 'react-i18next';
export type ConfirmProps = {
title?: string;
content?: string;
@@ -26,6 +27,7 @@ export const Confirm = ({
onCancel,
}: ConfirmProps) => {
const [open, setOpen] = useState(true);
const { t } = useTranslation();
return (
<Modal open={open}>
<StyledModalWrapper>
@@ -48,7 +50,7 @@ export const Confirm = ({
}}
style={{ marginRight: '24px' }}
>
Cancel
{t('Cancel')}
</Button>
<Button
type={confirmType}
+2 -2
View File
@@ -26,8 +26,8 @@
"typescript": "^4.8.4"
},
"dependencies": {
"@blocksuite/blocks": "^0.3.1",
"@blocksuite/store": "^0.3.1",
"@blocksuite/blocks": "=0.3.1-20230106060050-1aad55d",
"@blocksuite/store": "=0.3.1-20230106060050-1aad55d",
"debug": "^4.3.4",
"encoding": "^0.1.13",
"firebase": "^9.15.0",
@@ -0,0 +1,63 @@
import assert from 'assert';
import { LocalProvider } from '../local/index.js';
import { WebsocketProvider } from './sync.js';
export class SelfHostedProvider extends LocalProvider {
static id = 'selfhosted';
private _ws?: WebsocketProvider;
constructor() {
super();
}
async destroy() {
this._ws?.disconnect();
}
async initData() {
const databases = await indexedDB.databases();
await super.initData(
// set locally to true if exists a same name db
databases
.map(db => db.name)
.filter(v => v)
.includes(this._workspace.room)
);
const workspace = this._workspace;
const doc = workspace.doc;
if (workspace.room) {
try {
// Wait for ws synchronization to complete, otherwise the data will be modified in reverse, which can be optimized later
this._ws = new WebsocketProvider(this.host, workspace.room, doc);
await new Promise<void>((resolve, reject) => {
// TODO: synced will also be triggered on reconnection after losing sync
// There needs to be an event mechanism to emit the synchronization state to the upper layer
assert(this._ws);
this._ws.once('synced', () => resolve());
this._ws.once('lost-connection', () => resolve());
this._ws.once('connection-error', () => reject());
});
this._signals.listAdd.emit({
workspace: workspace.room,
provider: this.id,
locally: true,
});
} catch (e) {
this._logger('Failed to init cloud workspace', e);
}
}
// if after update, the space:meta is empty
// then we need to get map with doc
// just a workaround for yjs
doc.getMap('space:meta');
}
private get host() {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${protocol}//${location.host}/collaboration/`;
}
}
@@ -0,0 +1,508 @@
/* eslint-disable no-undef */
/**
* @module provider/websocket
*/
/* eslint-env browser */
// import * as Y from 'yjs'; // eslint-disable-line
import * as bc from 'lib0/broadcastchannel';
import * as time from 'lib0/time';
import * as encoding from 'lib0/encoding';
import * as decoding from 'lib0/decoding';
import * as syncProtocol from 'y-protocols/sync';
import * as authProtocol from 'y-protocols/auth';
import * as awarenessProtocol from 'y-protocols/awareness';
import { Observable } from 'lib0/observable';
import * as math from 'lib0/math';
import * as url from 'lib0/url';
export const messageSync = 0;
export const messageQueryAwareness = 3;
export const messageAwareness = 1;
export const messageAuth = 2;
/**
* encoder, decoder, provider, emitSynced, messageType
* @type {Array<function(encoding.Encoder, decoding.Decoder, WebsocketProvider, boolean, number):void>}
*/
const messageHandlers = [];
messageHandlers[messageSync] = (
encoder,
decoder,
provider,
emitSynced,
_messageType
) => {
encoding.writeVarUint(encoder, messageSync);
const syncMessageType = syncProtocol.readSyncMessage(
decoder,
encoder,
provider.doc,
provider
);
if (
emitSynced &&
syncMessageType === syncProtocol.messageYjsSyncStep2 &&
!provider.synced
) {
provider.synced = true;
}
};
messageHandlers[messageQueryAwareness] = (
encoder,
_decoder,
provider,
_emitSynced,
_messageType
) => {
encoding.writeVarUint(encoder, messageAwareness);
encoding.writeVarUint8Array(
encoder,
awarenessProtocol.encodeAwarenessUpdate(
provider.awareness,
Array.from(provider.awareness.getStates().keys())
)
);
};
messageHandlers[messageAwareness] = (
_encoder,
decoder,
provider,
_emitSynced,
_messageType
) => {
awarenessProtocol.applyAwarenessUpdate(
provider.awareness,
decoding.readVarUint8Array(decoder),
provider
);
};
messageHandlers[messageAuth] = (
_encoder,
decoder,
provider,
_emitSynced,
_messageType
) => {
authProtocol.readAuthMessage(decoder, provider.doc, (_ydoc, reason) =>
permissionDeniedHandler(provider, reason)
);
};
// @todo - this should depend on awareness.outdatedTime
const messageReconnectTimeout = 30000;
/**
* @param {WebsocketProvider} provider
* @param {string} reason
*/
const permissionDeniedHandler = (provider, reason) =>
console.warn(`Permission denied to access ${provider.url}.\n${reason}`);
/**
* @param {WebsocketProvider} provider
* @param {Uint8Array} buf
* @param {boolean} emitSynced
* @return {encoding.Encoder}
*/
const readMessage = (provider, buf, emitSynced) => {
const decoder = decoding.createDecoder(buf);
const encoder = encoding.createEncoder();
const messageType = decoding.readVarUint(decoder);
const messageHandler = provider.messageHandlers[messageType];
if (/** @type {any} */ (messageHandler)) {
messageHandler(encoder, decoder, provider, emitSynced, messageType);
} else {
console.error('Unable to compute message');
}
return encoder;
};
/**
* @param {WebsocketProvider} provider
*/
const setupWS = provider => {
if (provider.shouldConnect && provider.ws === null) {
const websocket = new provider._WS(provider.url, 'AFFiNE');
websocket.binaryType = 'arraybuffer';
provider.ws = websocket;
provider.wsconnecting = true;
provider.wsconnected = false;
provider.synced = false;
websocket.onmessage = event => {
provider.wsLastMessageReceived = time.getUnixTime();
const encoder = readMessage(provider, new Uint8Array(event.data), true);
if (encoding.length(encoder) > 1) {
websocket.send(encoding.toUint8Array(encoder));
}
};
websocket.onerror = event => {
provider.emit('connection-error', [event, provider]);
};
websocket.onclose = event => {
provider.emit('connection-close', [event, provider]);
provider.ws = null;
provider.wsconnecting = false;
if (provider.wsconnected) {
provider.wsconnected = false;
provider.synced = false;
// update awareness (all users except local left)
awarenessProtocol.removeAwarenessStates(
provider.awareness,
Array.from(provider.awareness.getStates().keys()).filter(
client => client !== provider.doc.clientID
),
provider
);
provider.emit('status', [
{
status: 'disconnected',
},
]);
} else {
provider.wsUnsuccessfulReconnects++;
}
// Start with no reconnect timeout and increase timeout by
// using exponential backoff starting with 100ms
setTimeout(
setupWS,
math.min(
math.pow(2, provider.wsUnsuccessfulReconnects) * 100,
provider.maxBackoffTime
),
provider
);
};
websocket.onopen = () => {
provider.wsLastMessageReceived = time.getUnixTime();
provider.wsconnecting = false;
provider.wsconnected = true;
provider.wsUnsuccessfulReconnects = 0;
provider.emit('status', [
{
status: 'connected',
},
]);
// always send sync step 1 when connected
const encoder = encoding.createEncoder();
encoding.writeVarUint(encoder, messageSync);
syncProtocol.writeSyncStep1(encoder, provider.doc);
websocket.send(encoding.toUint8Array(encoder));
// broadcast local awareness state
if (provider.awareness.getLocalState() !== null) {
const encoderAwarenessState = encoding.createEncoder();
encoding.writeVarUint(encoderAwarenessState, messageAwareness);
encoding.writeVarUint8Array(
encoderAwarenessState,
awarenessProtocol.encodeAwarenessUpdate(provider.awareness, [
provider.doc.clientID,
])
);
websocket.send(encoding.toUint8Array(encoderAwarenessState));
}
};
provider.emit('status', [
{
status: 'connecting',
},
]);
}
};
/**
* @param {WebsocketProvider} provider
* @param {ArrayBuffer} buf
*/
const broadcastMessage = (provider, buf) => {
if (provider.wsconnected) {
/** @type {WebSocket} */ (provider.ws).send(buf);
}
if (provider.bcconnected) {
bc.publish(provider.bcChannel, buf, provider);
}
};
/**
* Websocket Provider for Yjs. Creates a websocket connection to sync the shared document.
* The document name is attached to the provided url. I.e. the following example
* creates a websocket connection to http://localhost:1234/my-document-name
*
* @example
* import * as Y from 'yjs'
* import { WebsocketProvider } from 'y-websocket'
* const doc = new Y.Doc()
* const provider = new WebsocketProvider('http://localhost:1234', 'my-document-name', doc)
*
* @extends {Observable<string>}
*/
export class WebsocketProvider extends Observable {
/**
* @param {string} serverUrl
* @param {string} roomname
* @param {Y.Doc} doc
* @param {object} [opts]
* @param {boolean} [opts.connect]
* @param {awarenessProtocol.Awareness} [opts.awareness]
* @param {Object<string,string>} [opts.params]
* @param {typeof WebSocket} [opts.WebSocketPolyfill] Optionall provide a WebSocket polyfill
* @param {number} [opts.resyncInterval] Request server state every `resyncInterval` milliseconds
* @param {number} [opts.maxBackoffTime] Maximum amount of time to wait before trying to reconnect (we try to reconnect using exponential backoff)
* @param {boolean} [opts.disableBc] Disable cross-tab BroadcastChannel communication
*/
constructor(
serverUrl,
roomname,
doc,
{
connect = true,
awareness = new awarenessProtocol.Awareness(doc),
params = {},
WebSocketPolyfill = WebSocket,
resyncInterval = -1,
maxBackoffTime = 2500,
disableBc = false,
} = {}
) {
super();
// ensure that url is always ends with /
while (serverUrl[serverUrl.length - 1] === '/') {
serverUrl = serverUrl.slice(0, serverUrl.length - 1);
}
const encodedParams = url.encodeQueryParams(params);
this.maxBackoffTime = maxBackoffTime;
this.bcChannel = serverUrl + '/' + roomname;
this.url =
serverUrl +
'/' +
roomname +
(encodedParams.length === 0 ? '' : '?' + encodedParams);
this.roomname = roomname;
this.doc = doc;
this._WS = WebSocketPolyfill;
this.awareness = awareness;
this.wsconnected = false;
this.wsconnecting = false;
this.bcconnected = false;
this.disableBc = disableBc;
this.wsUnsuccessfulReconnects = 0;
this.messageHandlers = messageHandlers.slice();
/**
* @type {boolean}
*/
this._synced = false;
/**
* @type {WebSocket?}
*/
this.ws = null;
this.wsLastMessageReceived = 0;
/**
* Whether to connect to other peers or not
* @type {boolean}
*/
this.shouldConnect = connect;
/**
* @type {number}
*/
this._resyncInterval = 0;
if (resyncInterval > 0) {
this._resyncInterval = /** @type {any} */ (
setInterval(() => {
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
// resend sync step 1
const encoder = encoding.createEncoder();
encoding.writeVarUint(encoder, messageSync);
syncProtocol.writeSyncStep1(encoder, doc);
this.ws.send(encoding.toUint8Array(encoder));
}
}, resyncInterval)
);
}
/**
* @param {ArrayBuffer} data
* @param {any} origin
*/
this._bcSubscriber = (data, origin) => {
if (origin !== this) {
const encoder = readMessage(this, new Uint8Array(data), false);
if (encoding.length(encoder) > 1) {
bc.publish(this.bcChannel, encoding.toUint8Array(encoder), this);
}
}
};
/**
* Listens to Yjs updates and sends them to remote peers (ws and broadcastchannel)
* @param {Uint8Array} update
* @param {any} origin
*/
this._updateHandler = (update, origin) => {
if (origin !== this) {
const encoder = encoding.createEncoder();
encoding.writeVarUint(encoder, messageSync);
syncProtocol.writeUpdate(encoder, update);
broadcastMessage(this, encoding.toUint8Array(encoder));
}
};
this.doc.on('update', this._updateHandler);
/**
* @param {any} changed
* @param {any} _origin
*/
this._awarenessUpdateHandler = ({ added, updated, removed }, _origin) => {
const changedClients = added.concat(updated).concat(removed);
const encoder = encoding.createEncoder();
encoding.writeVarUint(encoder, messageAwareness);
encoding.writeVarUint8Array(
encoder,
awarenessProtocol.encodeAwarenessUpdate(awareness, changedClients)
);
broadcastMessage(this, encoding.toUint8Array(encoder));
};
this._unloadHandler = () => {
awarenessProtocol.removeAwarenessStates(
this.awareness,
[doc.clientID],
'window unload'
);
};
if (typeof window !== 'undefined') {
window.addEventListener('unload', this._unloadHandler);
} else if (typeof process !== 'undefined') {
process.on('exit', this._unloadHandler);
}
awareness.on('update', this._awarenessUpdateHandler);
this._checkInterval = /** @type {any} */ (
setInterval(() => {
if (
this.wsconnected &&
messageReconnectTimeout <
time.getUnixTime() - this.wsLastMessageReceived
) {
// no message received in a long time - not even your own awareness
// updates (which are updated every 15 seconds)
/** @type {WebSocket} */ (this.ws).close();
}
}, messageReconnectTimeout / 10)
);
if (connect) {
this.connect();
}
}
/**
* @type {boolean}
*/
get synced() {
return this._synced;
}
set synced(state) {
if (this._synced !== state) {
this._synced = state;
this.emit('synced', [state]);
this.emit('sync', [state]);
}
}
destroy() {
if (this._resyncInterval !== 0) {
clearInterval(this._resyncInterval);
}
clearInterval(this._checkInterval);
this.disconnect();
if (typeof window !== 'undefined') {
window.removeEventListener('unload', this._unloadHandler);
} else if (typeof process !== 'undefined') {
process.off('exit', this._unloadHandler);
}
this.awareness.off('update', this._awarenessUpdateHandler);
this.doc.off('update', this._updateHandler);
super.destroy();
}
connectBc() {
if (this.disableBc) {
return;
}
if (!this.bcconnected) {
bc.subscribe(this.bcChannel, this._bcSubscriber);
this.bcconnected = true;
}
// send sync step1 to bc
// write sync step 1
const encoderSync = encoding.createEncoder();
encoding.writeVarUint(encoderSync, messageSync);
syncProtocol.writeSyncStep1(encoderSync, this.doc);
bc.publish(this.bcChannel, encoding.toUint8Array(encoderSync), this);
// broadcast local state
const encoderState = encoding.createEncoder();
encoding.writeVarUint(encoderState, messageSync);
syncProtocol.writeSyncStep2(encoderState, this.doc);
bc.publish(this.bcChannel, encoding.toUint8Array(encoderState), this);
// write queryAwareness
const encoderAwarenessQuery = encoding.createEncoder();
encoding.writeVarUint(encoderAwarenessQuery, messageQueryAwareness);
bc.publish(
this.bcChannel,
encoding.toUint8Array(encoderAwarenessQuery),
this
);
// broadcast local awareness state
const encoderAwarenessState = encoding.createEncoder();
encoding.writeVarUint(encoderAwarenessState, messageAwareness);
encoding.writeVarUint8Array(
encoderAwarenessState,
awarenessProtocol.encodeAwarenessUpdate(this.awareness, [
this.doc.clientID,
])
);
bc.publish(
this.bcChannel,
encoding.toUint8Array(encoderAwarenessState),
this
);
}
disconnectBc() {
// broadcast message with local awareness state set to null (indicating disconnect)
const encoder = encoding.createEncoder();
encoding.writeVarUint(encoder, messageAwareness);
encoding.writeVarUint8Array(
encoder,
awarenessProtocol.encodeAwarenessUpdate(
this.awareness,
[this.doc.clientID],
new Map()
)
);
broadcastMessage(this, encoding.toUint8Array(encoder));
if (this.bcconnected) {
bc.unsubscribe(this.bcChannel, this._bcSubscriber);
this.bcconnected = false;
}
}
disconnect() {
this.shouldConnect = false;
this.disconnectBc();
if (this.ws !== null) {
this.ws.close();
}
}
connect() {
this.shouldConnect = true;
if (!this.wsconnected && this.ws === null) {
setupWS(this);
this.connectBc();
}
}
}
+30 -55
View File
@@ -43,10 +43,10 @@ importers:
packages/app:
specifiers:
'@affine/datacenter': workspace:*
'@blocksuite/blocks': 0.3.1
'@blocksuite/editor': 0.3.1
'@blocksuite/blocks': '=0.3.1-20230106060050-1aad55d'
'@blocksuite/editor': '=0.3.1-20230106060050-1aad55d'
'@blocksuite/icons': ^2.0.2
'@blocksuite/store': 0.3.1
'@blocksuite/store': '=0.3.1-20230106060050-1aad55d'
'@emotion/css': ^11.10.0
'@emotion/react': ^11.10.4
'@emotion/server': ^11.10.0
@@ -61,7 +61,7 @@ importers:
'@types/react': 18.0.20
'@types/react-dom': 18.0.6
'@types/wicg-file-system-access': ^2020.9.5
chalk-next: ^6.1.5
chalk: ^4.1.2
cmdk: ^0.1.20
css-spring: ^4.1.0
dayjs: ^1.11.7
@@ -85,10 +85,10 @@ importers:
yjs: ^13.5.44
dependencies:
'@affine/datacenter': link:../data-center
'@blocksuite/blocks': 0.3.1_yjs@13.5.44
'@blocksuite/editor': 0.3.1_yjs@13.5.44
'@blocksuite/blocks': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
'@blocksuite/editor': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
'@blocksuite/icons': 2.0.4_w5j4k42lgipnm43s3brx6h3c34
'@blocksuite/store': 0.3.1_yjs@13.5.44
'@blocksuite/store': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
'@emotion/css': 11.10.0
'@emotion/react': 11.10.4_w5j4k42lgipnm43s3brx6h3c34
'@emotion/server': 11.10.0_@emotion+css@11.10.0
@@ -118,7 +118,7 @@ importers:
'@types/react': 18.0.20
'@types/react-dom': 18.0.6
'@types/wicg-file-system-access': 2020.9.5
chalk-next: 6.1.5
chalk: 4.1.2
eslint: 8.22.0
eslint-config-next: 12.3.1_76twfck5d7crjqrmw4yltga7zm
eslint-config-prettier: 8.5.0_eslint@8.22.0
@@ -129,8 +129,8 @@ importers:
packages/data-center:
specifiers:
'@blocksuite/blocks': ^0.3.1
'@blocksuite/store': ^0.3.1
'@blocksuite/blocks': '=0.3.1-20230106060050-1aad55d'
'@blocksuite/store': '=0.3.1-20230106060050-1aad55d'
'@playwright/test': ^1.29.1
'@types/debug': ^4.1.7
debug: ^4.3.4
@@ -146,8 +146,8 @@ importers:
y-protocols: ^1.0.5
yjs: ^13.5.44
dependencies:
'@blocksuite/blocks': 0.3.1_yjs@13.5.44
'@blocksuite/store': 0.3.1_yjs@13.5.44
'@blocksuite/blocks': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
'@blocksuite/store': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
debug: 4.3.4
encoding: 0.1.13
firebase: 9.15.0_encoding@0.1.13
@@ -1443,10 +1443,11 @@ packages:
to-fast-properties: 2.0.0
dev: true
/@blocksuite/blocks/0.3.1_yjs@13.5.44:
resolution: {integrity: sha512-b0dGz2MG4yIgngJPRumaMY58wAsd2FEVSZl3tpCXlagK9I0HD165Bq70PxcaRHVjBSV1Gf29ZVHUF6BVTYogPw==}
/@blocksuite/blocks/0.3.1-20230106060050-1aad55d_yjs@13.5.44:
resolution: {integrity: sha512-qRNXmhjw+GAGsV1mI2XXPxYTlHfsFHv9ttTCNQ6IIcxvc5Hh6lWmdwVibxvlpYUkgEc1zv3/GxOEsR/ngpZXzQ==}
dependencies:
'@blocksuite/store': 0.3.1_yjs@13.5.44
'@blocksuite/phasor': 0.3.1_yjs@13.5.44
'@blocksuite/store': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
'@tldraw/intersect': 1.8.0
autosize: 5.0.2
highlight.js: 11.7.0
@@ -1462,11 +1463,11 @@ packages:
- yjs
dev: false
/@blocksuite/editor/0.3.1_yjs@13.5.44:
resolution: {integrity: sha512-ycKcyvPW6R8R2GZOFneGH1xNi5gJBx5WtWjW9YwcQslFzXVWMCCBips1Bud2uL4kkbWQoodyua6k2vsXxGAKLw==}
/@blocksuite/editor/0.3.1-20230106060050-1aad55d_yjs@13.5.44:
resolution: {integrity: sha512-wSlAF9XVxIkHFJ1qCzn7oQ/gwXybFYMrzRl35UTJV509D+DuWZefRZWvpdIDCOUJ24uQscr1HxwsON11ltfWgA==}
dependencies:
'@blocksuite/blocks': 0.3.1_yjs@13.5.44
'@blocksuite/store': 0.3.1_yjs@13.5.44
'@blocksuite/blocks': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
'@blocksuite/store': 0.3.1-20230106060050-1aad55d_yjs@13.5.44
lit: 2.5.0
marked: 4.2.5
turndown: 7.1.1
@@ -1487,8 +1488,16 @@ packages:
react: 18.2.0
dev: false
/@blocksuite/store/0.3.1_yjs@13.5.44:
resolution: {integrity: sha512-kynVTDfNCSChz2JI2rtGHxRIV2YrLzvAgVajcbfDVCuXKG0siBoEjLasG1a0kvevbvW/FabrNAj+xaIplklioA==}
/@blocksuite/phasor/0.3.1_yjs@13.5.44:
resolution: {integrity: sha512-aJmAQn2qoF6HxFZWgq7xa/pWVyzg3MmD6dynIHAKdfN7rBdKk3PNA+lRX919QkD2e270N/zgHEGFFQI1Nj5xrA==}
peerDependencies:
yjs: ^13
dependencies:
yjs: 13.5.44
dev: false
/@blocksuite/store/0.3.1-20230106060050-1aad55d_yjs@13.5.44:
resolution: {integrity: sha512-dRy+YzlWMwiYq0Im9NogK/NTkV+NKK+lgejYq56m6nH2m16/G9AMODqP0oQy/XeYFevUpL9i9RdV0rHsJ2gc0Q==}
peerDependencies:
yjs: ^13
dependencies:
@@ -4006,14 +4015,6 @@ packages:
engines: {node: '>=4'}
dev: true
/axios/0.21.4:
resolution: {integrity: sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==}
dependencies:
follow-redirects: 1.15.2
transitivePeerDependencies:
- debug
dev: true
/axobject-query/2.2.0:
resolution: {integrity: sha512-Td525n+iPOOyUQIeBfcASuG6uJsDOITl7Mds5gFyerkWiX7qhUTdYUBlSgNMyVqtSJqwpt1kXGLdUt6SykLMRA==}
dev: true
@@ -4215,18 +4216,6 @@ packages:
type-detect: 4.0.8
dev: true
/chalk-next/6.1.5:
resolution: {integrity: sha512-OAx9F3vSk18qpfCohk0849/j3GyaoIpv8eXjmpdbmLZt+5+sWYq8xwt3B5ue25irLcxFcLL2hAbxxHSsBxupbw==}
engines: {node: '>=10'}
dependencies:
ansi-styles: 4.3.0
axios: 0.21.4
fs: 0.0.1-security
supports-color: 7.2.0
transitivePeerDependencies:
- debug
dev: true
/chalk/2.4.2:
resolution: {integrity: sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==}
engines: {node: '>=4'}
@@ -5562,16 +5551,6 @@ packages:
resolution: {integrity: sha512-W7cHV7Hrwjid6lWmy0IhsWDFQboWSng25U3VVywpHOTJnnAZNPScog67G+cVpeX9f7yDD21ih0WDrMMT+JoaYg==}
dev: false
/follow-redirects/1.15.2:
resolution: {integrity: sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
peerDependenciesMeta:
debug:
optional: true
dev: true
/form-data-encoder/2.1.4:
resolution: {integrity: sha512-yDYSgNMraqvnxiEXO4hi88+YZxaHC6QKzb5N84iRCTDeRO7ZALpir/lVmf/uXUhnwUr2O4HU8s/n6x+yNjQkHw==}
engines: {node: '>= 14.17'}
@@ -5616,10 +5595,6 @@ packages:
resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
dev: true
/fs/0.0.1-security:
resolution: {integrity: sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==}
dev: true
/fsevents/2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
+1 -4
View File
@@ -12,10 +12,7 @@ test.describe('web console', () => {
//Later on, call this function with some arguments.
// const msg = await getEditoVersionHandle.evaluate((post, args) => post);
// console.log(getEditoVersionHandle);
await page.waitForTimeout(500);
const editoVersion = await page.evaluate(
() => (window as any).__editoVersion
);
const editoVersion = await page.evaluate(() => window.__editoVersion);
// const documentEditorVersion = await page.inputValue('input#editor-version');
const pkgEditorVersion = pkg.dependencies['@blocksuite/editor'];
+1 -1
View File
@@ -8,6 +8,6 @@ export function loadPage() {
test.beforeEach(async ({ page }: IType) => {
await page.goto('http://localhost:8080');
// waiting for page loading end
// await page.waitForTimeout(1000);
await page.waitForSelector('#__next');
});
}
+10 -7
View File
@@ -7,10 +7,13 @@ loadPage();
const openQuickSearchByShortcut = async (page: Page) =>
await withCtrlOrMeta(page, () => page.keyboard.press('k', { delay: 50 }));
async function assertTitleTexts(page: Page, texts: string[]) {
const actual = await page
.locator('.affine-default-page-block-title')
.allTextContents();
async function assertTitleTexts(page: Page, texts: string) {
const actual = await page.evaluate(() => {
const titleElement = <HTMLTextAreaElement>(
document.querySelector('.affine-default-page-block-title')
);
return titleElement.value;
});
expect(actual).toEqual(texts);
}
async function assertResultList(page: Page, texts: string[]) {
@@ -55,7 +58,7 @@ test.describe('Add new page in quick search', () => {
const addNewPage = page.locator('[data-testid=quickSearch-addNewPage]');
await addNewPage.click();
await page.waitForTimeout(200);
await assertTitleTexts(page, ['']);
await assertTitleTexts(page, '');
});
test('Create a new page with keyword', async ({ page }) => {
@@ -65,7 +68,7 @@ test.describe('Add new page in quick search', () => {
const addNewPage = page.locator('[data-testid=quickSearch-addNewPage]');
await addNewPage.click();
await page.waitForTimeout(200);
await assertTitleTexts(page, ['test123456']);
await assertTitleTexts(page, 'test123456');
});
});
@@ -81,6 +84,6 @@ test.describe('Search and select', () => {
await page.keyboard.insertText('test123456');
await assertResultList(page, ['test123456']);
await page.keyboard.press('Enter', { delay: 50 });
await assertTitleTexts(page, ['test123456']);
await assertTitleTexts(page, 'test123456');
});
});