refactor(editor): rename store api (#9518)

This commit is contained in:
Saul-Mirone committed 2025-01-04 12:51:56 +00:00
1 parent 650e4fb6b2
commit c773982ced
83 files changed
+293 -290

No files matched your search

@@ -53,7 +53,7 @@ todoMeta.addProperty({
metaConfig: propertyPresets.textPropertyConfig, metaConfig: propertyPresets.textPropertyConfig,
get: block => block.doc.meta?.title ?? '', get: block => block.doc.meta?.title ?? '',
updated: (block, callback) => { updated: (block, callback) => {
return block.doc.collection.slots.docListUpdated.on(() => { return block.doc.workspace.slots.docListUpdated.on(() => {
callback(); callback();
}); });
}, },
@@ -59,7 +59,7 @@ export class BlockQueryDataSource extends DataSourceBase {
} }
get workspace() { get workspace() {
return this.host.doc.collection; return this.host.doc.workspace;
} }
constructor( constructor(
@@ -73,14 +73,14 @@ export class BlockQueryDataSource extends DataSourceBase {
this.columnMetaMap.set(property.metaConfig.type, property.metaConfig); this.columnMetaMap.set(property.metaConfig.type, property.metaConfig);
} }
for (const collection of this.workspace.docs.values()) { for (const collection of this.workspace.docs.values()) {
for (const block of Object.values(collection.getDoc().blocks.peek())) { for (const block of Object.values(collection.getBlocks().blocks.peek())) {
if (this.meta.selector(block)) { if (this.meta.selector(block)) {
this.blockMap.set(block.id, block); this.blockMap.set(block.id, block);
} }
} }
} }
this.workspace.docs.forEach(doc => { this.workspace.docs.forEach(doc => {
this.listenToDoc(doc.getDoc()); this.listenToDoc(doc.getBlocks());
}); });
this.workspace.slots.docCreated.on(id => { this.workspace.slots.docCreated.on(id => {
const doc = this.workspace.getDoc(id); const doc = this.workspace.getDoc(id);
@@ -167,7 +167,7 @@ export class BlockQueryDataSource extends DataSourceBase {
type ?? propertyPresets.multiSelectPropertyConfig.type type ?? propertyPresets.multiSelectPropertyConfig.type
].create(this.newColumnName()); ].create(this.newColumnName());
const id = doc.collection.idGenerator(); const id = doc.workspace.idGenerator();
if (this.block.columns.some(v => v.id === id)) { if (this.block.columns.some(v => v.id === id)) {
return id; return id;
} }
@@ -33,7 +33,7 @@ export class DataViewBlockModel extends BlockModel<Props> {
} }
duplicateView(id: string): string { duplicateView(id: string): string {
const newId = this.doc.collection.idGenerator(); const newId = this.doc.workspace.idGenerator();
this.doc.transact(() => { this.doc.transact(() => {
const index = this.views.findIndex(v => v.id === id); const index = this.views.findIndex(v => v.id === id);
const view = this.views[index]; const view = this.views[index];
@@ -47,7 +47,7 @@ export class NoteRenderer
} }
addNote() { addNote() {
const collection = this.host?.std.collection; const collection = this.host?.std.workspace;
if (!collection) { if (!collection) {
return; return;
} }
@@ -132,7 +132,7 @@ export class LinkCell extends BaseCellRenderer<string> {
override render() { override render() {
const linkText = this.value ?? ''; const linkText = this.value ?? '';
const docName = const docName =
this.docId && this.std?.collection.getDoc(this.docId)?.meta?.title; this.docId && this.std?.workspace.getDoc(this.docId)?.meta?.title;
return html` return html`
<div class="affine-database-link" @click="${this._onClick}"> <div class="affine-database-link" @click="${this._onClick}">
${docName ${docName
@@ -19,7 +19,7 @@ export const titlePurePropertyConfig = titleColumnType.modelConfig<Text>({
cellToJson: ({ value, dataSource }) => { cellToJson: ({ value, dataSource }) => {
const host = dataSource.contextGet(HostContextKey); const host = dataSource.contextGet(HostContextKey);
if (host) { if (host) {
const collection = host.std.collection; const collection = host.std.workspace;
const deltas = value.deltas$.value; const deltas = value.deltas$.value;
const text = deltas const text = deltas
.map(delta => { .map(delta => {
@@ -98,7 +98,7 @@ abstract class BaseTextCell extends BaseCellRenderer<Text> {
if (!this.docId$.value) { if (!this.docId$.value) {
return this.value; return this.value;
} }
const doc = this.host?.std.collection.getDoc(this.docId$.value); const doc = this.host?.std.workspace.getDoc(this.docId$.value);
const root = doc?.root as RootBlockModel; const root = doc?.root as RootBlockModel;
return root.title; return root.title;
}); });
@@ -19,7 +19,7 @@ export function addProperty(
id?: string; id?: string;
} }
): string { ): string {
const id = column.id ?? model.doc.collection.idGenerator(); const id = column.id ?? model.doc.workspace.idGenerator();
if (model.columns.some(v => v.id === id)) { if (model.columns.some(v => v.id === id)) {
return id; return id;
} }
@@ -101,7 +101,7 @@ export function deleteView(model: DatabaseBlockModel, id: string) {
} }
export function duplicateView(model: DatabaseBlockModel, id: string): string { export function duplicateView(model: DatabaseBlockModel, id: string): string {
const newId = model.doc.collection.idGenerator(); const newId = model.doc.workspace.idGenerator();
model.doc.transact(() => { model.doc.transact(() => {
const index = model.views.findIndex(v => v.id === id); const index = model.views.findIndex(v => v.id === id);
const view = model.views[index]; const view = model.views[index];
@@ -196,7 +196,7 @@ async function renderNoteContent(
mode: 'strict', mode: 'strict',
match: ids.map(id => ({ id, viewType: BlockViewType.Display })), match: ids.map(id => ({ id, viewType: BlockViewType.Display })),
}; };
const previewDoc = doc.blockCollection.getDoc({ query }); const previewDoc = doc.doc.getBlocks({ query });
const previewSpec = SpecProvider.getInstance().getSpec('page:preview'); const previewSpec = SpecProvider.getInstance().getSpec('page:preview');
const previewStd = new BlockStdScope({ const previewStd = new BlockStdScope({
doc: previewDoc, doc: previewDoc,
@@ -405,7 +405,7 @@ export function createLinkedDocFromSlice(
docTitle?: string docTitle?: string
) { ) {
// const modelsWithChildren = (list:BlockModel[]):BlockModel[]=>list.flatMap(model=>[model,...modelsWithChildren(model.children)]) // const modelsWithChildren = (list:BlockModel[]):BlockModel[]=>list.flatMap(model=>[model,...modelsWithChildren(model.children)])
const linkedDoc = doc.collection.createDoc({}); const linkedDoc = doc.workspace.createDoc({});
linkedDoc.load(() => { linkedDoc.load(() => {
const rootId = linkedDoc.addBlock('affine:page', { const rootId = linkedDoc.addBlock('affine:page', {
title: new Text(docTitle), title: new Text(docTitle),
@@ -114,7 +114,7 @@ export class EmbedLinkedDocBlockComponent extends EmbedBlockComponent<EmbedLinke
}; };
private readonly _setDocUpdatedAt = () => { private readonly _setDocUpdatedAt = () => {
const meta = this.doc.collection.meta.getDocMeta(this.model.pageId); const meta = this.doc.workspace.meta.getDocMeta(this.model.pageId);
if (meta) { if (meta) {
const date = meta.updatedDate || meta.createDate; const date = meta.updatedDate || meta.createDate;
this._docUpdatedAt = new Date(date); this._docUpdatedAt = new Date(date);
@@ -241,7 +241,7 @@ export class EmbedLinkedDocBlockComponent extends EmbedBlockComponent<EmbedLinke
} }
get linkedDoc() { get linkedDoc() {
return this.std.collection.getDoc(this.model.pageId); return this.std.workspace.getDoc(this.model.pageId);
} }
private _handleDoubleClick(event: MouseEvent) { private _handleDoubleClick(event: MouseEvent) {
@@ -296,7 +296,7 @@ export class EmbedLinkedDocBlockComponent extends EmbedBlockComponent<EmbedLinke
const linkedDoc = this.linkedDoc; const linkedDoc = this.linkedDoc;
if (linkedDoc) { if (linkedDoc) {
this.disposables.add( this.disposables.add(
linkedDoc.collection.slots.docListUpdated.on(() => { linkedDoc.workspace.slots.docListUpdated.on(() => {
this._load().catch(e => { this._load().catch(e => {
console.error(e); console.error(e);
this.isError = true; this.isError = true;
@@ -329,7 +329,7 @@ export class EmbedLinkedDocBlockComponent extends EmbedBlockComponent<EmbedLinke
this._setDocUpdatedAt(); this._setDocUpdatedAt();
this.disposables.add( this.disposables.add(
this.doc.collection.slots.docListUpdated.on(() => { this.doc.workspace.slots.docListUpdated.on(() => {
this._setDocUpdatedAt(); this._setDocUpdatedAt();
}) })
); );
@@ -100,7 +100,7 @@ export class EmbedSyncedDocCard extends WithDisposable(ShadowlessElement) {
} }
this.disposables.add( this.disposables.add(
syncedDoc.collection.slots.docListUpdated.on(() => { syncedDoc.workspace.slots.docListUpdated.on(() => {
renderLinkedDocInCard(this); renderLinkedDocInCard(this);
}) })
); );
@@ -27,7 +27,7 @@ import { GfxControllerIdentifier } from '@blocksuite/block-std/gfx';
import { assertExists, Bound, getCommonBound } from '@blocksuite/global/utils'; import { assertExists, Bound, getCommonBound } from '@blocksuite/global/utils';
import { import {
BlockViewType, BlockViewType,
type GetDocOptions, type GetBlocksOptions,
type Query, type Query,
Text, Text,
} from '@blocksuite/store'; } from '@blocksuite/store';
@@ -365,9 +365,9 @@ export class EmbedSyncedDocBlockComponent extends EmbedBlockComponent<EmbedSynce
} }
get syncedDoc() { get syncedDoc() {
const options: GetDocOptions = { readonly: true }; const options: GetBlocksOptions = { readonly: true };
if (this.isPageMode) options.query = this._pageFilter; if (this.isPageMode) options.query = this._pageFilter;
return this.std.collection.getDoc(this.model.pageId, options); return this.std.workspace.getDoc(this.model.pageId, options);
} }
private _checkCycle() { private _checkCycle() {
@@ -440,7 +440,7 @@ export class EmbedSyncedDocBlockComponent extends EmbedBlockComponent<EmbedSynce
} }
private _setDocUpdatedAt() { private _setDocUpdatedAt() {
const meta = this.doc.collection.meta.getDocMeta(this.model.pageId); const meta = this.doc.workspace.meta.getDocMeta(this.model.pageId);
if (meta) { if (meta) {
const date = meta.updatedDate || meta.createDate; const date = meta.updatedDate || meta.createDate;
this._docUpdatedAt = new Date(date); this._docUpdatedAt = new Date(date);
@@ -476,7 +476,7 @@ export class EmbedSyncedDocBlockComponent extends EmbedBlockComponent<EmbedSynce
this._setDocUpdatedAt(); this._setDocUpdatedAt();
this.disposables.add( this.disposables.add(
this.doc.collection.slots.docListUpdated.on(() => { this.doc.workspace.slots.docListUpdated.on(() => {
this._setDocUpdatedAt(); this._setDocUpdatedAt();
}) })
); );
@@ -55,7 +55,7 @@ export class SurfaceRefNotePortal extends WithDisposable(ShadowlessElement) {
const doc = this.model.doc; const doc = this.model.doc;
this._disposables.add(() => { this._disposables.add(() => {
doc.blockCollection.clearQuery(query, true); doc.doc.clearQuery(query, true);
}); });
} }
@@ -114,7 +114,7 @@ export class SurfaceRefNotePortal extends WithDisposable(ShadowlessElement) {
console.error('Query is not set before rendering note preview'); console.error('Query is not set before rendering note preview');
return nothing; return nothing;
} }
const doc = this.model.doc.blockCollection.getDoc({ const doc = this.model.doc.doc.getBlocks({
query: this.query, query: this.query,
readonly: true, readonly: true,
}); });
@@ -336,8 +336,8 @@ export class SurfaceRefBlockComponent extends BlockComponent<SurfaceRefBlockMode
]; ];
} }
const doc = [...this.std.collection.docs.values()] const doc = [...this.std.workspace.docs.values()]
.map(doc => doc.getDoc()) .map(doc => doc.getBlocks())
.find( .find(
doc => doc =>
doc.getBlock(this.model.reference) || doc.getBlock(this.model.reference) ||
@@ -370,7 +370,7 @@ export class SurfaceRefBlockComponent extends BlockComponent<SurfaceRefBlockMode
this._referencedModel = this._referencedModel =
referencedModel && referencedModel.xywh ? referencedModel : null; referencedModel && referencedModel.xywh ? referencedModel : null;
this._previewDoc = this.doc.collection.getDoc(docId, { this._previewDoc = this.doc.workspace.getDoc(docId, {
readonly: true, readonly: true,
}); });
this._referenceXYWH = this._referencedModel?.xywh ?? null; this._referenceXYWH = this._referencedModel?.xywh ?? null;
@@ -77,7 +77,7 @@ export class AffineReference extends WithDisposable(ShadowlessElement) {
return; return;
} }
const refMeta = doc.collection.meta.docMetas.find( const refMeta = doc.workspace.meta.docMetas.find(
doc => doc.id === refAttribute.pageId doc => doc.id === refAttribute.pageId
); );
this.refMeta = refMeta this.refMeta = refMeta
@@ -221,7 +221,7 @@ export class AffineReference extends WithDisposable(ShadowlessElement) {
const doc = this.doc; const doc = this.doc;
if (doc) { if (doc) {
this._disposables.add( this._disposables.add(
doc.collection.slots.docListUpdated.on(() => this._updateRefMeta(doc)) doc.workspace.slots.docListUpdated.on(() => this._updateRefMeta(doc))
); );
} }
@@ -150,7 +150,7 @@ function tryConvertToLinkedDoc(std: BlockStdScope, inlineEditor: InlineEditor) {
}); });
inlineEditor.setInlineRange({ index: inlineRange.index - 1, length: 0 }); inlineEditor.setInlineRange({ index: inlineRange.index - 1, length: 0 });
const doc = createDefaultDoc(std.doc.collection, { const doc = createDefaultDoc(std.doc.workspace, {
title: docName, title: docName,
}); });
insertLinkedNode({ insertLinkedNode({
@@ -12,9 +12,9 @@ export class RootBlockModel extends BlockModel<RootBlockProps> {
this.doc.slots.rootAdded.on(id => { this.doc.slots.rootAdded.on(id => {
const model = this.doc.getBlockById(id); const model = this.doc.getBlockById(id);
if (model instanceof RootBlockModel) { if (model instanceof RootBlockModel) {
const newDocMeta = this.doc.collection.meta.getDocMeta(model.doc.id); const newDocMeta = this.doc.workspace.meta.getDocMeta(model.doc.id);
if (!newDocMeta || newDocMeta.title !== model.title.toString()) { if (!newDocMeta || newDocMeta.title !== model.title.toString()) {
this.doc.collection.meta.setDocMeta(model.doc.id, { this.doc.workspace.meta.setDocMeta(model.doc.id, {
title: model.title.toString(), title: model.title.toString(),
}); });
} }
@@ -400,7 +400,7 @@ class PasteTr {
op.attributes.link op.attributes.link
); );
if (searchResult) { if (searchResult) {
const doc = this.std.collection.getDoc(searchResult.docId); const doc = this.std.workspace.getDoc(searchResult.docId);
if (doc) { if (doc) {
docId = doc.id; docId = doc.id;
linkToDocId.set(op.attributes.link, doc.id); linkToDocId.set(op.attributes.link, doc.id);
@@ -88,7 +88,7 @@ export class DocDisplayMetaService
pageId: string, pageId: string,
{ params, title, referenced }: DocDisplayMetaParams = {} { params, title, referenced }: DocDisplayMetaParams = {}
): Signal<TemplateResult> { ): Signal<TemplateResult> {
const doc = this.std.collection.getDoc(pageId); const doc = this.std.workspace.getDoc(pageId);
if (!doc) { if (!doc) {
return signal(DocDisplayMetaService.icons.deleted); return signal(DocDisplayMetaService.icons.deleted);
@@ -114,7 +114,7 @@ export class DocDisplayMetaService
this.disposables.push(disposable); this.disposables.push(disposable);
this.disposables.push( this.disposables.push(
this.std.collection.slots.docRemoved this.std.workspace.slots.docRemoved
.filter(docId => docId === doc.id) .filter(docId => docId === doc.id)
.once(() => { .once(() => {
const index = this.disposables.findIndex(d => d === disposable); const index = this.disposables.findIndex(d => d === disposable);
@@ -152,7 +152,7 @@ export class DocDisplayMetaService
} }
title(pageId: string, { title }: DocDisplayMetaParams = {}): Signal<string> { title(pageId: string, { title }: DocDisplayMetaParams = {}): Signal<string> {
const doc = this.std.collection.getDoc(pageId); const doc = this.std.workspace.getDoc(pageId);
if (!doc) { if (!doc) {
return signal(title || 'Deleted doc'); return signal(title || 'Deleted doc');
@@ -162,13 +162,13 @@ export class DocDisplayMetaService
if (!title$) { if (!title$) {
title$ = signal(doc.meta?.title || 'Untitled'); title$ = signal(doc.meta?.title || 'Untitled');
const disposable = this.std.collection.slots.docListUpdated.on(() => { const disposable = this.std.workspace.slots.docListUpdated.on(() => {
title$!.value = doc.meta?.title || 'Untitled'; title$!.value = doc.meta?.title || 'Untitled';
}); });
this.disposables.push(disposable); this.disposables.push(disposable);
this.disposables.push( this.disposables.push(
this.std.collection.slots.docRemoved this.std.workspace.slots.docRemoved
.filter(docId => docId === doc.id) .filter(docId => docId === doc.id)
.once(() => { .once(() => {
const index = this.disposables.findIndex(d => d === disposable); const index = this.disposables.findIndex(d => d === disposable);
@@ -54,7 +54,7 @@ export class DNDAPIExtension extends Extension {
...snapshot, ...snapshot,
content: [ content: [
{ {
id: this.std.collection.idGenerator(), id: this.std.workspace.idGenerator(),
type: 'block', type: 'block',
flavour, flavour,
props, props,
@@ -79,7 +79,7 @@ export class PreviewHelper {
const query = this._calculateQuery(selectedIds); const query = this._calculateQuery(selectedIds);
const doc = this.widget.doc.blockCollection.getDoc({ query }); const doc = this.widget.doc.doc.getBlocks({ query });
const previewSpec = SpecProvider.getInstance().getSpec('page:preview'); const previewSpec = SpecProvider.getInstance().getSpec('page:preview');
const previewStd = new BlockStdScope({ const previewStd = new BlockStdScope({
@@ -96,7 +96,7 @@ export class PreviewHelper {
dragPreview = new DragPreview(offset); dragPreview = new DragPreview(offset);
dragPreview.template = previewTemplate; dragPreview.template = previewTemplate;
dragPreview.onRemove = () => { dragPreview.onRemove = () => {
this.widget.doc.blockCollection.clearQuery(query); this.widget.doc.doc.clearQuery(query);
}; };
dragPreview.style.width = `${width / this.widget.scaleInNote.peek()}px`; dragPreview.style.width = `${width / this.widget.scaleInNote.peek()}px`;
dragPreview.style.transform = `translate(${posX}px, ${posY}px) scale(${this.widget.scaleInNote.peek()})`; dragPreview.style.transform = `translate(${posX}px, ${posY}px) scale(${this.widget.scaleInNote.peek()})`;
@@ -10,7 +10,7 @@ export const newIdCrossDoc =
samePage = payload.snapshot.pageId === std.doc.id; samePage = payload.snapshot.pageId === std.doc.id;
} }
if (payload.type === 'block' && !samePage) { if (payload.type === 'block' && !samePage) {
payload.snapshot.id = std.collection.idGenerator(); payload.snapshot.id = std.workspace.idGenerator();
} }
}); });
}; };
@@ -18,7 +18,7 @@ export const surfaceRefToEmbed =
!std.doc.hasBlock(payload.snapshot.id) !std.doc.hasBlock(payload.snapshot.id)
) { ) {
const id = payload.snapshot.id; const id = payload.snapshot.id;
payload.snapshot.id = std.collection.idGenerator(); payload.snapshot.id = std.workspace.idGenerator();
payload.snapshot.flavour = 'affine:embed-linked-doc'; payload.snapshot.flavour = 'affine:embed-linked-doc';
payload.snapshot.props = { payload.snapshot.props = {
blockId: id, blockId: id,
@@ -5,7 +5,7 @@ import { multiPlayersColor } from './color-picker';
export class RemoteColorManager { export class RemoteColorManager {
private get awarenessStore() { private get awarenessStore() {
return this.std.doc.collection.awarenessStore; return this.std.doc.workspace.awarenessStore;
} }
constructor(readonly std: BlockStdScope) { constructor(readonly std: BlockStdScope) {
@@ -48,13 +48,13 @@ async function exportDoc(doc: Blocks) {
schema: doc.schema, schema: doc.schema,
blobCRUD: doc.blobSync, blobCRUD: doc.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => doc.collection.createDoc({ id }), create: (id: string) => doc.workspace.createDoc({ id }),
get: (id: string) => doc.collection.getDoc(id), get: (id: string) => doc.workspace.getDoc(id),
delete: (id: string) => doc.collection.removeDoc(id), delete: (id: string) => doc.workspace.removeDoc(id),
}, },
middlewares: [ middlewares: [
docLinkBaseURLMiddleware(doc.collection.id), docLinkBaseURLMiddleware(doc.workspace.id),
titleMiddleware(doc.collection.meta.docMetas), titleMiddleware(doc.workspace.meta.docMetas),
], ],
}); });
const snapshot = job.docToSnapshot(doc); const snapshot = job.docToSnapshot(doc);
@@ -54,13 +54,13 @@ async function exportDoc(doc: Blocks) {
schema: doc.schema, schema: doc.schema,
blobCRUD: doc.blobSync, blobCRUD: doc.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => doc.collection.createDoc({ id }), create: (id: string) => doc.workspace.createDoc({ id }),
get: (id: string) => doc.collection.getDoc(id), get: (id: string) => doc.workspace.getDoc(id),
delete: (id: string) => doc.collection.removeDoc(id), delete: (id: string) => doc.workspace.removeDoc(id),
}, },
middlewares: [ middlewares: [
docLinkBaseURLMiddleware(doc.collection.id), docLinkBaseURLMiddleware(doc.workspace.id),
titleMiddleware(doc.collection.meta.docMetas), titleMiddleware(doc.workspace.meta.docMetas),
], ],
}); });
const snapshot = job.docToSnapshot(doc); const snapshot = job.docToSnapshot(doc);
@@ -113,20 +113,20 @@ async function importMarkdownToBlock({
schema: doc.schema, schema: doc.schema,
blobCRUD: doc.blobSync, blobCRUD: doc.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => doc.collection.createDoc({ id }), create: (id: string) => doc.workspace.createDoc({ id }),
get: (id: string) => doc.collection.getDoc(id), get: (id: string) => doc.workspace.getDoc(id),
delete: (id: string) => doc.collection.removeDoc(id), delete: (id: string) => doc.workspace.removeDoc(id),
}, },
middlewares: [ middlewares: [
defaultImageProxyMiddleware, defaultImageProxyMiddleware,
docLinkBaseURLMiddleware(doc.collection.id), docLinkBaseURLMiddleware(doc.workspace.id),
], ],
}); });
const adapter = new MarkdownAdapter(job, provider); const adapter = new MarkdownAdapter(job, provider);
const snapshot = await adapter.toSliceSnapshot({ const snapshot = await adapter.toSliceSnapshot({
file: markdown, file: markdown,
assets: job.assetsManager, assets: job.assetsManager,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
pageId: doc.id, pageId: doc.id,
}); });
@@ -60,10 +60,10 @@ export class PageClipboard {
this._std.clipboard.use(copy); this._std.clipboard.use(copy);
this._std.clipboard.use(paste); this._std.clipboard.use(paste);
this._std.clipboard.use( this._std.clipboard.use(
replaceIdMiddleware(this._std.doc.collection.idGenerator) replaceIdMiddleware(this._std.doc.workspace.idGenerator)
); );
this._std.clipboard.use( this._std.clipboard.use(
titleMiddleware(this._std.doc.collection.meta.docMetas) titleMiddleware(this._std.doc.workspace.meta.docMetas)
); );
this._std.clipboard.use(defaultImageProxyMiddleware); this._std.clipboard.use(defaultImageProxyMiddleware);
@@ -85,10 +85,10 @@ export class PageClipboard {
this._std.clipboard.unuse(copy); this._std.clipboard.unuse(copy);
this._std.clipboard.unuse(paste); this._std.clipboard.unuse(paste);
this._std.clipboard.unuse( this._std.clipboard.unuse(
replaceIdMiddleware(this._std.doc.collection.idGenerator) replaceIdMiddleware(this._std.doc.workspace.idGenerator)
); );
this._std.clipboard.unuse( this._std.clipboard.unuse(
titleMiddleware(this._std.doc.collection.meta.docMetas) titleMiddleware(this._std.doc.workspace.meta.docMetas)
); );
this._std.clipboard.unuse(defaultImageProxyMiddleware); this._std.clipboard.unuse(defaultImageProxyMiddleware);
}, },
@@ -370,12 +370,12 @@ export class EdgelessClipboardController extends PageClipboard {
const elementsRawData = JSON.parse(mayBeSurfaceDataJson); const elementsRawData = JSON.parse(mayBeSurfaceDataJson);
const { snapshot, blobs } = elementsRawData; const { snapshot, blobs } = elementsRawData;
const job = new Job({ const job = new Job({
schema: this.std.collection.schema, schema: this.std.workspace.schema,
blobCRUD: this.std.collection.blobSync, blobCRUD: this.std.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => this.std.collection.createDoc({ id }), create: (id: string) => this.std.workspace.createDoc({ id }),
get: (id: string) => this.std.collection.getDoc(id), get: (id: string) => this.std.workspace.getDoc(id),
delete: (id: string) => this.std.collection.removeDoc(id), delete: (id: string) => this.std.workspace.removeDoc(id),
}, },
}); });
const map = job.assetsManager.getAssets(); const map = job.assetsManager.getAssets();
@@ -475,7 +475,7 @@ export class EdgelessClipboardController extends PageClipboard {
const { xywh, rotate, sourceId, name, size, type, embed, style } = const { xywh, rotate, sourceId, name, size, type, embed, style } =
attachment.props; attachment.props;
if (!(await this.host.std.collection.blobSync.get(sourceId as string))) { if (!(await this.host.std.workspace.blobSync.get(sourceId as string))) {
return null; return null;
} }
const attachmentId = this.crud.addBlock( const attachmentId = this.crud.addBlock(
@@ -741,7 +741,7 @@ export class EdgelessClipboardController extends PageClipboard {
const { xywh, rotate, sourceId, size, width, height, caption } = const { xywh, rotate, sourceId, size, width, height, caption } =
image.props; image.props;
if (!(await this.host.std.collection.blobSync.get(sourceId as string))) { if (!(await this.host.std.workspace.blobSync.get(sourceId as string))) {
return null; return null;
} }
return this.crud.addBlock( return this.crud.addBlock(
@@ -1374,12 +1374,12 @@ export async function prepareClipboardData(
std: BlockStdScope std: BlockStdScope
) { ) {
const job = new Job({ const job = new Job({
schema: std.collection.schema, schema: std.workspace.schema,
blobCRUD: std.collection.blobSync, blobCRUD: std.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => std.collection.createDoc({ id }), create: (id: string) => std.workspace.createDoc({ id }),
get: (id: string) => std.collection.getDoc(id), get: (id: string) => std.workspace.getDoc(id),
delete: (id: string) => std.collection.removeDoc(id), delete: (id: string) => std.workspace.removeDoc(id),
}, },
}); });
const selected = await Promise.all( const selected = await Promise.all(
@@ -104,7 +104,7 @@ export class FramePreview extends WithDisposable(ShadowlessElement) {
} }
private _initPreviewDoc() { private _initPreviewDoc() {
this._previewDoc = this._originalDoc.collection.getDoc( this._previewDoc = this._originalDoc.workspace.getDoc(
this._originalDoc.id, this._originalDoc.id,
{ {
query: this._docFilter, query: this._docFilter,
@@ -112,7 +112,7 @@ export class FramePreview extends WithDisposable(ShadowlessElement) {
} }
); );
this.disposables.add(() => { this.disposables.add(() => {
this._originalDoc.blockCollection.clearQuery(this._docFilter); this._originalDoc.doc.clearQuery(this._docFilter);
}); });
} }
@@ -20,7 +20,7 @@ export const replaceIdMiddleware = (job: TemplateJob) => {
const { blockJson } = data; const { blockJson } = data;
const newId = regeneratedIdMap.has(blockJson.id) const newId = regeneratedIdMap.has(blockJson.id)
? regeneratedIdMap.get(blockJson.id)! ? regeneratedIdMap.get(blockJson.id)!
: job.model.doc.collection.idGenerator(); : job.model.doc.workspace.idGenerator();
if (!regeneratedIdMap.has(blockJson.id)) { if (!regeneratedIdMap.has(blockJson.id)) {
regeneratedIdMap.set(blockJson.id, newId); regeneratedIdMap.set(blockJson.id, newId);
@@ -62,7 +62,7 @@ export const replaceIdMiddleware = (job: TemplateJob) => {
}); });
blockJson.children.forEach(block => { blockJson.children.forEach(block => {
regeneratedIdMap.set(block.id, job.model.doc.collection.idGenerator()); regeneratedIdMap.set(block.id, job.model.doc.workspace.idGenerator());
}); });
defered.forEach(id => { defered.forEach(id => {
@@ -87,12 +87,12 @@ export class TemplateJob {
constructor({ model, type, middlewares }: TemplateJobConfig) { constructor({ model, type, middlewares }: TemplateJobConfig) {
this.job = new Job({ this.job = new Job({
schema: model.doc.collection.schema, schema: model.doc.workspace.schema,
blobCRUD: model.doc.collection.blobSync, blobCRUD: model.doc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => model.doc.collection.createDoc({ id }), create: (id: string) => model.doc.workspace.createDoc({ id }),
get: (id: string) => model.doc.collection.getDoc(id), get: (id: string) => model.doc.workspace.getDoc(id),
delete: (id: string) => model.doc.collection.removeDoc(id), delete: (id: string) => model.doc.workspace.removeDoc(id),
}, },
middlewares: [], middlewares: [],
}); });
@@ -317,7 +317,7 @@ export class TemplateJob {
to: Y.Map<Y.Map<unknown>> to: Y.Map<Y.Map<unknown>>
) { ) {
const schema = const schema =
this.model.doc.collection.schema.flavourSchemaMap.get('affine:surface'); this.model.doc.workspace.schema.flavourSchemaMap.get('affine:surface');
const surfaceTransformer = const surfaceTransformer =
schema?.transformer?.() as SurfaceBlockTransformer; schema?.transformer?.() as SurfaceBlockTransformer;
@@ -40,12 +40,12 @@ export function getSortedCloneElements(elements: GfxModel[]) {
export function prepareCloneData(elements: GfxModel[], std: BlockStdScope) { export function prepareCloneData(elements: GfxModel[], std: BlockStdScope) {
elements = sortEdgelessElements(elements); elements = sortEdgelessElements(elements);
const job = new Job({ const job = new Job({
schema: std.collection.schema, schema: std.workspace.schema,
blobCRUD: std.collection.blobSync, blobCRUD: std.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => std.collection.createDoc({ id }), create: (id: string) => std.workspace.createDoc({ id }),
get: (id: string) => std.collection.getDoc(id), get: (id: string) => std.workspace.getDoc(id),
delete: (id: string) => std.collection.removeDoc(id), delete: (id: string) => std.workspace.removeDoc(id),
}, },
}); });
const res = elements.map(element => { const res = elements.map(element => {
@@ -501,7 +501,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
get _originalDocInfo(): AliasInfo | undefined { get _originalDocInfo(): AliasInfo | undefined {
const model = this.model; const model = this.model;
const doc = isInternalEmbedModel(model) const doc = isInternalEmbedModel(model)
? this.std.collection.getDoc(model.pageId) ? this.std.workspace.getDoc(model.pageId)
: null; : null;
if (doc) { if (doc) {
@@ -518,7 +518,7 @@ export class EdgelessChangeEmbedCardButton extends WithDisposable(LitElement) {
get _originalDocTitle() { get _originalDocTitle() {
const model = this.model; const model = this.model;
const doc = isInternalEmbedModel(model) const doc = isInternalEmbedModel(model)
? this.std.collection.getDoc(model.pageId) ? this.std.workspace.getDoc(model.pageId)
: null; : null;
return doc?.meta?.title || 'Untitled'; return doc?.meta?.title || 'Untitled';
@@ -40,7 +40,7 @@ export function createLinkedDocFromNote(
note: NoteBlockModel, note: NoteBlockModel,
docTitle?: string docTitle?: string
) { ) {
const linkedDoc = doc.collection.createDoc({}); const linkedDoc = doc.workspace.createDoc({});
linkedDoc.load(() => { linkedDoc.load(() => {
const rootId = linkedDoc.addBlock('affine:page', { const rootId = linkedDoc.addBlock('affine:page', {
title: new Text(docTitle), title: new Text(docTitle),
@@ -71,7 +71,7 @@ export function createLinkedDocFromEdgelessElements(
elements: BlockSuite.EdgelessModel[], elements: BlockSuite.EdgelessModel[],
docTitle?: string docTitle?: string
) { ) {
const linkedDoc = host.doc.collection.createDoc({}); const linkedDoc = host.doc.workspace.createDoc({});
linkedDoc.load(() => { linkedDoc.load(() => {
const rootId = linkedDoc.addBlock('affine:page', { const rootId = linkedDoc.addBlock('affine:page', {
title: new Text(docTitle), title: new Text(docTitle),
@@ -263,7 +263,7 @@ export class EmbedCardToolbar extends WidgetComponent<
if (!model) return undefined; if (!model) return undefined;
const doc = isInternalEmbedModel(model) const doc = isInternalEmbedModel(model)
? this.std.collection.getDoc(model.pageId) ? this.std.workspace.getDoc(model.pageId)
: null; : null;
if (doc) { if (doc) {
@@ -282,7 +282,7 @@ export class EmbedCardToolbar extends WidgetComponent<
if (!model) return undefined; if (!model) return undefined;
const doc = isInternalEmbedModel(model) const doc = isInternalEmbedModel(model)
? this.std.collection.getDoc(model.pageId) ? this.std.workspace.getDoc(model.pageId)
: null; : null;
return doc?.meta?.title || 'Untitled'; return doc?.meta?.title || 'Untitled';
@@ -275,7 +275,7 @@ const pageToolGroup: KeyboardToolPanelGroup = {
.chain() .chain()
.getSelectedModels() .getSelectedModels()
.inline(({ selectedModels }) => { .inline(({ selectedModels }) => {
const newDoc = createDefaultDoc(std.doc.collection); const newDoc = createDefaultDoc(std.doc.workspace);
if (!selectedModels?.length) return; if (!selectedModels?.length) return;
insertContent(std.host, selectedModels[0], REFERENCE_NODE, { insertContent(std.host, selectedModels[0], REFERENCE_NODE, {
reference: { reference: {
@@ -105,7 +105,7 @@ export function createLinkedDocMenuGroup(
inlineEditor: AffineInlineEditor inlineEditor: AffineInlineEditor
) { ) {
const doc = editorHost.doc; const doc = editorHost.doc;
const { docMetas } = doc.collection.meta; const { docMetas } = doc.workspace.meta;
const filteredDocList = docMetas const filteredDocList = docMetas
.filter(({ id }) => id !== doc.id) .filter(({ id }) => id !== doc.id)
.filter(({ title }) => isFuzzyMatch(title, query)); .filter(({ title }) => isFuzzyMatch(title, query));
@@ -164,7 +164,7 @@ export function createNewDocMenuGroup(
action: () => { action: () => {
abort(); abort();
const docName = query; const docName = query;
const newDoc = createDefaultDoc(doc.collection, { const newDoc = createDefaultDoc(doc.workspace, {
title: docName, title: docName,
}); });
insertLinkedNode({ insertLinkedNode({
@@ -213,7 +213,7 @@ export function createNewDocMenuGroup(
toast(editorHost, message); toast(editorHost, message);
}; };
showImportModal({ showImportModal({
collection: doc.collection, collection: doc.workspace,
onSuccess, onSuccess,
onFail, onFail,
}); });
@@ -194,7 +194,7 @@ export const defaultSlashMenuConfig: SlashMenuConfig = {
showWhen: ({ model }) => showWhen: ({ model }) =>
model.doc.schema.flavourSchemaMap.has('affine:embed-linked-doc'), model.doc.schema.flavourSchemaMap.has('affine:embed-linked-doc'),
action: ({ rootComponent, model }) => { action: ({ rootComponent, model }) => {
const newDoc = createDefaultDoc(rootComponent.doc.collection); const newDoc = createDefaultDoc(rootComponent.doc.workspace);
insertContent(rootComponent.host, model, REFERENCE_NODE, { insertContent(rootComponent.host, model, REFERENCE_NODE, {
reference: { reference: {
type: 'LinkedPage', type: 'LinkedPage',
@@ -138,7 +138,7 @@ export class Clipboard extends LifeCycleWatcher {
const payload = { const payload = {
file: item, file: item,
assets: job.assetsManager, assets: job.assetsManager,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
pageId: doc.id, pageId: doc.id,
}; };
const result = await adapterInstance.toSlice( const result = await adapterInstance.toSlice(
@@ -30,7 +30,7 @@ export abstract class BlockService extends Extension {
readonly specSlots = getSlots(); readonly specSlots = getSlots();
get collection() { get collection() {
return this.std.collection; return this.std.workspace;
} }
get doc() { get doc() {
@@ -74,8 +74,8 @@ export class BlockStdScope {
return this.get(Clipboard); return this.get(Clipboard);
} }
get collection() { get workspace() {
return this.doc.collection; return this.doc.workspace;
} }
get command() { get command() {
@@ -170,12 +170,12 @@ export class BlockStdScope {
getJob(middlewares: JobMiddleware[] = []) { getJob(middlewares: JobMiddleware[] = []) {
return new Job({ return new Job({
schema: this.collection.schema, schema: this.workspace.schema,
blobCRUD: this.collection.blobSync, blobCRUD: this.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => this.collection.createDoc({ id }), create: (id: string) => this.workspace.createDoc({ id }),
get: (id: string) => this.collection.getDoc(id), get: (id: string) => this.workspace.getDoc(id),
delete: (id: string) => this.collection.removeDoc(id), delete: (id: string) => this.workspace.removeDoc(id),
}, },
middlewares, middlewares,
}); });
@@ -58,7 +58,7 @@ export class SelectionManager extends LifeCycleWatcher {
}; };
private get _store() { private get _store() {
return this.std.collection.awarenessStore; return this.std.workspace.awarenessStore;
} }
get id() { get id() {
+32 -35
View File
@@ -23,7 +23,7 @@ export class Blocks {
runQuery(this._query, block); runQuery(this._query, block);
}; };
protected readonly _blockCollection: Doc; protected readonly _doc: Doc;
protected readonly _blocks = signal<Record<string, Block>>({}); protected readonly _blocks = signal<Record<string, Block>>({});
@@ -136,19 +136,19 @@ export class Blocks {
}; };
private get _yBlocks() { private get _yBlocks() {
return this._blockCollection.yBlocks; return this._doc.yBlocks;
} }
get awarenessStore() { get awarenessStore() {
return this._blockCollection.awarenessStore; return this._doc.awarenessStore;
} }
get blobSync() { get blobSync() {
return this.collection.blobSync; return this.workspace.blobSync;
} }
get blockCollection() { get doc() {
return this._blockCollection; return this._doc;
} }
get blocks() { get blocks() {
@@ -160,31 +160,31 @@ export class Blocks {
} }
get canRedo() { get canRedo() {
return this._blockCollection.canRedo; return this._doc.canRedo;
} }
get canUndo() { get canUndo() {
return this._blockCollection.canUndo; return this._doc.canUndo;
} }
get captureSync() { get captureSync() {
return this._blockCollection.captureSync.bind(this._blockCollection); return this._doc.captureSync.bind(this._doc);
} }
get clear() { get clear() {
return this._blockCollection.clear.bind(this._blockCollection); return this._doc.clear.bind(this._doc);
} }
get collection() { get workspace() {
return this._blockCollection.collection; return this._doc.workspace;
} }
get history() { get history() {
return this._blockCollection.history; return this._doc.history;
} }
get id() { get id() {
return this._blockCollection.id; return this._doc.id;
} }
get isEmpty() { get isEmpty() {
@@ -192,40 +192,37 @@ export class Blocks {
} }
get loaded() { get loaded() {
return this._blockCollection.loaded; return this._doc.loaded;
} }
get meta() { get meta() {
return this._blockCollection.meta; return this._doc.meta;
} }
get readonly() { get readonly() {
if (this._blockCollection.readonly) { if (this._doc.readonly) {
return true; return true;
} }
return this._readonly === true; return this._readonly === true;
} }
set readonly(value: boolean) { set readonly(value: boolean) {
this._blockCollection.awarenessStore.setReadonly( this._doc.awarenessStore.setReadonly(this._doc, value);
this._blockCollection,
value
);
if (this._readonly !== undefined && this._readonly !== value) { if (this._readonly !== undefined && this._readonly !== value) {
this._readonly = value; this._readonly = value;
} }
} }
get ready() { get ready() {
return this._blockCollection.ready; return this._doc.ready;
} }
get redo() { get redo() {
return this._blockCollection.redo.bind(this._blockCollection); return this._doc.redo.bind(this._doc);
} }
get resetHistory() { get resetHistory() {
return this._blockCollection.resetHistory.bind(this._blockCollection); return this._doc.resetHistory.bind(this._doc);
} }
get root() { get root() {
@@ -235,7 +232,7 @@ export class Blocks {
} }
get rootDoc() { get rootDoc() {
return this._blockCollection.rootDoc; return this._doc.rootDoc;
} }
get schema() { get schema() {
@@ -243,31 +240,31 @@ export class Blocks {
} }
get spaceDoc() { get spaceDoc() {
return this._blockCollection.spaceDoc; return this._doc.spaceDoc;
} }
get transact() { get transact() {
return this._blockCollection.transact.bind(this._blockCollection); return this._doc.transact.bind(this._doc);
} }
get undo() { get undo() {
return this._blockCollection.undo.bind(this._blockCollection); return this._doc.undo.bind(this._doc);
} }
get withoutTransact() { get withoutTransact() {
return this._blockCollection.withoutTransact.bind(this._blockCollection); return this._doc.withoutTransact.bind(this._doc);
} }
constructor({ schema, blockCollection, readonly, query }: DocOptions) { constructor({ schema, blockCollection, readonly, query }: DocOptions) {
this._blockCollection = blockCollection; this._doc = blockCollection;
this.slots = { this.slots = {
ready: new Slot(), ready: new Slot(),
rootAdded: new Slot(), rootAdded: new Slot(),
rootDeleted: new Slot(), rootDeleted: new Slot(),
blockUpdated: new Slot(), blockUpdated: new Slot(),
historyUpdated: this._blockCollection.slots.historyUpdated, historyUpdated: this._doc.slots.historyUpdated,
yBlockUpdated: this._blockCollection.slots.yBlockUpdated, yBlockUpdated: this._doc.slots.yBlockUpdated,
}; };
this._crud = new DocCRUD(this._yBlocks, blockCollection.schema); this._crud = new DocCRUD(this._yBlocks, blockCollection.schema);
@@ -284,7 +281,7 @@ export class Blocks {
this._onBlockAdded(id, true); this._onBlockAdded(id, true);
}); });
this._disposeBlockUpdated = this._blockCollection.slots.yBlockUpdated.on( this._disposeBlockUpdated = this._doc.slots.yBlockUpdated.on(
({ type, id }) => { ({ type, id }) => {
switch (type) { switch (type) {
case 'add': { case 'add': {
@@ -424,7 +421,7 @@ export class Blocks {
); );
} }
const id = blockProps.id ?? this._blockCollection.collection.idGenerator(); const id = blockProps.id ?? this._doc.workspace.idGenerator();
this.transact(() => { this.transact(() => {
this._crud.addBlock( this._crud.addBlock(
@@ -635,7 +632,7 @@ export class Blocks {
} }
load(initFn?: () => void) { load(initFn?: () => void) {
this._blockCollection.load(initFn); this._doc.load(initFn);
this.slots.ready.emit(); this.slots.ready.emit();
return this; return this;
} }
@@ -30,17 +30,18 @@ export interface DocMeta {
favorite?: boolean; favorite?: boolean;
} }
export type GetDocOptions = { export type GetBlocksOptions = {
query?: Query; query?: Query;
readonly?: boolean; readonly?: boolean;
}; };
export type CreateDocOptions = GetDocOptions & { export type CreateBlocksOptions = GetBlocksOptions & {
id?: string; id?: string;
}; };
export interface WorkspaceMeta { export interface WorkspaceMeta {
get docMetas(): DocMeta[]; get docMetas(): DocMeta[];
addDocMeta(props: DocMeta, index?: number): void;
getDocMeta(id: string): DocMeta | undefined; getDocMeta(id: string): DocMeta | undefined;
setDocMeta(id: string, props: Partial<DocMeta>): void; setDocMeta(id: string, props: Partial<DocMeta>): void;
removeDocMeta(id: string): void; removeDocMeta(id: string): void;
@@ -60,6 +61,10 @@ export interface WorkspaceMeta {
writeVersion(workspace: Workspace): void; writeVersion(workspace: Workspace): void;
get docs(): unknown[] | undefined; get docs(): unknown[] | undefined;
initialize(): void; initialize(): void;
docMetaAdded: Slot<string>;
docMetaRemoved: Slot<string>;
docMetaUpdated: Slot;
} }
export interface Workspace { export interface Workspace {
@@ -80,8 +85,8 @@ export interface Workspace {
docRemoved: Slot<string>; docRemoved: Slot<string>;
}; };
createDoc(options?: CreateDocOptions): Blocks; createDoc(options?: CreateBlocksOptions): Blocks;
getDoc(docId: string, options?: GetDocOptions): Blocks | null; getDoc(docId: string, options?: GetBlocksOptions): Blocks | null;
removeDoc(docId: string): void; removeDoc(docId: string): void;
dispose(): void; dispose(): void;
@@ -111,6 +116,7 @@ export interface Doc {
>; >;
}; };
get history(): Y.UndoManager;
get canRedo(): boolean; get canRedo(): boolean;
get canUndo(): boolean; get canUndo(): boolean;
undo(): void; undo(): void;
@@ -121,15 +127,14 @@ export interface Doc {
captureSync(): void; captureSync(): void;
clear(): void; clear(): void;
getDoc(options?: GetDocOptions): Blocks; getBlocks(options?: GetBlocksOptions): Blocks;
clearQuery(query: Query, readonly?: boolean): void; clearQuery(query: Query, readonly?: boolean): void;
get history(): Y.UndoManager;
get loaded(): boolean; get loaded(): boolean;
get readonly(): boolean; get readonly(): boolean;
get awarenessStore(): AwarenessStore; get awarenessStore(): AwarenessStore;
get collection(): Workspace; get workspace(): Workspace;
get rootDoc(): BlockSuiteDoc; get rootDoc(): BlockSuiteDoc;
get spaceDoc(): Y.Doc; get spaceDoc(): Y.Doc;
+11 -11
View File
@@ -5,7 +5,7 @@ import * as Y from 'yjs';
import { Blocks } from '../store/doc/doc.js'; import { Blocks } from '../store/doc/doc.js';
import type { YBlock } from '../store/doc/index.js'; import type { YBlock } from '../store/doc/index.js';
import type { Query } from '../store/doc/query.js'; import type { Query } from '../store/doc/query.js';
import type { Doc, GetDocOptions, Workspace } from '../store/workspace.js'; import type { Doc, GetBlocksOptions, Workspace } from '../store/workspace.js';
import type { AwarenessStore, BlockSuiteDoc } from '../yjs/index.js'; import type { AwarenessStore, BlockSuiteDoc } from '../yjs/index.js';
type DocOptions = { type DocOptions = {
@@ -124,7 +124,7 @@ export class TestDoc implements Doc {
}; };
get blobSync() { get blobSync() {
return this.collection.blobSync; return this.workspace.blobSync;
} }
get canRedo() { get canRedo() {
@@ -143,12 +143,12 @@ export class TestDoc implements Doc {
return this._canUndo$; return this._canUndo$;
} }
get collection() { get workspace() {
return this._collection; return this._collection;
} }
get docSync() { get docSync() {
return this.collection.docSync; return this.workspace.docSync;
} }
get history() { get history() {
@@ -164,7 +164,7 @@ export class TestDoc implements Doc {
} }
get meta() { get meta() {
return this.collection.meta.getDocMeta(this.id); return this.workspace.meta.getDocMeta(this.id);
} }
get readonly(): boolean { get readonly(): boolean {
@@ -176,7 +176,7 @@ export class TestDoc implements Doc {
} }
get schema() { get schema() {
return this.collection.schema; return this.workspace.schema;
} }
get spaceDoc() { get spaceDoc() {
@@ -204,8 +204,8 @@ export class TestDoc implements Doc {
private _handleVersion() { private _handleVersion() {
// Initialization from empty yDoc, indicating that the document is new. // Initialization from empty yDoc, indicating that the document is new.
if (!this.collection.meta.hasVersion) { if (!this.workspace.meta.hasVersion) {
this.collection.meta.writeVersion(this.collection); this.workspace.meta.writeVersion(this.workspace);
} }
} }
@@ -283,7 +283,7 @@ export class TestDoc implements Doc {
} }
} }
getDoc({ readonly, query }: GetDocOptions = {}) { getBlocks({ readonly, query }: GetBlocksOptions = {}) {
const readonlyKey = this._getReadonlyKey(readonly); const readonlyKey = this._getReadonlyKey(readonly);
const key = JSON.stringify(query); const key = JSON.stringify(query);
@@ -294,7 +294,7 @@ export class TestDoc implements Doc {
const doc = new Blocks({ const doc = new Blocks({
blockCollection: this, blockCollection: this,
schema: this.collection.schema, schema: this.workspace.schema,
readonly, readonly,
query, query,
}); });
@@ -311,7 +311,7 @@ export class TestDoc implements Doc {
this._ySpaceDoc.load(); this._ySpaceDoc.load();
if ((this.collection.meta.docs?.length ?? 0) <= 1) { if ((this.workspace.meta.docs?.length ?? 0) <= 1) {
this._handleVersion(); this._handleVersion();
} }
@@ -18,10 +18,11 @@ import { Awareness } from 'y-protocols/awareness.js';
import type { Schema } from '../schema/index.js'; import type { Schema } from '../schema/index.js';
import { import {
type Blocks, type Blocks,
type CreateDocOptions, type CreateBlocksOptions,
DocCollectionMeta, DocCollectionMeta,
type GetDocOptions, type GetBlocksOptions,
type Workspace, type Workspace,
type WorkspaceMeta,
} from '../store/index.js'; } from '../store/index.js';
import { type IdGenerator, nanoid } from '../utils/id-generator.js'; import { type IdGenerator, nanoid } from '../utils/id-generator.js';
import { import {
@@ -90,7 +91,7 @@ export class TestWorkspace implements Workspace {
readonly idGenerator: IdGenerator; readonly idGenerator: IdGenerator;
meta: DocCollectionMeta; meta: WorkspaceMeta;
slots = { slots = {
docListUpdated: new Slot(), docListUpdated: new Slot(),
@@ -191,7 +192,7 @@ export class TestWorkspace implements Workspace {
* If the `init` parameter is passed, a `surface`, `note`, and `paragraph` block * If the `init` parameter is passed, a `surface`, `note`, and `paragraph` block
* will be created in the doc simultaneously. * will be created in the doc simultaneously.
*/ */
createDoc(options: CreateDocOptions = {}) { createDoc(options: CreateBlocksOptions = {}) {
const { id: docId = this.idGenerator(), query, readonly } = options; const { id: docId = this.idGenerator(), query, readonly } = options;
if (this._hasDoc(docId)) { if (this._hasDoc(docId)) {
throw new BlockSuiteError( throw new BlockSuiteError(
@@ -229,9 +230,9 @@ export class TestWorkspace implements Workspace {
return space ?? null; return space ?? null;
} }
getDoc(docId: string, options?: GetDocOptions): Blocks | null { getDoc(docId: string, options?: GetBlocksOptions): Blocks | null {
const collection = this.getBlockCollection(docId); const collection = this.getBlockCollection(docId);
return collection?.getDoc(options) ?? null; return collection?.getBlocks(options) ?? null;
} }
removeDoc(docId: string) { removeDoc(docId: string) {
@@ -25,7 +25,7 @@ export class Slice {
static fromModels(doc: Blocks, models: DraftModel[]) { static fromModels(doc: Blocks, models: DraftModel[]) {
return new Slice({ return new Slice({
content: models, content: models,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
pageId: doc.id, pageId: doc.id,
}); });
} }
@@ -6,7 +6,7 @@ import {
} from '@blocksuite/blocks'; } from '@blocksuite/blocks';
import { WithDisposable } from '@blocksuite/global/utils'; import { WithDisposable } from '@blocksuite/global/utils';
import type { AffineEditorContainer } from '@blocksuite/presets'; import type { AffineEditorContainer } from '@blocksuite/presets';
import type { BlockCollection, DocCollection } from '@blocksuite/store'; import type { Doc, Workspace } from '@blocksuite/store';
import { css, html, nothing } from 'lit'; import { css, html, nothing } from 'lit';
import { customElement, property } from 'lit/decorators.js'; import { customElement, property } from 'lit/decorators.js';
import { repeat } from 'lit/directives/repeat.js'; import { repeat } from 'lit/directives/repeat.js';
@@ -64,23 +64,23 @@ export class DocsPanel extends WithDisposable(ShadowlessElement) {
`; `;
createDoc = () => { createDoc = () => {
createDocBlock(this.editor.doc.collection); createDocBlock(this.editor.doc.workspace);
}; };
gotoDoc = (doc: BlockCollection) => { gotoDoc = (doc: Doc) => {
const url = this.editor.std const url = this.editor.std
.getOptional(GenerateDocUrlProvider) .getOptional(GenerateDocUrlProvider)
?.generateDocUrl(doc.id); ?.generateDocUrl(doc.id);
if (url) history.pushState({}, '', url); if (url) history.pushState({}, '', url);
this.editor.doc = doc.getDoc(); this.editor.doc = doc.getBlocks();
this.editor.doc.load(); this.editor.doc.load();
this.editor.doc.resetHistory(); this.editor.doc.resetHistory();
this.requestUpdate(); this.requestUpdate();
}; };
private get collection() { private get collection() {
return this.editor.doc.collection; return this.editor.doc.workspace;
} }
private get docs() { private get docs() {
@@ -110,7 +110,7 @@ export class DocsPanel extends WithDisposable(ShadowlessElement) {
}); });
this.disposables.add( this.disposables.add(
this.editor.doc.collection.slots.docListUpdated.on(() => { this.editor.doc.workspace.slots.docListUpdated.on(() => {
this.requestUpdate(); this.requestUpdate();
}) })
); );
@@ -146,7 +146,7 @@ export class DocsPanel extends WithDisposable(ShadowlessElement) {
removeModeFromStorage(doc.id); removeModeFromStorage(doc.id);
// When delete the current doc, we need to set the editor doc to the first remaining doc // When delete the current doc, we need to set the editor doc to the first remaining doc
if (isDeleteCurrent) { if (isDeleteCurrent) {
this.editor.doc = this.docs[0].getDoc(); this.editor.doc = this.docs[0].getBlocks();
} }
}; };
return html`<div class="doc-item" @click="${click}" style="${style}"> return html`<div class="doc-item" @click="${click}" style="${style}">
@@ -169,7 +169,7 @@ export class DocsPanel extends WithDisposable(ShadowlessElement) {
accessor onClose!: () => void; accessor onClose!: () => void;
} }
function createDocBlock(collection: DocCollection) { function createDocBlock(collection: Workspace) {
const id = collection.idGenerator(); const id = collection.idGenerator();
createDefaultDoc(collection, { id }); createDefaultDoc(collection, { id });
} }
@@ -1,11 +1,11 @@
import type { DocModeProvider } from '@blocksuite/blocks'; import type { DocModeProvider } from '@blocksuite/blocks';
import { assertExists } from '@blocksuite/global/utils'; import { assertExists } from '@blocksuite/global/utils';
import type { AffineEditorContainer } from '@blocksuite/presets'; import type { AffineEditorContainer } from '@blocksuite/presets';
import type { BlockCollection, Doc, DocCollection } from '@blocksuite/store'; import type { Blocks, Doc, Workspace } from '@blocksuite/store';
import type { LitElement } from 'lit'; import type { LitElement } from 'lit';
export function getDocFromUrlParams(collection: DocCollection, url: URL) { export function getDocFromUrlParams(collection: Workspace, url: URL) {
let doc: Doc | null = null; let doc: Blocks | null = null;
const docId = decodeURIComponent(url.hash.slice(1)); const docId = decodeURIComponent(url.hash.slice(1));
@@ -13,10 +13,9 @@ export function getDocFromUrlParams(collection: DocCollection, url: URL) {
doc = collection.getDoc(docId); doc = collection.getDoc(docId);
} }
if (!doc) { if (!doc) {
const blockCollection = collection.docs.values().next() const blockCollection = collection.docs.values().next().value as Doc;
.value as BlockCollection;
assertExists(blockCollection, 'Need to create a doc first'); assertExists(blockCollection, 'Need to create a doc first');
doc = blockCollection.getDoc(); doc = blockCollection.getBlocks();
} }
doc.load(); doc.load();
@@ -41,7 +40,7 @@ export function setDocModeFromUrlParams(
} }
export function listenHashChange( export function listenHashChange(
collection: DocCollection, collection: Workspace,
editor: AffineEditorContainer, editor: AffineEditorContainer,
panel?: LitElement panel?: LitElement
) { ) {
@@ -14,7 +14,7 @@ import {
SpecProvider, SpecProvider,
} from '@blocksuite/blocks'; } from '@blocksuite/blocks';
import { AffineEditorContainer } from '@blocksuite/presets'; import { AffineEditorContainer } from '@blocksuite/presets';
import type { DocCollection } from '@blocksuite/store'; import type { Workspace } from '@blocksuite/store';
import { AttachmentViewerPanel } from '../../_common/components/attachment-viewer-panel.js'; import { AttachmentViewerPanel } from '../../_common/components/attachment-viewer-panel.js';
import { CollabDebugMenu } from '../../_common/components/collab-debug-menu.js'; import { CollabDebugMenu } from '../../_common/components/collab-debug-menu.js';
@@ -36,7 +36,7 @@ import {
} from '../../_common/mock-services.js'; } from '../../_common/mock-services.js';
import { getExampleSpecs } from '../specs-examples/index.js'; import { getExampleSpecs } from '../specs-examples/index.js';
export async function mountDefaultDocEditor(collection: DocCollection) { export async function mountDefaultDocEditor(collection: Workspace) {
const app = document.getElementById('app'); const app = document.getElementById('app');
if (!app) return; if (!app) return;
+3 -3
View File
@@ -1,7 +1,7 @@
import type { EditorHost } from '@blocksuite/block-std'; import type { EditorHost } from '@blocksuite/block-std';
import type { TestUtils } from '@blocksuite/blocks'; import type { TestUtils } from '@blocksuite/blocks';
import type { AffineEditorContainer } from '@blocksuite/presets'; import type { AffineEditorContainer } from '@blocksuite/presets';
import type { BlockSchema, Doc, DocCollection, Job } from '@blocksuite/store'; import type { BlockSchema, Blocks, Workspace, Job } from '@blocksuite/store';
import type { z } from 'zod'; import type { z } from 'zod';
import type * as Y from 'yjs'; import type * as Y from 'yjs';
@@ -14,8 +14,8 @@ declare global {
interface Window { interface Window {
editor: AffineEditorContainer; editor: AffineEditorContainer;
doc: Doc; doc: Blocks;
collection: DocCollection; collection: Workspace;
blockSchemas: z.infer<typeof BlockSchema>[]; blockSchemas: z.infer<typeof BlockSchema>[];
job: Job; job: Job;
Y: typeof Y; Y: typeof Y;
@@ -37,7 +37,7 @@ const snapshotTest = async (snapshotUrl: string, elementsCount: number) => {
throw e; throw e;
}); });
const [newDoc] = await transformer.importDocs( const [newDoc] = await transformer.importDocs(
window.editor.doc.collection, window.editor.doc.workspace,
snapshotFile snapshotFile
); );
@@ -59,7 +59,7 @@ async function createEditor(collection: TestWorkspace, mode: DocMode = 'page') {
const app = document.createElement('div'); const app = document.createElement('div');
const blockCollection = collection.docs.values().next().value; const blockCollection = collection.docs.values().next().value;
assertExists(blockCollection, 'Need to create a doc first'); assertExists(blockCollection, 'Need to create a doc first');
const doc = blockCollection.getDoc(); const doc = blockCollection.getBlocks();
const editor = new AffineEditorContainer(); const editor = new AffineEditorContainer();
editor.doc = doc; editor.doc = doc;
editor.mode = mode; editor.mode = mode;
@@ -44,7 +44,7 @@ export class CommentManager {
} }
const { quote, range } = parseResult; const { quote, range } = parseResult;
const id = this.host.doc.collection.idGenerator(); const id = this.host.doc.workspace.idGenerator();
const comment: Comment = { const comment: Comment = {
id, id,
date: Date.now(), date: Date.now(),
@@ -84,7 +84,7 @@ export class DocTitle extends WithDisposable(ShadowlessElement) {
}; };
private readonly _updateTitleInMeta = () => { private readonly _updateTitleInMeta = () => {
this.doc.collection.meta.setDocMeta(this.doc.id, { this.doc.workspace.meta.setDocMeta(this.doc.id, {
title: this._rootModel.title.toString(), title: this._rootModel.title.toString(),
}); });
}; };
@@ -170,7 +170,7 @@ export class OutlineBlockPreview extends SignalWatcher(
if (delta.attributes?.reference) { if (delta.attributes?.reference) {
// If linked doc, render linked doc icon and the doc title. // If linked doc, render linked doc icon and the doc title.
const refAttribute = delta.attributes.reference; const refAttribute = delta.attributes.reference;
const refMeta = block.doc.collection.meta.docMetas.find( const refMeta = block.doc.workspace.meta.docMetas.find(
doc => doc.id === refAttribute.pageId doc => doc.id === refAttribute.pageId
); );
const unavailable = !refMeta; const unavailable = !refMeta;
@@ -225,7 +225,7 @@ test.describe('Embed synced doc', () => {
}; };
const doc2Collection = getDocCollection(); const doc2Collection = getDocCollection();
const doc2 = doc2Collection!.getDoc(); const doc2 = doc2Collection!.getBlocks();
const [noteBlock] = doc2!.getBlocksByFlavour('affine:note'); const [noteBlock] = doc2!.getBlocksByFlavour('affine:note');
const noteId = noteBlock.id; const noteId = noteBlock.id;
@@ -194,7 +194,7 @@ async function initEmptyEditor({
} }
if (noInit) { if (noInit) {
const firstDoc = collection.docs.values().next().value?.getDoc() as const firstDoc = collection.docs.values().next().value?.getBlocks() as
| ReturnType<typeof collection.createDoc> | ReturnType<typeof collection.createDoc>
| undefined; | undefined;
if (firstDoc) { if (firstDoc) {
+7 -7
View File
@@ -174,16 +174,16 @@ const frameworkProvider = framework.provider();
const blockSuiteDoc = doc.blockSuiteDoc; const blockSuiteDoc = doc.blockSuiteDoc;
const job = new Job({ const job = new Job({
schema: blockSuiteDoc.collection.schema, schema: blockSuiteDoc.workspace.schema,
blobCRUD: blockSuiteDoc.collection.blobSync, blobCRUD: blockSuiteDoc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => blockSuiteDoc.collection.createDoc({ id }), create: (id: string) => blockSuiteDoc.workspace.createDoc({ id }),
get: (id: string) => blockSuiteDoc.collection.getDoc(id), get: (id: string) => blockSuiteDoc.workspace.getDoc(id),
delete: (id: string) => blockSuiteDoc.collection.removeDoc(id), delete: (id: string) => blockSuiteDoc.workspace.removeDoc(id),
}, },
middlewares: [ middlewares: [
docLinkBaseURLMiddleware(blockSuiteDoc.collection.id), docLinkBaseURLMiddleware(blockSuiteDoc.workspace.id),
titleMiddleware(blockSuiteDoc.collection.meta.docMetas), titleMiddleware(blockSuiteDoc.workspace.meta.docMetas),
], ],
}); });
const snapshot = job.docToSnapshot(blockSuiteDoc); const snapshot = job.docToSnapshot(blockSuiteDoc);
@@ -195,7 +195,7 @@ export class TextRenderer extends WithDisposable(ShadowlessElement) {
if (this._answers.length > 0) { if (this._answers.length > 0) {
const latestAnswer = this._answers.pop(); const latestAnswer = this._answers.pop();
this._answers = []; this._answers = [];
const schema = this.schema ?? this.host?.std.doc.collection.schema; const schema = this.schema ?? this.host?.std.doc.workspace.schema;
let provider: ServiceProvider; let provider: ServiceProvider;
if (this.host) { if (this.host) {
provider = this.host.std.provider; provider = this.host.std.provider;
@@ -220,11 +220,11 @@ export class TextRenderer extends WithDisposable(ShadowlessElement) {
) )
.then(doc => { .then(doc => {
this.disposeDoc(); this.disposeDoc();
this._doc = doc.blockCollection.getDoc({ this._doc = doc.doc.getBlocks({
query: this._query, query: this._query,
}); });
this.disposables.add(() => { this.disposables.add(() => {
doc.blockCollection.clearQuery(this._query); doc.doc.clearQuery(this._query);
}); });
this._doc.readonly = true; this._doc.readonly = true;
this.requestUpdate(); this.requestUpdate();
@@ -256,7 +256,7 @@ export class TextRenderer extends WithDisposable(ShadowlessElement) {
private disposeDoc() { private disposeDoc() {
this._doc?.dispose(); this._doc?.dispose();
this._doc?.collection.dispose(); this._doc?.workspace.dispose();
} }
override disconnectedCallback() { override disconnectedCallback() {
@@ -1,4 +1,4 @@
import { WorkspaceImpl } from '@affine/core/modules/workspace/impl/workspace'; import { WorkspaceImpl } from '@affine/core/modules/workspace/impls/workspace';
import type { import type {
EditorHost, EditorHost,
TextRangePoint, TextRangePoint,
@@ -80,15 +80,15 @@ export async function getContentFromSlice(
type: 'markdown' | 'plain-text' = 'markdown' type: 'markdown' | 'plain-text' = 'markdown'
) { ) {
const job = new Job({ const job = new Job({
schema: host.std.doc.collection.schema, schema: host.std.doc.workspace.schema,
blobCRUD: host.std.doc.collection.blobSync, blobCRUD: host.std.doc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => host.std.doc.collection.createDoc({ id }), create: (id: string) => host.std.doc.workspace.createDoc({ id }),
get: (id: string) => host.std.doc.collection.getDoc(id), get: (id: string) => host.std.doc.workspace.getDoc(id),
delete: (id: string) => host.std.doc.collection.removeDoc(id), delete: (id: string) => host.std.doc.workspace.removeDoc(id),
}, },
middlewares: [ middlewares: [
titleMiddleware(host.std.doc.collection.meta.docMetas), titleMiddleware(host.std.doc.workspace.meta.docMetas),
embedSyncedDocMiddleware('content'), embedSyncedDocMiddleware('content'),
], ],
}); });
@@ -110,14 +110,14 @@ export async function getContentFromSlice(
export async function getPlainTextFromSlice(host: EditorHost, slice: Slice) { export async function getPlainTextFromSlice(host: EditorHost, slice: Slice) {
const job = new Job({ const job = new Job({
schema: host.std.doc.collection.schema, schema: host.std.doc.workspace.schema,
blobCRUD: host.std.doc.collection.blobSync, blobCRUD: host.std.doc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => host.std.doc.collection.createDoc({ id }), create: (id: string) => host.std.doc.workspace.createDoc({ id }),
get: (id: string) => host.std.doc.collection.getDoc(id), get: (id: string) => host.std.doc.workspace.getDoc(id),
delete: (id: string) => host.std.doc.collection.removeDoc(id), delete: (id: string) => host.std.doc.workspace.removeDoc(id),
}, },
middlewares: [titleMiddleware(host.std.doc.collection.meta.docMetas)], middlewares: [titleMiddleware(host.std.doc.workspace.meta.docMetas)],
}); });
const snapshot = job.sliceToSnapshot(slice); const snapshot = job.sliceToSnapshot(slice);
if (!snapshot) { if (!snapshot) {
@@ -137,12 +137,12 @@ export const markdownToSnapshot = async (
host: EditorHost host: EditorHost
) => { ) => {
const job = new Job({ const job = new Job({
schema: host.std.doc.collection.schema, schema: host.std.doc.workspace.schema,
blobCRUD: host.std.doc.collection.blobSync, blobCRUD: host.std.doc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => host.std.doc.collection.createDoc({ id }), create: (id: string) => host.std.doc.workspace.createDoc({ id }),
get: (id: string) => host.std.doc.collection.getDoc(id), get: (id: string) => host.std.doc.workspace.getDoc(id),
delete: (id: string) => host.std.doc.collection.removeDoc(id), delete: (id: string) => host.std.doc.workspace.removeDoc(id),
}, },
middlewares: [defaultImageProxyMiddleware, pasteMiddleware(host.std)], middlewares: [defaultImageProxyMiddleware, pasteMiddleware(host.std)],
}); });
@@ -150,7 +150,7 @@ export const markdownToSnapshot = async (
const payload = { const payload = {
file: markdown, file: markdown,
assets: job.assetsManager, assets: job.assetsManager,
workspaceId: host.std.doc.collection.id, workspaceId: host.std.doc.workspace.id,
pageId: host.std.doc.id, pageId: host.std.doc.id,
}; };
@@ -107,7 +107,7 @@ export async function constructRootChatBlockMessages(
// Convert chat messages to AI chat block messages // Convert chat messages to AI chat block messages
const userInfo = await AIProvider.userInfo; const userInfo = await AIProvider.userInfo;
const forkMessages = await queryHistoryMessages( const forkMessages = await queryHistoryMessages(
doc.collection.id, doc.workspace.id,
doc.id, doc.id,
forkSessionId forkSessionId
); );
@@ -171,7 +171,7 @@ function addAIChatBlock(
messages: JSON.stringify(messages), messages: JSON.stringify(messages),
index, index,
sessionId, sessionId,
rootWorkspaceId: doc.collection.id, rootWorkspaceId: doc.workspace.id,
rootDocId: doc.id, rootDocId: doc.id,
}, },
surfaceBlock.id surfaceBlock.id
@@ -330,7 +330,7 @@ const SAVE_CHAT_TO_BLOCK_ACTION: ChatAction = {
try { try {
const newSessionId = await AIProvider.forkChat?.({ const newSessionId = await AIProvider.forkChat?.({
workspaceId: host.doc.collection.id, workspaceId: host.doc.workspace.id,
docId: host.doc.id, docId: host.doc.id,
sessionId: parentSessionId, sessionId: parentSessionId,
latestMessageId: messageId, latestMessageId: messageId,
@@ -425,7 +425,7 @@ const CREATE_AS_DOC = {
toast: 'New doc created', toast: 'New doc created',
handler: (host: EditorHost, content: string) => { handler: (host: EditorHost, content: string) => {
reportResponse('result:add-page'); reportResponse('result:add-page');
const newDoc = host.doc.collection.createDoc(); const newDoc = host.doc.workspace.createDoc();
newDoc.load(); newDoc.load();
const rootId = newDoc.addBlock('affine:page'); const rootId = newDoc.addBlock('affine:page');
newDoc.addBlock('affine:surface', {}, rootId); newDoc.addBlock('affine:surface', {}, rootId);
@@ -479,7 +479,7 @@ const CREATE_AS_LINKED_DOC = {
} }
// Create a new doc and add the content to it // Create a new doc and add the content to it
const newDoc = host.doc.collection.createDoc(); const newDoc = host.doc.workspace.createDoc();
newDoc.load(); newDoc.load();
const rootId = newDoc.addBlock('affine:page'); const rootId = newDoc.addBlock('affine:page');
newDoc.addBlock('affine:surface', {}, rootId); newDoc.addBlock('affine:surface', {}, rootId);
@@ -107,7 +107,7 @@ export function actionToStream<T extends keyof BlockSuitePresets.AIActions>(
control, control,
where, where,
docId: host.doc.id, docId: host.doc.id,
workspaceId: host.doc.collection.id, workspaceId: host.doc.workspace.id,
} as Parameters<typeof action>[0]; } as Parameters<typeof action>[0];
// @ts-expect-error TODO(@Peng): maybe fix this // @ts-expect-error TODO(@Peng): maybe fix this
stream = action(options); stream = action(options);
@@ -238,7 +238,7 @@ export function handleInlineAskAIAction(host: EditorHost) {
where: 'inline-chat-panel', where: 'inline-chat-panel',
control: 'chat-send', control: 'chat-send',
docId: host.doc.id, docId: host.doc.id,
workspaceId: host.doc.collection.id, workspaceId: host.doc.workspace.id,
}); });
bindTextStream(stream, { update, finish, signal }); bindTextStream(stream, { update, finish, signal });
}) })
@@ -189,7 +189,7 @@ function actionToStream<T extends keyof BlockSuitePresets.AIActions>(
models, models,
host, host,
docId: host.doc.id, docId: host.doc.id,
workspaceId: host.doc.collection.id, workspaceId: host.doc.workspace.id,
} as Parameters<typeof action>[0]; } as Parameters<typeof action>[0];
const content = ctx.get().content; const content = ctx.get().content;
@@ -230,7 +230,7 @@ function actionToStream<T extends keyof BlockSuitePresets.AIActions>(
control: 'format-bar', control: 'format-bar',
host, host,
docId: host.doc.id, docId: host.doc.id,
workspaceId: host.doc.collection.id, workspaceId: host.doc.workspace.id,
} as Parameters<typeof action>[0]; } as Parameters<typeof action>[0];
// @ts-expect-error TODO(@Peng): maybe fix this // @ts-expect-error TODO(@Peng): maybe fix this
@@ -488,7 +488,7 @@ export class ChatPanelInput extends WithDisposable(LitElement) {
input: content, input: content,
docId: doc.id, docId: doc.id,
attachments: images, attachments: images,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
host: this.host, host: this.host,
stream: true, stream: true,
signal: abortController.signal, signal: abortController.signal,
@@ -519,7 +519,7 @@ export class ChatPanelInput extends WithDisposable(LitElement) {
const last = items[items.length - 1] as ChatMessage; const last = items[items.length - 1] as ChatMessage;
if (!last.id) { if (!last.id) {
const historyIds = await AIProvider.histories?.ids( const historyIds = await AIProvider.histories?.ids(
doc.collection.id, doc.workspace.id,
doc.id, doc.id,
{ sessionId: this.chatContextValue.chatSessionId } { sessionId: this.chatContextValue.chatSessionId }
); );
@@ -426,7 +426,7 @@ export class ChatPanelMessages extends WithDisposable(ShadowlessElement) {
sessionId: chatSessionId, sessionId: chatSessionId,
retry: true, retry: true,
docId: doc.id, docId: doc.id,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
host: this.host, host: this.host,
stream: true, stream: true,
signal: abortController.signal, signal: abortController.signal,
@@ -107,8 +107,8 @@ export class ChatPanel extends WithDisposable(ShadowlessElement) {
const { doc } = this; const { doc } = this;
const [histories, actions] = await Promise.all([ const [histories, actions] = await Promise.all([
AIProvider.histories?.chats(doc.collection.id, doc.id, { fork: false }), AIProvider.histories?.chats(doc.workspace.id, doc.id, { fork: false }),
AIProvider.histories?.actions(doc.collection.id, doc.id), AIProvider.histories?.actions(doc.workspace.id, doc.id),
]); ]);
if (counter !== this._resettingCounter) return; if (counter !== this._resettingCounter) return;
@@ -175,7 +175,7 @@ export class ChatPanel extends WithDisposable(ShadowlessElement) {
cancelText: 'Cancel', cancelText: 'Cancel',
}) })
) { ) {
await AIProvider.histories?.cleanup(this.doc.collection.id, this.doc.id, [ await AIProvider.histories?.cleanup(this.doc.workspace.id, this.doc.id, [
this.chatContextValue.chatSessionId ?? '', this.chatContextValue.chatSessionId ?? '',
...( ...(
this.chatContextValue.items.filter( this.chatContextValue.items.filter(
@@ -1,4 +1,4 @@
import { WorkspaceImpl } from '@affine/core/modules/workspace/impl/workspace'; import { WorkspaceImpl } from '@affine/core/modules/workspace/impls/workspace';
import { BlockStdScope, type EditorHost } from '@blocksuite/affine/block-std'; import { BlockStdScope, type EditorHost } from '@blocksuite/affine/block-std';
import { import {
type AffineAIPanelWidgetConfig, type AffineAIPanelWidgetConfig,
@@ -1,4 +1,4 @@
import { WorkspaceImpl } from '@affine/core/modules/workspace/impl/workspace.js'; import { WorkspaceImpl } from '@affine/core/modules/workspace/impls/workspace.js';
import { BlockStdScope, type EditorHost } from '@blocksuite/affine/block-std'; import { BlockStdScope, type EditorHost } from '@blocksuite/affine/block-std';
import { import {
MarkdownAdapter, MarkdownAdapter,
@@ -239,12 +239,12 @@ export const markdownToMindmap = (
) => { ) => {
let result: Node | null = null; let result: Node | null = null;
const job = new Job({ const job = new Job({
schema: doc.collection.schema, schema: doc.workspace.schema,
blobCRUD: doc.collection.blobSync, blobCRUD: doc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => doc.collection.createDoc({ id }), create: (id: string) => doc.workspace.createDoc({ id }),
get: (id: string) => doc.collection.getDoc(id), get: (id: string) => doc.workspace.getDoc(id),
delete: (id: string) => doc.collection.removeDoc(id), delete: (id: string) => doc.workspace.removeDoc(id),
}, },
}); });
const markdown = new MarkdownAdapter(job, provider); const markdown = new MarkdownAdapter(job, provider);
@@ -403,7 +403,7 @@ export class ChatBlockInput extends LitElement {
let chatSessionId = currentSessionId; let chatSessionId = currentSessionId;
if (!chatSessionId) { if (!chatSessionId) {
const forkSessionId = await AIProvider.forkChat?.({ const forkSessionId = await AIProvider.forkChat?.({
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
docId: doc.id, docId: doc.id,
sessionId: this.parentSessionId, sessionId: this.parentSessionId,
latestMessageId: this.latestMessageId, latestMessageId: this.latestMessageId,
@@ -421,7 +421,7 @@ export class ChatBlockInput extends LitElement {
sessionId: chatSessionId, sessionId: chatSessionId,
docId: doc.id, docId: doc.id,
attachments: images, attachments: images,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
host: this.host, host: this.host,
stream: true, stream: true,
signal: abortController.signal, signal: abortController.signal,
@@ -269,7 +269,7 @@ export class AIChatBlockPeekView extends LitElement {
) { ) {
const { doc } = this.host; const { doc } = this.host;
if (currentSessionId) { if (currentSessionId) {
await AIProvider.histories?.cleanup(doc.collection.id, doc.id, [ await AIProvider.histories?.cleanup(doc.workspace.id, doc.id, [
currentSessionId, currentSessionId,
]); ]);
} }
@@ -323,7 +323,7 @@ export class AIChatBlockPeekView extends LitElement {
sessionId: currentSessionId, sessionId: currentSessionId,
retry: true, retry: true,
docId: doc.id, docId: doc.id,
workspaceId: doc.collection.id, workspaceId: doc.workspace.id,
host: this.host, host: this.host,
stream: true, stream: true,
signal: abortController.signal, signal: abortController.signal,
@@ -155,6 +155,6 @@ export const copyText = async (host: EditorHost, text: string) => {
const slice = Slice.fromModels(previewDoc, models); const slice = Slice.fromModels(previewDoc, models);
await host.std.clipboard.copySlice(slice); await host.std.clipboard.copySlice(slice);
previewDoc.dispose(); previewDoc.dispose();
previewDoc.collection.dispose(); previewDoc.workspace.dispose();
return true; return true;
}; };
@@ -2,7 +2,7 @@ import { useDocMetaHelper } from '@affine/core/components/hooks/use-block-suite-
import { useDocCollectionPage } from '@affine/core/components/hooks/use-block-suite-workspace-page'; import { useDocCollectionPage } from '@affine/core/components/hooks/use-block-suite-workspace-page';
import { FetchService, GraphQLService } from '@affine/core/modules/cloud'; import { FetchService, GraphQLService } from '@affine/core/modules/cloud';
import { getAFFiNEWorkspaceSchema } from '@affine/core/modules/workspace'; import { getAFFiNEWorkspaceSchema } from '@affine/core/modules/workspace';
import { WorkspaceImpl } from '@affine/core/modules/workspace/impl/workspace'; import { WorkspaceImpl } from '@affine/core/modules/workspace/impls/workspace';
import { DebugLogger } from '@affine/debug'; import { DebugLogger } from '@affine/debug';
import type { ListHistoryQuery } from '@affine/graphql'; import type { ListHistoryQuery } from '@affine/graphql';
import { listHistoryQuery, recoverDocMutation } from '@affine/graphql'; import { listHistoryQuery, recoverDocMutation } from '@affine/graphql';
@@ -41,7 +41,7 @@ const BlockSuiteEditorImpl = ({
}: EditorProps) => { }: EditorProps) => {
useEffect(() => { useEffect(() => {
const disposable = page.slots.blockUpdated.once(() => { const disposable = page.slots.blockUpdated.once(() => {
page.collection.meta.setDocMeta(page.id, { page.workspace.meta.setDocMeta(page.id, {
updatedDate: Date.now(), updatedDate: Date.now(),
}); });
}); });
@@ -59,16 +59,16 @@ async function exportDoc(
config: AdapterConfig config: AdapterConfig
) { ) {
const job = new Job({ const job = new Job({
schema: doc.collection.schema, schema: doc.workspace.schema,
blobCRUD: doc.collection.blobSync, blobCRUD: doc.workspace.blobSync,
docCRUD: { docCRUD: {
create: (id: string) => doc.collection.createDoc({ id }), create: (id: string) => doc.workspace.createDoc({ id }),
get: (id: string) => doc.collection.getDoc(id), get: (id: string) => doc.workspace.getDoc(id),
delete: (id: string) => doc.collection.removeDoc(id), delete: (id: string) => doc.workspace.removeDoc(id),
}, },
middlewares: [ middlewares: [
docLinkBaseURLMiddleware(doc.collection.id), docLinkBaseURLMiddleware(doc.workspace.id),
titleMiddleware(doc.collection.meta.docMetas), titleMiddleware(doc.workspace.meta.docMetas),
embedSyncedDocMiddleware('content'), embedSyncedDocMiddleware('content'),
], ],
}); });
@@ -148,7 +148,7 @@ async function exportHandler({
await exportToMarkdown(page, editorRoot?.std); await exportToMarkdown(page, editorRoot?.std);
return; return;
case 'snapshot': case 'snapshot':
await ZipTransformer.exportDocs(page.collection, [page]); await ZipTransformer.exportDocs(page.workspace, [page]);
return; return;
case 'pdf': case 'pdf':
await printToPdf(editorContainer); await printToPdf(editorContainer);
@@ -1,4 +1,4 @@
import { WorkspaceImpl } from '@affine/core/modules/workspace/impl/workspace'; import { WorkspaceImpl } from '@affine/core/modules/workspace/impls/workspace';
import { AffineSchemas } from '@blocksuite/affine/blocks'; import { AffineSchemas } from '@blocksuite/affine/blocks';
import type { Blocks, DocSnapshot } from '@blocksuite/affine/store'; import type { Blocks, DocSnapshot } from '@blocksuite/affine/store';
import { Job, Schema } from '@blocksuite/affine/store'; import { Job, Schema } from '@blocksuite/affine/store';
@@ -265,7 +265,7 @@ const WorkspacePage = ({ meta }: { meta: WorkspaceMetadata }) => {
workspace.docCollection, workspace.docCollection,
Array.from(workspace.docCollection.docs.values()) Array.from(workspace.docCollection.docs.values())
.filter(doc => (docs ? docs.includes(doc.id) : true)) .filter(doc => (docs ? docs.includes(doc.id) : true))
.map(doc => doc.getDoc()) .map(doc => doc.getBlocks())
); );
}; };
window.importWorkspaceSnapshot = async () => { window.importWorkspaceSnapshot = async () => {
@@ -34,7 +34,7 @@ import {
} from 'yjs'; } from 'yjs';
import { getAFFiNEWorkspaceSchema } from '../../workspace/global-schema'; import { getAFFiNEWorkspaceSchema } from '../../workspace/global-schema';
import { WorkspaceImpl } from '../../workspace/impl/workspace'; import { WorkspaceImpl } from '../../workspace/impls/workspace';
import type { BlockIndexSchema, DocIndexSchema } from '../schema'; import type { BlockIndexSchema, DocIndexSchema } from '../schema';
import type { import type {
WorkerIngoingMessage, WorkerIngoingMessage,
@@ -41,7 +41,7 @@ import {
type WorkspaceMetadata, type WorkspaceMetadata,
type WorkspaceProfileInfo, type WorkspaceProfileInfo,
} from '../../workspace'; } from '../../workspace';
import { WorkspaceImpl } from '../../workspace/impl/workspace'; import { WorkspaceImpl } from '../../workspace/impls/workspace';
import type { WorkspaceEngineStorageProvider } from '../providers/engine'; import type { WorkspaceEngineStorageProvider } from '../providers/engine';
import { BroadcastChannelAwarenessConnection } from './engine/awareness-broadcast-channel'; import { BroadcastChannelAwarenessConnection } from './engine/awareness-broadcast-channel';
import { CloudAwarenessConnection } from './engine/awareness-cloud'; import { CloudAwarenessConnection } from './engine/awareness-cloud';
@@ -19,7 +19,7 @@ import {
type WorkspaceMetadata, type WorkspaceMetadata,
type WorkspaceProfileInfo, type WorkspaceProfileInfo,
} from '../../workspace'; } from '../../workspace';
import { WorkspaceImpl } from '../../workspace/impl/workspace'; import { WorkspaceImpl } from '../../workspace/impls/workspace';
import type { WorkspaceEngineStorageProvider } from '../providers/engine'; import type { WorkspaceEngineStorageProvider } from '../providers/engine';
import { BroadcastChannelAwarenessConnection } from './engine/awareness-broadcast-channel'; import { BroadcastChannelAwarenessConnection } from './engine/awareness-broadcast-channel';
import { StaticBlobStorage } from './engine/blob-static'; import { StaticBlobStorage } from './engine/blob-static';
@@ -5,7 +5,7 @@ import type { Awareness } from 'y-protocols/awareness.js';
import { WorkspaceDBService } from '../../db'; import { WorkspaceDBService } from '../../db';
import { getAFFiNEWorkspaceSchema } from '../global-schema'; import { getAFFiNEWorkspaceSchema } from '../global-schema';
import { WorkspaceImpl } from '../impl/workspace'; import { WorkspaceImpl } from '../impls/workspace';
import type { WorkspaceScope } from '../scopes/workspace'; import type { WorkspaceScope } from '../scopes/workspace';
import { WorkspaceEngineService } from '../services/engine'; import { WorkspaceEngineService } from '../services/engine';
@@ -4,7 +4,7 @@ import {
Blocks, Blocks,
type BlockSuiteDoc, type BlockSuiteDoc,
type Doc, type Doc,
type GetDocOptions, type GetBlocksOptions,
type Query, type Query,
type Workspace, type Workspace,
type YBlock, type YBlock,
@@ -128,7 +128,7 @@ export class DocImpl implements Doc {
}; };
get blobSync() { get blobSync() {
return this.collection.blobSync; return this.workspace.blobSync;
} }
get canRedo() { get canRedo() {
@@ -139,12 +139,12 @@ export class DocImpl implements Doc {
return this._canUndo.peek(); return this._canUndo.peek();
} }
get collection() { get workspace() {
return this._collection; return this._collection;
} }
get docSync() { get docSync() {
return this.collection.docSync; return this.workspace.docSync;
} }
get history() { get history() {
@@ -160,7 +160,7 @@ export class DocImpl implements Doc {
} }
get meta() { get meta() {
return this.collection.meta.getDocMeta(this.id); return this.workspace.meta.getDocMeta(this.id);
} }
get readonly(): boolean { get readonly(): boolean {
@@ -172,7 +172,7 @@ export class DocImpl implements Doc {
} }
get schema() { get schema() {
return this.collection.schema; return this.workspace.schema;
} }
get spaceDoc() { get spaceDoc() {
@@ -200,8 +200,8 @@ export class DocImpl implements Doc {
private _handleVersion() { private _handleVersion() {
// Initialization from empty yDoc, indicating that the document is new. // Initialization from empty yDoc, indicating that the document is new.
if (!this.collection.meta.hasVersion) { if (!this.workspace.meta.hasVersion) {
this.collection.meta.writeVersion(this.collection); this.workspace.meta.writeVersion(this.workspace);
} }
} }
@@ -279,7 +279,7 @@ export class DocImpl implements Doc {
} }
} }
getDoc({ readonly, query }: GetDocOptions = {}) { getBlocks({ readonly, query }: GetBlocksOptions = {}) {
const readonlyKey = this._getReadonlyKey(readonly); const readonlyKey = this._getReadonlyKey(readonly);
const key = JSON.stringify(query); const key = JSON.stringify(query);
@@ -290,7 +290,7 @@ export class DocImpl implements Doc {
const doc = new Blocks({ const doc = new Blocks({
blockCollection: this, blockCollection: this,
schema: this.collection.schema, schema: this.workspace.schema,
readonly, readonly,
query, query,
}); });
@@ -307,7 +307,7 @@ export class DocImpl implements Doc {
this._ySpaceDoc.load(); this._ySpaceDoc.load();
if ((this.collection.meta.docs?.length ?? 0) <= 1) { if ((this.workspace.meta.docs?.length ?? 0) <= 1) {
this._handleVersion(); this._handleVersion();
} }
@@ -8,14 +8,15 @@ import {
AwarenessStore, AwarenessStore,
type Blocks, type Blocks,
BlockSuiteDoc, BlockSuiteDoc,
type CreateDocOptions, type CreateBlocksOptions,
type Doc, type Doc,
DocCollectionMeta, DocCollectionMeta,
type GetDocOptions, type GetBlocksOptions,
type IdGenerator, type IdGenerator,
nanoid, nanoid,
type Schema, type Schema,
type Workspace, type Workspace,
type WorkspaceMeta,
} from '@blocksuite/affine/store'; } from '@blocksuite/affine/store';
import { import {
AwarenessEngine, AwarenessEngine,
@@ -74,7 +75,7 @@ export class WorkspaceImpl implements Workspace {
readonly idGenerator: IdGenerator; readonly idGenerator: IdGenerator;
meta: DocCollectionMeta; meta: WorkspaceMeta;
slots = { slots = {
docListUpdated: new Slot(), docListUpdated: new Slot(),
@@ -153,7 +154,7 @@ export class WorkspaceImpl implements Workspace {
* If the `init` parameter is passed, a `surface`, `note`, and `paragraph` block * If the `init` parameter is passed, a `surface`, `note`, and `paragraph` block
* will be created in the doc simultaneously. * will be created in the doc simultaneously.
*/ */
createDoc(options: CreateDocOptions = {}) { createDoc(options: CreateBlocksOptions = {}) {
const { id: docId = this.idGenerator(), query, readonly } = options; const { id: docId = this.idGenerator(), query, readonly } = options;
if (this._hasDoc(docId)) { if (this._hasDoc(docId)) {
throw new BlockSuiteError( throw new BlockSuiteError(
@@ -191,9 +192,9 @@ export class WorkspaceImpl implements Workspace {
return space ?? null; return space ?? null;
} }
getDoc(docId: string, options?: GetDocOptions): Blocks | null { getDoc(docId: string, options?: GetBlocksOptions): Blocks | null {
const collection = this.getBlockCollection(docId); const collection = this.getBlockCollection(docId);
return collection?.getDoc(options) ?? null; return collection?.getBlocks(options) ?? null;
} }
removeDoc(docId: string) { removeDoc(docId: string) {