chore: merge blocksuite source code (#9213)

This commit is contained in:
Mirone
2024-12-20 15:38:06 +08:00
committed by GitHub
parent 2c9ef916f4
commit 30200ff86d
2031 changed files with 238888 additions and 229 deletions
@@ -0,0 +1,138 @@
import { AffineSchemas, TestUtils } from '@blocksuite/blocks';
import type { BlockSuiteFlags } from '@blocksuite/global/types';
import { assertExists } from '@blocksuite/global/utils';
import {
type BlockCollection,
DocCollection,
type DocCollectionOptions,
IdGeneratorType,
Job,
Schema,
} from '@blocksuite/store';
import {
type BlobSource,
BroadcastChannelAwarenessSource,
BroadcastChannelDocSource,
IndexedDBBlobSource,
MemoryBlobSource,
} from '@blocksuite/sync';
import { MockServerBlobSource } from '../../_common/sync/blob/mock-server.js';
import type { InitFn } from '../data/utils.js';
const params = new URLSearchParams(location.search);
const room = params.get('room');
const isE2E = room?.startsWith('playwright');
const blobSourceArgs = (params.get('blobSource') ?? '').split(',');
export function createStarterDocCollection() {
const collectionId = room ?? 'starter';
const schema = new Schema();
schema.register(AffineSchemas);
const idGenerator = isE2E
? IdGeneratorType.AutoIncrement
: IdGeneratorType.NanoID;
let docSources: DocCollectionOptions['docSources'];
if (room) {
docSources = {
main: new BroadcastChannelDocSource(`broadcast-channel-${room}`),
};
}
const id = room ?? `starter-${Math.random().toString(16).slice(2, 8)}`;
const blobSources = {
main: new MemoryBlobSource(),
shadows: [] as BlobSource[],
} satisfies DocCollectionOptions['blobSources'];
if (blobSourceArgs.includes('mock')) {
blobSources.shadows.push(new MockServerBlobSource(collectionId));
}
if (blobSourceArgs.includes('idb')) {
blobSources.shadows.push(new IndexedDBBlobSource(collectionId));
}
const flags: Partial<BlockSuiteFlags> = Object.fromEntries(
[...params.entries()]
.filter(([key]) => key.startsWith('enable_'))
.map(([k, v]) => [k, v === 'true'])
);
const options: DocCollectionOptions = {
id: collectionId,
schema,
idGenerator,
defaultFlags: {
enable_synced_doc_block: true,
enable_pie_menu: true,
enable_lasso_tool: true,
enable_edgeless_text: true,
enable_color_picker: true,
enable_mind_map_import: true,
enable_advanced_block_visibility: true,
enable_shape_shadow_blur: false,
...flags,
},
awarenessSources: [new BroadcastChannelAwarenessSource(id)],
docSources,
blobSources,
};
const collection = new DocCollection(options);
collection.start();
// debug info
window.collection = collection;
window.blockSchemas = AffineSchemas;
window.job = new Job({ collection: collection });
window.Y = DocCollection.Y;
window.testUtils = new TestUtils();
return collection;
}
export async function initStarterDocCollection(collection: DocCollection) {
// init from other clients
if (room && !params.has('init')) {
const firstCollection = collection.docs.values().next().value as
| BlockCollection
| undefined;
let firstDoc = firstCollection?.getDoc();
if (!firstDoc) {
await new Promise<string>(resolve =>
collection.slots.docAdded.once(resolve)
);
const firstCollection = collection.docs.values().next().value as
| BlockCollection
| undefined;
firstDoc = firstCollection?.getDoc();
}
assertExists(firstDoc);
const doc = firstDoc;
doc.load();
if (!doc.root) {
await new Promise(resolve => doc.slots.rootAdded.once(resolve));
}
doc.resetHistory();
return;
}
// use built-in init function
const functionMap = new Map<
string,
(collection: DocCollection, id: string) => Promise<void> | void
>();
Object.values(
(await import('../data/index.js')) as Record<string, InitFn>
).forEach(fn => functionMap.set(fn.id, fn));
const init = params.get('init') || 'preset';
if (functionMap.has(init)) {
collection.meta.initialize();
await functionMap.get(init)?.(collection, 'doc:home');
const doc = collection.getDoc('doc:home');
if (!doc?.loaded) {
doc?.load();
}
doc?.resetHistory();
}
}
@@ -0,0 +1,203 @@
import {
BlockServiceWatcher,
type EditorHost,
type ExtensionType,
} from '@blocksuite/block-std';
import {
AffineFormatBarWidget,
CommunityCanvasTextFonts,
DocModeProvider,
FontConfigExtension,
GenerateDocUrlExtension,
NotificationExtension,
OverrideThemeExtension,
type PageRootService,
ParseDocUrlExtension,
RefNodeSlotsExtension,
RefNodeSlotsProvider,
SpecProvider,
toolbarDefaultConfig,
} from '@blocksuite/blocks';
import { AffineEditorContainer, CommentPanel } from '@blocksuite/presets';
import type { DocCollection } from '@blocksuite/store';
import { AttachmentViewerPanel } from '../../_common/components/attachment-viewer-panel.js';
import { CustomFramePanel } from '../../_common/components/custom-frame-panel.js';
import { CustomOutlinePanel } from '../../_common/components/custom-outline-panel.js';
import { CustomOutlineViewer } from '../../_common/components/custom-outline-viewer.js';
import { DocsPanel } from '../../_common/components/docs-panel.js';
import { LeftSidePanel } from '../../_common/components/left-side-panel.js';
import { SidePanel } from '../../_common/components/side-panel.js';
import { StarterDebugMenu } from '../../_common/components/starter-debug-menu.js';
import {
getDocFromUrlParams,
listenHashChange,
setDocModeFromUrlParams,
} from '../../_common/history.js';
import {
mockDocModeService,
mockGenerateDocUrlService,
mockNotificationService,
mockParseDocUrlService,
themeExtension,
} from '../../_common/mock-services';
function configureFormatBar(formatBar: AffineFormatBarWidget) {
toolbarDefaultConfig(formatBar);
}
export async function mountDefaultDocEditor(collection: DocCollection) {
const app = document.getElementById('app');
if (!app) return;
const url = new URL(location.toString());
const doc = getDocFromUrlParams(collection, url);
const attachmentViewerPanel = new AttachmentViewerPanel();
const editor = new AffineEditorContainer();
class PatchPageServiceWatcher extends BlockServiceWatcher {
static override readonly flavour = 'affine:page';
override mounted() {
const pageRootService = this.blockService as PageRootService;
const onFormatBarConnected = pageRootService.specSlots.widgetConnected.on(
view => {
if (view.component instanceof AffineFormatBarWidget) {
configureFormatBar(view.component);
}
}
);
pageRootService.disposables.add(onFormatBarConnected);
}
}
const refNodeSlotsExtension = RefNodeSlotsExtension();
const extensions: ExtensionType[] = [
refNodeSlotsExtension,
PatchPageServiceWatcher,
FontConfigExtension(CommunityCanvasTextFonts),
ParseDocUrlExtension(mockParseDocUrlService(collection)),
GenerateDocUrlExtension(mockGenerateDocUrlService(collection)),
NotificationExtension(mockNotificationService(editor)),
OverrideThemeExtension(themeExtension),
{
setup: di => {
di.override(DocModeProvider, () =>
mockDocModeService(getEditorModeCallback, setEditorModeCallBack)
);
},
},
// mockPeekViewExtension(attachmentViewerPanel),
];
const pageSpecs = SpecProvider.getInstance().getSpec('page');
const setEditorModeCallBack = editor.switchEditor.bind(editor);
const getEditorModeCallback = () => editor.mode;
pageSpecs.extend([...extensions]);
editor.pageSpecs = pageSpecs.value;
const edgelessSpecs = SpecProvider.getInstance().getSpec('edgeless');
edgelessSpecs.extend([...extensions]);
editor.edgelessSpecs = edgelessSpecs.value;
SpecProvider.getInstance().extendSpec('edgeless:preview', [
OverrideThemeExtension(themeExtension),
]);
editor.mode = 'page';
editor.doc = doc;
editor.std
.get(RefNodeSlotsProvider)
.docLinkClicked.on(({ pageId: docId }) => {
const target = collection.getDoc(docId);
if (!target) {
throw new Error(`Failed to jump to doc ${docId}`);
}
target.load();
editor.doc = target;
});
app.append(editor);
await editor.updateComplete;
const modeService = editor.std.provider.get(DocModeProvider);
editor.mode = modeService.getPrimaryMode(doc.id);
setDocModeFromUrlParams(modeService, url.searchParams, doc.id);
editor.slots.docUpdated.on(({ newDocId }) => {
editor.mode = modeService.getPrimaryMode(newDocId);
});
const outlinePanel = new CustomOutlinePanel();
outlinePanel.editor = editor;
const outlineViewer = new CustomOutlineViewer();
outlineViewer.editor = editor;
outlineViewer.toggleOutlinePanel = () => {
outlinePanel.toggleDisplay();
};
const framePanel = new CustomFramePanel();
framePanel.editor = editor;
const sidePanel = new SidePanel();
const leftSidePanel = new LeftSidePanel();
const docsPanel = new DocsPanel();
docsPanel.editor = editor;
const commentPanel = new CommentPanel();
commentPanel.editor = editor;
const debugMenu = new StarterDebugMenu();
debugMenu.collection = collection;
debugMenu.editor = editor;
debugMenu.outlinePanel = outlinePanel;
debugMenu.outlineViewer = outlineViewer;
debugMenu.framePanel = framePanel;
debugMenu.sidePanel = sidePanel;
debugMenu.leftSidePanel = leftSidePanel;
debugMenu.docsPanel = docsPanel;
debugMenu.commentPanel = commentPanel;
document.body.append(attachmentViewerPanel);
document.body.append(outlinePanel);
document.body.append(outlineViewer);
document.body.append(framePanel);
document.body.append(sidePanel);
document.body.append(leftSidePanel);
document.body.append(debugMenu);
// for multiple editor
const params = new URLSearchParams(location.search);
const init = params.get('init');
if (init && init.startsWith('multiple-editor')) {
app.childNodes.forEach(node => {
if (node instanceof AffineEditorContainer) {
node.style.flex = '1';
if (init === 'multiple-editor-vertical') {
node.style.overflow = 'auto';
}
}
});
}
// debug info
window.editor = editor;
window.doc = doc;
Object.defineProperty(globalThis, 'host', {
get() {
return document.querySelector<EditorHost>('editor-host');
},
});
Object.defineProperty(globalThis, 'std', {
get() {
return document.querySelector<EditorHost>('editor-host')?.std;
},
});
listenHashChange(collection, editor, docsPanel);
return editor;
}
@@ -0,0 +1,12 @@
// This file is used to test blocksuite can run in a web worker. SEE: tests/worker.spec.ts
import '@blocksuite/store';
// import '@blocksuite/block-std'; // seems not working
import '@blocksuite/blocks/schemas';
globalThis.onmessage = event => {
const { data } = event;
if (data === 'ping') {
postMessage('pong');
}
};