refactor(editor): improve query methods in toolbar context (#10714)

This commit is contained in:
fundon
2025-03-19 00:52:22 +00:00
parent 02d707feab
commit 3cce147c60
14 changed files with 317 additions and 359 deletions
@@ -11,10 +11,8 @@ import {
ActionPlacement,
type ToolbarAction,
type ToolbarActionGroup,
type ToolbarContext,
type ToolbarModuleConfig,
} from '@blocksuite/affine-shared/services';
import { BlockSelection, SurfaceSelection } from '@blocksuite/block-std';
import { Bound } from '@blocksuite/global/gfx';
import {
CaptionIcon,
@@ -25,7 +23,6 @@ import {
EditIcon,
ResetIcon,
} from '@blocksuite/icons/lit';
import type { SelectionConstructor } from '@blocksuite/store';
import { flip, offset } from '@floating-ui/dom';
import { computed } from '@preact/signals-core';
import { html } from 'lit';
@@ -44,101 +41,95 @@ const trackBaseProps = {
type: 'card view',
};
const createAttachmentViewDropdownMenuWith = <T extends SelectionConstructor>(
t: T
) => {
return {
id: 'b.conversions',
actions: [
{
id: 'card',
label: 'Card view',
run(ctx) {
const model = ctx.getCurrentModelByType(t, AttachmentBlockModel);
if (!model) return;
export const attachmentViewDropdownMenu = {
id: 'b.conversions',
actions: [
{
id: 'card',
label: 'Card view',
run(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return;
const style = defaultAttachmentProps.style!;
const width = EMBED_CARD_WIDTH[style];
const height = EMBED_CARD_HEIGHT[style];
const bound = Bound.deserialize(model.xywh);
bound.w = width;
bound.h = height;
const style = defaultAttachmentProps.style!;
const width = EMBED_CARD_WIDTH[style];
const height = EMBED_CARD_HEIGHT[style];
const bound = Bound.deserialize(model.xywh);
bound.w = width;
bound.h = height;
ctx.store.updateBlock(model, {
style,
embed: false,
xywh: bound.serialize(),
});
},
},
{
id: 'embed',
label: 'Embed view',
run(ctx) {
const model = ctx.getCurrentModelByType(t, AttachmentBlockModel);
if (!model) return;
// Clears
ctx.reset();
ctx.select('note');
ctx.std.get(AttachmentEmbedProvider).convertTo(model);
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'embed view',
});
},
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(t, AttachmentBlockModel);
if (!model) return null;
const embedProvider = ctx.std.get(AttachmentEmbedProvider);
const actions = this.actions.map(action => ({ ...action }));
const viewType$ = computed(() => {
const [cardAction, embedAction] = actions;
const embed = model.props.embed$.value ?? false;
cardAction.disabled = !embed;
embedAction.disabled = embed && embedProvider.embedded(model);
return embed ? embedAction.label : cardAction.label;
});
const toggle = (e: CustomEvent<boolean>) => {
const opened = e.detail;
if (!opened) return;
ctx.track('OpenedViewSelector', {
...trackBaseProps,
control: 'switch view',
ctx.store.updateBlock(model, {
style,
embed: false,
xywh: bound.serialize(),
});
};
return html`${keyed(
model,
html`<affine-view-dropdown-menu
.actions=${actions}
.context=${ctx}
.toggle=${toggle}
.viewType$=${viewType$}
></affine-view-dropdown-menu>`
)}`;
},
},
} satisfies ToolbarActionGroup<ToolbarAction>;
};
{
id: 'embed',
label: 'Embed view',
run(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return;
// Clears
ctx.reset();
ctx.select('note');
ctx.std.get(AttachmentEmbedProvider).convertTo(model);
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'embed view',
});
},
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return null;
const embedProvider = ctx.std.get(AttachmentEmbedProvider);
const actions = this.actions.map(action => ({ ...action }));
const viewType$ = computed(() => {
const [cardAction, embedAction] = actions;
const embed = model.props.embed$.value ?? false;
cardAction.disabled = !embed;
embedAction.disabled = embed && embedProvider.embedded(model);
return embed ? embedAction.label : cardAction.label;
});
const toggle = (e: CustomEvent<boolean>) => {
const opened = e.detail;
if (!opened) return;
ctx.track('OpenedViewSelector', {
...trackBaseProps,
control: 'switch view',
});
};
return html`${keyed(
model,
html`<affine-view-dropdown-menu
.actions=${actions}
.context=${ctx}
.toggle=${toggle}
.viewType$=${viewType$}
></affine-view-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>;
export const builtinToolbarConfig = {
actions: [
{
id: 'a.rename',
content(cx) {
const component = cx.getCurrentBlockComponentBy(
AttachmentBlockComponent
);
if (!component) return null;
const block = cx.getCurrentBlockByType(AttachmentBlockComponent);
if (!block) return null;
const abortController = new AbortController();
abortController.signal.onabort = () => cx.show();
@@ -152,12 +143,12 @@ export const builtinToolbarConfig = {
createLitPortal({
template: RenameModal({
model: component.model,
model: block.model,
editorHost: cx.host,
abortController,
}),
computePosition: {
referenceElement: component,
referenceElement: block,
placement: 'top-start',
middleware: [flip(), offset(4)],
},
@@ -170,16 +161,14 @@ export const builtinToolbarConfig = {
`;
},
},
createAttachmentViewDropdownMenuWith(BlockSelection),
attachmentViewDropdownMenu,
{
id: 'c.download',
tooltip: 'Download',
icon: DownloadIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
AttachmentBlockComponent
);
component?.download();
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.download();
},
},
{
@@ -187,10 +176,8 @@ export const builtinToolbarConfig = {
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
AttachmentBlockComponent
);
component?.captionEditor?.show();
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
@@ -208,10 +195,8 @@ export const builtinToolbarConfig = {
icon: CopyIcon(),
run(ctx) {
// TODO(@fundon): unify `clone` method
const component = ctx.getCurrentBlockComponentBy(
AttachmentBlockComponent
);
component?.copy();
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.copy();
},
},
{
@@ -219,9 +204,7 @@ export const builtinToolbarConfig = {
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentBlockComponentBy(
AttachmentBlockComponent
)?.model;
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return;
// TODO(@fundon): unify `duplicate` method
@@ -241,10 +224,8 @@ export const builtinToolbarConfig = {
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
AttachmentBlockComponent
);
component?.refreshData();
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.refreshData();
},
},
{
@@ -257,7 +238,7 @@ export const builtinToolbarConfig = {
const model = ctx.getCurrentModel();
if (!model) return;
ctx.store.deleteBlock(model);
ctx.store.deleteBlock(model.id);
// Clears
ctx.select('note');
@@ -266,7 +247,3 @@ export const builtinToolbarConfig = {
},
],
} as const satisfies ToolbarModuleConfig;
export const attachmentViewDropdownMenu = (ctx: ToolbarContext) => {
return createAttachmentViewDropdownMenuWith(SurfaceSelection).content(ctx);
};
@@ -39,10 +39,7 @@ export const builtinToolbarConfig = {
{
id: 'a.preview',
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
BookmarkBlockModel
);
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const { url } = model.props;
@@ -57,10 +54,7 @@ export const builtinToolbarConfig = {
id: 'inline',
label: 'Inline view',
run(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
BookmarkBlockModel
);
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { title, caption, url } = model.props;
@@ -98,10 +92,7 @@ export const builtinToolbarConfig = {
id: 'embed',
label: 'Embed view',
disabled(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
BookmarkBlockModel
);
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return true;
const url = model.props.url;
@@ -121,10 +112,7 @@ export const builtinToolbarConfig = {
return !canEmbedAsIframe && options?.viewType !== 'embed';
},
run(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
BookmarkBlockModel
);
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { caption, url, style } = model.props;
@@ -189,10 +177,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
BookmarkBlockModel
);
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
@@ -230,10 +215,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
BookmarkBlockModel
);
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({
@@ -275,10 +257,8 @@ export const builtinToolbarConfig = {
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
BookmarkBlockComponent
);
component?.captionEditor?.show();
const block = ctx.getCurrentBlockByType(BookmarkBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
@@ -295,7 +275,7 @@ export const builtinToolbarConfig = {
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
@@ -310,7 +290,7 @@ export const builtinToolbarConfig = {
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { flavour, parent } = model;
@@ -328,10 +308,8 @@ export const builtinToolbarConfig = {
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
BookmarkBlockComponent
);
component?.refreshData();
const block = ctx.getCurrentBlockByType(BookmarkBlockComponent);
block?.refreshData();
},
},
{
@@ -341,7 +319,7 @@ export const builtinToolbarConfig = {
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
ctx.store.deleteBlock(model);
@@ -52,7 +52,7 @@ export function createBuiltinToolbarConfigForExternal(
{
id: 'a.preview',
content(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return null;
const { url } = model.props;
@@ -72,7 +72,7 @@ export function createBuiltinToolbarConfigForExternal(
id: 'inline',
label: 'Inline view',
run(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return;
const { title, caption, url: link } = model.props;
@@ -105,7 +105,7 @@ export function createBuiltinToolbarConfigForExternal(
id: 'card',
label: 'Card view',
disabled(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return true;
const { url } = model.props;
@@ -116,7 +116,7 @@ export function createBuiltinToolbarConfigForExternal(
return options?.viewType === 'card';
},
run(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return;
const { url, caption } = model.props;
@@ -165,7 +165,7 @@ export function createBuiltinToolbarConfigForExternal(
id: 'embed',
label: 'Embed view',
disabled(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return false;
const { url } = model.props;
@@ -176,7 +176,7 @@ export function createBuiltinToolbarConfigForExternal(
return options?.viewType === 'embed';
},
when(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return false;
const { url } = model.props;
@@ -187,7 +187,7 @@ export function createBuiltinToolbarConfigForExternal(
return options?.viewType === 'embed';
},
run(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return;
const { url, caption } = model.props;
@@ -231,7 +231,7 @@ export function createBuiltinToolbarConfigForExternal(
},
],
content(ctx) {
const model = ctx.getCurrentModel();
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return null;
const { url } = model.props;
@@ -277,10 +277,7 @@ export function createBuiltinToolbarConfigForExternal(
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedGithubModel
);
const model = ctx.getCurrentModelByType(EmbedGithubModel);
if (!model) return null;
const actions = this.actions.map(action => ({
@@ -322,10 +319,8 @@ export function createBuiltinToolbarConfigForExternal(
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(klass);
if (!component) return;
component.captionEditor?.show();
const block = ctx.getCurrentBlockByType(klass);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
@@ -342,7 +337,7 @@ export function createBuiltinToolbarConfigForExternal(
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return;
const slice = Slice.fromModels(ctx.store, [model]);
@@ -357,7 +352,7 @@ export function createBuiltinToolbarConfigForExternal(
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return;
const { flavour, parent } = model;
@@ -375,8 +370,8 @@ export function createBuiltinToolbarConfigForExternal(
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(klass);
component?.refreshData();
const block = ctx.getCurrentBlockByType(klass);
block?.refreshData();
},
},
{
@@ -386,10 +381,10 @@ export function createBuiltinToolbarConfigForExternal(
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model || !isExternalEmbedModel(model)) return;
ctx.store.deleteBlock(model);
ctx.store.deleteBlock(model.id);
// Clears
ctx.select('note');
@@ -7,7 +7,6 @@ import {
type ToolbarModuleConfig,
} from '@blocksuite/affine-shared/services';
import { getBlockProps } from '@blocksuite/affine-shared/utils';
import { BlockSelection } from '@blocksuite/block-std';
import {
CaptionIcon,
CopyIcon,
@@ -36,10 +35,8 @@ export const builtinToolbarConfig = {
icon: ExpandFullIcon(),
tooltip: 'Open this doc',
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedHtmlBlockComponent
);
component?.open();
const block = ctx.getCurrentBlockByType(EmbedHtmlBlockComponent);
block?.open();
},
},
{
@@ -55,7 +52,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(BlockSelection, EmbedHtmlModel);
const model = ctx.getCurrentModelByType(EmbedHtmlModel);
if (!model) return null;
const actions = this.actions.map<ToolbarAction>(action => ({
@@ -97,10 +94,8 @@ export const builtinToolbarConfig = {
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedHtmlBlockComponent
);
component?.captionEditor?.show();
const block = ctx.getCurrentBlockByType(EmbedHtmlBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
@@ -117,7 +112,7 @@ export const builtinToolbarConfig = {
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedHtmlModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
@@ -132,7 +127,7 @@ export const builtinToolbarConfig = {
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedHtmlModel);
if (!model) return;
const { flavour, parent } = model;
@@ -151,7 +146,7 @@ export const builtinToolbarConfig = {
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedHtmlModel);
if (!model) return;
ctx.store.deleteBlock(model);
@@ -40,10 +40,7 @@ export const builtinToolbarConfig = {
id: 'inline',
label: 'Inline view',
run(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedIframeBlockModel
);
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { title, caption, url } = model.props;
@@ -76,10 +73,7 @@ export const builtinToolbarConfig = {
id: 'card',
label: 'Card view',
run(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedIframeBlockModel
);
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { url, caption } = model.props;
@@ -119,10 +113,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedIframeBlockModel
);
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
@@ -152,9 +143,7 @@ export const builtinToolbarConfig = {
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedIframeBlockComponent
);
const component = ctx.getCurrentBlockByType(EmbedIframeBlockComponent);
component?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
@@ -172,7 +161,7 @@ export const builtinToolbarConfig = {
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentBlockBy(BlockSelection)?.model;
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
@@ -187,7 +176,7 @@ export const builtinToolbarConfig = {
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentBlockBy(BlockSelection)?.model;
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { flavour, parent } = model;
@@ -205,9 +194,7 @@ export const builtinToolbarConfig = {
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedIframeBlockComponent
);
const component = ctx.getCurrentBlockByType(EmbedIframeBlockComponent);
component?.refreshData().catch(console.error);
},
},
@@ -218,7 +205,7 @@ export const builtinToolbarConfig = {
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentBlockBy(BlockSelection)?.model;
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
ctx.store.deleteBlock(model);
@@ -10,7 +10,6 @@ import {
getBlockProps,
referenceToNode,
} from '@blocksuite/affine-shared/utils';
import { BlockSelection } from '@blocksuite/block-std';
import {
CaptionIcon,
CopyIcon,
@@ -37,12 +36,10 @@ export const builtinToolbarConfig = {
{
id: 'a.doc-title',
content(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedLinkedDocBlockComponent
);
if (!component) return null;
const block = ctx.getCurrentBlockByType(EmbedLinkedDocBlockComponent);
if (!block) return null;
const model = component.model;
const model = block.model;
if (!model.props.title) return null;
const originalTitle =
@@ -50,7 +47,7 @@ export const builtinToolbarConfig = {
return html`<affine-linked-doc-title
.title=${originalTitle}
.open=${(event: MouseEvent) => component.open({ event })}
.open=${(event: MouseEvent) => block.open({ event })}
></affine-linked-doc-title>`;
},
},
@@ -61,10 +58,10 @@ export const builtinToolbarConfig = {
id: 'inline',
label: 'Inline view',
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedLinkedDocBlockComponent
);
component?.covertToInline();
block?.covertToInline();
// Clears
ctx.select('note');
@@ -86,14 +83,14 @@ export const builtinToolbarConfig = {
id: 'embed',
label: 'Embed view',
disabled(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedLinkedDocBlockComponent
);
if (!component) return true;
if (!block) return true;
if (component.closest('affine-embed-synced-doc-block')) return true;
if (block.closest('affine-embed-synced-doc-block')) return true;
const model = component.model;
const model = block.model;
// same doc
if (model.props.pageId === ctx.store.id) return true;
@@ -104,10 +101,10 @@ export const builtinToolbarConfig = {
return false;
},
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedLinkedDocBlockComponent
);
component?.convertToEmbed();
block?.convertToEmbed();
ctx.track('SelectedView', {
...trackBaseProps,
@@ -118,10 +115,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedLinkedDocModel
);
const model = ctx.getCurrentModelByType(EmbedLinkedDocModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
@@ -159,10 +153,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedLinkedDocModel
);
const model = ctx.getCurrentModelByType(EmbedLinkedDocModel);
if (!model) return null;
const actions = this.actions.map(action => ({
@@ -203,10 +194,8 @@ export const builtinToolbarConfig = {
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedLinkedDocBlockComponent
);
component?.captionEditor?.show();
const block = ctx.getCurrentBlockByType(EmbedLinkedDocBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
@@ -223,7 +212,7 @@ export const builtinToolbarConfig = {
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedLinkedDocModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
@@ -238,7 +227,7 @@ export const builtinToolbarConfig = {
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedLinkedDocModel);
if (!model) return;
const { flavour, parent } = model;
@@ -257,7 +246,7 @@ export const builtinToolbarConfig = {
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedLinkedDocModel);
if (!model) return;
ctx.store.deleteBlock(model);
@@ -9,7 +9,6 @@ import {
type ToolbarModuleConfig,
} from '@blocksuite/affine-shared/services';
import { getBlockProps } from '@blocksuite/affine-shared/utils';
import { BlockSelection } from '@blocksuite/block-std';
import {
ArrowDownSmallIcon,
CaptionIcon,
@@ -49,10 +48,8 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedSyncedDocBlockComponent
);
if (!component) return null;
const block = ctx.getCurrentBlockByType(EmbedSyncedDocBlockComponent);
if (!block) return null;
const actions = this.actions
.map<ToolbarAction>(action => {
@@ -64,11 +61,11 @@ export const builtinToolbarConfig = {
return {
...action,
disabled: shouldOpenInActiveView
? component.model.props.pageId === ctx.store.id
? block.model.props.pageId === ctx.store.id
: false,
when: allowed,
run: (_ctx: ToolbarContext) =>
component.open({
block.open({
openMode: action.id as OpenDocMode,
}),
};
@@ -115,10 +112,10 @@ export const builtinToolbarConfig = {
id: 'inline',
label: 'Inline view',
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedSyncedDocBlockComponent
);
component?.covertToInline();
block?.covertToInline();
// Clears
ctx.select('note');
@@ -135,10 +132,10 @@ export const builtinToolbarConfig = {
id: 'card',
label: 'Card view',
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedSyncedDocBlockComponent
);
component?.convertToCard();
block?.convertToCard();
ctx.track('SelectedView', {
...trackBaseProps,
@@ -154,10 +151,7 @@ export const builtinToolbarConfig = {
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedSyncedDocModel
);
const model = ctx.getCurrentModelByType(EmbedSyncedDocModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
@@ -188,10 +182,8 @@ export const builtinToolbarConfig = {
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
EmbedSyncedDocBlockComponent
);
component?.captionEditor?.show();
const block = ctx.getCurrentBlockByType(EmbedSyncedDocBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
control: 'add caption',
@@ -207,7 +199,7 @@ export const builtinToolbarConfig = {
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedSyncedDocModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
@@ -222,7 +214,7 @@ export const builtinToolbarConfig = {
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedSyncedDocModel);
if (!model) return;
const { flavour, parent } = model;
@@ -241,7 +233,7 @@ export const builtinToolbarConfig = {
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelBy(BlockSelection);
const model = ctx.getCurrentModelByType(EmbedSyncedDocModel);
if (!model) return;
ctx.store.deleteBlock(model);
@@ -109,7 +109,7 @@ export class EdgelessChangeAttachmentButton extends WithDisposable(LitElement) {
`,
// TODO(@fundon): should remove it when refactoring the element toolbar
attachmentViewDropdownMenu(new ToolbarContext(this.std)),
attachmentViewDropdownMenu.content(new ToolbarContext(this.std)),
html`
<editor-icon-button
@@ -1,9 +1,12 @@
import type { Placement } from '@floating-ui/dom';
import type { ToolbarActions } from './action';
import type { ToolbarContext } from './context';
export type ToolbarModuleConfig = {
actions: ToolbarActions;
when?: ((ctx: ToolbarContext) => boolean) | boolean;
placement?: Extract<Placement, 'top' | 'top-start'>;
};
@@ -4,15 +4,18 @@ import {
type BlockStdScope,
SurfaceSelection,
} from '@blocksuite/block-std';
import { GfxControllerIdentifier } from '@blocksuite/block-std/gfx';
import {
GfxControllerIdentifier,
type GfxElementModelView,
type GfxModel,
} from '@blocksuite/block-std/gfx';
import { nextTick } from '@blocksuite/global/utils';
import type {
BaseSelection,
Block,
BlockModel,
SelectionConstructor,
} from '@blocksuite/store';
import { matchModels } from '../../utils';
import { DocModeProvider } from '../doc-mode-service';
import { TelemetryProvider, type TelemetryService } from '../telemetry-service';
import { ThemeProvider } from '../theme-service';
@@ -106,60 +109,99 @@ abstract class ToolbarContextBase {
return this.toolbarRegistry.flags;
}
get flavour$() {
return this.toolbarRegistry.flavour$;
}
get message$() {
return this.toolbarRegistry.message$;
}
getCurrentElement() {
const selection = this.selection.find(SurfaceSelection);
return selection?.elements.length
? this.gfx.getElementById(selection.elements[0])
: null;
get elementsMap$() {
return this.toolbarRegistry.elementsMap$;
}
getCurrentBlock(): Block | null {
return this.getCurrentBlockBy();
get hasSelectedSurfaceModels() {
return (
this.flavour$.peek().includes('surface') &&
this.elementsMap$.peek().size > 0
);
}
getCurrentBlockComponent(): BlockComponent | null {
getSurfaceElementsByType<M extends abstract new (...args: any) => any>(
klass: M
) {
if (this.hasSelectedSurfaceModels) {
const elements = this.elementsMap$.peek().get(this.flavour$.peek());
if (elements?.length) {
return elements.filter(e => this.matchModel(e, klass));
}
}
return [];
}
getCurrentBlockBy<T extends SelectionConstructor>(type: T) {
const selection = this.selection.find(type);
if (!selection) return null;
if (selection.is(SurfaceSelection)) {
const elementId = selection.elements[0];
const model = this.gfx.getElementById(elementId);
if (!model) return null;
return this.gfx.view.get(model.id) ?? null;
}
const model = this.store.getBlock(selection.blockId);
if (!model) return null;
return this.view.getBlock(model.id);
}
getCurrentBlock() {
return this.hasSelectedSurfaceModels
? this.getCurrentBlockBy(SurfaceSelection)
: this.getCurrentBlockBy(BlockSelection);
}
getCurrentBlockByType<K extends abstract new (...args: any) => any>(
klass: K
) {
const block = this.getCurrentBlock();
return block && this.view.getBlock(block.id);
return this.matchBlock(block, klass) ? block : null;
}
getCurrentModel() {
return this.getCurrentBlock()?.model ?? null;
}
getCurrentBlockBy<T extends SelectionConstructor>(type?: T): Block | null {
const selection = this.selection.find(type ?? BlockSelection);
return (selection && this.store.getBlock(selection.blockId)) ?? null;
matchBlock<K extends abstract new (...args: any) => any>(
component: GfxElementModelView | BlockComponent | null,
klass: K
): component is InstanceType<K> {
return component instanceof klass;
}
getCurrentModelBy<T extends SelectionConstructor>(type: T) {
return this.getCurrentBlockBy<T>(type)?.model ?? null;
const selection = this.selection.find(type);
if (!selection) return null;
if (selection.is(SurfaceSelection)) {
const elementId = selection.elements[0];
return elementId ? this.gfx.getElementById(elementId) : null;
}
return this.store.getBlock(selection.blockId)?.model ?? null;
}
getCurrentModelByType<
T extends SelectionConstructor,
M extends Parameters<typeof matchModels>[1][number],
>(type: T, klass: M) {
const model = this.getCurrentModelBy(type);
return matchModels(model, [klass]) ? model : null;
getCurrentModel() {
return this.hasSelectedSurfaceModels
? this.getCurrentModelBy(SurfaceSelection)
: this.getCurrentModelBy(BlockSelection);
}
getCurrentBlockComponentBy<K extends abstract new (...args: any) => any>(
getCurrentModelByType<M extends abstract new (...args: any) => any>(
klass: M
) {
const model = this.getCurrentModel();
return this.matchModel(model, klass) ? model : null;
}
matchModel<K extends abstract new (...args: any) => any>(
model: GfxModel | BlockModel | null,
klass: K
): InstanceType<K> | null {
const block = this.getCurrentBlockBy();
const component = block && this.view.getBlock(block.id);
return this.blockComponentIs(component, klass) ? component : null;
}
blockComponentIs<K extends abstract new (...args: any) => any>(
component: BlockComponent | null,
...classes: K[]
): component is InstanceType<K> {
return classes.some(k => component instanceof k);
): model is InstanceType<K> {
return model instanceof klass;
}
select(group: string, selections: BaseSelection[] = []) {
@@ -1,4 +1,5 @@
import { type BlockStdScope, StdIdentifier } from '@blocksuite/block-std';
import type { GfxModel } from '@blocksuite/block-std/gfx';
import { type Container, createIdentifier } from '@blocksuite/global/di';
import { Extension, type ExtensionType } from '@blocksuite/store';
import { signal } from '@preact/signals-core';
@@ -22,12 +23,16 @@ export function ToolbarModuleExtension(module: ToolbarModule): ExtensionType {
}
export class ToolbarRegistryExtension extends Extension {
flavour$ = signal<string>('affine:note');
message$ = signal<{
flavour: string;
element: Element;
setFloating: (element?: Element) => void;
} | null>(null);
elementsMap$ = signal<Map<string, GfxModel[]>>(new Map());
flags = new Flags();
constructor(readonly std: BlockStdScope) {
@@ -72,8 +72,6 @@ export class AffineToolbarWidget extends WidgetComponent {
}
`;
flavour$ = signal('affine:note');
placement$ = signal<Placement>('top');
sideOptions$ = signal<Partial<SideObject> | null>(null);
@@ -139,7 +137,6 @@ export class AffineToolbarWidget extends WidgetComponent {
super.connectedCallback();
const {
flavour$,
placement$,
sideOptions$,
referenceElement$,
@@ -149,7 +146,7 @@ export class AffineToolbarWidget extends WidgetComponent {
host,
std,
} = this;
const { flags, message$ } = toolbarRegistry;
const { flags, elementsMap$, flavour$, message$ } = toolbarRegistry;
const context = new ToolbarContext(std);
// TODO(@fundon): fix toolbar position shaking when the wheel scrolls
@@ -303,6 +300,7 @@ export class AffineToolbarWidget extends WidgetComponent {
let elements: GfxModel[] = [];
let hasLocked = false;
let sideOptions = null;
let paired: [string, GfxModel[]][] = [];
if (activated && surface) {
elements = elementIds
@@ -326,7 +324,10 @@ export class AffineToolbarWidget extends WidgetComponent {
e => e.flavour
);
const paired = toPairs(grouped);
paired = toPairs(grouped).map(([flavour, items]) => [
flavour,
items.map(({ model }) => model),
]);
if (paired.length === 1) {
flavour = paired[0][0];
@@ -350,6 +351,8 @@ export class AffineToolbarWidget extends WidgetComponent {
batch(() => {
flags.toggle(Flag.Surface, activated);
elementsMap$.value = new Map(paired);
if (!activated || !flavour) return;
this.setReferenceElementWithElements(gfx, elements);
@@ -42,7 +42,7 @@ export const sideMap = new Map([
['affine:surface:frame', { top: 28 }],
// includes group element
['affine:surface:group', { top: 20 }],
// only one shape element
// has only one shape element
['affine:surface:shape', { top: 26, bottom: -26 }],
]);
@@ -196,6 +196,11 @@ export function renderToolbar(
.flat()
.map(key => toolbarRegistry.modules.get(key))
.filter(module => !!module)
.filter(module =>
typeof module.config.when === 'function'
? module.config.when(context)
: (module.config.when ?? true)
)
.map<ToolbarActions>(module => module.config.actions)
.flat();
@@ -220,7 +225,7 @@ export function renderToolbar(
);
// if (moreMenuItems.length) {
// TODO(@fundon): edgeless case needs to be considered
const key = `${context.getCurrentModel()?.id ?? context.getCurrentElement()?.id}`;
const key = `${context.getCurrentModel()?.id}`;
primaryActionGroup.push({
id: 'more',
@@ -313,33 +313,34 @@ function createToolbarMoreMenuConfigV2(baseUrl?: string) {
actions: [
{
id: 'block-meta-display',
when: cx => {
const featureFlag = cx.std.get(FeatureFlagService);
when: ctx => {
const featureFlag = ctx.std.get(FeatureFlagService);
const isEnabled = featureFlag.getFlag('enable_block_meta');
if (!isEnabled) return false;
// only display when one block is selected by block selection
const { selection, getCurrentBlockBy } = cx;
const hasBlockSelection =
selection.filter(BlockSelection).length === 1;
ctx.selection.filter(BlockSelection).length === 1;
if (!hasBlockSelection) return false;
const block = getCurrentBlockBy.call(cx, BlockSelection);
if (!block) return false;
const model = ctx.getCurrentModelBy(BlockSelection);
if (!model) return false;
const createdAt = 'meta:createdAt';
const createdBy = 'meta:createdBy';
return (
createdAt in block.model.props &&
block.model.props[createdAt] !== undefined &&
createdBy in block.model.props &&
block.model.props[createdBy] !== undefined &&
typeof block.model.props[createdBy] === 'string' &&
typeof block.model.props[createdAt] === 'number'
'props' in model &&
createdAt in model.props &&
model.props[createdAt] !== undefined &&
createdBy in model.props &&
model.props[createdBy] !== undefined &&
typeof model.props[createdBy] === 'string' &&
typeof model.props[createdAt] === 'number'
);
},
content: cx => {
const model = cx.getCurrentModelBy(BlockSelection);
content: ctx => {
const model = ctx.getCurrentModelBy(BlockSelection);
if (!model) return null;
if (!('props' in model)) return null;
const createdAt = 'meta:createdAt';
if (!(createdAt in model.props)) return null;
const createdBy = 'meta:createdBy';
@@ -347,7 +348,7 @@ function createToolbarMoreMenuConfigV2(baseUrl?: string) {
const createdByUserId = model.props[createdBy] as string;
const createdAtTimestamp = model.props[createdAt] as number;
const date = new Date(createdAtTimestamp);
const userProvider = cx.std.get(UserProvider);
const userProvider = ctx.std.get(UserProvider);
userProvider.revalidateUserInfo(createdByUserId);
const userSignal = userProvider.userInfo$(createdByUserId);
const isLoadingSignal = userProvider.isLoading$(createdByUserId);
@@ -415,7 +416,7 @@ function createExternalLinkableToolbarConfig(
tooltip: 'Copy link',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentBlockComponentBy(klass)?.model;
const model = ctx.getCurrentBlockByType(klass)?.model;
if (!model) return;
const { url } = model.props;
@@ -440,12 +441,12 @@ function createExternalLinkableToolbarConfig(
tooltip: 'Edit',
icon: EditIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(klass);
if (!component) return;
const block = ctx.getCurrentBlockByType(klass);
if (!block) return;
ctx.hide();
const model = component.model;
const model = block.model;
const abortController = new AbortController();
abortController.signal.onabort = () => ctx.show();
@@ -457,7 +458,7 @@ function createExternalLinkableToolbarConfig(
undefined,
(_std, _component, props) => {
ctx.store.updateBlock(model, props);
component.requestUpdate();
block.requestUpdate();
},
abortController
);
@@ -514,8 +515,8 @@ function createOpenDocActionGroup(
id: 'A.open-doc',
actions: openDocActions,
content(ctx) {
const component = ctx.getCurrentBlockComponentBy(klass);
if (!component) return null;
const block = ctx.getCurrentBlockByType(klass);
if (!block) return null;
const actions = this.actions
.map<ToolbarAction>(action => {
@@ -528,15 +529,14 @@ function createOpenDocActionGroup(
return {
...action,
disabled: shouldOpenInActiveView
? component.model.props.pageId === ctx.store.id
? block.model.props.pageId === ctx.store.id
: false,
when:
allowed &&
(shouldOpenInCenterPeek ? isPeekable(component) : true),
allowed && (shouldOpenInCenterPeek ? isPeekable(block) : true),
run: shouldOpenInCenterPeek
? (_ctx: ToolbarContext) => peek(component)
? (_ctx: ToolbarContext) => peek(block)
: (_ctx: ToolbarContext) =>
component.open({
block.open({
openMode: action.id as OpenDocMode,
}),
};
@@ -589,10 +589,7 @@ const embedLinkedDocToolbarConfig = {
tooltip: 'Copy link',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedLinkedDocModel
);
const model = ctx.getCurrentModelByType(EmbedLinkedDocModel);
if (!model) return;
const { pageId, params } = model.props;
@@ -621,21 +618,21 @@ const embedLinkedDocToolbarConfig = {
tooltip: 'Edit',
icon: EditIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedLinkedDocBlockComponent
);
if (!component) return;
if (!block) return;
ctx.hide();
const model = component.model;
const model = block.model;
const doc = ctx.workspace.getDoc(model.props.pageId);
const abortController = new AbortController();
abortController.signal.onabort = () => ctx.show();
toggleEmbedCardEditModal(
ctx.host,
component.model,
model,
'card',
doc
? {
@@ -644,12 +641,12 @@ const embedLinkedDocToolbarConfig = {
}
: undefined,
std => {
component.refreshData();
block.refreshData();
notifyLinkedDocClearedAliases(std);
},
(_std, _component, props) => {
ctx.store.updateBlock(model, props);
component.requestUpdate();
block.requestUpdate();
},
abortController
);
@@ -681,10 +678,7 @@ const embedSyncedDocToolbarConfig = {
tooltip: 'Copy link',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(
BlockSelection,
EmbedSyncedDocModel
);
const model = ctx.getCurrentModelByType(EmbedSyncedDocModel);
if (!model) return;
const { pageId, params } = model.props;
@@ -713,14 +707,14 @@ const embedSyncedDocToolbarConfig = {
tooltip: 'Edit',
icon: EditIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const block = ctx.getCurrentBlockByType(
EmbedSyncedDocBlockComponent
);
if (!component) return;
if (!block) return;
ctx.hide();
const model = component.model;
const model = block.model;
const doc = ctx.workspace.getDoc(model.props.pageId);
const abortController = new AbortController();
abortController.signal.onabort = () => ctx.show();
@@ -732,7 +726,7 @@ const embedSyncedDocToolbarConfig = {
doc ? { title: doc.meta?.title } : undefined,
undefined,
(std, _component, props) => {
component.convertToCard(props);
block.convertToCard(props);
notifyLinkedDocSwitchedToCard(std);
},
@@ -761,8 +755,7 @@ const inlineReferenceToolbarConfig = {
id: 'A.open-doc',
actions: openDocActions,
content(ctx) {
const registry = ctx.toolbarRegistry;
const target = registry.message$.peek()?.element;
const target = ctx.message$.peek()?.element;
if (!(target instanceof AffineReference)) return null;
const actions = this.actions
@@ -917,7 +910,7 @@ const embedIframeToolbarConfig = {
tooltip: 'Copy link',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentBlockComponentBy(
const model = ctx.getCurrentBlockByType(
EmbedIframeBlockComponent
)?.model;
if (!model) return;
@@ -928,9 +921,6 @@ const embedIframeToolbarConfig = {
toast(ctx.host, 'Copied link to clipboard');
ctx.track('CopiedLink', {
segment: 'doc',
page: 'doc editor',
module: 'toolbar',
category: matchModels(model, [BookmarkBlockModel])
? 'bookmark'
: 'link',
@@ -944,7 +934,7 @@ const embedIframeToolbarConfig = {
tooltip: 'Edit',
icon: EditIcon(),
run(ctx) {
const component = ctx.getCurrentBlockComponentBy(
const component = ctx.getCurrentBlockByType(
EmbedIframeBlockComponent
);
if (!component) return;
@@ -969,9 +959,6 @@ const embedIframeToolbarConfig = {
);
ctx.track('OpenedAliasPopup', {
segment: 'doc',
page: 'doc editor',
module: 'toolbar',
category: matchModels(model, [BookmarkBlockModel])
? 'bookmark'
: 'link',