snapshot of https://github.com/toeverything/AFFiNE.git (canary, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Build & Test / Analyze (javascript, affine) (push) Failing after 4s
Build & Test / Analyze (typescript, affine) (push) Failing after 3s
Build & Test / Rust test filter (push) Failing after 4s
Build & Test / Check yarn binary (push) Failing after 3s
Build & Test / E2E BlockSuite Test (3) (push) Failing after 3s
Build & Test / Analyze (javascript, blocksuite) (push) Failing after 3s
Build & Test / Analyze (typescript, blocksuite) (push) Failing after 3s
Build & Test / Mobile native build filter (push) Failing after 3s
Build & Test / E2E BlockSuite Test (1) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (2) (push) Failing after 4s
Build & Test / E2E Mobile Test (1) (push) Failing after 3s
Build & Test / Unit Test (1) (push) Has been skipped
Build & Test / Unit Test (2) (push) Has been skipped
Build & Test / Unit Test (3) (push) Has been skipped
Build & Test / Unit Test (4) (push) Has been skipped
Build & Test / Unit Test (5) (push) Has been skipped
Build & Test / Native Unit Test (push) Has been skipped
Build & Test / E2E BlockSuite Test (4) (push) Failing after 3s
Build & Test / E2E BlockSuite Test (5) (push) Failing after 3s
Build & Test / E2E BlockSuite Cross Browser Test (push) Failing after 3s
Build & Test / E2E Mobile Test (2) (push) Failing after 3s
Build & Test / Build AFFiNE native (x86_64-unknown-linux-gnu) (push) Failing after 3s
Build & Test / Build Server native (push) Failing after 3s
Build & Test / Check Git Status (push) Has been skipped
Build & Test / Server Test (0, 4) (push) Has been skipped
Build & Test / Server Test (1, 4) (push) Has been skipped
Build & Test / Server Test (2, 4) (push) Has been skipped
Build & Test / Server Test (3, 4) (push) Has been skipped
Build & Test / Server Test with Elasticsearch (push) Has been skipped
Build & Test / Build @affine/electron renderer (push) Failing after 3s
Build & Test / Copilot test filter (push) Failing after 4s
Build & Test / Lint Rust (push) Has been skipped
Build & Test / Server Test with Embedded Search (push) Has been skipped
Build & Test / Server Test with Manticore Search (push) Has been skipped
Build & Test / Server E2E Test (push) Has been skipped
Build & Test / Cloud Desktop E2E Test (push) Has been skipped
Build & Test / Cloud E2E Test 1/2 (push) Has been skipped
Build & Test / Cloud E2E Test 2/2 (push) Has been skipped
Build & Test / Build Android app (push) Has been skipped
Build & Test / Test Android app (push) Has been skipped
Build & Test / Run native tests (push) Has been skipped
Build & Test / Server Copilot Api Test (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (1, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (2, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (3, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (4, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (5, 5) (push) Has been skipped
Release / Canary Gate (push) Has been skipped
Build & Test / Build AFFiNE native (aarch64-apple-darwin) (push) Has been cancelled
Build & Test / Lint (push) Has been cancelled
Build & Test / Typecheck (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-apple-darwin) (push) Has been cancelled
Build & Test / Desktop Test (ubuntu-latest, linux, x64, x86_64-unknown-linux-gnu, true) (push) Has been cancelled
Build & Test / Desktop Test (windows-latest, windows, x64, x86_64-pc-windows-msvc, true) (push) Has been cancelled
Build & Test / E2E Test (1) (push) Has been cancelled
Build & Test / E2E Test (2) (push) Has been cancelled
Build & Test / E2E Test (3) (push) Has been cancelled
Build & Test / E2E Test (4) (push) Has been cancelled
Build & Test / E2E Test (5) (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, arm64, aarch64-apple-darwin, true) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, x64, x86_64-apple-darwin, false) (push) Has been cancelled
Build & Test / 3, 2, 1 Launch (push) Has been cancelled
Build & Test / Build iOS app (push) Has been cancelled
Copilot Test Automatically / Setup Test (push) Failing after 1s
Release / Prepare (push) Failing after 2s
Release / Release Cloud (push) Has been skipped
Release / Release Desktop (push) Has been skipped
Release / Release Docker Image (push) Has been skipped
Release / Release Mobile (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-16 04:01:20 +05:00
commit 702cc698a7
9990 changed files with 1073618 additions and 0 deletions

View File

@@ -0,0 +1,41 @@
{
"name": "@blocksuite/affine-block-attachment",
"description": "Attachment block for BlockSuite.",
"type": "module",
"scripts": {
"build": "yarn run -T tsc"
},
"sideEffects": false,
"keywords": [],
"author": "toeverything",
"license": "MIT",
"dependencies": {
"@blocksuite/affine-block-surface": "workspace:*",
"@blocksuite/affine-components": "workspace:*",
"@blocksuite/affine-ext-loader": "workspace:*",
"@blocksuite/affine-model": "workspace:*",
"@blocksuite/affine-shared": "workspace:*",
"@blocksuite/affine-widget-slash-menu": "workspace:*",
"@blocksuite/global": "workspace:*",
"@blocksuite/icons": "^2.2.17",
"@blocksuite/std": "workspace:*",
"@blocksuite/store": "workspace:*",
"@floating-ui/dom": "^1.6.13",
"@preact/signals-core": "^1.8.0",
"file-type": "^21.0.0",
"lit": "^3.2.0",
"rxjs": "^7.8.2"
},
"exports": {
".": "./src/index.ts",
"./store": "./src/store.ts",
"./view": "./src/view.ts"
},
"files": [
"src",
"dist",
"!src/__tests__",
"!dist/__tests__"
],
"version": "0.27.5"
}

View File

@@ -0,0 +1,9 @@
import type { ExtensionType } from '@blocksuite/store';
import { AttachmentBlockMarkdownAdapterExtension } from './markdown.js';
import { AttachmentBlockNotionHtmlAdapterExtension } from './notion-html.js';
export const AttachmentBlockAdapterExtensions: ExtensionType[] = [
AttachmentBlockNotionHtmlAdapterExtension,
AttachmentBlockMarkdownAdapterExtension,
];

View File

@@ -0,0 +1,2 @@
export * from './markdown.js';
export * from './notion-html.js';

View File

@@ -0,0 +1,83 @@
import {
AttachmentBlockSchema,
FootNoteReferenceParamsSchema,
} from '@blocksuite/affine-model';
import {
BlockMarkdownAdapterExtension,
type BlockMarkdownAdapterMatcher,
createAttachmentBlockSnapshot,
FOOTNOTE_DEFINITION_PREFIX,
getFootnoteDefinitionText,
isFootnoteDefinitionNode,
type MarkdownAST,
} from '@blocksuite/affine-shared/adapters';
import { nanoid } from '@blocksuite/store';
const isAttachmentFootnoteDefinitionNode = (node: MarkdownAST) => {
if (!isFootnoteDefinitionNode(node)) return false;
const footnoteDefinition = getFootnoteDefinitionText(node);
try {
const footnoteDefinitionJson = FootNoteReferenceParamsSchema.parse(
JSON.parse(footnoteDefinition)
);
return (
footnoteDefinitionJson.type === 'attachment' &&
!!footnoteDefinitionJson.blobId
);
} catch {
return false;
}
};
export const attachmentBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher =
{
flavour: AttachmentBlockSchema.model.flavour,
toMatch: o => isAttachmentFootnoteDefinitionNode(o.node),
fromMatch: o => o.node.flavour === AttachmentBlockSchema.model.flavour,
toBlockSnapshot: {
enter: (o, context) => {
if (!isFootnoteDefinitionNode(o.node)) {
return;
}
const { walkerContext, configs } = context;
const footnoteIdentifier = o.node.identifier;
const footnoteDefinitionKey = `${FOOTNOTE_DEFINITION_PREFIX}${footnoteIdentifier}`;
const footnoteDefinition = configs.get(footnoteDefinitionKey);
if (!footnoteDefinition) {
return;
}
try {
const footnoteDefinitionJson = FootNoteReferenceParamsSchema.parse(
JSON.parse(footnoteDefinition)
);
const { blobId, fileName } = footnoteDefinitionJson;
if (!blobId || !fileName) {
return;
}
walkerContext
.openNode(
createAttachmentBlockSnapshot({
id: nanoid(),
props: {
name: fileName,
sourceId: blobId,
footnoteIdentifier,
style: 'citation',
},
}),
'children'
)
.closeNode();
walkerContext.skipAllChildren();
} catch (err) {
console.warn('Failed to parse attachment footnote definition:', err);
return;
}
},
},
fromBlockSnapshot: {},
};
export const AttachmentBlockMarkdownAdapterExtension =
BlockMarkdownAdapterExtension(attachmentBlockMarkdownAdapterMatcher);

View File

@@ -0,0 +1,115 @@
import { AttachmentBlockSchema } from '@blocksuite/affine-model';
import {
BlockNotionHtmlAdapterExtension,
type BlockNotionHtmlAdapterMatcher,
FetchUtils,
HastUtils,
} from '@blocksuite/affine-shared/adapters';
import { getFilenameFromContentDisposition } from '@blocksuite/affine-shared/utils';
import { sha } from '@blocksuite/global/utils';
import { getAssetName, nanoid } from '@blocksuite/store';
export const attachmentBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatcher =
{
flavour: AttachmentBlockSchema.model.flavour,
toMatch: o => {
return (
HastUtils.isElement(o.node) &&
o.node.tagName === 'figure' &&
!!HastUtils.querySelector(o.node, '.source')
);
},
fromMatch: () => false,
toBlockSnapshot: {
enter: async (o, context) => {
if (!HastUtils.isElement(o.node)) {
return;
}
const { assets, walkerContext } = context;
if (!assets) {
return;
}
const embededFigureWrapper = HastUtils.querySelector(o.node, '.source');
let embededURL = '';
if (embededFigureWrapper) {
const embedA = HastUtils.querySelector(embededFigureWrapper, 'a');
embededURL =
typeof embedA?.properties.href === 'string'
? embedA.properties.href
: '';
}
if (embededURL) {
let blobId = '';
let name = '';
let type = '';
let size = 0;
if (!FetchUtils.fetchable(embededURL)) {
const embededURLSplit = embededURL.split('/');
while (embededURLSplit.length > 0) {
const key = assets
.getPathBlobIdMap()
.get(decodeURIComponent(embededURLSplit.join('/')));
if (key) {
blobId = key;
break;
}
embededURLSplit.shift();
}
const value = assets.getAssets().get(blobId);
if (value) {
name = getAssetName(assets.getAssets(), blobId);
size = value.size;
type = value.type;
}
} else {
const res = await fetch(embededURL).catch(error => {
console.warn('Error fetching embed:', error);
return null;
});
if (!res) {
return;
}
const resCloned = res.clone();
name =
getFilenameFromContentDisposition(
res.headers.get('Content-Disposition') ?? ''
) ??
(embededURL.split('/').at(-1) ?? 'file') +
'.' +
(res.headers.get('Content-Type')?.split('/').at(-1) ?? 'blob');
const file = new File([await res.blob()], name, {
type: res.headers.get('Content-Type') ?? '',
});
size = file.size;
type = file.type;
blobId = await sha(await resCloned.arrayBuffer());
assets?.getAssets().set(blobId, file);
await assets?.writeToBlob(blobId);
}
walkerContext
.openNode(
{
type: 'block',
id: nanoid(),
flavour: AttachmentBlockSchema.model.flavour,
props: {
name,
size,
type,
sourceId: blobId,
},
children: [],
},
'children'
)
.closeNode();
walkerContext.skipAllChildren();
}
},
},
fromBlockSnapshot: {},
};
export const AttachmentBlockNotionHtmlAdapterExtension =
BlockNotionHtmlAdapterExtension(attachmentBlockNotionHtmlAdapterMatcher);

View File

@@ -0,0 +1,533 @@
import {
CaptionedBlockComponent,
SelectedStyle,
} from '@blocksuite/affine-components/caption';
import {
getAttachmentFileIcon,
LoadingIcon,
} from '@blocksuite/affine-components/icons';
import { Peekable } from '@blocksuite/affine-components/peek';
import {
type ResolvedStateInfo,
ResourceController,
} from '@blocksuite/affine-components/resource';
import { toast } from '@blocksuite/affine-components/toast';
import {
type AttachmentBlockModel,
AttachmentBlockStyles,
} from '@blocksuite/affine-model';
import {
BlockElementCommentManager,
CitationProvider,
DocModeProvider,
FileSizeLimitProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import {
formatSize,
openSingleFileWith,
} from '@blocksuite/affine-shared/utils';
import {
AttachmentIcon,
ResetIcon,
UpgradeIcon,
WarningIcon,
} from '@blocksuite/icons/lit';
import { BlockSelection } from '@blocksuite/std';
import { nanoid, Slice } from '@blocksuite/store';
import { batch, computed, signal } from '@preact/signals-core';
import { html, type TemplateResult } from 'lit';
import { choose } from 'lit/directives/choose.js';
import { type ClassInfo, classMap } from 'lit/directives/class-map.js';
import { guard } from 'lit/directives/guard.js';
import { styleMap } from 'lit/directives/style-map.js';
import { when } from 'lit/directives/when.js';
import { filter } from 'rxjs/operators';
import { AttachmentEmbedProvider } from './embed';
import { styles } from './styles';
import { downloadAttachmentBlob, getFileType, refreshData } from './utils';
type AttachmentResolvedStateInfo = ResolvedStateInfo & {
kind?: TemplateResult;
};
@Peekable({
enableOn: ({ model }: AttachmentBlockComponent) => {
return model.props.type.endsWith('pdf');
},
})
export class AttachmentBlockComponent extends CaptionedBlockComponent<AttachmentBlockModel> {
static override styles = styles;
blockDraggable = true;
resourceController = new ResourceController(
computed(() => this.model.props.sourceId$.value)
);
get blobUrl() {
return this.resourceController.blobUrl$.value;
}
get filetype() {
const name = this.model.props.name$.value;
return name.split('.').pop() ?? '';
}
protected containerStyleMap = styleMap({
position: 'relative',
width: '100%',
margin: '18px 0px',
});
private get _maxFileSize() {
return this.std.get(FileSizeLimitProvider).maxFileSize;
}
get citationService() {
return this.std.get(CitationProvider);
}
get isCitation() {
return this.citationService.isCitationModel(this.model);
}
get isCommentHighlighted() {
return (
this.std
.getOptional(BlockElementCommentManager)
?.isBlockCommentHighlighted(this.model) ?? false
);
}
convertTo = () => {
return this.std
.get(AttachmentEmbedProvider)
.convertTo(this.model, this._maxFileSize);
};
copy = () => {
const slice = Slice.fromModels(this.store, [this.model]);
this.std.clipboard.copySlice(slice).catch(console.error);
toast(this.host, 'Copied to clipboard');
};
download = () => {
downloadAttachmentBlob(this);
};
embedded = () => {
return (
Boolean(this.blobUrl) &&
this.std
.get(AttachmentEmbedProvider)
.embedded(this.model, this._maxFileSize)
);
};
open = () => {
const blobUrl = this.blobUrl;
if (!blobUrl) return;
window.open(blobUrl, '_blank');
};
// Refreshes data.
refreshData = () => {
refreshData(this).catch(console.error);
};
private readonly _refreshKey$ = signal<string | null>(null);
// Refreshes the embed component.
reload = () => {
batch(() => {
if (this.model.props.embed$.value) {
this._refreshKey$.value = nanoid();
return;
}
this.refreshData();
});
};
// Replaces the current attachment.
replace = async () => {
const state = this.resourceController.state$.peek();
if (state.uploading) return;
const file = await openSingleFileWith();
if (!file) return;
const sourceId = await this.std.store.blobSync.set(file);
const type = await getFileType(file);
const { name, size } = file;
let embed = this.model.props.embed$.value ?? false;
this.std.store.captureSync();
this.std.store.transact(() => {
this.std.store.updateBlock(this.blockId, {
name,
size,
type,
sourceId,
embed: false,
});
const provider = this.std.get(AttachmentEmbedProvider);
embed &&= provider.embedded(this.model);
if (embed) {
provider.convertTo(this.model);
}
// Reloads
this.reload();
});
};
private _selectBlock() {
const selectionManager = this.host.selection;
const blockSelection = selectionManager.create(BlockSelection, {
blockId: this.blockId,
});
selectionManager.setGroup('note', [blockSelection]);
}
private readonly _trackCitationDeleteEvent = () => {
// Check citation delete event
this._disposables.add(
this.std.store.slots.blockUpdated
.pipe(
filter(payload => {
if (!payload.isLocal) return false;
const { flavour, id, type } = payload;
if (
type !== 'delete' ||
flavour !== this.model.flavour ||
id !== this.model.id
)
return false;
const { model } = payload;
if (!this.citationService.isCitationModel(model)) return false;
return true;
})
)
.subscribe(() => {
this.citationService.trackEvent('Delete');
})
);
};
override connectedCallback() {
super.connectedCallback();
this.contentEditable = 'false';
this.resourceController.setEngine(this.std.store.blobSync);
this.disposables.add(this.resourceController.subscribe());
this.disposables.add(this.resourceController);
this.disposables.add(
this.model.props.sourceId$.subscribe(() => {
this.refreshData();
})
);
if (!this.model.props.style && !this.store.readonly) {
this.store.withoutTransact(() => {
this.store.updateBlock(this.model, {
style: AttachmentBlockStyles[1],
});
});
}
this._trackCitationDeleteEvent();
}
override firstUpdated() {
// lazy bindings
this.disposables.addFromEvent(this, 'click', this.onClick);
}
protected onClick(event: MouseEvent) {
// the peek view need handle shift + click
if (event.defaultPrevented) return;
event.stopPropagation();
if (!this.selected$.peek()) {
this._selectBlock();
}
}
protected renderUpgradeButton = () => {
if (this.std.store.readonly) return null;
const onOverFileSize = this.std.get(FileSizeLimitProvider).onOverFileSize;
return when(
onOverFileSize,
() => html`
<button
class="affine-attachment-content-button"
@click=${(event: MouseEvent) => {
event.stopPropagation();
onOverFileSize?.();
{
const mode =
this.std.get(DocModeProvider).getEditorMode() ?? 'page';
const segment = mode === 'page' ? 'doc' : 'whiteboard';
this.std
.getOptional(TelemetryProvider)
?.track('AttachmentUpgradedEvent', {
segment,
page: `${segment} editor`,
module: 'attachment',
control: 'upgrade',
category: 'card',
type: this.model.props.name.split('.').pop() ?? '',
});
}
}}
>
${UpgradeIcon()} Upgrade
</button>
`
);
};
protected renderNormalButton = (needUpload: boolean) => {
const label = needUpload ? 'retry' : 'reload';
const run = async () => {
if (needUpload) {
await this.resourceController.upload();
return;
}
this.refreshData();
};
return html`
<button
class="affine-attachment-content-button"
@click=${(event: MouseEvent) => {
event.stopPropagation();
run().catch(console.error);
{
const mode =
this.std.get(DocModeProvider).getEditorMode() ?? 'page';
const segment = mode === 'page' ? 'doc' : 'whiteboard';
this.std
.getOptional(TelemetryProvider)
?.track('AttachmentReloadedEvent', {
segment,
page: `${segment} editor`,
module: 'attachment',
control: label,
category: 'card',
type: this.filetype,
});
}
}}
>
${ResetIcon()} ${label}
</button>
`;
};
protected renderWithHorizontal(
classInfo: ClassInfo,
{
icon,
title,
description,
kind,
state,
needUpload,
}: AttachmentResolvedStateInfo
) {
return html`
<div class=${classMap(classInfo)}>
<div class="affine-attachment-content">
<div class="affine-attachment-content-title">
<div class="affine-attachment-content-title-icon">${icon}</div>
<div class="affine-attachment-content-title-text truncate">
${title}
</div>
</div>
<div class="affine-attachment-content-description">
<div class="affine-attachment-content-info truncate">
${description}
</div>
${choose(state, [
['error', () => this.renderNormalButton(needUpload)],
['error:oversize', this.renderUpgradeButton],
])}
</div>
</div>
<div class="affine-attachment-banner">${kind}</div>
</div>
`;
}
protected renderWithVertical(
classInfo: ClassInfo,
{
icon,
title,
description,
kind,
state,
needUpload,
}: AttachmentResolvedStateInfo
) {
return html`
<div class=${classMap(classInfo)}>
<div class="affine-attachment-content">
<div class="affine-attachment-content-title">
<div class="affine-attachment-content-title-icon">${icon}</div>
<div class="affine-attachment-content-title-text truncate">
${title}
</div>
</div>
<div class="affine-attachment-content-info truncate">
${description}
</div>
</div>
<div class="affine-attachment-banner">
${kind}
${choose(state, [
['error', () => this.renderNormalButton(needUpload)],
['error:oversize', this.renderUpgradeButton],
])}
</div>
</div>
`;
}
protected resolvedState$ = computed<AttachmentResolvedStateInfo>(() => {
const size = this.model.props.size;
const name = this.model.props.name$.value;
const kind = getAttachmentFileIcon(this.filetype);
const resolvedState = this.resourceController.resolveStateWith({
loadingIcon: LoadingIcon(),
errorIcon: WarningIcon(),
icon: AttachmentIcon(),
title: name,
description: formatSize(size),
});
return { ...resolvedState, kind };
});
protected renderCardView = () => {
const resolvedState = this.resolvedState$.value;
const cardStyle = this.model.props.style$.value ?? AttachmentBlockStyles[1];
const classInfo = {
'affine-attachment-card': true,
[cardStyle]: true,
loading: resolvedState.loading,
error: resolvedState.error,
};
return when(
cardStyle === 'cubeThick',
() => this.renderWithVertical(classInfo, resolvedState),
() => this.renderWithHorizontal(classInfo, resolvedState)
);
};
protected renderEmbedView = () => {
const { model, blobUrl } = this;
if (!model.props.embed$.value || !blobUrl) return null;
const { std, _maxFileSize } = this;
const provider = std.get(AttachmentEmbedProvider);
const render = provider.getRender(model, _maxFileSize);
if (!render) return null;
const enabled = provider.shouldShowStatus(model);
return html`
<div class="affine-attachment-embed-container">
${guard([this._refreshKey$.value], () => render(model, blobUrl))}
</div>
${when(enabled, () => {
const resolvedState = this.resolvedState$.value;
if (resolvedState.state !== 'error') return null;
// It should be an error messge.
const message = resolvedState.description;
if (!message) return null;
const needUpload = resolvedState.needUpload;
const action = () =>
needUpload ? this.resourceController.upload() : this.reload();
return html`
<affine-resource-status
class="affine-attachment-embed-status"
.message=${message}
.needUpload=${needUpload}
.action=${action}
></affine-resource-status>
`;
})}
`;
};
private readonly _renderCitation = () => {
const { name, footnoteIdentifier } = this.model.props;
const icon = getAttachmentFileIcon(this.filetype);
return html`<affine-citation-card
.icon=${icon}
.citationTitle=${name}
.citationIdentifier=${footnoteIdentifier}
.active=${this.selected$.value}
></affine-citation-card>`;
};
override renderBlock() {
return html`
<div
class=${classMap({
'affine-attachment-container': true,
focused: this.selected$.value,
'comment-highlighted': this.isCommentHighlighted,
})}
style=${this.containerStyleMap}
>
${when(
this.isCitation,
() => this._renderCitation(),
() => this.renderEmbedView() ?? this.renderCardView()
)}
</div>
`;
}
override accessor selectedStyle = SelectedStyle.Border;
override accessor useCaptionEditor = true;
}
declare global {
interface HTMLElementTagNameMap {
'affine-attachment': AttachmentBlockComponent;
}
}

View File

@@ -0,0 +1,72 @@
import { EdgelessLegacySlotIdentifier } from '@blocksuite/affine-block-surface';
import {
AttachmentBlockSchema,
AttachmentBlockStyles,
} from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import { toGfxBlockComponent } from '@blocksuite/std';
import { GfxViewInteractionExtension } from '@blocksuite/std/gfx';
import { styleMap } from 'lit/directives/style-map.js';
import { AttachmentBlockComponent } from './attachment-block.js';
export class AttachmentEdgelessBlockComponent extends toGfxBlockComponent(
AttachmentBlockComponent
) {
override blockDraggable = false;
get slots() {
return this.std.get(EdgelessLegacySlotIdentifier);
}
override onClick(_: MouseEvent) {
return;
}
override renderGfxBlock() {
const { style$ } = this.model.props;
const cardStyle = style$.value ?? AttachmentBlockStyles[1];
const width = EMBED_CARD_WIDTH[cardStyle];
const height = EMBED_CARD_HEIGHT[cardStyle];
const bound = this.model.elementBound;
const scaleX = bound.w / width;
const scaleY = bound.h / height;
this.containerStyleMap = styleMap({
width: `${width}px`,
height: `${height}px`,
transform: `scale(${scaleX}, ${scaleY})`,
transformOrigin: '0 0',
overflow: 'hidden',
});
return this.renderPageContent();
}
}
declare global {
interface HTMLElementTagNameMap {
'affine-edgeless-attachment': AttachmentEdgelessBlockComponent;
}
}
export const AttachmentBlockInteraction = GfxViewInteractionExtension(
AttachmentBlockSchema.model.flavour,
{
resizeConstraint: {
lockRatio: true,
},
handleRotate: () => {
return {
beforeRotate: context => {
context.set({
rotatable: false,
});
},
};
},
}
);

View File

@@ -0,0 +1,51 @@
import { SurfaceBlockModel } from '@blocksuite/affine-block-surface';
import { FileDropConfigExtension } from '@blocksuite/affine-components/drop-indicator';
import { AttachmentBlockSchema } from '@blocksuite/affine-model';
import { TelemetryProvider } from '@blocksuite/affine-shared/services';
import {
isInsideEdgelessEditor,
matchModels,
} from '@blocksuite/affine-shared/utils';
import { GfxControllerIdentifier } from '@blocksuite/std/gfx';
import { addAttachments, addSiblingAttachmentBlocks } from './utils.js';
export const AttachmentDropOption = FileDropConfigExtension({
flavour: AttachmentBlockSchema.model.flavour,
onDrop: ({ files, targetModel, placement, point, std }) => {
// generic attachment block for all files except images
const attachmentFiles = files.filter(
file => !file.type.startsWith('image/')
);
if (!attachmentFiles.length) return false;
if (targetModel && !matchModels(targetModel, [SurfaceBlockModel])) {
addSiblingAttachmentBlocks(
std,
attachmentFiles,
targetModel,
placement
).catch(console.error);
return true;
}
if (isInsideEdgelessEditor(std.host)) {
const gfx = std.get(GfxControllerIdentifier);
point = gfx.viewport.toViewCoordFromClientCoord(point);
addAttachments(std, attachmentFiles, point).catch(console.error);
std.getOptional(TelemetryProvider)?.track('CanvasElementAdded', {
control: 'canvas:drop',
page: 'whiteboard editor',
module: 'toolbar',
segment: 'toolbar',
type: 'attachment',
});
return true;
}
return false;
},
});

View File

@@ -0,0 +1,95 @@
import { ConfirmIcon } from '@blocksuite/affine-components/icons';
import { toast } from '@blocksuite/affine-components/toast';
import type { AttachmentBlockModel } from '@blocksuite/affine-model';
import { CitationProvider } from '@blocksuite/affine-shared/services';
import type { EditorHost } from '@blocksuite/std';
import { html } from 'lit';
import { createRef, ref } from 'lit/directives/ref.js';
import { renameStyles } from './styles';
export const RenameModal = ({
editorHost,
model,
abortController,
}: {
editorHost: EditorHost;
model: AttachmentBlockModel;
abortController: AbortController;
}) => {
const inputRef = createRef<HTMLInputElement>();
// Fix auto focus
setTimeout(() => inputRef.value?.focus());
const originalName = model.props.name;
const nameWithoutExtension = originalName.slice(
0,
originalName.lastIndexOf('.')
);
const originalExtension = originalName.slice(originalName.lastIndexOf('.'));
const includeExtension =
originalExtension.includes('.') &&
originalExtension.length <= 7 &&
// including the dot
originalName.length > originalExtension.length;
let fileName = includeExtension ? nameWithoutExtension : originalName;
const extension = includeExtension ? originalExtension : '';
const citationService = editorHost.std.get(CitationProvider);
const abort = () => abortController.abort();
const onConfirm = () => {
const newFileName = fileName + extension;
if (!newFileName) {
toast(editorHost, 'File name cannot be empty');
return;
}
model.store.updateBlock(model, {
name: newFileName,
});
if (citationService.isCitationModel(model)) {
citationService.trackEvent('Edit');
}
abort();
};
const onInput = (e: InputEvent) => {
fileName = (e.target as HTMLInputElement).value;
};
const onKeydown = (e: KeyboardEvent) => {
e.stopPropagation();
if (e.key === 'Escape' && !e.isComposing) {
abort();
return;
}
if (e.key === 'Enter' && !e.isComposing) {
onConfirm();
return;
}
};
return html`
<style>
${renameStyles}
</style>
<div class="affine-attachment-rename-overlay-mask" @click="${abort}"></div>
<div class="affine-attachment-rename-container">
<div class="affine-attachment-rename-input-wrapper">
<input
${ref(inputRef)}
type="text"
.value=${fileName}
@input=${onInput}
@keydown=${onKeydown}
/>
<span class="affine-attachment-rename-extension">${extension}</span>
</div>
<editor-icon-button
class="affine-confirm-button"
.iconSize=${'24px'}
@click=${onConfirm}
>
${ConfirmIcon}
</editor-icon-button>
</div>
`;
};

View File

@@ -0,0 +1,64 @@
import { fontXSStyle, panelBaseStyle } from '@blocksuite/affine-shared/styles';
import { css } from 'lit';
export const renameStyles = css`
${panelBaseStyle('.affine-attachment-rename-container')}
.affine-attachment-rename-container {
position: relative;
display: flex;
align-items: center;
width: 320px;
gap: 12px;
padding: 12px;
z-index: var(--affine-z-index-popover);
}
.affine-attachment-rename-input-wrapper {
display: flex;
min-width: 280px;
height: 30px;
box-sizing: border-box;
padding: 4px 10px;
background: var(--affine-white-10);
border-radius: 4px;
border: 1px solid var(--affine-border-color);
}
.affine-attachment-rename-input-wrapper:focus-within {
border-color: var(--affine-blue-700);
box-shadow: var(--affine-active-shadow);
}
.affine-attachment-rename-input-wrapper input {
flex: 1;
border: none;
outline: none;
background: transparent;
color: var(--affine-text-primary-color);
}
${fontXSStyle('.affine-attachment-rename-input-wrapper input')}
.affine-attachment-rename-input-wrapper input::placeholder {
color: var(--affine-placeholder-color);
}
.affine-attachment-rename-extension {
font-size: var(--affine-font-xs);
color: var(--affine-text-secondary-color);
}
.affine-attachment-rename-overlay-mask {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: var(--affine-z-index-popover);
}
`;
export const styles = css`
:host {
z-index: 1;
}
`;

View File

@@ -0,0 +1,58 @@
import { openSingleFileWith } from '@blocksuite/affine-shared/utils';
import { type SlashMenuConfig } from '@blocksuite/affine-widget-slash-menu';
import { ExportToPdfIcon, FileIcon } from '@blocksuite/icons/lit';
import { addSiblingAttachmentBlocks } from '../utils';
import { AttachmentTooltip, PDFTooltip } from './tooltips';
export const attachmentSlashMenuConfig: SlashMenuConfig = {
items: [
{
name: 'Attachment',
description: 'Attach a file to document.',
icon: FileIcon(),
tooltip: {
figure: AttachmentTooltip,
caption: 'Attachment',
},
searchAlias: ['file'],
group: '4_Content & Media@3',
when: ({ model }) =>
model.store.schema.flavourSchemaMap.has('affine:attachment'),
action: ({ std, model }) => {
(async () => {
const file = await openSingleFileWith();
if (!file) return;
await addSiblingAttachmentBlocks(std, [file], model);
if (model.text?.length === 0) {
std.store.deleteBlock(model);
}
})().catch(console.error);
},
},
{
name: 'PDF',
description: 'Upload a PDF to document.',
icon: ExportToPdfIcon(),
tooltip: {
figure: PDFTooltip,
caption: 'PDF',
},
group: '4_Content & Media@4',
when: ({ model }) =>
model.store.schema.flavourSchemaMap.has('affine:attachment'),
action: ({ std, model }) => {
(async () => {
const file = await openSingleFileWith();
if (!file) return;
await addSiblingAttachmentBlocks(std, [file], model);
if (model.text?.length === 0) {
std.store.deleteBlock(model);
}
})().catch(console.error);
},
},
],
};

View File

@@ -0,0 +1,406 @@
import { createLitPortal } from '@blocksuite/affine-components/portal';
import {
AttachmentBlockModel,
defaultAttachmentProps,
type EmbedCardStyle,
} from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import {
ActionPlacement,
type ToolbarAction,
type ToolbarActionGroup,
type ToolbarModuleConfig,
ToolbarModuleExtension,
} from '@blocksuite/affine-shared/services';
import { getBlockProps } from '@blocksuite/affine-shared/utils';
import { Bound } from '@blocksuite/global/gfx';
import {
CaptionIcon,
CopyIcon,
DeleteIcon,
DownloadIcon,
DuplicateIcon,
EditIcon,
ReplaceIcon,
ResetIcon,
} from '@blocksuite/icons/lit';
import { BlockFlavourIdentifier } from '@blocksuite/std';
import type { ExtensionType } from '@blocksuite/store';
import { flip, offset } from '@floating-ui/dom';
import { computed } from '@preact/signals-core';
import { html } from 'lit';
import { keyed } from 'lit/directives/keyed.js';
import { AttachmentBlockComponent } from '../attachment-block';
import { RenameModal } from '../components/rename-model';
import { AttachmentEmbedProvider } from '../embed';
const trackBaseProps = {
category: 'attachment',
type: 'card view',
};
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 bounds = Bound.deserialize(model.xywh);
bounds.w = width;
bounds.h = height;
ctx.store.updateBlock(model, {
style,
embed: false,
xywh: bounds.serialize(),
});
},
},
{
id: 'embed',
label: 'Embed view',
disabled: ctx => {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
return block ? !block.embedded() : true;
},
run(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return;
const provider = ctx.std.get(AttachmentEmbedProvider);
// TODO(@fundon): should auto focus image block.
if (
provider.shouldBeConverted(model) &&
!ctx.hasSelectedSurfaceModels
) {
// Clears
ctx.reset();
ctx.select('note');
}
provider.convertTo(model);
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'embed view',
});
},
},
],
content(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
if (!block) return null;
const model = block.model;
const embedProvider = ctx.std.get(AttachmentEmbedProvider);
const actions = computed(() => {
const [cardAction, embedAction] = this.actions.map(action => ({
...action,
}));
const ok = block.resourceController.resolvedState$.value.state === 'none';
const sourceId = Boolean(model.props.sourceId$.value);
const embed = model.props.embed$.value ?? false;
// 1. Check whether `sourceId` exists.
// 2. Check if `embedded` is allowed.
// 3. Check `blobState$`
const allowed = ok && sourceId && embedProvider.embedded(model) && !embed;
cardAction.disabled = !embed;
embedAction.disabled = !allowed;
return [cardAction, embedAction];
});
const viewType$ = computed(() => {
const [cardAction, embedAction] = actions.value;
const embed = model.props.embed$.value ?? false;
return embed ? embedAction.label : cardAction.label;
});
const onToggle = (e: CustomEvent<boolean>) => {
e.stopPropagation();
const opened = e.detail;
if (!opened) return;
ctx.track('OpenedViewSelector', {
...trackBaseProps,
control: 'switch view',
});
};
return html`<affine-view-dropdown-menu
@toggle=${onToggle}
.actions=${actions.value}
.context=${ctx}
.viewTypeSignal=${viewType$}
></affine-view-dropdown-menu>`;
},
} as const satisfies ToolbarActionGroup<ToolbarAction>;
const replaceAction = {
id: 'c.replace',
tooltip: 'Replace attachment',
icon: ReplaceIcon(),
disabled(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
if (!block) return true;
const { downloading = false, uploading = false } =
block.resourceController.state$.value;
return downloading || uploading;
},
run(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.replace().catch(console.error);
},
} as const satisfies ToolbarAction;
const downloadAction = {
id: 'd.download',
tooltip: 'Download',
icon: DownloadIcon(),
run(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.download();
},
when(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return false;
// Current citation attachment block does not support download
return model.props.style !== 'citation' && !model.props.footnoteIdentifier;
},
} as const satisfies ToolbarAction;
const captionAction = {
id: 'e.caption',
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
control: 'add caption',
});
},
} as const satisfies ToolbarAction;
const builtinToolbarConfig = {
actions: [
{
id: 'a.rename',
content(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
if (!block) return null;
const abortController = new AbortController();
abortController.signal.onabort = () => ctx.show();
return html`
<editor-icon-button
aria-label="Rename"
.tooltip="${'Rename'}"
@click=${() => {
ctx.hide();
createLitPortal({
template: RenameModal({
model: block.model,
editorHost: ctx.host,
abortController,
}),
computePosition: {
referenceElement: block,
placement: 'top-start',
middleware: [flip(), offset(4)],
},
abortController,
});
}}
>
${EditIcon()}
</editor-icon-button>
`;
},
},
attachmentViewDropdownMenu,
replaceAction,
downloadAction,
captionAction,
{
placement: ActionPlacement.More,
id: 'a.clipboard',
actions: [
{
id: 'copy',
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
// TODO(@fundon): unify `clone` method
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.copy();
},
},
{
id: 'duplicate',
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return;
// TODO(@fundon): unify `duplicate` method
ctx.store.addSiblingBlocks(model, [
{
flavour: model.flavour,
...getBlockProps(model),
},
]);
},
},
],
},
{
placement: ActionPlacement.More,
id: 'b.refresh',
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const block = ctx.getCurrentBlockByType(AttachmentBlockComponent);
block?.reload();
ctx.track('AttachmentReloadedEvent', {
...trackBaseProps,
control: 'reload',
type: block?.model.props.name.split('.').pop() ?? '',
});
},
},
{
placement: ActionPlacement.More,
id: 'c.delete',
label: 'Delete',
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModel();
if (!model) return;
ctx.store.deleteBlock(model.id);
// Clears
ctx.select('note');
ctx.reset();
},
},
],
} as const satisfies ToolbarModuleConfig;
const builtinSurfaceToolbarConfig = {
actions: [
attachmentViewDropdownMenu,
{
id: 'c.style',
actions: [
{
id: 'horizontalThin',
label: 'Horizontal style',
},
{
id: 'cubeThick',
label: 'Vertical style',
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(AttachmentBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({
...action,
run: ({ store }) => {
const style = action.id as EmbedCardStyle;
const bounds = Bound.deserialize(model.xywh);
bounds.w = EMBED_CARD_WIDTH[style];
bounds.h = EMBED_CARD_HEIGHT[style];
const xywh = bounds.serialize();
store.updateBlock(model, { style, xywh });
ctx.track('SelectedCardStyle', {
...trackBaseProps,
page: 'whiteboard editor',
control: 'select card style',
type: style,
});
},
})) satisfies ToolbarAction[];
const style$ = model.props.style$;
const onToggle = (e: CustomEvent<boolean>) => {
e.stopPropagation();
const opened = e.detail;
if (!opened) return;
ctx.track('OpenedCardStyleSelector', {
...trackBaseProps,
page: 'whiteboard editor',
control: 'switch card style',
});
};
return html`${keyed(
model,
html`<affine-card-style-dropdown-menu
@toggle=${onToggle}
.actions=${actions}
.context=${ctx}
.styleSignal=${style$}
></affine-card-style-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
{
...replaceAction,
id: 'd.replace',
},
{
...downloadAction,
id: 'e.download',
},
{
...captionAction,
id: 'f.caption',
},
],
when: ctx => ctx.getSurfaceModelsByType(AttachmentBlockModel).length === 1,
} as const satisfies ToolbarModuleConfig;
export const createBuiltinToolbarConfigExtension = (
flavour: string
): ExtensionType[] => {
const name = flavour.split(':').pop();
return [
ToolbarModuleExtension({
id: BlockFlavourIdentifier(flavour),
config: builtinToolbarConfig,
}),
ToolbarModuleExtension({
id: BlockFlavourIdentifier(`affine:surface:${name}`),
config: builtinSurfaceToolbarConfig,
}),
];
};

View File

@@ -0,0 +1,77 @@
import { html } from 'lit';
// prettier-ignore
export const AttachmentTooltip = html`<svg width="170" height="68" viewBox="0 0 170 68" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="170" height="68" rx="2" fill="white"/>
<mask id="mask0_16460_1013" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="170" height="68">
<rect width="170" height="68" rx="2" fill="white"/>
</mask>
<g mask="url(#mask0_16460_1013)">
<rect x="8.5" y="28.5" width="169" height="67" rx="3.5" fill="white" stroke="#E3E2E4"/>
<mask id="mask1_16460_1013" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="28" width="170" height="68">
<rect x="8" y="28" width="170" height="68" rx="4" fill="white"/>
</mask>
<g mask="url(#mask1_16460_1013)">
<g filter="url(#filter0_d_16460_1013)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M149.686 42.516C149.796 41.7313 149.251 41.0057 148.47 40.8954L130.084 38.2995C128.913 38.1341 127.829 38.9542 127.665 40.1313L122.298 78.494C122.133 79.671 122.95 80.7593 124.121 80.9248L157.357 85.6174C158.529 85.7828 159.612 84.9627 159.777 83.7856L163.057 60.3418C163.166 59.5571 162.622 58.8315 161.841 58.7212L151.941 57.3234C149.598 56.9926 147.965 54.816 148.294 52.4619L149.686 42.516ZM133.567 59.8003C133.649 59.2118 134.191 58.8017 134.776 58.8844L152.455 61.3805C153.041 61.4632 153.449 62.0074 153.367 62.5959C153.284 63.1844 152.743 63.5945 152.157 63.5118L134.478 61.0157C133.892 60.933 133.484 60.3888 133.567 59.8003ZM133.932 64.923C133.346 64.8403 132.804 65.2504 132.722 65.8389C132.64 66.4274 133.048 66.9716 133.634 67.0543L151.312 69.5504C151.898 69.6331 152.44 69.223 152.522 68.6345C152.604 68.046 152.196 67.5018 151.61 67.4191L133.932 64.923Z" fill="white"/>
<path d="M153.295 43.1135C152.819 42.4792 151.818 42.7394 151.708 43.5259L150.416 52.7614C150.251 53.9385 151.067 55.0268 152.239 55.1922L161.432 56.4901C162.215 56.6007 162.74 55.7051 162.264 55.0708L153.295 43.1135Z" fill="white"/>
</g>
<g clip-path="url(#clip0_16460_1013)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.1088 36.804L17.0887 39.8241C16.1371 40.7509 16.1371 42.2492 17.0886 43.1759C18.0457 44.108 19.6014 44.108 20.5584 43.1759L23.5034 40.3144C23.6519 40.1701 23.8893 40.1735 24.0337 40.322C24.178 40.4706 24.1746 40.708 24.026 40.8523L21.0817 43.7132C21.0817 43.7133 21.0818 43.7131 21.0817 43.7132C19.8334 44.9288 17.8136 44.9289 16.5653 43.7132C15.3122 42.4926 15.3116 40.5099 16.5635 39.2886L19.5838 36.2683C20.4645 35.4105 21.8884 35.4106 22.7691 36.2683C23.6548 37.1309 23.6554 38.5332 22.771 39.3965L19.7507 42.4169C19.2376 42.9167 18.4095 42.9166 17.8964 42.4168C17.3777 41.9116 17.3777 41.0884 17.8964 40.5832L20.9956 37.5647C21.1439 37.4202 21.3813 37.4233 21.5259 37.5717C21.6704 37.7201 21.6672 37.9575 21.5189 38.102L18.4197 41.1205C18.2033 41.3312 18.2033 41.6688 18.4197 41.8796C18.6411 42.0952 19.0038 42.0957 19.2259 41.881L22.2458 38.861C22.8298 38.2923 22.8298 37.3744 22.2459 36.8056C21.6569 36.232 20.6984 36.2315 20.1088 36.804Z" fill="#77757D"/>
</g>
<text fill="#121212" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" font-weight="600" letter-spacing="0em"><tspan x="30" y="43.6364">Rickroll.mp3</tspan></text>
</g>
<text fill="#8E8D91" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" letter-spacing="0px"><tspan x="10" y="18.6364">Attach a file.</tspan></text>
</g>
<defs>
<filter id="filter0_d_16460_1013" x="118.277" y="34.2783" width="48.7936" height="55.3602" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset/>
<feGaussianBlur stdDeviation="2"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0.258824 0 0 0 0 0.254902 0 0 0 0 0.286275 0 0 0 0.18 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_16460_1013"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_16460_1013" result="shape"/>
</filter>
<clipPath id="clip0_16460_1013">
<rect width="12" height="12" fill="white" transform="translate(14 34)"/>
</clipPath>
</defs>
</svg>
`;
// prettier-ignore
export const PDFTooltip = html`<svg width="170" height="68" viewBox="0 0 170 68" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="170" height="68" rx="2" fill="white"/>
<mask id="mask0_689_35293" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="170" height="68">
<rect width="170" height="68" rx="2" fill="white"/>
</mask>
<g mask="url(#mask0_689_35293)">
<rect x="8.5" y="28.5" width="169" height="67" rx="3.5" fill="white" stroke="#E3E2E4"/>
<mask id="mask1_689_35293" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="28" width="170" height="68">
<rect x="8" y="28" width="170" height="68" rx="4" fill="white"/>
</mask>
<g mask="url(#mask1_689_35293)">
<g filter="url(#filter0_d_689_35293)">
<path fill-rule="evenodd" clip-rule="evenodd" d="M149.686 42.516C149.796 41.7313 149.251 41.0057 148.47 40.8954L130.084 38.2995C128.913 38.1341 127.829 38.9542 127.665 40.1313L122.298 78.494C122.133 79.671 122.95 80.7593 124.121 80.9248L157.357 85.6174C158.529 85.7828 159.612 84.9627 159.777 83.7856L163.057 60.3418C163.166 59.5571 162.622 58.8315 161.841 58.7212L151.941 57.3234C149.598 56.9926 147.965 54.816 148.294 52.4619L149.686 42.516ZM133.567 59.8003C133.649 59.2118 134.191 58.8017 134.776 58.8844L152.455 61.3805C153.041 61.4632 153.449 62.0074 153.367 62.5959C153.284 63.1844 152.743 63.5945 152.157 63.5118L134.478 61.0157C133.892 60.933 133.484 60.3888 133.567 59.8003ZM133.932 64.923C133.346 64.8403 132.804 65.2504 132.722 65.8389C132.64 66.4274 133.048 66.9716 133.634 67.0543L151.312 69.5504C151.898 69.6331 152.44 69.223 152.522 68.6345C152.604 68.046 152.196 67.5018 151.61 67.4191L133.932 64.923Z" fill="white"/>
<path d="M153.295 43.1135C152.819 42.4792 151.818 42.7394 151.708 43.5259L150.416 52.7614C150.251 53.9385 151.067 55.0268 152.239 55.1922L161.432 56.4901C162.215 56.6007 162.74 55.7051 162.264 55.0708L153.295 43.1135Z" fill="white"/>
</g>
<path fill-rule="evenodd" clip-rule="evenodd" d="M18 35.125C17.2406 35.125 16.625 35.7406 16.625 36.5V38C16.625 38.2071 16.7929 38.375 17 38.375C17.2071 38.375 17.375 38.2071 17.375 38V36.5C17.375 36.1548 17.6548 35.875 18 35.875H20.5H21.7609C21.9538 35.875 22.1359 35.964 22.2543 36.1163L23.4933 37.7094C23.5787 37.8191 23.625 37.9541 23.625 38.0931V40V43C23.625 43.3452 23.3452 43.625 23 43.625H18C17.6548 43.625 17.375 43.3452 17.375 43V42.25C17.375 42.0429 17.2071 41.875 17 41.875C16.7929 41.875 16.625 42.0429 16.625 42.25V43C16.625 43.7594 17.2406 44.375 18 44.375H23C23.7594 44.375 24.375 43.7594 24.375 43V40V38.0931C24.375 37.7873 24.2731 37.4903 24.0854 37.2489L22.8463 35.6558C22.5858 35.3209 22.1852 35.125 21.7609 35.125H20.5H18ZM15.3965 40.9614C15.3965 41.1694 15.5093 41.2866 15.707 41.2866C15.9048 41.2866 16.0176 41.1694 16.0176 40.9614V40.6729H16.3193C16.813 40.6729 17.1484 40.3726 17.1484 39.9067C17.1484 39.4365 16.832 39.1362 16.3618 39.1362H15.707C15.5093 39.1362 15.3965 39.2534 15.3965 39.4614V40.9614ZM16.1919 40.2144H16.0176V39.6035H16.1963C16.3984 39.6035 16.5215 39.7075 16.5215 39.9082C16.5215 40.1104 16.3984 40.2144 16.1919 40.2144ZM17.3682 40.9248C17.3682 41.1328 17.481 41.25 17.6787 41.25H18.272C18.9121 41.25 19.29 40.8545 19.29 40.1777C19.29 39.501 18.9136 39.1362 18.272 39.1362H17.6787C17.481 39.1362 17.3682 39.2534 17.3682 39.4614V40.9248ZM18.1841 40.7563H17.9893V39.6299H18.1841C18.4814 39.6299 18.6572 39.8218 18.6572 40.1777C18.6572 40.5674 18.4946 40.7563 18.1841 40.7563ZM19.5332 40.9614C19.5332 41.1694 19.646 41.2866 19.8438 41.2866C20.0415 41.2866 20.1543 41.1694 20.1543 40.9614V40.5015H20.7109C20.8691 40.5015 20.9658 40.4165 20.9658 40.2686C20.9658 40.1206 20.8662 40.0356 20.7109 40.0356H20.1543V39.6313H20.7739C20.938 39.6313 21.0479 39.542 21.0479 39.3838C21.0479 39.2256 20.9409 39.1362 20.7739 39.1362H19.8438C19.646 39.1362 19.5332 39.2534 19.5332 39.4614V40.9614Z" fill="#7A7A7A"/>
<text fill="#121212" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" font-weight="600" letter-spacing="0em"><tspan x="30" y="43.6364">Rickroll.pdf</tspan></text>
</g>
<text fill="#8E8D91" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" letter-spacing="0px"><tspan x="10" y="18.6364">Upload a pdf to document.</tspan></text>
</g>
<defs>
<filter id="filter0_d_689_35293" x="118.277" y="34.2783" width="48.7936" height="55.3604" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
<feOffset/>
<feGaussianBlur stdDeviation="2"/>
<feComposite in2="hardAlpha" operator="out"/>
<feColorMatrix type="matrix" values="0 0 0 0 0.258824 0 0 0 0 0.254902 0 0 0 0 0.286275 0 0 0 0.18 0"/>
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_689_35293"/>
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_689_35293" result="shape"/>
</filter>
</defs>
</svg>
`;

View File

@@ -0,0 +1,34 @@
import { EdgelessClipboardConfig } from '@blocksuite/affine-block-surface';
import { type BlockSnapshot } from '@blocksuite/store';
export class EdgelessClipboardAttachmentConfig extends EdgelessClipboardConfig {
static override readonly key = 'affine:attachment';
override async createBlock(
attachment: BlockSnapshot
): Promise<string | null> {
if (!this.surface) return null;
const { xywh, rotate, sourceId, name, size, type, embed, style } =
attachment.props;
if (!(await this.std.workspace.blobSync.get(sourceId as string))) {
return null;
}
const attachmentId = this.crud.addBlock(
'affine:attachment',
{
xywh,
rotate,
sourceId,
name,
size,
type,
embed,
style,
},
this.surface.model.id
);
return attachmentId;
}
}

View File

@@ -0,0 +1,10 @@
import { AttachmentBlockComponent } from './attachment-block';
import { AttachmentEdgelessBlockComponent } from './attachment-edgeless-block';
export function effects() {
customElements.define(
'affine-edgeless-attachment',
AttachmentEdgelessBlockComponent
);
customElements.define('affine-attachment', AttachmentBlockComponent);
}

View File

@@ -0,0 +1,305 @@
import {
type AttachmentBlockModel,
type ImageBlockProps,
MAX_IMAGE_WIDTH,
} from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import { FileSizeLimitProvider } from '@blocksuite/affine-shared/services';
import {
readImageSize,
transformModel,
withTempBlobData,
} from '@blocksuite/affine-shared/utils';
import type { Container } from '@blocksuite/global/di';
import { createIdentifier } from '@blocksuite/global/di';
import { Bound } from '@blocksuite/global/gfx';
import { type BlockStdScope, StdIdentifier } from '@blocksuite/std';
import type { ExtensionType } from '@blocksuite/store';
import { Extension } from '@blocksuite/store';
import type { TemplateResult } from 'lit';
import { html } from 'lit';
import { styleMap } from 'lit/directives/style-map.js';
import { getAttachmentBlob } from './utils';
export type AttachmentEmbedConfig = {
name: string;
/**
* Check if the attachment can be turned into embed view.
*/
check: (model: AttachmentBlockModel, maxFileSize: number) => boolean;
/**
* The action will be executed when the 「Turn into embed view」 button is clicked.
*/
action?: (
model: AttachmentBlockModel,
std: BlockStdScope
) => Promise<void> | void;
/**
* Renders the embed view.
*/
render?: (
model: AttachmentBlockModel,
blobUrl: string
) => TemplateResult | null;
/**
* Should show status when turned on.
*/
shouldShowStatus?: boolean;
/**
* Should block type conversion be required.
*/
shouldBeConverted?: boolean;
};
// Single embed config.
export const AttachmentEmbedConfigIdentifier =
createIdentifier<AttachmentEmbedConfig>(
'AffineAttachmentEmbedConfigIdentifier'
);
export function AttachmentEmbedConfigExtension(
configs: AttachmentEmbedConfig[] = embedConfig
): ExtensionType {
return {
setup: di => {
configs.forEach(option => {
di.addImpl(AttachmentEmbedConfigIdentifier(option.name), () => option);
});
},
};
}
// A embed config map.
export const AttachmentEmbedConfigMapIdentifier = createIdentifier<
Map<string, AttachmentEmbedConfig>
>('AffineAttachmentEmbedConfigMapIdentifier');
export const AttachmentEmbedProvider = createIdentifier<AttachmentEmbedService>(
'AffineAttachmentEmbedProvider'
);
export class AttachmentEmbedService extends Extension {
private get _maxFileSize() {
return this.std.get(FileSizeLimitProvider).maxFileSize;
}
get keys() {
return this.configs.keys();
}
get values() {
return this.configs.values();
}
get configs(): Map<string, AttachmentEmbedConfig> {
return this.std.get(AttachmentEmbedConfigMapIdentifier);
}
constructor(private readonly std: BlockStdScope) {
super();
}
static override setup(di: Container) {
di.addImpl(AttachmentEmbedConfigMapIdentifier, provider =>
provider.getAll(AttachmentEmbedConfigIdentifier)
);
di.addImpl(AttachmentEmbedProvider, this, [StdIdentifier]);
}
// Converts to embed view.
convertTo(model: AttachmentBlockModel, maxFileSize = this._maxFileSize) {
const config = this.values.find(config => config.check(model, maxFileSize));
if (config?.action) {
config.action(model, this.std)?.catch(console.error);
return;
}
model.store.updateBlock(model, { embed: true });
}
embedded(model: AttachmentBlockModel, maxFileSize = this._maxFileSize) {
return this.values.some(config => config.check(model, maxFileSize));
}
getRender(model: AttachmentBlockModel, maxFileSize = this._maxFileSize) {
return (
this.values.find(config => config.check(model, maxFileSize))?.render ??
null
);
}
shouldShowStatus(
model: AttachmentBlockModel,
maxFileSize = this._maxFileSize
) {
return (
this.values.find(config => config.check(model, maxFileSize))
?.shouldShowStatus ?? false
);
}
shouldBeConverted(
model: AttachmentBlockModel,
maxFileSize = this._maxFileSize
) {
return (
this.values.find(config => config.check(model, maxFileSize))
?.shouldBeConverted ?? false
);
}
}
const embedConfig: AttachmentEmbedConfig[] = [
{
name: 'image',
shouldBeConverted: true,
check: model =>
model.store.schema.flavourSchemaMap.has('affine:image') &&
model.props.type.startsWith('image/'),
async action(model, std) {
const component = std.view.getBlock(model.id);
if (!component) return;
await turnIntoImageBlock(model);
},
},
{
name: 'pdf',
shouldShowStatus: true,
check: (model, maxFileSize) =>
model.props.type === 'application/pdf' && model.props.size <= maxFileSize,
action: model => {
const bound = Bound.deserialize(model.props.xywh);
bound.w = EMBED_CARD_WIDTH.pdf;
bound.h = EMBED_CARD_HEIGHT.pdf;
model.store.updateBlock(model, {
embed: true,
style: 'pdf',
xywh: bound.serialize(),
});
},
render: (_, blobUrl) => {
// More options: https://tinytip.co/tips/html-pdf-params/
// https://chromium.googlesource.com/chromium/src/+/refs/tags/121.0.6153.1/chrome/browser/resources/pdf/open_pdf_params_parser.ts
const parameters = '#toolbar=0';
return html`
<iframe
style=${styleMap({
width: '100%',
minHeight: '480px',
colorScheme: 'auto',
})}
src=${blobUrl + parameters}
loading="lazy"
scrolling="no"
frameborder="no"
allowTransparency
allowfullscreen
type="application/pdf"
credentialless
></iframe>
<div class="affine-attachment-embed-event-mask"></div>
`;
},
},
{
name: 'video',
shouldShowStatus: true,
check: (model, maxFileSize) =>
model.props.type.startsWith('video/') && model.props.size <= maxFileSize,
action: model => {
const bound = Bound.deserialize(model.props.xywh);
bound.w = EMBED_CARD_WIDTH.video;
bound.h = EMBED_CARD_HEIGHT.video;
model.store.updateBlock(model, {
embed: true,
style: 'video',
xywh: bound.serialize(),
});
},
render: (_, blobUrl) =>
html`<video
style=${styleMap({
display: 'flex',
objectFit: 'cover',
backgroundSize: 'cover',
width: '100%',
height: '100%',
})}
src=${blobUrl}
width="100%"
height="100%"
controls
></video>`,
},
{
name: 'audio',
check: (model, maxFileSize) =>
model.props.type.startsWith('audio/') && model.props.size <= maxFileSize,
render: (_, blobUrl) =>
html`<audio
style=${styleMap({ margin: '4px' })}
src=${blobUrl}
controls
></audio>`,
},
];
/**
* Turn the attachment block into an image block.
*/
async function turnIntoImageBlock(model: AttachmentBlockModel) {
if (!model.store.schema.flavourSchemaMap.has('affine:image')) {
console.error('The image flavour is not supported!');
return;
}
const sourceId = model.props.sourceId;
if (!sourceId) return;
const { saveAttachmentData, getImageData } = withTempBlobData();
saveAttachmentData(sourceId, { name: model.props.name });
let imageSize = model.props.sourceId
? getImageData(model.props.sourceId)
: undefined;
const bounds = model.xywh
? Bound.fromXYWH(model.deserializedXYWH)
: undefined;
if (bounds) {
if (!imageSize?.width || !imageSize?.height) {
const blob = await getAttachmentBlob(model);
if (blob) {
imageSize = await readImageSize(blob);
}
}
if (imageSize?.width && imageSize?.height) {
const p = imageSize.height / imageSize.width;
imageSize.width = Math.min(imageSize.width, MAX_IMAGE_WIDTH);
imageSize.height = imageSize.width * p;
bounds.w = imageSize.width;
bounds.h = imageSize.height;
}
}
const others = bounds ? { xywh: bounds.serialize() } : undefined;
const imageProp: Partial<ImageBlockProps> = {
sourceId,
caption: model.props.caption,
size: model.props.size,
...imageSize,
...others,
};
transformModel(model, 'affine:image', imageProp);
}

View File

@@ -0,0 +1,11 @@
export * from './adapters';
export * from './attachment-block';
export * from './attachment-service';
export { attachmentViewDropdownMenu } from './configs/toolbar';
export * from './edgeless-clipboard-config';
export {
type AttachmentEmbedConfig,
AttachmentEmbedConfigIdentifier,
AttachmentEmbedProvider,
} from './embed';
export { addAttachments, addSiblingAttachmentBlocks } from './utils';

View File

@@ -0,0 +1,17 @@
import {
type StoreExtensionContext,
StoreExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { AttachmentBlockSchemaExtension } from '@blocksuite/affine-model';
import { AttachmentBlockAdapterExtensions } from './adapters/extension';
export class AttachmentStoreExtension extends StoreExtensionProvider {
override name = 'affine-attachment-block';
override setup(context: StoreExtensionContext) {
super.setup(context);
context.register(AttachmentBlockSchemaExtension);
context.register(AttachmentBlockAdapterExtensions);
}
}

View File

@@ -0,0 +1,160 @@
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { css } from 'lit';
export const styles = css`
.affine-attachment-container {
border-radius: 8px;
box-sizing: border-box;
user-select: none;
overflow: hidden;
border: 1px solid ${unsafeCSSVarV2('layer/background/tertiary')};
background: ${unsafeCSSVarV2('layer/background/primary')};
&.focused {
border-color: ${unsafeCSSVarV2('layer/insideBorder/primaryBorder')};
}
}
.affine-attachment-container.comment-highlighted {
outline: 2px solid ${unsafeCSSVarV2('block/comment/highlightUnderline')};
}
.affine-attachment-card {
display: flex;
gap: 12px;
padding: 12px;
}
.affine-attachment-content {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 12px;
flex: 1 0 0;
min-width: 0;
}
.truncate {
align-self: stretch;
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
}
.affine-attachment-content-title {
display: flex;
flex-direction: row;
gap: 8px;
align-items: center;
align-self: stretch;
}
.affine-attachment-content-title-icon {
display: flex;
align-items: center;
justify-content: center;
color: var(--affine-text-primary-color);
font-size: 16px;
}
.affine-attachment-content-title-text {
color: var(--affine-text-primary-color);
font-family: var(--affine-font-family);
font-size: var(--affine-font-sm);
font-style: normal;
font-weight: 600;
line-height: 22px;
}
.affine-attachment-content-description {
display: flex;
align-items: center;
align-self: stretch;
gap: 8px;
}
.affine-attachment-content-info {
color: var(--affine-text-secondary-color);
font-family: var(--affine-font-family);
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 400;
line-height: 20px;
}
.affine-attachment-content-button {
display: flex;
height: 20px;
align-items: center;
align-self: stretch;
gap: 4px;
white-space: nowrap;
padding: 0 4px;
color: ${unsafeCSSVarV2('button/primary')};
font-family: var(--affine-font-family);
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 500;
text-transform: capitalize;
line-height: 20px;
svg {
font-size: 16px;
}
}
.affine-attachment-banner {
display: flex;
align-items: center;
justify-content: center;
}
.affine-attachment-card.loading {
.affine-attachment-content-title-text {
color: ${unsafeCSSVarV2('text/placeholder')};
}
}
.affine-attachment-card.error {
.affine-attachment-content-title-icon {
color: ${unsafeCSSVarV2('status/error')};
}
}
.affine-attachment-card.loading,
.affine-attachment-card.error {
background: ${unsafeCSSVarV2('layer/background/secondary')};
}
.affine-attachment-card.cubeThick {
flex-direction: column-reverse;
.affine-attachment-content {
width: 100%;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
}
.affine-attachment-banner {
justify-content: space-between;
}
}
.affine-attachment-embed-container {
position: relative;
width: 100%;
height: 100%;
}
.affine-attachment-embed-status {
position: absolute;
left: 14px;
bottom: 64px;
}
.affine-attachment-embed-event-mask {
position: absolute;
inset: 0;
}
`;

View File

@@ -0,0 +1,216 @@
import { toast } from '@blocksuite/affine-components/toast';
import {
type AttachmentBlockModel,
type AttachmentBlockProps,
AttachmentBlockSchema,
} from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import {
type AttachmentUploadedEvent,
FileSizeLimitProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { formatSize } from '@blocksuite/affine-shared/utils';
import { Bound, type IVec, Vec } from '@blocksuite/global/gfx';
import type { BlockStdScope } from '@blocksuite/std';
import { GfxControllerIdentifier } from '@blocksuite/std/gfx';
import type { BlockModel } from '@blocksuite/store';
import type { AttachmentBlockComponent } from './attachment-block';
export async function getAttachmentBlob(model: AttachmentBlockModel) {
const { sourceId$, type$ } = model.props;
const sourceId = sourceId$.peek();
const type = type$.peek();
if (!sourceId) return null;
const doc = model.store;
const blob = await doc.blobSync.get(sourceId);
if (!blob) return null;
return new Blob([blob], { type });
}
/**
* Since the size of the attachment may be very large,
* the download process may take a long time!
*/
export function downloadAttachmentBlob(block: AttachmentBlockComponent) {
const { host, model, blobUrl, resourceController } = block;
if (resourceController.state$.peek().downloading) {
toast(host, 'Download in progress...');
return;
}
const name = model.props.name;
const shortName = name.length < 20 ? name : name.slice(0, 20) + '...';
if (!blobUrl) {
toast(host, `Failed to download ${shortName}!`);
return;
}
resourceController.updateState({ downloading: true });
toast(host, `Downloading ${shortName}`);
const tmpLink = document.createElement('a');
const event = new MouseEvent('click');
tmpLink.download = name;
tmpLink.href = blobUrl;
tmpLink.dispatchEvent(event);
tmpLink.remove();
resourceController.updateState({ downloading: false });
}
export async function refreshData(block: AttachmentBlockComponent) {
const model = block.model;
const type = model.props.type$.peek();
await block.resourceController.refreshUrlWith(type);
}
export async function getFileType(file: File) {
if (file.type) return file.type;
// If the file type is not available, try to get it from the buffer.
const buffer = await file.arrayBuffer();
const FileType = await import('file-type');
const fileType = await FileType.fileTypeFromBuffer(buffer);
return fileType?.mime ?? '';
}
function hasExceeded(
std: BlockStdScope,
files: File[],
maxFileSize = std.get(FileSizeLimitProvider).maxFileSize
) {
const exceeded = files.some(file => file.size > maxFileSize);
if (exceeded) {
const size = formatSize(maxFileSize);
toast(std.host, `You can only upload files less than ${size}`);
}
return exceeded;
}
async function buildPropsWith(
std: BlockStdScope,
file: File,
embed?: boolean,
mode: 'doc' | 'whiteboard' = 'doc'
) {
let type = file.type;
let category: AttachmentUploadedEvent['category'] = 'success';
try {
const { name, size } = file;
// TODO(@fundon): should re-upload when upload timeout
const sourceId = await std.store.blobSync.set(file);
type = await getFileType(file);
return {
name,
size,
type,
sourceId,
embed,
} satisfies Partial<AttachmentBlockProps>;
} catch (err) {
category = 'failure';
throw err;
} finally {
// TODO(@fundon): should change event name because this is just a local operation.
std.getOptional(TelemetryProvider)?.track('AttachmentUploadedEvent', {
page: `${mode} editor`,
module: 'attachment',
segment: mode,
control: 'uploader',
type,
category,
});
}
}
/**
* Add a new attachment block before / after the specified block.
*/
export async function addSiblingAttachmentBlocks(
std: BlockStdScope,
files: File[],
targetModel: BlockModel,
placement: 'before' | 'after' = 'after',
embed?: boolean
) {
if (!files.length) return [];
if (hasExceeded(std, files)) return [];
const flavour = AttachmentBlockSchema.model.flavour;
const propsArray = await Promise.all(
files.map(file => buildPropsWith(std, file, embed))
);
const blockIds = std.store.addSiblingBlocks(
targetModel,
propsArray.map(props => ({ ...props, flavour })),
placement
);
return blockIds;
}
export async function addAttachments(
std: BlockStdScope,
files: File[],
point?: IVec,
shouldTransformPoint?: boolean // determines whether we should use `toModelCoord` to convert the point
): Promise<string[]> {
if (!files.length) return [];
if (hasExceeded(std, files)) return [];
const propsArray = await Promise.all(
files.map(file => buildPropsWith(std, file, undefined, 'whiteboard'))
);
const gfx = std.get(GfxControllerIdentifier);
let { x, y } = gfx.viewport.center;
if (point) {
shouldTransformPoint = shouldTransformPoint ?? true;
if (shouldTransformPoint) {
[x, y] = gfx.viewport.toModelCoord(...point);
} else {
[x, y] = point;
}
}
const xy = [x, y];
const style = 'cubeThick';
const gap = 32;
const width = EMBED_CARD_WIDTH.cubeThick;
const height = EMBED_CARD_HEIGHT.cubeThick;
const flavour = AttachmentBlockSchema.model.flavour;
const blocks = propsArray.map((props, index) => {
const center = Vec.addScalar(xy, index * gap);
const xywh = Bound.fromCenter(center, width, height).serialize();
return { flavour, blockProps: { ...props, style, xywh } };
});
const blockIds = std.store.addBlocks(blocks, gfx.surface);
gfx.selection.set({
elements: blockIds,
editing: false,
});
return blockIds;
}

View File

@@ -0,0 +1,51 @@
import {
type ViewExtensionContext,
ViewExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { AttachmentBlockSchema } from '@blocksuite/affine-model';
import { SlashMenuConfigExtension } from '@blocksuite/affine-widget-slash-menu';
import { BlockViewExtension, FlavourExtension } from '@blocksuite/std';
import { literal } from 'lit/static-html.js';
import { AttachmentBlockInteraction } from './attachment-edgeless-block.js';
import { AttachmentDropOption } from './attachment-service.js';
import { attachmentSlashMenuConfig } from './configs/slash-menu.js';
import { createBuiltinToolbarConfigExtension } from './configs/toolbar';
import { EdgelessClipboardAttachmentConfig } from './edgeless-clipboard-config';
import { effects } from './effects.js';
import {
AttachmentEmbedConfigExtension,
AttachmentEmbedService,
} from './embed';
const flavour = AttachmentBlockSchema.model.flavour;
export class AttachmentViewExtension extends ViewExtensionProvider {
override name = 'affine-attachment-block';
override effect() {
super.effect();
effects();
}
override setup(context: ViewExtensionContext) {
super.setup(context);
context.register([
FlavourExtension(flavour),
BlockViewExtension(flavour, model => {
return model.parent?.flavour === 'affine:surface'
? literal`affine-edgeless-attachment`
: literal`affine-attachment`;
}),
AttachmentDropOption,
AttachmentEmbedConfigExtension(),
AttachmentEmbedService,
SlashMenuConfigExtension(flavour, attachmentSlashMenuConfig),
...createBuiltinToolbarConfigExtension(flavour),
]);
if (this.isEdgeless(context.scope)) {
context.register(EdgelessClipboardAttachmentConfig);
context.register(AttachmentBlockInteraction);
}
}
}

View File

@@ -0,0 +1,20 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo"
},
"include": ["./src"],
"references": [
{ "path": "../surface" },
{ "path": "../../components" },
{ "path": "../../ext-loader" },
{ "path": "../../model" },
{ "path": "../../shared" },
{ "path": "../../widgets/slash-menu" },
{ "path": "../../../framework/global" },
{ "path": "../../../framework/std" },
{ "path": "../../../framework/store" }
]
}

View File

@@ -0,0 +1,48 @@
{
"name": "@blocksuite/affine-block-bookmark",
"description": "Bookmark block for BlockSuite.",
"type": "module",
"scripts": {
"build": "yarn run -T tsc"
},
"sideEffects": false,
"keywords": [],
"author": "toeverything",
"license": "MIT",
"dependencies": {
"@blocksuite/affine-block-embed": "workspace:*",
"@blocksuite/affine-block-embed-doc": "workspace:*",
"@blocksuite/affine-block-surface": "workspace:*",
"@blocksuite/affine-components": "workspace:*",
"@blocksuite/affine-ext-loader": "workspace:*",
"@blocksuite/affine-model": "workspace:*",
"@blocksuite/affine-shared": "workspace:*",
"@blocksuite/affine-widget-slash-menu": "workspace:*",
"@blocksuite/global": "workspace:*",
"@blocksuite/icons": "^2.2.17",
"@blocksuite/std": "workspace:*",
"@blocksuite/store": "workspace:*",
"@preact/signals-core": "^1.8.0",
"@toeverything/theme": "^1.1.23",
"lit": "^3.2.0",
"rxjs": "^7.8.2",
"yjs": "^13.6.27"
},
"devDependencies": {
"@vitest/browser-playwright": "^4.1.10",
"playwright": "=1.58.2",
"vitest": "^4.1.8"
},
"exports": {
".": "./src/index.ts",
"./store": "./src/store.ts",
"./view": "./src/view.ts"
},
"files": [
"src",
"dist",
"!src/__tests__",
"!dist/__tests__"
],
"version": "0.27.5"
}

View File

@@ -0,0 +1,155 @@
import { describe, expect, it } from 'vitest';
import { footnoteUrlPreprocessor } from '../../adapters/markdown/preprocessor';
describe('footnoteUrlPreprocessor', () => {
it('should encode unencoded URLs in footnote definitions', () => {
const input =
'[^ref]: {"type":"url","url":"https://example.com?param=value"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com%3Fparam%3Dvalue"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should not encode already encoded URLs', () => {
const input = '[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com"}';
expect(footnoteUrlPreprocessor(input)).toBe(input);
});
it('should handle invalid JSON content', () => {
const input = '[^ref]: {"invalid json"}';
expect(footnoteUrlPreprocessor(input)).toBe(input);
});
it('should handle non-object footnote data', () => {
const input = '[^ref]: "not an object"';
expect(footnoteUrlPreprocessor(input)).toBe(input);
});
it('should handle footnote data without url property', () => {
const input = '[^ref]: {"type":"url"}';
expect(footnoteUrlPreprocessor(input)).toBe(input);
});
it('should handle multiple footnote definitions', () => {
const input = `
[^ref1]: {"type":"url","url":"https://example1.com"}
[^ref2]: {"type":"url","url":"https://example2.com"}
`.trim();
const expected = `
[^ref1]: {"type":"url","url":"https%3A%2F%2Fexample1.com"}
[^ref2]: {"type":"url","url":"https%3A%2F%2Fexample2.com"}
`.trim();
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should handle special characters in URLs', () => {
const input =
'[^ref]: {"type":"url","url":"https://example.com/path with spaces?param=value&another=param"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com%2Fpath%20with%20spaces%3Fparam%3Dvalue%26another%3Dparam"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should encode unencoded favicon URLs', () => {
const input =
'[^ref]: {"type":"url","url":"https://example.com","favicon":"https://example.com/icon.png"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com","favicon":"https%3A%2F%2Fexample.com%2Ficon.png"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should not encode already encoded favicon URLs', () => {
const input =
'[^ref]: {"type":"url","url":"https://example.com","favicon":"https%3A%2F%2Fexample.com%2Ficon.png"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com","favicon":"https%3A%2F%2Fexample.com%2Ficon.png"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should handle both URL and icon encoding in the same footnote', () => {
const input =
'[^ref]: {"type":"url","url":"https://example.com?param=value","favicon":"https://example.com/icon.png?size=large"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com%3Fparam%3Dvalue","favicon":"https%3A%2F%2Fexample.com%2Ficon.png%3Fsize%3Dlarge"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should format footnote definition with space', () => {
const input =
'[^ref]:{"type":"url","url":"https://example.com?param=value"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com%3Fparam%3Dvalue"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should format footnote definition with multiple spaces', () => {
const input =
'[^ref]: {"type":"url","url":"https://example.com?param=value"}';
const expected =
'[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com%3Fparam%3Dvalue"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should handle special characters in reference tags', () => {
const input =
'[^ref-with-special-chars!@#]: {"type":"url","url":"https://example.com"}';
const expected =
'[^ref-with-special-chars!@#]: {"type":"url","url":"https%3A%2F%2Fexample.com"}';
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should handle incomplete footnote definitions', () => {
const input = '[^ref]:';
expect(footnoteUrlPreprocessor(input)).toBe(input);
});
it('should handle mixed content with non-footnote text', () => {
const input = `
Some regular text
[^ref]: {"type":"url","url":"https://example.com"}
More regular text
`.trim();
const expected = `
Some regular text
[^ref]: {"type":"url","url":"https%3A%2F%2Fexample.com"}
More regular text
`.trim();
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should handle empty input', () => {
expect(footnoteUrlPreprocessor('')).toBe('');
});
it('should handle malformed footnote definitions', () => {
const input = '[^ref: {"type":"url","url":"https://example.com"}';
expect(footnoteUrlPreprocessor(input)).toBe(input);
});
it('should handle multiple footnotes with mixed content', () => {
const input = `
[^ref1]: {"type":"url","url":"https://example1.com"}
Some text in between
[^ref2]: {"type":"url","url":"https://example2.com"}
`.trim();
const expected = `
[^ref1]: {"type":"url","url":"https%3A%2F%2Fexample1.com"}
Some text in between
[^ref2]: {"type":"url","url":"https%3A%2F%2Fexample2.com"}
`.trim();
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
it('should encode partial encoded URLs in footnote definitions', () => {
const input = `
[^ref]: {"type":"url","url":"https://zh.wikipedia.org/zh-hans/%E5%B0%8F%E7%B1%B3SU7"}
[^ref2]: {"type":"url","url":"https://www.dw.com/zh/%E5%B0%8F%E7%B1%B3%E9%A6%96%E6%AC%BE%E6%B1%BD%E8%BD%A6%E5%8F%91%E5%B8%83-su7%E8%B5%B7%E4%BB%B72159%E4%B8%87%E5%85%83/a-68693432"}
`.trim();
const expected = `
[^ref]: {"type":"url","url":"https%3A%2F%2Fzh.wikipedia.org%2Fzh-hans%2F%25E5%25B0%258F%25E7%25B1%25B3SU7"}
[^ref2]: {"type":"url","url":"https%3A%2F%2Fwww.dw.com%2Fzh%2F%25E5%25B0%258F%25E7%25B1%25B3%25E9%25A6%2596%25E6%25AC%25BE%25E6%25B1%25BD%25E8%25BD%25A6%25E5%258F%2591%25E5%25B8%2583-su7%25E8%25B5%25B7%25E4%25BB%25B72159%25E4%25B8%2587%25E5%2585%2583%2Fa-68693432"}
`.trim();
expect(footnoteUrlPreprocessor(input)).toBe(expected);
});
});

View File

@@ -0,0 +1,13 @@
import type { ExtensionType } from '@blocksuite/store';
import { BookmarkBlockHtmlAdapterExtension } from './html.js';
import { BookmarkBlockMarkdownAdapterExtensions } from './markdown/index.js';
import { BookmarkBlockNotionHtmlAdapterExtension } from './notion-html.js';
import { BookmarkBlockPlainTextAdapterExtension } from './plain-text.js';
export const BookmarkBlockAdapterExtensions: ExtensionType[] = [
BookmarkBlockHtmlAdapterExtension,
BookmarkBlockMarkdownAdapterExtensions,
BookmarkBlockNotionHtmlAdapterExtension,
BookmarkBlockPlainTextAdapterExtension,
].flat();

View File

@@ -0,0 +1,10 @@
import { createEmbedBlockHtmlAdapterMatcher } from '@blocksuite/affine-block-embed';
import { BookmarkBlockSchema } from '@blocksuite/affine-model';
import { BlockHtmlAdapterExtension } from '@blocksuite/affine-shared/adapters';
export const bookmarkBlockHtmlAdapterMatcher =
createEmbedBlockHtmlAdapterMatcher(BookmarkBlockSchema.model.flavour);
export const BookmarkBlockHtmlAdapterExtension = BlockHtmlAdapterExtension(
bookmarkBlockHtmlAdapterMatcher
);

View File

@@ -0,0 +1,4 @@
export * from './html.js';
export * from './markdown/index.js';
export * from './notion-html.js';
export * from './plain-text.js';

View File

@@ -0,0 +1,12 @@
import type { ExtensionType } from '@blocksuite/store';
import { BookmarkBlockMarkdownAdapterExtension } from './markdown.js';
import { BookmarkBlockMarkdownPreprocessorExtension } from './preprocessor.js';
export * from './markdown.js';
export * from './preprocessor.js';
export const BookmarkBlockMarkdownAdapterExtensions: ExtensionType[] = [
BookmarkBlockMarkdownPreprocessorExtension,
BookmarkBlockMarkdownAdapterExtension,
];

View File

@@ -0,0 +1,93 @@
import { createEmbedBlockMarkdownAdapterMatcher } from '@blocksuite/affine-block-embed';
import {
BookmarkBlockSchema,
FootNoteReferenceParamsSchema,
} from '@blocksuite/affine-model';
import {
BlockMarkdownAdapterExtension,
FOOTNOTE_DEFINITION_PREFIX,
getFootnoteDefinitionText,
isFootnoteDefinitionNode,
type MarkdownAST,
} from '@blocksuite/affine-shared/adapters';
import { nanoid } from '@blocksuite/store';
const isUrlFootnoteDefinitionNode = (node: MarkdownAST) => {
if (!isFootnoteDefinitionNode(node)) return false;
const footnoteDefinition = getFootnoteDefinitionText(node);
try {
const footnoteDefinitionJson = FootNoteReferenceParamsSchema.parse(
JSON.parse(footnoteDefinition)
);
return (
footnoteDefinitionJson.type === 'url' && !!footnoteDefinitionJson.url
);
} catch {
return false;
}
};
export const bookmarkBlockMarkdownAdapterMatcher =
createEmbedBlockMarkdownAdapterMatcher(BookmarkBlockSchema.model.flavour, {
toMatch: o => isUrlFootnoteDefinitionNode(o.node),
toBlockSnapshot: {
enter: (o, context) => {
if (!isFootnoteDefinitionNode(o.node)) {
return;
}
const { walkerContext, configs } = context;
const footnoteIdentifier = o.node.identifier;
const footnoteDefinitionKey = `${FOOTNOTE_DEFINITION_PREFIX}${footnoteIdentifier}`;
const footnoteDefinition = configs.get(footnoteDefinitionKey);
if (!footnoteDefinition) {
return;
}
let footnoteDefinitionJson;
try {
footnoteDefinitionJson = FootNoteReferenceParamsSchema.parse(
JSON.parse(footnoteDefinition)
);
// If the footnote definition contains url, decode it
if (footnoteDefinitionJson.url) {
footnoteDefinitionJson.url = decodeURIComponent(
footnoteDefinitionJson.url
);
}
if (footnoteDefinitionJson.favicon) {
footnoteDefinitionJson.favicon = decodeURIComponent(
footnoteDefinitionJson.favicon
);
}
} catch (err) {
console.warn('Failed to parse or decode footnote definition:', err);
return;
}
const { url, favicon, title, description } = footnoteDefinitionJson;
walkerContext
.openNode(
{
type: 'block',
id: nanoid(),
flavour: BookmarkBlockSchema.model.flavour,
props: {
url,
footnoteIdentifier,
icon: favicon,
title,
description,
style: 'citation',
},
children: [],
},
'children'
)
.closeNode();
walkerContext.skipAllChildren();
},
},
});
export const BookmarkBlockMarkdownAdapterExtension =
BlockMarkdownAdapterExtension(bookmarkBlockMarkdownAdapterMatcher);

View File

@@ -0,0 +1,263 @@
import {
type FootNoteReferenceParams,
FootNoteReferenceParamsSchema,
} from '@blocksuite/affine-model';
import {
type MarkdownAdapterPreprocessor,
MarkdownPreprocessorExtension,
} from '@blocksuite/affine-shared/adapters';
// Types for footnote parser tokens
type Token = {
type:
| 'FOOTNOTE_START'
| 'REFERENCE'
| 'SEPARATOR'
| 'JSON_CONTENT'
| 'NEWLINE';
value: string;
};
type FootnoteDefinition = {
reference: string;
content: FootNoteReferenceParams;
};
/**
* Check if a URL is already encoded with encodeURIComponent to avoid markdown link parsing
* @example
* https://example.com/path%20with%20spaces should return false
* https://example.com/ should return false
* https%3A%2F%2Fexample.com%2F should return true
*/
function isFullyEncoded(uri: string): boolean {
try {
// Should check if the components of the URI are fully encoded
return uri === encodeURIComponent(decodeURIComponent(uri));
} catch {
// If decoding fails, the URI contains invalid percent-encoding
return true;
}
}
// Format footnote definition with consistent spacing
function formatFootnoteDefinition(reference: string, data: object): string {
return `[^${reference}]: ${JSON.stringify(data)}`;
}
class FootnoteParser {
private pos: number = 0;
private input: string = '';
private tokens: Token[] = [];
// Lexer: Convert input string into tokens
private tokenize(input: string): Token[] {
this.input = input;
this.pos = 0;
this.tokens = [];
while (this.pos < this.input.length) {
const char = this.input[this.pos];
// Handle newlines
if (char === '\n') {
this.tokens.push({ type: 'NEWLINE', value: '\n' });
this.pos++;
continue;
}
// Match footnote start [^
if (char === '[' && this.input[this.pos + 1] === '^') {
this.tokens.push({ type: 'FOOTNOTE_START', value: '[^' });
this.pos += 2;
continue;
}
// Match reference content until ]
if (
this.tokens.length > 0 &&
this.tokens[this.tokens.length - 1].type === 'FOOTNOTE_START'
) {
let reference = '';
while (this.pos < this.input.length && this.input[this.pos] !== ']') {
reference += this.input[this.pos];
this.pos++;
}
if (reference) {
this.tokens.push({ type: 'REFERENCE', value: reference });
}
this.pos++; // Skip the closing ]
continue;
}
// Match separator ': '
if (char === ':') {
let nextPos = this.pos + 1;
while (nextPos < this.input.length && this.input[nextPos] === ' ') {
nextPos++;
}
this.tokens.push({
type: 'SEPARATOR',
value: this.input.slice(this.pos, nextPos),
});
this.pos = nextPos;
continue;
}
// Match JSON content
if (char === '{') {
let jsonContent = '';
let braceCount = 1;
let startPos = this.pos;
this.pos++; // Move past the opening brace
let inString = false;
let escaped = false;
while (this.pos < this.input.length && braceCount > 0) {
const char = this.input[this.pos];
if (!inString) {
if (char === '{') braceCount++;
else if (char === '}') braceCount--;
}
if (escaped) {
escaped = false;
} else {
if (char === '\\') {
escaped = true;
} else if (char === '"') {
inString = !inString;
}
}
jsonContent += char;
this.pos++;
}
if (braceCount === 0) {
this.tokens.push({
type: 'JSON_CONTENT',
value: '{' + jsonContent,
});
} else {
// Reset position if JSON is malformed
this.pos = startPos;
this.pos++;
}
continue;
}
// Skip other characters
this.pos++;
}
return this.tokens;
}
// Parser: Convert tokens into structured data
private parse(tokens: Token[]): FootnoteDefinition[] {
const footnotes: FootnoteDefinition[] = [];
let currentFootnote: Partial<FootnoteDefinition> = {};
let isParsingFootnote = false;
for (const token of tokens) {
switch (token.type) {
case 'FOOTNOTE_START':
isParsingFootnote = true;
currentFootnote = {};
break;
case 'REFERENCE':
if (isParsingFootnote) {
currentFootnote.reference = token.value;
}
break;
case 'JSON_CONTENT':
if (isParsingFootnote) {
try {
currentFootnote.content = FootNoteReferenceParamsSchema.parse(
JSON.parse(token.value)
);
footnotes.push(currentFootnote as FootnoteDefinition);
} catch {
// Invalid JSON, ignore this footnote
}
isParsingFootnote = false;
currentFootnote = {};
}
break;
case 'NEWLINE':
isParsingFootnote = false;
currentFootnote = {};
break;
}
}
return footnotes;
}
// Process URLs in footnote content
private processUrls(footnote: FootnoteDefinition): FootnoteDefinition {
const content = footnote.content;
if (content.url && !isFullyEncoded(content.url)) {
content.url = encodeURIComponent(content.url);
}
if (content.favicon && !isFullyEncoded(content.favicon)) {
content.favicon = encodeURIComponent(content.favicon);
}
return footnote;
}
// Main processing function
public process(input: string): string {
// 1. Tokenize the input
const tokens = this.tokenize(input);
// 2. Parse tokens into footnotes
const footnotes = this.parse(tokens);
// 3. Process URLs in footnotes
const processedFootnotes = footnotes.map(fn => this.processUrls(fn));
// 4. Convert back to original format
const footnoteMap = new Map(
processedFootnotes.map(fn => [
fn.reference,
formatFootnoteDefinition(fn.reference, fn.content),
])
);
// 5. Replace in original text
return input
.split('\n')
.map(line => {
const match = line.match(/^\[\^([^\]]+)\]:/);
if (match && footnoteMap.has(match[1])) {
return footnoteMap.get(match[1])!;
}
return line;
})
.join('\n');
}
}
/**
* Preprocessor for footnote url
* We should encode url in footnote definition to avoid markdown link parsing
*
* Example of footnote definition:
* [^ref]: {"type":"url","url":"https://example.com"}
*/
export function footnoteUrlPreprocessor(content: string): string {
const parser = new FootnoteParser();
return parser.process(content);
}
const bookmarkBlockPreprocessor: MarkdownAdapterPreprocessor = {
name: 'bookmark-block',
levels: ['block', 'slice', 'doc'],
preprocess: footnoteUrlPreprocessor,
};
export const BookmarkBlockMarkdownPreprocessorExtension =
MarkdownPreprocessorExtension(bookmarkBlockPreprocessor);

View File

@@ -0,0 +1,71 @@
import { BookmarkBlockSchema } from '@blocksuite/affine-model';
import {
BlockNotionHtmlAdapterExtension,
type BlockNotionHtmlAdapterMatcher,
HastUtils,
} from '@blocksuite/affine-shared/adapters';
import { nanoid } from '@blocksuite/store';
export const bookmarkBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatcher =
{
flavour: BookmarkBlockSchema.model.flavour,
toMatch: o => {
return (
HastUtils.isElement(o.node) &&
o.node.tagName === 'figure' &&
!!HastUtils.querySelector(o.node, '.bookmark')
);
},
fromMatch: () => false,
toBlockSnapshot: {
enter: (o, context) => {
if (!HastUtils.isElement(o.node)) {
return;
}
const bookmark = HastUtils.querySelector(o.node, '.bookmark');
if (!bookmark) {
return;
}
const { walkerContext } = context;
const bookmarkURL = bookmark.properties?.href;
const bookmarkTitle = HastUtils.getTextContent(
HastUtils.querySelector(bookmark, '.bookmark-title')
);
const bookmarkDescription = HastUtils.getTextContent(
HastUtils.querySelector(bookmark, '.bookmark-description')
);
const bookmarkIcon = HastUtils.querySelector(
bookmark,
'.bookmark-icon'
);
const bookmarkIconURL =
typeof bookmarkIcon?.properties?.src === 'string'
? bookmarkIcon.properties.src
: '';
walkerContext
.openNode(
{
type: 'block',
id: nanoid(),
flavour: BookmarkBlockSchema.model.flavour,
props: {
type: 'card',
url: bookmarkURL ?? '',
title: bookmarkTitle,
description: bookmarkDescription,
icon: bookmarkIconURL,
},
children: [],
},
'children'
)
.closeNode();
walkerContext.skipAllChildren();
},
},
fromBlockSnapshot: {},
};
export const BookmarkBlockNotionHtmlAdapterExtension =
BlockNotionHtmlAdapterExtension(bookmarkBlockNotionHtmlAdapterMatcher);

View File

@@ -0,0 +1,9 @@
import { createEmbedBlockPlainTextAdapterMatcher } from '@blocksuite/affine-block-embed';
import { BookmarkBlockSchema } from '@blocksuite/affine-model';
import { BlockPlainTextAdapterExtension } from '@blocksuite/affine-shared/adapters';
export const bookmarkBlockPlainTextAdapterMatcher =
createEmbedBlockPlainTextAdapterMatcher(BookmarkBlockSchema.model.flavour);
export const BookmarkBlockPlainTextAdapterExtension =
BlockPlainTextAdapterExtension(bookmarkBlockPlainTextAdapterMatcher);

View File

@@ -0,0 +1,293 @@
import {
CaptionedBlockComponent,
SelectedStyle,
} from '@blocksuite/affine-components/caption';
import type {
BookmarkBlockModel,
LinkPreviewData,
} from '@blocksuite/affine-model';
import { ImageProxyService } from '@blocksuite/affine-shared/adapters';
import {
BlockElementCommentManager,
CitationProvider,
DocModeProvider,
LinkPreviewServiceIdentifier,
} from '@blocksuite/affine-shared/services';
import { normalizeUrl } from '@blocksuite/affine-shared/utils';
import { BlockSelection } from '@blocksuite/std';
import { computed, type ReadonlySignal, signal } from '@preact/signals-core';
import { html } from 'lit';
import { property, query } from 'lit/decorators.js';
import { type ClassInfo, classMap } from 'lit/directives/class-map.js';
import { type StyleInfo, styleMap } from 'lit/directives/style-map.js';
import { filter } from 'rxjs/operators';
import { refreshBookmarkUrlData } from './utils.js';
export const BOOKMARK_MIN_WIDTH = 450;
export class BookmarkBlockComponent extends CaptionedBlockComponent<BookmarkBlockModel> {
selectedStyle$: ReadonlySignal<ClassInfo> | null = computed<ClassInfo>(
() => ({
'selected-style': this.selected$.value,
})
);
private _fetchAbortController?: AbortController;
blockDraggable = true;
protected containerStyleMap!: ReturnType<typeof styleMap>;
/**
* @description Local link preview data
* When the doc is in readonly mode, and the link preview data are not provided (stored in the block model),
* We will use the local link preview data fetched from the link previewer service to render the block.
*/
private readonly _localLinkPreview$ = signal<LinkPreviewData>({
icon: null,
title: null,
description: null,
image: null,
});
/**
* @description Link preview data for actual rendering
* When the doc is not in readonly mode, and the link preview data are provided (stored in the block model),
* We will use the model props to render the block.
* Otherwise, we will use the local link preview data to render the block.
*/
linkPreview$ = computed(() => {
const modelProps = this.model.props;
const local = this._localLinkPreview$.value;
return {
icon: modelProps.icon$.value ?? local.icon ?? null,
title: modelProps.title$.value ?? local.title ?? null,
description: modelProps.description$.value ?? local.description ?? null,
image: modelProps.image$.value ?? local.image ?? null,
};
});
private readonly _updateLocalLinkPreview = () => {
// cancel any inflight request
this._fetchAbortController?.abort();
this._fetchAbortController = new AbortController();
this.loading = true;
this.error = false;
this.std
.get(LinkPreviewServiceIdentifier)
.query(this.model.props.url, this._fetchAbortController.signal)
.then(data => {
this._localLinkPreview$.value = {
icon: data.icon ?? null,
title: data.title ?? null,
description: data.description ?? null,
image: data.image ?? null,
};
})
.catch(() => {
this.error = true;
})
.finally(() => {
this.loading = false;
});
};
selectBlock = () => {
const selectionManager = this.std.selection;
const blockSelection = selectionManager.create(BlockSelection, {
blockId: this.blockId,
});
selectionManager.setGroup('note', [blockSelection]);
};
get link() {
return normalizeUrl(this.model.props.url);
}
open = () => {
const link = this.link;
if (!link) return;
window.open(link, '_blank', 'noopener,noreferrer');
};
refreshData = () => {
refreshBookmarkUrlData(this, this._fetchAbortController?.signal).catch(
console.error
);
};
get citationService() {
return this.std.get(CitationProvider);
}
get isCitation() {
return this.citationService.isCitationModel(this.model);
}
get imageProxyService() {
return this.std.get(ImageProxyService);
}
get isCommentHighlighted() {
return (
this.std
.getOptional(BlockElementCommentManager)
?.isBlockCommentHighlighted(this.model) ?? false
);
}
handleClick = (event: MouseEvent) => {
event.stopPropagation();
if (
this.model.parent?.flavour !== 'affine:surface' &&
!this.store.readonly
) {
this.selectBlock();
}
};
handleDoubleClick = (event: MouseEvent) => {
event.stopPropagation();
this.open();
};
private readonly _renderCitationView = () => {
const { url, footnoteIdentifier } = this.model.props;
const { icon, title, description } = this.linkPreview$.value;
const iconSrc = icon ? this.imageProxyService.buildUrl(icon) : undefined;
return html`
<affine-citation-card
.icon=${iconSrc}
.citationTitle=${title || url}
.citationContent=${description}
.citationIdentifier=${footnoteIdentifier}
.onClickCallback=${this.handleClick}
.onDoubleClickCallback=${this.handleDoubleClick}
.active=${this.selected$.value}
></affine-citation-card>
`;
};
private readonly _renderCardView = () => {
return html`<bookmark-card
.bookmark=${this}
.loading=${this.loading}
.error=${this.error}
></bookmark-card>`;
};
private readonly _trackCitationDeleteEvent = () => {
// Check citation delete event
this._disposables.add(
this.std.store.slots.blockUpdated
.pipe(
filter(payload => {
if (!payload.isLocal) return false;
const { flavour, id, type } = payload;
if (
type !== 'delete' ||
flavour !== this.model.flavour ||
id !== this.model.id
)
return false;
const { model } = payload;
if (!this.citationService.isCitationModel(model)) return false;
return true;
})
)
.subscribe(() => {
this.citationService.trackEvent('Delete');
})
);
};
override connectedCallback() {
super.connectedCallback();
const mode = this.std.get(DocModeProvider).getEditorMode();
const miniWidth = `${BOOKMARK_MIN_WIDTH}px`;
this.containerStyleMap = styleMap({
position: 'relative',
width: '100%',
...(mode === 'edgeless' ? { miniWidth } : {}),
});
this._fetchAbortController = new AbortController();
this.contentEditable = 'false';
if (
(!this.model.props.description && !this.model.props.title) ||
(!this.model.props.image && this.model.props.style === 'vertical')
) {
// When the doc is readonly, and the preview data not provided
// We should fetch the preview data and update the local link preview data
if (this.store.readonly) {
this._updateLocalLinkPreview();
return;
}
// Otherwise, we should refresh the data to the model props
this.refreshData();
}
this.disposables.add(
this.model.propsUpdated.subscribe(({ key }) => {
if (key === 'url') {
this.refreshData();
}
})
);
this._trackCitationDeleteEvent();
}
override disconnectedCallback(): void {
super.disconnectedCallback();
this._fetchAbortController?.abort();
}
override renderBlock() {
return html`
<div
draggable="${this.blockDraggable ? 'true' : 'false'}"
class=${classMap({
'affine-bookmark-container': true,
...this.selectedStyle$?.value,
})}
style=${this.containerStyleMap}
>
${this.isCitation ? this._renderCitationView() : this._renderCardView()}
</div>
`;
}
protected override accessor blockContainerStyles: StyleInfo = {
margin: '18px 0',
};
@query('bookmark-card')
accessor bookmarkCard!: HTMLElement;
@property({ attribute: false })
accessor error = false;
@property({ attribute: false })
accessor loading = false;
override accessor selectedStyle = SelectedStyle.Border;
override accessor useCaptionEditor = true;
override accessor useZeroWidth = true;
}
declare global {
interface HTMLElementTagNameMap {
'affine-bookmark': BookmarkBlockComponent;
}
}

View File

@@ -0,0 +1,88 @@
import { BookmarkBlockSchema } from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import { toGfxBlockComponent } from '@blocksuite/std';
import { GfxViewInteractionExtension } from '@blocksuite/std/gfx';
import { type StyleInfo, styleMap } from 'lit/directives/style-map.js';
import { BookmarkBlockComponent } from './bookmark-block.js';
export class BookmarkEdgelessBlockComponent extends toGfxBlockComponent(
BookmarkBlockComponent
) {
override selectedStyle$ = null;
override blockDraggable = false;
override getRenderingRect() {
const elementBound = this.model.elementBound;
const style = this.model.props.style$.value;
return {
x: elementBound.x,
y: elementBound.y,
w: EMBED_CARD_WIDTH[style],
h: EMBED_CARD_HEIGHT[style],
zIndex: this.toZIndex(),
};
}
override connectedCallback(): void {
super.connectedCallback();
this.disposables.add(
this.gfx.selection.slots.updated.subscribe(() => {
this.requestUpdate();
})
);
}
override renderGfxBlock() {
const style = this.model.props.style$.value;
const width = EMBED_CARD_WIDTH[style];
const height = EMBED_CARD_HEIGHT[style];
const bound = this.model.elementBound;
const scaleX = bound.w / width;
const scaleY = bound.h / height;
const isSelected = this.gfx.selection.has(this.model.id);
this.containerStyleMap = styleMap({
width: `100%`,
height: `100%`,
transform: `scale(${scaleX}, ${scaleY})`,
transformOrigin: '0 0',
pointerEvents: isSelected ? 'auto' : 'none',
});
return this.renderPageContent();
}
protected override accessor blockContainerStyles: StyleInfo = {
height: '100%',
};
}
export const BookmarkBlockInteraction = GfxViewInteractionExtension(
BookmarkBlockSchema.model.flavour,
{
resizeConstraint: {
lockRatio: true,
},
handleRotate: () => {
return {
beforeRotate(context) {
context.set({
rotatable: false,
});
},
};
},
}
);
declare global {
interface HTMLElementTagNameMap {
'affine-edgeless-bookmark': BookmarkEdgelessBlockComponent;
}
}

View File

@@ -0,0 +1,2 @@
export { insertBookmarkCommand } from './insert-bookmark.js';
export { insertLinkByQuickSearchCommand } from './insert-link-by-quick-search.js';

View File

@@ -0,0 +1,23 @@
import { insertEmbedCard } from '@blocksuite/affine-block-embed';
import type { EmbedCardStyle } from '@blocksuite/affine-model';
import { EmbedOptionProvider } from '@blocksuite/affine-shared/services';
import type { Command } from '@blocksuite/std';
export const insertBookmarkCommand: Command<
{ url: string },
{ blockId: string; flavour: string }
> = (ctx, next) => {
const { url, std } = ctx;
const embedOptions = std.get(EmbedOptionProvider).getEmbedBlockOptions(url);
let flavour = 'affine:bookmark';
let targetStyle: EmbedCardStyle = 'vertical';
const props: Record<string, unknown> = { url };
if (embedOptions) {
flavour = embedOptions.flavour;
targetStyle = embedOptions.styles[0];
}
const blockId = insertEmbedCard(std, { flavour, targetStyle, props });
if (!blockId) return;
next({ blockId, flavour });
};

View File

@@ -0,0 +1,79 @@
import { insertEmbedIframeWithUrlCommand } from '@blocksuite/affine-block-embed';
import {
type InsertedLinkType,
insertEmbedLinkedDocCommand,
insertEmbedSyncedDocCommand,
type LinkableFlavour,
} from '@blocksuite/affine-block-embed-doc';
import {
DocModeProvider,
EditorSettingProvider,
QuickSearchProvider,
} from '@blocksuite/affine-shared/services';
import type { Command } from '@blocksuite/std';
import { insertBookmarkCommand } from './insert-bookmark';
export const insertLinkByQuickSearchCommand: Command<
{},
{ insertedLinkType: Promise<InsertedLinkType> }
> = (ctx, next) => {
const { std } = ctx;
const quickSearchService = std.getOptional(QuickSearchProvider);
if (!quickSearchService) {
return;
}
const insertedLinkType: Promise<InsertedLinkType> = quickSearchService
.openQuickSearch()
.then(result => {
if (!result) return null;
// add linked doc
if ('docId' in result) {
const editorMode = std.get(DocModeProvider).getEditorMode();
const editorSettings = std.get(EditorSettingProvider);
let flavour: LinkableFlavour = 'affine:embed-linked-doc';
if (editorMode === 'edgeless') {
flavour =
editorSettings.setting$.value.docCanvasPreferView ?? flavour;
}
const insertCommand =
flavour === 'affine:embed-linked-doc'
? insertEmbedLinkedDocCommand
: insertEmbedSyncedDocCommand;
std.command.exec(insertCommand, {
docId: result.docId,
params: result.params,
});
return {
flavour,
};
}
// add normal link;
if ('externalUrl' in result) {
// try to insert embed iframe block first
const [success, { flavour }] = std.command
.chain()
.try(chain => [
chain.pipe(insertEmbedIframeWithUrlCommand, {
url: result.externalUrl,
}),
chain.pipe(insertBookmarkCommand, { url: result.externalUrl }),
])
.run();
if (!success || !flavour) return null;
return {
flavour: flavour as LinkableFlavour,
};
}
return null;
});
next({ insertedLinkType });
};

View File

@@ -0,0 +1,139 @@
import { getEmbedCardIcons } from '@blocksuite/affine-block-embed';
import { LoadingIcon, WebIcon16 } from '@blocksuite/affine-components/icons';
import { ImageProxyService } from '@blocksuite/affine-shared/adapters';
import {
LinkPreviewServiceIdentifier,
ThemeProvider,
} from '@blocksuite/affine-shared/services';
import { getHostName } from '@blocksuite/affine-shared/utils';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
import { OpenInNewIcon } from '@blocksuite/icons/lit';
import { isGfxBlockComponent, ShadowlessElement } from '@blocksuite/std';
import { html } from 'lit';
import { property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import type { BookmarkBlockComponent } from '../bookmark-block.js';
import { styles } from '../styles.js';
export class BookmarkCard extends SignalWatcher(
WithDisposable(ShadowlessElement)
) {
static override styles = styles;
override connectedCallback(): void {
super.connectedCallback();
this.disposables.add(
this.bookmark.model.propsUpdated.subscribe(() => {
this.requestUpdate();
})
);
this.disposables.add(
this.bookmark.std
.get(ThemeProvider)
.theme$.subscribe(() => this.requestUpdate())
);
}
override render() {
const { url, style } = this.bookmark.model.props;
const { icon, title, description, image } =
this.bookmark.linkPreview$.value;
const cardClassMap = classMap({
loading: this.loading,
error: this.error,
[style]: true,
selected: this.bookmark.selected$.value,
edgeless: isGfxBlockComponent(this.bookmark),
'comment-highlighted': this.bookmark.isCommentHighlighted,
});
const domainName = url.match(
/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:/\n]+)/im
)?.[1];
const titleText = this.loading
? 'Loading...'
: !title
? this.error
? (domainName ?? 'Link card')
: ''
: title;
const theme = this.bookmark.std.get(ThemeProvider).theme;
const { EmbedCardBannerIcon } = getEmbedCardIcons(theme);
const imageProxyService = this.bookmark.store.get(ImageProxyService);
const titleIcon = this.loading
? LoadingIcon()
: icon
? html`<img src=${imageProxyService.buildUrl(icon)} alt="icon" />`
: WebIcon16;
const descriptionText = this.loading
? ''
: !description
? this.error
? 'Failed to retrieve link information.'
: url
: (description ?? '');
const bannerImage =
!this.loading && image
? html`<img src=${imageProxyService.buildUrl(image)} alt="banner" />`
: EmbedCardBannerIcon;
return html`
<div
class="affine-bookmark-card ${cardClassMap}"
@click=${this.bookmark.handleClick}
@dblclick=${this.bookmark.handleDoubleClick}
>
<div class="affine-bookmark-content">
<div class="affine-bookmark-content-title">
<div class="affine-bookmark-content-title-icon">${titleIcon}</div>
<div class="affine-bookmark-content-title-text">${titleText}</div>
</div>
<div class="affine-bookmark-content-description">
${descriptionText}
</div>
<div class="affine-bookmark-content-url-wrapper">
<div
class="affine-bookmark-content-url"
@click=${this.bookmark.open}
>
<span>${getHostName(url)}</span>
<div class="affine-bookmark-content-url-icon">
${OpenInNewIcon({ width: '12', height: '12' })}
</div>
</div>
</div>
</div>
<div class="affine-bookmark-banner">${bannerImage}</div>
</div>
<affine-link-preview-details
.url=${url}
.floating=${isGfxBlockComponent(this.bookmark)}
.provider=${this.bookmark.std.get(LinkPreviewServiceIdentifier)}
></affine-link-preview-details>
`;
}
@property({ attribute: false })
accessor bookmark!: BookmarkBlockComponent;
@property({ attribute: false })
accessor error!: boolean;
@property({ attribute: false })
accessor loading!: boolean;
}
declare global {
interface HTMLElementTagNameMap {
'bookmark-card': BookmarkCard;
}
}

View File

@@ -0,0 +1 @@
export * from './bookmark-card';

View File

@@ -0,0 +1,65 @@
import { DefaultTool } from '@blocksuite/affine-block-surface';
import { toggleEmbedCardCreateModal } from '@blocksuite/affine-components/embed-card-modal';
import { BookmarkBlockSchema } from '@blocksuite/affine-model';
import {
type SlashMenuConfig,
SlashMenuConfigIdentifier,
} from '@blocksuite/affine-widget-slash-menu';
import { LinkIcon } from '@blocksuite/icons/lit';
import { GfxControllerIdentifier } from '@blocksuite/std/gfx';
import type { ExtensionType } from '@blocksuite/store';
import { LinkTooltip } from './tooltips';
const bookmarkSlashMenuConfig: SlashMenuConfig = {
items: [
{
name: 'Link',
description: 'Add a bookmark for reference.',
icon: LinkIcon(),
tooltip: {
figure: LinkTooltip,
caption: 'Link',
},
group: '4_Content & Media@2',
when: ({ model }) =>
model.store.schema.flavourSchemaMap.has('affine:bookmark'),
action: ({ std, model }) => {
const { host } = std;
const parentModel = host.store.getParent(model);
if (!parentModel) {
return;
}
const index = parentModel.children.indexOf(model) + 1;
toggleEmbedCardCreateModal(
host,
'Links',
'The added link will be displayed as a card view.',
{ mode: 'page', parentModel, index },
({ mode }) => {
if (mode === 'edgeless') {
const gfx = std.get(GfxControllerIdentifier);
gfx.tool.setTool(DefaultTool);
}
}
)
.then(() => {
if (model.text?.length === 0) {
model.store.deleteBlock(model);
}
})
.catch(console.error);
},
},
],
};
export const BookmarkSlashMenuConfigIdentifier = SlashMenuConfigIdentifier(
BookmarkBlockSchema.model.flavour
);
export const BookmarkSlashMenuConfigExtension: ExtensionType = {
setup: di => {
di.addImpl(BookmarkSlashMenuConfigIdentifier, bookmarkSlashMenuConfig);
},
};

View File

@@ -0,0 +1,620 @@
import {
canEmbedAsEmbedBlock,
canEmbedAsIframe,
EMBED_IFRAME_DEFAULT_HEIGHT_IN_SURFACE,
EMBED_IFRAME_DEFAULT_WIDTH_IN_SURFACE,
} from '@blocksuite/affine-block-embed';
import { reassociateConnectorsCommand } from '@blocksuite/affine-block-surface';
import { toast } from '@blocksuite/affine-components/toast';
import {
BookmarkBlockModel,
BookmarkStyles,
type EmbedCardStyle,
} from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import {
ActionPlacement,
EmbedIframeService,
EmbedOptionProvider,
type LinkEventType,
type ToolbarAction,
type ToolbarActionGroup,
type ToolbarContext,
type ToolbarModuleConfig,
ToolbarModuleExtension,
} from '@blocksuite/affine-shared/services';
import { getBlockProps } from '@blocksuite/affine-shared/utils';
import { Bound } from '@blocksuite/global/gfx';
import {
CaptionIcon,
CopyIcon,
DeleteIcon,
DuplicateIcon,
ResetIcon,
} from '@blocksuite/icons/lit';
import { BlockFlavourIdentifier, BlockSelection } from '@blocksuite/std';
import { type ExtensionType, Slice, Text } from '@blocksuite/store';
import { computed, signal } from '@preact/signals-core';
import { html } from 'lit';
import { keyed } from 'lit/directives/keyed.js';
import * as Y from 'yjs';
import { BookmarkBlockComponent } from '../bookmark-block';
const trackBaseProps = {
category: 'bookmark',
type: 'card view',
};
const previewAction = {
id: 'a.preview',
content(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const { url } = model.props;
return html`<affine-link-preview .url=${url}></affine-link-preview>`;
},
} satisfies ToolbarAction;
const captionAction = {
id: 'd.caption',
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const block = ctx.getCurrentBlockByType(BookmarkBlockComponent);
block?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
control: 'add caption',
});
},
} satisfies ToolbarAction;
const createOnToggleFn =
(
ctx: ToolbarContext,
name: Extract<
LinkEventType,
| 'OpenedViewSelector'
| 'OpenedCardStyleSelector'
| 'OpenedCardScaleSelector'
>,
control: string
) =>
(e: CustomEvent<boolean>) => {
e.stopPropagation();
const opened = e.detail;
if (!opened) return;
ctx.track(name, {
...trackBaseProps,
control,
});
};
const builtinToolbarConfig = {
actions: [
previewAction,
{
id: 'b.conversions',
actions: [
{
id: 'inline',
label: 'Inline view',
run(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { title, caption, url } = model.props;
const { parent } = model;
const index = parent?.children.indexOf(model);
const yText = new Y.Text();
const insert = title || caption || url;
yText.insert(0, insert);
yText.format(0, insert.length, { link: url });
const text = new Text(yText);
ctx.store.addBlock('affine:paragraph', { text }, parent, index);
ctx.store.deleteBlock(model);
// Clears
ctx.reset();
ctx.select('note');
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'inline view',
});
},
},
{
id: 'card',
label: 'Card view',
disabled: true,
},
{
id: 'embed',
label: 'Embed view',
disabled(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return true;
const url = model.props.url;
return (
!canEmbedAsIframe(ctx.std, url) &&
!canEmbedAsEmbedBlock(ctx.std, url)
);
},
run(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { caption, url, title, description, style } = model.props;
const { parent } = model;
const index = parent?.children.indexOf(model);
if (!parent) return;
let blockId: string | undefined;
// first try to embed as a custom embed block
if (canEmbedAsEmbedBlock(ctx.std, url)) {
const options = ctx.std
.get(EmbedOptionProvider)
.getEmbedBlockOptions(url);
if (!options) return;
const { flavour, styles } = options;
const newStyle = styles.includes(style)
? style
: styles.find(s => s !== 'vertical' && s !== 'cube');
blockId = ctx.store.addBlock(
flavour,
{
url,
caption,
title,
description,
style: newStyle,
},
parent,
index
);
} else if (canEmbedAsIframe(ctx.std, url)) {
const embedIframeService = ctx.std.get(EmbedIframeService);
blockId = embedIframeService.addEmbedIframeBlock(
{ url, caption, title, description },
parent.id,
index
);
}
if (!blockId) return;
ctx.store.deleteBlock(model);
// Selects new block
ctx.select('note', [
ctx.selection.create(BlockSelection, { blockId }),
]);
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'embed view',
});
},
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
const viewType$ = signal(actions[1].label);
const onToggle = createOnToggleFn(
ctx,
'OpenedViewSelector',
'switch view'
);
return html`${keyed(
model,
html`<affine-view-dropdown-menu
@toggle=${onToggle}
.actions=${actions}
.context=${ctx}
.viewTypeSignal=${viewType$}
></affine-view-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
{
id: 'c.style',
actions: [
{
id: 'horizontal',
label: 'Large horizontal style',
},
{
id: 'list',
label: 'Small horizontal style',
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({
...action,
run: ({ store }) => {
store.updateBlock(model, { style: action.id });
ctx.track('SelectedCardStyle', {
...trackBaseProps,
control: 'select card style',
type: action.id,
});
},
})) satisfies ToolbarAction[];
const onToggle = createOnToggleFn(
ctx,
'OpenedCardStyleSelector',
'switch card style'
);
return html`${keyed(
model,
html`<affine-card-style-dropdown-menu
@toggle=${onToggle}
.actions=${actions}
.context=${ctx}
.styleSignal=${model.props.style$}
></affine-card-style-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
captionAction,
{
placement: ActionPlacement.More,
id: 'a.clipboard',
actions: [
{
id: 'copy',
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
ctx.clipboard
.copySlice(slice)
.then(() => toast(ctx.host, 'Copied to clipboard'))
.catch(console.error);
},
},
{
id: 'duplicate',
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { flavour, parent } = model;
const props = getBlockProps(model);
const index = parent?.children.indexOf(model);
ctx.store.addBlock(flavour, props, parent, index);
},
},
],
},
{
placement: ActionPlacement.More,
id: 'b.refresh',
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const block = ctx.getCurrentBlockByType(BookmarkBlockComponent);
block?.refreshData();
},
},
{
placement: ActionPlacement.More,
id: 'c.delete',
label: 'Delete',
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
ctx.store.deleteBlock(model);
// Clears
ctx.select('note');
ctx.reset();
},
},
],
} as const satisfies ToolbarModuleConfig;
const builtinSurfaceToolbarConfig = {
actions: [
previewAction,
{
id: 'b.conversions',
actions: [
{
id: 'card',
label: 'Card view',
disabled: true,
},
{
id: 'embed',
label: 'Embed view',
run(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return;
const { id: oldId, xywh, parent } = model;
const { url, caption, title, description } = model.props;
let newId: string | undefined;
// first try to embed as a custom embed block
if (canEmbedAsEmbedBlock(ctx.std, url)) {
const options = ctx.std
.get(EmbedOptionProvider)
.getEmbedBlockOptions(url);
if (options?.viewType !== 'embed') return;
const { flavour, styles } = options;
let style: EmbedCardStyle = model.props.style;
if (!styles.includes(style)) {
style = styles[0];
}
const bound = Bound.deserialize(xywh);
bound.w = EMBED_CARD_WIDTH[style];
bound.h = EMBED_CARD_HEIGHT[style];
newId = ctx.store.addBlock(
flavour,
{
url,
caption,
title,
description,
style,
xywh: bound.serialize(),
},
parent
);
} else if (canEmbedAsIframe(ctx.std, url)) {
const embedIframeService = ctx.std.get(EmbedIframeService);
const config = embedIframeService.getConfig(url);
if (!config) {
return;
}
const bound = Bound.deserialize(xywh);
const options = config.options;
const { widthInSurface, heightInSurface } = options ?? {};
bound.w = widthInSurface ?? EMBED_IFRAME_DEFAULT_WIDTH_IN_SURFACE;
bound.h =
heightInSurface ?? EMBED_IFRAME_DEFAULT_HEIGHT_IN_SURFACE;
newId = ctx.store.addBlock(
'affine:embed-iframe',
{ url, caption, title, description, xywh: bound.serialize() },
parent
);
}
if (!newId) return;
ctx.command.exec(reassociateConnectorsCommand, { oldId, newId });
ctx.store.deleteBlock(model);
// Selects new block
ctx.gfx.selection.set({ editing: false, elements: [newId] });
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'embed view',
});
},
},
],
when(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return false;
const { url } = model.props;
return (
canEmbedAsIframe(ctx.std, url) || canEmbedAsEmbedBlock(ctx.std, url)
);
},
content(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
const viewType$ = signal('Card view');
const onToggle = createOnToggleFn(
ctx,
'OpenedViewSelector',
'switch view'
);
return html`${keyed(
model,
html`<affine-view-dropdown-menu
@toggle=${onToggle}
.actions=${actions}
.context=${ctx}
.viewTypeSignal=${viewType$}
></affine-view-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
{
id: 'b.style',
actions: (
[
{
id: 'horizontal',
label: 'Large horizontal style',
},
{
id: 'list',
label: 'Small horizontal style',
},
{
id: 'vertical',
label: 'Large vertical style',
},
{
id: 'cube',
label: 'Small vertical style',
},
] as const
).filter(action => BookmarkStyles.includes(action.id)),
content(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({
...action,
run: ({ store }) => {
const style = action.id as EmbedCardStyle;
const bounds = Bound.deserialize(model.xywh);
bounds.w = EMBED_CARD_WIDTH[style];
bounds.h = EMBED_CARD_HEIGHT[style];
const xywh = bounds.serialize();
store.updateBlock(model, { style, xywh });
ctx.track('SelectedCardStyle', {
...trackBaseProps,
control: 'select card style',
type: style,
});
},
})) satisfies ToolbarAction[];
const style$ = model.props.style$;
const onToggle = createOnToggleFn(
ctx,
'OpenedCardStyleSelector',
'switch card style'
);
return html`${keyed(
model,
html`<affine-card-style-dropdown-menu
@toggle=${onToggle}
.actions=${actions}
.context=${ctx}
.styleSignal=${style$}
></affine-card-style-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
{
...captionAction,
id: 'c.caption',
},
{
id: 'd.scale',
content(ctx) {
const model = ctx.getCurrentModelByType(BookmarkBlockModel);
if (!model) return null;
const scale$ = computed(() => {
const {
xywh$: { value: xywh },
} = model;
const {
style$: { value: style },
} = model.props;
const bounds = Bound.deserialize(xywh);
const height = EMBED_CARD_HEIGHT[style];
return Math.round(100 * (bounds.h / height));
});
const onSelect = (e: CustomEvent<number>) => {
e.stopPropagation();
const scale = e.detail / 100;
const bounds = Bound.deserialize(model.xywh);
const style = model.props.style;
bounds.w = EMBED_CARD_WIDTH[style] * scale;
bounds.h = EMBED_CARD_HEIGHT[style] * scale;
const xywh = bounds.serialize();
ctx.store.updateBlock(model, { xywh });
ctx.track('SelectedCardScale', {
...trackBaseProps,
control: 'select card scale',
});
};
const onToggle = createOnToggleFn(
ctx,
'OpenedCardScaleSelector',
'switch card scale'
);
const format = (value: number) => `${value}%`;
return html`${keyed(
model,
html`<affine-size-dropdown-menu
@select=${onSelect}
@toggle=${onToggle}
.format=${format}
.sizeSignal=${scale$}
></affine-size-dropdown-menu>`
)}`;
},
},
],
when: ctx => ctx.getSurfaceModelsByType(BookmarkBlockModel).length === 1,
} as const satisfies ToolbarModuleConfig;
export const createBuiltinToolbarConfigExtension = (
flavour: string
): ExtensionType[] => {
const name = flavour.split(':').pop();
return [
ToolbarModuleExtension({
id: BlockFlavourIdentifier(flavour),
config: builtinToolbarConfig,
}),
ToolbarModuleExtension({
id: BlockFlavourIdentifier(`affine:surface:${name}`),
config: builtinSurfaceToolbarConfig,
}),
];
};

View File

@@ -0,0 +1,13 @@
import { html } from 'lit';
// prettier-ignore
export const LinkTooltip = html`<svg width="170" height="68" viewBox="0 0 170 68" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="170" height="68" rx="2" fill="white"/>
<mask id="mask0_16460_1007" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="170" height="68">
<rect width="170" height="68" rx="2" fill="white"/>
</mask>
<g mask="url(#mask0_16460_1007)">
<text fill="#121212" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" letter-spacing="0px"><tspan x="8" y="15.6364">In a decentralized system, we can have a kaleidoscopic </tspan><tspan x="8" y="27.6364">complexity to our data.&#10;</tspan><tspan x="8" y="63.6364">Any user may have a different perspective on what data they </tspan><tspan x="8" y="75.6364">either have, choose to share, or accept.&#10;</tspan><tspan x="8" y="111.636">For example, one user&#x2019;s edits to a document might be on </tspan><tspan x="8" y="123.636">their laptop on an airplane; when the plane lands and the </tspan><tspan x="8" y="135.636">computer reconnects, those changes are distributed to </tspan><tspan x="8" y="147.636">other users.&#10;</tspan><tspan x="8" y="183.636">Other users might choose to accept all, some, or none of </tspan><tspan x="8" y="195.636">those changes to their version of the document.</tspan></text>
<text fill="#1E67AF" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="11" letter-spacing="0em"><tspan x="8" y="45.5">Learn about AFFiNE</tspan></text>
</g>
</svg>
`;

View File

@@ -0,0 +1,29 @@
import { EdgelessClipboardConfig } from '@blocksuite/affine-block-surface';
import { type BlockSnapshot } from '@blocksuite/store';
export class EdgelessClipboardBookmarkConfig extends EdgelessClipboardConfig {
static override readonly key = 'affine:bookmark';
override createBlock(bookmark: BlockSnapshot): string | null {
if (!this.surface) return null;
const { xywh, style, url, caption, description, icon, image, title } =
bookmark.props;
const bookmarkId = this.crud.addBlock(
'affine:bookmark',
{
xywh,
style,
url,
caption,
description,
icon,
image,
title,
},
this.surface.model.id
);
return bookmarkId;
}
}

View File

@@ -0,0 +1,12 @@
import { BookmarkBlockComponent } from './bookmark-block';
import { BookmarkEdgelessBlockComponent } from './bookmark-edgeless-block';
import { BookmarkCard } from './components/bookmark-card';
export function effects() {
customElements.define(
'affine-edgeless-bookmark',
BookmarkEdgelessBlockComponent
);
customElements.define('affine-bookmark', BookmarkBlockComponent);
customElements.define('bookmark-card', BookmarkCard);
}

View File

@@ -0,0 +1,6 @@
export * from './adapters';
export * from './bookmark-block';
export * from './commands';
export * from './components';
export { BookmarkSlashMenuConfigIdentifier } from './configs/slash-menu';
export * from './edgeless-clipboard-config';

View File

@@ -0,0 +1,17 @@
import {
type StoreExtensionContext,
StoreExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { BookmarkBlockSchemaExtension } from '@blocksuite/affine-model';
import { BookmarkBlockAdapterExtensions } from './adapters/extension';
export class BookmarkStoreExtension extends StoreExtensionProvider {
override name = 'affine-bookmark-block';
override setup(context: StoreExtensionContext) {
super.setup(context);
context.register(BookmarkBlockSchemaExtension);
context.register(BookmarkBlockAdapterExtensions);
}
}

View File

@@ -0,0 +1,283 @@
import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { baseTheme } from '@toeverything/theme';
import { css, unsafeCSS } from 'lit';
export const styles = css`
bookmark-card {
position: relative;
display: block;
height: 100%;
width: 100%;
}
.affine-bookmark-card {
container: affine-bookmark-card / inline-size;
margin: 0 auto;
box-sizing: border-box;
display: flex;
width: 100%;
border-radius: 8px;
border: 1px solid ${unsafeCSSVarV2('layer/background/tertiary')};
background: ${unsafeCSSVarV2('layer/background/primary')};
user-select: none;
}
.affine-bookmark-content {
width: calc(100% - 204px);
display: flex;
flex-direction: column;
flex-grow: 1;
align-self: stretch;
gap: 4px;
padding: 12px;
}
.affine-bookmark-content-title {
display: flex;
flex-direction: row;
gap: 8px;
align-items: center;
align-self: stretch;
}
.affine-bookmark-content-title-icon {
display: flex;
width: 16px;
height: 16px;
justify-content: center;
align-items: center;
}
.affine-bookmark-content-title-icon img,
.affine-bookmark-content-title-icon object,
.affine-bookmark-content-title-icon svg {
width: 16px;
height: 16px;
fill: var(--affine-background-primary-color);
}
.affine-bookmark-content-title-text {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
word-break: break-word;
overflow: hidden;
text-overflow: ellipsis;
color: var(--affine-text-primary-color);
font-family: var(--affine-font-family);
font-size: var(--affine-font-sm);
font-style: normal;
font-weight: 600;
line-height: 22px;
}
.affine-bookmark-content-description {
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
flex-grow: 1;
white-space: normal;
word-break: break-word;
overflow: hidden;
text-overflow: ellipsis;
color: var(--affine-text-primary-color);
font-family: var(--affine-font-family);
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 400;
line-height: 20px;
}
.affine-bookmark-content-url {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 4px;
width: max-content;
max-width: 100%;
}
.affine-bookmark-content-url > span {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
word-break: break-all;
white-space: normal;
overflow: hidden;
text-overflow: ellipsis;
color: var(--affine-text-secondary-color);
font-family: ${unsafeCSS(baseTheme.fontSansFamily)};
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 400;
line-height: 20px;
}
.affine-bookmark-content-url:hover > span {
color: var(--affine-link-color);
}
.affine-bookmark-content-url:hover {
fill: var(--affine-link-color);
}
.affine-bookmark-content-url-icon {
display: flex;
align-items: center;
justify-content: center;
width: 12px;
height: 20px;
}
.affine-bookmark-content-url-icon {
height: 12px;
width: 12px;
color: ${unsafeCSSVar('iconSecondary')};
}
.affine-bookmark-banner {
margin: 12px 12px 0px 0px;
width: 204px;
max-width: 100%;
height: 102px;
}
.affine-bookmark-banner img,
.affine-bookmark-banner object,
.affine-bookmark-banner svg {
width: 204px;
max-width: 100%;
height: 102px;
object-fit: cover;
border-radius: 4px;
}
.affine-bookmark-card.comment-highlighted {
outline: 2px solid ${unsafeCSSVarV2('block/comment/highlightUnderline')};
}
.affine-bookmark-card.loading {
.affine-bookmark-content-title-text {
color: var(--affine-placeholder-color);
}
}
.affine-bookmark-card.error {
.affine-bookmark-content-description {
color: var(--affine-placeholder-color);
}
}
.affine-bookmark-card.selected {
.affine-bookmark-content-url > span {
color: var(--affine-link-color);
}
.affine-bookmark-content-url .affine-bookmark-content-url-icon {
color: var(--affine-link-color);
}
}
.affine-bookmark-card.list {
.affine-bookmark-content {
width: 100%;
flex-direction: row;
align-items: center;
justify-content: space-between;
}
.affine-bookmark-content-title {
width: calc(100% - 204px);
}
.affine-bookmark-content-url {
width: 204px;
justify-content: flex-end;
}
.affine-bookmark-content-description {
display: none;
}
.affine-bookmark-banner {
display: none;
}
}
.affine-bookmark-card.vertical {
flex-direction: column-reverse;
height: 100%;
.affine-bookmark-content {
width: 100%;
}
.affine-bookmark-content-description {
-webkit-line-clamp: 6;
max-height: 120px;
}
.affine-bookmark-content-url-wrapper {
max-width: fit-content;
display: flex;
align-items: flex-end;
flex-grow: 1;
cursor: pointer;
}
.affine-bookmark-banner {
width: 340px;
height: 170px;
margin-left: 12px;
}
.affine-bookmark-banner img,
.affine-bookmark-banner object,
.affine-bookmark-banner svg {
width: 340px;
height: 170px;
}
}
.affine-bookmark-card.cube {
.affine-bookmark-content {
width: 100%;
flex-direction: column;
align-items: flex-start;
justify-content: space-between;
}
.affine-bookmark-content-title {
flex-direction: column;
gap: 4px;
align-items: flex-start;
}
.affine-bookmark-content-title-text {
-webkit-line-clamp: 2;
}
.affine-bookmark-content-description {
display: none;
}
.affine-bookmark-banner {
display: none;
}
}
@container affine-bookmark-card (width < 375px) {
.affine-bookmark-content {
width: 100%;
}
.affine-bookmark-card:not(.edgeless) .affine-bookmark-banner {
display: none;
}
}
`;

View File

@@ -0,0 +1,47 @@
import { LinkPreviewServiceIdentifier } from '@blocksuite/affine-shared/services';
import { isAbortError } from '@blocksuite/affine-shared/utils';
import type { BookmarkBlockComponent } from './bookmark-block.js';
export async function refreshBookmarkUrlData(
bookmarkElement: BookmarkBlockComponent,
signal?: AbortSignal
) {
let title = null,
description = null,
icon = null,
image = null;
try {
bookmarkElement.loading = true;
const linkPreviewer = bookmarkElement.std.get(LinkPreviewServiceIdentifier);
const bookmarkUrlData = await linkPreviewer.query(
bookmarkElement.model.props.url,
signal
);
title = bookmarkUrlData.title ?? null;
description = bookmarkUrlData.description ?? null;
icon = bookmarkUrlData.icon ?? null;
image = bookmarkUrlData.image ?? null;
if (!title && !description && !icon && !image) {
bookmarkElement.error = true;
}
if (signal?.aborted) return;
bookmarkElement.store.updateBlock(bookmarkElement.model, {
title,
description,
icon,
image,
});
} catch (error) {
if (signal?.aborted || isAbortError(error)) return;
throw error;
} finally {
bookmarkElement.loading = false;
}
}

View File

@@ -0,0 +1,43 @@
import {
type ViewExtensionContext,
ViewExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { BookmarkBlockSchema } from '@blocksuite/affine-model';
import { BlockViewExtension, FlavourExtension } from '@blocksuite/std';
import { literal } from 'lit/static-html.js';
import { BookmarkBlockInteraction } from './bookmark-edgeless-block';
import { BookmarkSlashMenuConfigExtension } from './configs/slash-menu';
import { createBuiltinToolbarConfigExtension } from './configs/toolbar';
import { EdgelessClipboardBookmarkConfig } from './edgeless-clipboard-config';
import { effects } from './effects';
const flavour = BookmarkBlockSchema.model.flavour;
export class BookmarkViewExtension extends ViewExtensionProvider {
override name = 'affine-bookmark-block';
override effect() {
super.effect();
effects();
}
override setup(context: ViewExtensionContext) {
super.setup(context);
context.register([
FlavourExtension(flavour),
BlockViewExtension(flavour, model => {
return model.parent?.flavour === 'affine:surface'
? literal`affine-edgeless-bookmark`
: literal`affine-bookmark`;
}),
BookmarkSlashMenuConfigExtension,
]);
context.register(createBuiltinToolbarConfigExtension(flavour));
const isEdgeless = this.isEdgeless(context.scope);
if (isEdgeless) {
context.register(EdgelessClipboardBookmarkConfig);
context.register(BookmarkBlockInteraction);
}
}
}

View File

@@ -0,0 +1,22 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo"
},
"include": ["./src"],
"references": [
{ "path": "../embed" },
{ "path": "../embed-doc" },
{ "path": "../surface" },
{ "path": "../../components" },
{ "path": "../../ext-loader" },
{ "path": "../../model" },
{ "path": "../../shared" },
{ "path": "../../widgets/slash-menu" },
{ "path": "../../../framework/global" },
{ "path": "../../../framework/std" },
{ "path": "../../../framework/store" }
]
}

View File

@@ -0,0 +1,25 @@
import { playwright } from '@vitest/browser-playwright';
import { defineConfig } from 'vitest/config';
export default defineConfig({
esbuild: {
target: 'es2018',
},
test: {
browser: {
enabled: true,
headless: true,
instances: [{ browser: 'chromium' }],
provider: playwright(),
isolate: false,
},
include: ['src/__tests__/**/*.unit.spec.ts'],
testTimeout: 500,
coverage: {
provider: 'istanbul',
reporter: ['lcov'],
reportsDirectory: '../../../.coverage/bookmark',
},
restoreMocks: true,
},
});

View File

@@ -0,0 +1,40 @@
{
"name": "@blocksuite/affine-block-callout",
"description": "Callout block for BlockSuite.",
"type": "module",
"scripts": {
"build": "yarn run -T tsc"
},
"sideEffects": false,
"keywords": [],
"author": "toeverything",
"license": "MIT",
"dependencies": {
"@blocksuite/affine-components": "workspace:*",
"@blocksuite/affine-ext-loader": "workspace:*",
"@blocksuite/affine-inline-preset": "workspace:*",
"@blocksuite/affine-model": "workspace:*",
"@blocksuite/affine-rich-text": "workspace:*",
"@blocksuite/affine-shared": "workspace:*",
"@blocksuite/affine-widget-slash-menu": "workspace:*",
"@blocksuite/icons": "^2.2.17",
"@blocksuite/std": "workspace:*",
"@blocksuite/store": "workspace:*",
"@emotion/css": "^11.13.5",
"@preact/signals-core": "^1.8.0",
"@toeverything/theme": "^1.1.23",
"lit": "^3.2.0"
},
"exports": {
".": "./src/index.ts",
"./view": "./src/view.ts",
"./store": "./src/store.ts"
},
"files": [
"src",
"dist",
"!src/__tests__",
"!dist/__tests__"
],
"version": "0.27.5"
}

View File

@@ -0,0 +1,207 @@
import { CalloutBlockSchema } from '@blocksuite/affine-model';
import {
BlockMarkdownAdapterExtension,
type BlockMarkdownAdapterMatcher,
CALLOUT_MARKDOWN_EXPORT_OPTIONS_KEY,
type CalloutAdmonitionType,
CalloutAdmonitionTypeSet,
CalloutExportStyle,
type CalloutMarkdownExportOptions,
calloutMarkdownExportOptionsSchema,
DEFAULT_ADMONITION_TYPE,
getCalloutEmoji,
isCalloutNode,
} from '@blocksuite/affine-shared/adapters';
import { type DeltaInsert, nanoid } from '@blocksuite/store';
// Currently, the callout block children can only be paragraph block or list block
// In mdast, the node types are `paragraph`, `list`, `heading`, `blockquote`
const CALLOUT_BLOCK_CHILDREN_TYPES = new Set([
'paragraph',
'list',
'heading',
'blockquote',
]);
const ADMONITION_SYMBOL = ':::';
const DEFAULT_OPTIONS: CalloutMarkdownExportOptions = {
style: CalloutExportStyle.GFM,
};
/**
* Get the callout export options from the configs
* @param configs - The configs of the callout block
* @returns The callout export options
*/
function getCalloutExportOptions(
configs: Map<string, unknown>
): CalloutMarkdownExportOptions {
let exportOptions: CalloutMarkdownExportOptions = DEFAULT_OPTIONS;
try {
const options = configs.get(CALLOUT_MARKDOWN_EXPORT_OPTIONS_KEY);
if (options) {
exportOptions = calloutMarkdownExportOptionsSchema.parse(options);
}
} catch {}
return exportOptions;
}
export const calloutBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher = {
flavour: CalloutBlockSchema.model.flavour,
toMatch: o => isCalloutNode(o.node),
fromMatch: o => o.node.flavour === CalloutBlockSchema.model.flavour,
toBlockSnapshot: {
enter: (o, context) => {
if (!o.node.data || !isCalloutNode(o.node)) {
return;
}
// Currently, the callout block children can only be a paragraph or a list
// So we should filter out the other children
o.node.children = o.node.children.filter(child =>
CALLOUT_BLOCK_CHILDREN_TYPES.has(child.type)
);
const { walkerContext } = context;
const calloutEmoji = getCalloutEmoji(o.node);
walkerContext.openNode(
{
type: 'block',
id: nanoid(),
flavour: CalloutBlockSchema.model.flavour,
props: {
emoji: calloutEmoji,
},
children: [],
},
'children'
);
},
leave: (o, context) => {
const { walkerContext } = context;
if (isCalloutNode(o.node)) {
walkerContext.closeNode();
}
},
},
fromBlockSnapshot: {
enter: (o, context) => {
const emoji = o.node.props.emoji as string;
const { walkerContext, configs } = context;
const exportOptions = getCalloutExportOptions(configs);
const { style, admonitionType } = exportOptions;
// If the style is admonitions, we should handle the first child
if (style === CalloutExportStyle.Admonitions) {
let type = admonitionType ?? DEFAULT_ADMONITION_TYPE;
let customTitle = '';
let restOfText = '';
const firstChild = o.node.children[0];
const isTextNode = !!firstChild.props.text;
// If the first child is a text block, we should get the type and custom title from the first line of the text
// And remove the first child from the children
// Otherwise, we should use the default admonition type as the type
if (isTextNode) {
const textDelta = (firstChild.props.text ?? { delta: [] }) as {
delta: DeltaInsert[];
};
// Get the text of the first child
const text = textDelta.delta.reduce((acc, delta) => {
if (delta.insert) {
acc += delta.insert;
}
return acc;
}, '');
// If the text is not empty, we should try to get type and custom title from the text
if (text) {
// Get the first line of the text
const firstLine = text.includes('\n') ? text.split('\n')[0] : text;
// Get the rest of the text besides the first line
restOfText = text.split('\n').slice(1).join('\n');
// Get the possible type from the first line
const possibleType = firstLine.split(' ')[0].toLowerCase();
// If the type is a valid admonition type, we should use it as the type
if (CalloutAdmonitionTypeSet.has(possibleType)) {
type = possibleType as CalloutAdmonitionType;
// Get the custom title from the first line
customTitle = firstLine.split(' ').slice(1).join(' ').trim();
// Remove the first child from the children
o.node.children = o.node.children.slice(1);
}
}
}
// Add an admonition symbol paragraph to the start of the children
const admonitionSymbol =
`${ADMONITION_SYMBOL} ${type} ${customTitle}`.trim();
walkerContext
.openNode({
type: 'paragraph',
children: [
{
type: 'text',
value: admonitionSymbol,
},
],
})
.closeNode();
// Add the rest of the text to the children content
if (restOfText) {
walkerContext
.openNode({
type: 'paragraph',
children: [{ type: 'text', value: `${restOfText}` }],
})
.closeNode();
}
} else {
walkerContext
.openNode(
{
type: 'blockquote',
children: [],
},
'children'
)
.openNode({
type: 'paragraph',
children: [
{
type: 'text',
value: `[!${emoji}]`,
},
],
})
.closeNode();
}
},
leave: (_, context) => {
const { walkerContext, configs } = context;
const exportOptions = getCalloutExportOptions(configs);
const { style } = exportOptions;
// If the style is admonitions, we should add an admonition symbol paragraph to the end of the children
if (style === CalloutExportStyle.Admonitions) {
walkerContext
.openNode({
type: 'paragraph',
children: [
{
type: 'text',
value: ADMONITION_SYMBOL,
},
],
})
.closeNode();
} else {
// If the style is gfm, we should close the outer blockquote node
walkerContext.closeNode();
}
},
},
};
export const CalloutBlockMarkdownAdapterExtension =
BlockMarkdownAdapterExtension(calloutBlockMarkdownAdapterMatcher);

View File

@@ -0,0 +1,56 @@
import { css } from '@emotion/css';
export const calloutHostStyles = css({
display: 'block',
margin: '8px 0',
});
export const calloutBlockContainerStyles = css({
display: 'flex',
alignItems: 'flex-start',
padding: '5px 10px',
borderRadius: '8px',
});
export const calloutEmojiContainerStyles = css({
userSelect: 'none',
fontSize: '1.2em',
width: '24px',
height: '24px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
// marginTop is dynamically set by JavaScript based on first child's height
marginBottom: '10px',
flexShrink: 0,
position: 'relative',
});
export const calloutEmojiStyles = css({
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
':hover': {
cursor: 'pointer',
opacity: 0.7,
},
});
export const calloutChildrenStyles = css({
flex: 1,
minWidth: 0,
paddingLeft: '10px',
});
export const iconPickerContainerStyles = css({
position: 'absolute',
top: '100%',
left: 0,
zIndex: 1000,
background: 'white',
border: '1px solid #ccc',
borderRadius: '8px',
boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
width: '390px',
height: '400px',
});

View File

@@ -0,0 +1,263 @@
import { CaptionedBlockComponent } from '@blocksuite/affine-components/caption';
import {
createPopup,
popupTargetFromElement,
} from '@blocksuite/affine-components/context-menu';
import { DefaultInlineManagerExtension } from '@blocksuite/affine-inline-preset';
import {
type CalloutBlockModel,
type ParagraphBlockModel,
} from '@blocksuite/affine-model';
import { focusTextModel } from '@blocksuite/affine-rich-text';
import { EDGELESS_TOP_CONTENTEDITABLE_SELECTOR } from '@blocksuite/affine-shared/consts';
import {
DocModeProvider,
type IconData,
IconPickerServiceIdentifier,
IconType,
} from '@blocksuite/affine-shared/services';
import type { UniComponent } from '@blocksuite/affine-shared/types';
import * as icons from '@blocksuite/icons/lit';
import type { BlockComponent } from '@blocksuite/std';
import { type Signal } from '@preact/signals-core';
import { cssVarV2 } from '@toeverything/theme/v2';
import type { TemplateResult } from 'lit';
import { html } from 'lit';
import { type StyleInfo, styleMap } from 'lit/directives/style-map.js';
import {
calloutBlockContainerStyles,
calloutChildrenStyles,
calloutEmojiContainerStyles,
calloutEmojiStyles,
calloutHostStyles,
} from './callout-block-styles.js';
import { IconPickerWrapper } from './icon-picker-wrapper.js';
// Copy of renderUniLit and UniLit from affine-data-view
export const renderUniLit = <Props, Expose extends NonNullable<unknown>>(
uni: UniComponent<Props, Expose> | undefined,
props?: Props,
options?: {
ref?: Signal<Expose | undefined>;
style?: Readonly<StyleInfo>;
class?: string;
}
): TemplateResult => {
return html` <uni-lit
.uni="${uni}"
.props="${props}"
.ref="${options?.ref}"
style=${options?.style ? styleMap(options?.style) : ''}
></uni-lit>`;
};
const getIcon = (icon?: IconData) => {
if (!icon) {
return null;
}
if (icon.type === IconType.Emoji) {
return icon.unicode;
}
if (icon.type === IconType.AffineIcon) {
return (
icons as Record<string, (props: { style: string }) => TemplateResult>
)[`${icon.name}Icon`]?.({ style: `color:${icon.color}` });
}
return null;
};
export class CalloutBlockComponent extends CaptionedBlockComponent<CalloutBlockModel> {
private _popupCloseHandler: (() => void) | null = null;
override connectedCallback() {
super.connectedCallback();
this.classList.add(calloutHostStyles);
}
private _getEmojiMarginTop(): string {
if (this.model.children.length === 0) {
return '10px';
}
const firstChild = this.model.children[0];
const flavour = firstChild.flavour;
const marginTopMap: Record<string, string> = {
'affine:paragraph:h1': '23px',
'affine:paragraph:h2': '20px',
'affine:paragraph:h3': '16px',
'affine:paragraph:h4': '15px',
'affine:paragraph:h5': '14px',
'affine:paragraph:h6': '13px',
};
// For heading blocks, use the type to determine margin
if (flavour === 'affine:paragraph') {
const paragraph = firstChild as ParagraphBlockModel;
const type = paragraph.props.type$.value;
const key = `${flavour}:${type}`;
return marginTopMap[key] || '10px';
}
// Default for all other block types
return '10px';
}
private _closeIconPicker() {
if (this._popupCloseHandler) {
this._popupCloseHandler();
this._popupCloseHandler = null;
}
}
private _toggleIconPicker(event: MouseEvent) {
// If popup is already open, close it
if (this._popupCloseHandler) {
this._closeIconPicker();
return;
}
// Get IconPickerService from the framework
const iconPickerService = this.std.getOptional(IconPickerServiceIdentifier);
if (!iconPickerService) {
console.warn('IconPickerService not found');
return;
}
// Get the uni-component from the service
const iconPickerComponent = iconPickerService.iconPickerComponent;
// Create props for the icon picker
const props = {
onSelect: (iconData?: IconData) => {
this.model.props.icon$.value = iconData;
this._closeIconPicker(); // Close the picker after selection
},
onClose: () => {
this._closeIconPicker();
},
};
// Create IconPickerWrapper instance
const wrapper = new IconPickerWrapper();
wrapper.iconPickerComponent = iconPickerComponent;
wrapper.props = props;
wrapper.style.position = 'absolute';
wrapper.style.backgroundColor = cssVarV2.layer.background.overlayPanel;
wrapper.style.boxShadow = 'var(--affine-menu-shadow)';
wrapper.style.borderRadius = '8px';
// Create popup target from the clicked element
const target = popupTargetFromElement(event.currentTarget as HTMLElement);
// Create popup
this._popupCloseHandler = createPopup(target, wrapper, {
onClose: () => {
this._popupCloseHandler = null;
},
});
}
private readonly _handleBlockClick = (event: MouseEvent) => {
// Check if the click target is emoji related element
const target = event.target as HTMLElement;
if (
target.closest('.affine-callout-emoji-container') ||
target.classList.contains('affine-callout-emoji')
) {
return;
}
// If there's no icon, open icon picker on click
const icon = this.model.props.icon$.value;
if (!icon) {
this._toggleIconPicker(event);
return;
}
// Only handle clicks when there are no children
if (this.model.children.length > 0) {
return;
}
// Prevent event bubbling
event.stopPropagation();
// Create a new paragraph block
const paragraphId = this.store.addBlock('affine:paragraph', {}, this.model);
// Focus the new paragraph
focusTextModel(this.std, paragraphId);
};
get attributeRenderer() {
return this.inlineManager.getRenderer();
}
get attributesSchema() {
return this.inlineManager.getSchema();
}
get embedChecker() {
return this.inlineManager.embedChecker;
}
get inlineManager() {
return this.std.get(DefaultInlineManagerExtension.identifier);
}
override get topContenteditableElement() {
if (this.std.get(DocModeProvider).getEditorMode() === 'edgeless') {
return this.closest<BlockComponent>(
EDGELESS_TOP_CONTENTEDITABLE_SELECTOR
);
}
return this.rootComponent;
}
override renderBlock() {
const icon = this.model.props.icon$.value;
const backgroundColorName = this.model.props.backgroundColorName$.value;
const normalizedBackgroundName =
backgroundColorName === 'default' || backgroundColorName === ''
? 'grey'
: backgroundColorName;
const backgroundColor = (
cssVarV2.block.callout.background as Record<string, string>
)[normalizedBackgroundName ?? 'grey'];
const iconContent = getIcon(icon);
return html`
<div
class="${calloutBlockContainerStyles}"
@click=${this._handleBlockClick}
style=${styleMap({
backgroundColor: backgroundColor ?? 'transparent',
})}
>
${
iconContent
? html`
<div
@click=${this._toggleIconPicker}
contenteditable="false"
class="${calloutEmojiContainerStyles}"
style=${styleMap({
marginTop: this._getEmojiMarginTop(),
})}
>
<span
class="${calloutEmojiStyles}"
data-testid="callout-emoji"
>${iconContent}</span
>
</div>
`
: ''
}
<div class="${calloutChildrenStyles}">
${this.renderChildren(this.model)}
</div>
</div>
`;
}
}

View File

@@ -0,0 +1,86 @@
import {
CalloutBlockModel,
ParagraphBlockModel,
} from '@blocksuite/affine-model';
import { matchModels } from '@blocksuite/affine-shared/utils';
import {
BlockSelection,
KeymapExtension,
TextSelection,
} from '@blocksuite/std';
import { calloutToParagraphCommand } from './commands/callout-to-paragraph.js';
import { splitCalloutCommand } from './commands/split-callout.js';
export const CalloutKeymapExtension = KeymapExtension(std => {
return {
Enter: ctx => {
const text = std.selection.find(TextSelection);
if (!text) return false;
const currentBlock = std.store.getBlock(text.from.blockId);
if (!currentBlock) return false;
// Check if current block is a callout block
let calloutBlock = currentBlock;
if (!matchModels(currentBlock.model, [CalloutBlockModel])) {
// If not, check if the parent is a callout block
const parent = std.store.getParent(currentBlock.model);
if (!parent || !matchModels(parent, [CalloutBlockModel])) {
return false;
}
const parentBlock = std.store.getBlock(parent.id);
if (!parentBlock) return false;
calloutBlock = parentBlock;
}
ctx.get('keyboardState').raw.preventDefault();
std.command
.chain()
.pipe(splitCalloutCommand, {
blockId: calloutBlock.model.id,
inlineIndex: text.from.index,
currentBlockId: text.from.blockId,
})
.run();
return true;
},
Backspace: ctx => {
const text = std.selection.find(TextSelection);
if (text && text.isCollapsed() && text.from.index === 0) {
const event = ctx.get('defaultState').event;
const block = std.store.getBlock(text.from.blockId);
if (!block) return false;
const parent = std.store.getParent(block.model);
if (!parent) return false;
if (!matchModels(parent, [CalloutBlockModel])) return false;
// Check if current block is a paragraph inside callout
if (matchModels(block.model, [ParagraphBlockModel])) {
event.preventDefault();
std.command
.chain()
.pipe(calloutToParagraphCommand, {
id: block.model.id,
})
.run();
return true;
}
// Fallback to selecting the callout block
event.preventDefault();
std.selection.setGroup('note', [
std.selection.create(BlockSelection, {
blockId: parent.id,
}),
]);
return true;
}
return false;
},
};
});

View File

@@ -0,0 +1,86 @@
import {
CalloutBlockModel,
ParagraphBlockModel,
} from '@blocksuite/affine-model';
import { focusTextModel } from '@blocksuite/affine-rich-text';
import { matchModels } from '@blocksuite/affine-shared/utils';
import type { Command } from '@blocksuite/std';
import { BlockSelection } from '@blocksuite/std';
import { Text } from '@blocksuite/store';
export const calloutToParagraphCommand: Command<
{
id: string;
stopCapturing?: boolean;
},
{
success: boolean;
}
> = (ctx, next) => {
const { id, stopCapturing = true } = ctx;
const std = ctx.std;
const doc = std.store;
const model = doc.getBlock(id)?.model;
if (!model || !matchModels(model, [ParagraphBlockModel])) return false;
const parent = doc.getParent(model);
if (!parent || !matchModels(parent, [CalloutBlockModel])) return false;
if (stopCapturing) std.store.captureSync();
// Get current block index in callout
const currentIndex = parent.children.indexOf(model);
const hasText = model.text && model.text.length > 0;
// Find previous paragraph block in callout
let previousBlock = null;
for (let i = currentIndex - 1; i >= 0; i--) {
const sibling = parent.children[i];
if (matchModels(sibling, [ParagraphBlockModel])) {
previousBlock = sibling;
break;
}
}
if (previousBlock && hasText) {
// Clone current text content before any operations to prevent data loss
const currentText = model.text || new Text();
// Get previous block text and merge index
const previousText = previousBlock.text || new Text();
const mergeIndex = previousText.length;
// Apply each delta from cloned current text to previous block to preserve formatting
previousText.join(currentText);
// Remove current block after text has been merged
doc.deleteBlock(model, {
deleteChildren: false,
});
// Focus at merge point in previous block
focusTextModel(std, previousBlock.id, mergeIndex);
} else if (previousBlock && !hasText) {
// Move cursor to end of previous block
doc.deleteBlock(model, {
deleteChildren: false,
});
const previousText = previousBlock.text || new Text();
focusTextModel(std, previousBlock.id, previousText.length);
} else {
// No previous block, select the entire callout
doc.deleteBlock(model, {
deleteChildren: false,
});
std.selection.setGroup('note', [
std.selection.create(BlockSelection, {
blockId: parent.id,
}),
]);
}
return next({ success: true });
};

View File

@@ -0,0 +1,85 @@
import {
CalloutBlockModel,
ParagraphBlockModel,
} from '@blocksuite/affine-model';
import { focusTextModel } from '@blocksuite/affine-rich-text';
import { matchModels } from '@blocksuite/affine-shared/utils';
import type { Command, EditorHost } from '@blocksuite/std';
export const splitCalloutCommand: Command<{
blockId: string;
inlineIndex: number;
currentBlockId: string;
}> = (ctx, next) => {
const { blockId, inlineIndex, currentBlockId, std } = ctx;
const host = std.host as EditorHost;
const doc = host.store;
const calloutModel = doc.getBlock(blockId)?.model;
if (!calloutModel || !matchModels(calloutModel, [CalloutBlockModel])) {
console.error(`block ${blockId} is not a callout block`);
return;
}
const currentModel = doc.getBlock(currentBlockId)?.model;
if (!currentModel) {
console.error(`current block ${currentBlockId} not found`);
return;
}
doc.captureSync();
if (matchModels(currentModel, [ParagraphBlockModel])) {
// User is in a paragraph within the callout's children
const afterText = currentModel.props.text.split(inlineIndex);
// Update the current paragraph's text to keep only the part before cursor
doc.transact(() => {
currentModel.props.text.delete(
inlineIndex,
currentModel.props.text.length - inlineIndex
);
});
// Create a new paragraph block after the current one
const parent = doc.getParent(currentModel);
if (parent) {
const currentIndex = parent.children.indexOf(currentModel);
const newParagraphId = doc.addBlock(
'affine:paragraph',
{
text: afterText,
},
parent,
currentIndex + 1
);
if (newParagraphId) {
host.updateComplete
.then(() => {
focusTextModel(std, newParagraphId);
})
.catch(console.error);
}
}
} else {
// If current block is not a paragraph, create a new paragraph in callout
const newParagraphId = doc.addBlock(
'affine:paragraph',
{
text: new Text(),
},
calloutModel
);
if (newParagraphId) {
host.updateComplete
.then(() => {
focusTextModel(std, newParagraphId);
})
.catch(console.error);
}
}
next();
};

View File

@@ -0,0 +1,55 @@
import { focusBlockEnd } from '@blocksuite/affine-shared/commands';
import { isInsideBlockByFlavour } from '@blocksuite/affine-shared/utils';
import { type SlashMenuConfig } from '@blocksuite/affine-widget-slash-menu';
import { FontIcon } from '@blocksuite/icons/lit';
import { calloutTooltip } from './tooltips';
export const calloutSlashMenuConfig: SlashMenuConfig = {
items: [
{
name: 'Callout',
description: 'Let your words stand out.',
icon: FontIcon(),
tooltip: {
figure: calloutTooltip,
caption: 'Callout',
},
searchAlias: ['callout'],
group: '0_Basic@9',
when: ({ model }) => {
return !isInsideBlockByFlavour(
model.store,
model,
'affine:edgeless-text'
);
},
action: ({ model, std }) => {
const { store } = model;
const parent = store.getParent(model);
if (!parent) return;
const index = parent.children.indexOf(model);
if (index === -1) return;
const calloutId = store.addBlock(
'affine:callout',
{},
parent,
index + 1
);
if (!calloutId) return;
const paragraphId = store.addBlock('affine:paragraph', {}, calloutId);
if (!paragraphId) return;
std.host.updateComplete
.then(() => {
const paragraph = std.view.getBlock(paragraphId);
if (!paragraph) return;
std.command.exec(focusBlockEnd, {
focusBlock: paragraph,
});
})
.catch(console.error);
},
},
],
};

View File

@@ -0,0 +1,204 @@
import {
createPopup,
popupTargetFromElement,
} from '@blocksuite/affine-components/context-menu';
import { EditorChevronDown } from '@blocksuite/affine-components/toolbar';
import { CalloutBlockModel } from '@blocksuite/affine-model';
import {
ActionPlacement,
type IconData,
IconPickerServiceIdentifier,
type ToolbarAction,
type ToolbarActionGroup,
type ToolbarModuleConfig,
ToolbarModuleExtension,
} from '@blocksuite/affine-shared/services';
import { DeleteIcon, PaletteIcon, SmileIcon } from '@blocksuite/icons/lit';
import { BlockFlavourIdentifier } from '@blocksuite/std';
import type { ExtensionType } from '@blocksuite/store';
import { cssVarV2 } from '@toeverything/theme/v2';
import { html } from 'lit';
import { repeat } from 'lit/directives/repeat.js';
import { styleMap } from 'lit/directives/style-map.js';
import { IconPickerWrapper } from '../icon-picker-wrapper.js';
const colors = [
'default',
'red',
'orange',
'yellow',
'green',
'teal',
'blue',
'purple',
'grey',
] as const;
const backgroundColorAction = {
id: 'background-color',
label: 'Background Color',
tooltip: 'Change background color',
icon: PaletteIcon(),
run() {
// This will be handled by the content function
},
content(ctx) {
const model = ctx.getCurrentModelByType(CalloutBlockModel);
if (!model) return null;
const updateBackground = (color: string) => {
ctx.store.updateBlock(model, { backgroundColorName: color });
};
return html`
<editor-menu-button
.contentPadding=${'8px'}
.button=${html`
<editor-icon-button
aria-label="background"
.tooltip=${'Background Color'}
>
${PaletteIcon()} ${EditorChevronDown}
</editor-icon-button>
`}
>
<div data-size="large" data-orientation="vertical">
<div class="highlight-heading">Background</div>
${repeat(colors, color => {
const isDefault = color === 'default';
const value = isDefault
? cssVarV2.block.callout.background.grey
: `var(--affine-text-highlight-${color})`;
const displayName = `${color} Background`;
return html`
<editor-menu-action
data-testid="background-${color}"
@click=${() => updateBackground(isDefault ? 'grey' : color)}
>
<affine-text-duotone-icon
style=${styleMap({
'--color': 'var(--affine-text-primary-color)',
'--background': value ?? 'transparent',
})}
></affine-text-duotone-icon>
<span class="label capitalize">${displayName}</span>
</editor-menu-action>
`;
})}
</div>
</editor-menu-button>
`;
},
} satisfies ToolbarAction;
const iconPickerAction = {
id: 'icon-picker',
label: 'Icon Picker',
tooltip: 'Change icon',
icon: SmileIcon(),
run() {
// This will be handled by the content function
},
content(ctx) {
const model = ctx.getCurrentModelByType(CalloutBlockModel);
if (!model) return null;
const handleIconPickerClick = (event: MouseEvent) => {
// Get IconPickerService from the framework
const iconPickerService = ctx.std.getOptional(
IconPickerServiceIdentifier
);
if (!iconPickerService) {
console.warn('IconPickerService not found');
return;
}
// Get the uni-component from the service
const iconPickerComponent = iconPickerService.iconPickerComponent;
// Create props for the icon picker
const props = {
onSelect: (iconData?: IconData) => {
// When iconData is undefined (delete icon), set icon to undefined
ctx.store.updateBlock(model, { icon: iconData });
closeHandler(); // Close the picker after selection
},
onClose: () => {
closeHandler();
},
};
// Create IconPickerWrapper instance
const wrapper = new IconPickerWrapper();
wrapper.iconPickerComponent = iconPickerComponent;
wrapper.props = props;
wrapper.style.position = 'absolute';
wrapper.style.backgroundColor = cssVarV2.layer.background.overlayPanel;
wrapper.style.boxShadow = 'var(--affine-menu-shadow)';
wrapper.style.borderRadius = '8px';
// Create popup target from the clicked element
const target = popupTargetFromElement(event.currentTarget as HTMLElement);
// Create popup
const closeHandler = createPopup(target, wrapper, {
onClose: () => {
// Cleanup if needed
},
});
};
return html`
<editor-icon-button
aria-label="icon-picker"
.tooltip=${'Change Icon'}
@click=${handleIconPickerClick}
>
${SmileIcon()} ${EditorChevronDown}
</editor-icon-button>
`;
},
} satisfies ToolbarAction;
const builtinToolbarConfig = {
actions: [
{
id: 'style',
actions: [backgroundColorAction],
} satisfies ToolbarActionGroup<ToolbarAction>,
{
id: 'icon',
actions: [iconPickerAction],
} satisfies ToolbarActionGroup<ToolbarAction>,
{
placement: ActionPlacement.More,
id: 'c.delete',
label: 'Delete',
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelByType(CalloutBlockModel);
if (!model) return;
ctx.store.deleteBlock(model);
// Clears
ctx.select('note');
ctx.reset();
},
} satisfies ToolbarAction,
],
} as const satisfies ToolbarModuleConfig;
export const createBuiltinToolbarConfigExtension = (
flavour: string
): ExtensionType[] => {
return [
ToolbarModuleExtension({
id: BlockFlavourIdentifier(flavour),
config: builtinToolbarConfig,
}),
];
};

View File

@@ -0,0 +1,28 @@
import { html } from 'lit';
// prettier-ignore
export const calloutTooltip = html`<svg width="170" height="106" viewBox="0 0 170 106" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_3479_144688)">
<rect width="170" height="106" fill="white"/>
<text fill="#8E8D91" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" letter-spacing="0px"><tspan x="8" y="16.6364">Highlight important notes.</tspan></text>
<path d="M8 32.1816C8 29.3199 10.3199 27 13.1816 27H489.892C492.754 27 495.073 29.3199 495.073 32.1816V90.8403C495.073 93.702 492.754 96.0219 489.892 96.0219H13.1816C10.3199 96.0219 8 93.702 8 90.8403V32.1816Z" fill="#EEFFFD"/>
<g clip-path="url(#clip1_3479_144688)">
<g clip-path="url(#clip2_3479_144688)">
<text fill="black" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="15" font-weight="500" letter-spacing="0em"><tspan x="14.7494" y="50.1658">&#x1f44b;</tspan></text>
</g>
</g>
<text fill="#141414" xml:space="preserve" style="white-space: pre" font-family="Inter" font-size="10" letter-spacing="0px"><tspan x="44.9541" y="49.4196">A storyboard is a visual representation of a story, typically presented in the form of sequential </tspan><tspan x="44.9541" y="64.9645">panels. Each panel features illustrations or images accompanied by notes describing key </tspan><tspan x="44.9541" y="80.5094">scenes or shots, including details of action and dialogue. </tspan></text>
</g>
<defs>
<clipPath id="clip0_3479_144688">
<rect width="170" height="106" fill="white"/>
</clipPath>
<clipPath id="clip1_3479_144688">
<rect width="24" height="30.477" fill="white" transform="translate(14.477 30.2388)"/>
</clipPath>
<clipPath id="clip2_3479_144688">
<rect x="14.477" y="36.7158" width="24" height="24" rx="1.94311" fill="white"/>
</clipPath>
</defs>
</svg>
`;

View File

@@ -0,0 +1,14 @@
import { CalloutBlockComponent } from './callout-block';
import { IconPickerWrapper } from './icon-picker-wrapper';
export function effects() {
customElements.define('affine-callout', CalloutBlockComponent);
customElements.define('icon-picker-wrapper', IconPickerWrapper);
}
declare global {
interface HTMLElementTagNameMap {
'affine-callout': CalloutBlockComponent;
'icon-picker-wrapper': IconPickerWrapper;
}
}

View File

@@ -0,0 +1,52 @@
import type { IconData } from '@blocksuite/affine-shared/services';
import type { UniComponent } from '@blocksuite/affine-shared/types';
import { ShadowlessElement } from '@blocksuite/std';
import { type Signal } from '@preact/signals-core';
import { html, type TemplateResult } from 'lit';
import { type StyleInfo, styleMap } from 'lit/directives/style-map.js';
// Copy of renderUniLit from callout-block.ts
const renderUniLit = <Props, Expose extends NonNullable<unknown>>(
uni: UniComponent<Props, Expose> | undefined,
props?: Props,
options?: {
ref?: Signal<Expose | undefined>;
style?: Readonly<StyleInfo>;
class?: string;
}
): TemplateResult => {
return html` <uni-lit
.uni="${uni}"
.props="${props}"
.ref="${options?.ref}"
style=${options?.style ? styleMap(options?.style) : ''}
></uni-lit>`;
};
export interface IconPickerWrapperProps {
onSelect?: (iconData?: IconData) => void;
onClose?: () => void;
}
export class IconPickerWrapper extends ShadowlessElement {
iconPickerComponent?: UniComponent<IconPickerWrapperProps, any>;
props?: IconPickerWrapperProps;
constructor() {
super();
}
override render() {
if (!this.iconPickerComponent) {
return html``;
}
return renderUniLit(this.iconPickerComponent, this.props);
}
}
declare global {
interface HTMLElementTagNameMap {
'icon-picker-wrapper': IconPickerWrapper;
}
}

View File

@@ -0,0 +1,2 @@
export * from './callout-block.js';
export * from './effects.js';

View File

@@ -0,0 +1,17 @@
import {
type StoreExtensionContext,
StoreExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { CalloutBlockSchemaExtension } from '@blocksuite/affine-model';
import { CalloutBlockMarkdownAdapterExtension } from './adapters/markdown';
export class CalloutStoreExtension extends StoreExtensionProvider {
override name = 'affine-callout-block';
override setup(context: StoreExtensionContext) {
super.setup(context);
context.register(CalloutBlockSchemaExtension);
context.register(CalloutBlockMarkdownAdapterExtension);
}
}

View File

@@ -0,0 +1,32 @@
import {
type ViewExtensionContext,
ViewExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { SlashMenuConfigExtension } from '@blocksuite/affine-widget-slash-menu';
import { BlockViewExtension, FlavourExtension } from '@blocksuite/std';
import { literal } from 'lit/static-html.js';
import { CalloutKeymapExtension } from './callout-keymap';
import { calloutSlashMenuConfig } from './configs/slash-menu';
import { createBuiltinToolbarConfigExtension } from './configs/toolbar';
import { effects } from './effects';
export class CalloutViewExtension extends ViewExtensionProvider {
override name = 'affine-callout-block';
override effect() {
super.effect();
effects();
}
override setup(context: ViewExtensionContext) {
super.setup(context);
context.register([
FlavourExtension('affine:callout'),
BlockViewExtension('affine:callout', literal`affine-callout`),
CalloutKeymapExtension,
SlashMenuConfigExtension('affine:callout', calloutSlashMenuConfig),
...createBuiltinToolbarConfigExtension('affine:callout'),
]);
}
}

View File

@@ -0,0 +1,20 @@
{
"extends": "../../../tsconfig.json",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./dist",
"tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo"
},
"include": ["./src"],
"references": [
{ "path": "../../components" },
{ "path": "../../ext-loader" },
{ "path": "../../inlines/preset" },
{ "path": "../../model" },
{ "path": "../../rich-text" },
{ "path": "../../shared" },
{ "path": "../../widgets/slash-menu" },
{ "path": "../../../framework/std" },
{ "path": "../../../framework/store" }
]
}

View File

@@ -0,0 +1,48 @@
{
"name": "@blocksuite/affine-block-code",
"description": "Code block for BlockSuite.",
"type": "module",
"scripts": {
"build": "yarn run -T tsc"
},
"sideEffects": false,
"keywords": [],
"author": "toeverything",
"license": "MIT",
"dependencies": {
"@blocksuite/affine-components": "workspace:*",
"@blocksuite/affine-ext-loader": "workspace:*",
"@blocksuite/affine-gfx-turbo-renderer": "workspace:*",
"@blocksuite/affine-inline-comment": "workspace:*",
"@blocksuite/affine-inline-latex": "workspace:*",
"@blocksuite/affine-inline-link": "workspace:*",
"@blocksuite/affine-inline-preset": "workspace:*",
"@blocksuite/affine-model": "workspace:*",
"@blocksuite/affine-rich-text": "workspace:*",
"@blocksuite/affine-shared": "workspace:*",
"@blocksuite/affine-widget-slash-menu": "workspace:*",
"@blocksuite/global": "workspace:*",
"@blocksuite/icons": "^2.2.17",
"@blocksuite/std": "workspace:*",
"@blocksuite/store": "workspace:*",
"@floating-ui/dom": "^1.6.13",
"@preact/signals-core": "^1.8.0",
"@types/mdast": "^4.0.4",
"lit": "^3.2.0",
"shiki": "^3.19.0",
"zod": "^3.25.76"
},
"exports": {
".": "./src/index.ts",
"./turbo-painter": "./src/turbo/code-painter.worker.ts",
"./view": "./src/view.ts",
"./store": "./src/store.ts"
},
"files": [
"src",
"dist",
"!src/__tests__",
"!dist/__tests__"
],
"version": "0.27.5"
}

View File

@@ -0,0 +1,13 @@
import type { ExtensionType } from '@blocksuite/store';
import { CodeBlockHtmlAdapterExtension } from './html.js';
import { CodeBlockMarkdownAdapterExtensions } from './markdown/index.js';
import { CodeBlockNotionHtmlAdapterExtension } from './notion-html.js';
import { CodeBlockPlainTextAdapterExtension } from './plain-text.js';
export const CodeBlockAdapterExtensions: ExtensionType[] = [
CodeBlockHtmlAdapterExtension,
CodeBlockMarkdownAdapterExtensions,
CodeBlockPlainTextAdapterExtension,
CodeBlockNotionHtmlAdapterExtension,
].flat();

View File

@@ -0,0 +1,109 @@
import { CodeBlockSchema } from '@blocksuite/affine-model';
import {
BlockHtmlAdapterExtension,
type BlockHtmlAdapterMatcher,
CODE_BLOCK_WRAP_KEY,
HastUtils,
} from '@blocksuite/affine-shared/adapters';
import type { DeltaInsert } from '@blocksuite/store';
import { nanoid } from '@blocksuite/store';
export const codeBlockHtmlAdapterMatcher: BlockHtmlAdapterMatcher = {
flavour: CodeBlockSchema.model.flavour,
toMatch: o => HastUtils.isElement(o.node) && o.node.tagName === 'pre',
fromMatch: o => o.node.flavour === 'affine:code',
toBlockSnapshot: {
enter: (o, context) => {
if (!HastUtils.isElement(o.node)) {
return;
}
const code = HastUtils.querySelector(o.node, 'code');
if (!code) {
return;
}
const codeText =
code.children.length === 1 && code.children[0].type === 'text'
? code.children[0]
: { ...code, tagName: 'div' };
let codeLang = Array.isArray(code.properties?.className)
? code.properties.className.find(
className =>
typeof className === 'string' && className.startsWith('code-')
)
: undefined;
codeLang =
typeof codeLang === 'string'
? codeLang.replace('code-', '')
: undefined;
const { walkerContext, deltaConverter, configs } = context;
const wrap = configs.get(CODE_BLOCK_WRAP_KEY) === 'true';
walkerContext
.openNode(
{
type: 'block',
id: nanoid(),
flavour: 'affine:code',
props: {
language: codeLang ?? 'Plain Text',
wrap,
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(codeText, {
trim: false,
pre: true,
}),
},
},
children: [],
},
'children'
)
.closeNode();
walkerContext.skipAllChildren();
},
},
fromBlockSnapshot: {
enter: async (o, context) => {
const { walkerContext } = context;
const rawLang = o.node.props.language as string | null;
const text = (o.node.props.text as Record<string, unknown>)
.delta as DeltaInsert[];
const code = text.map(delta => delta.insert).join('');
walkerContext
.openNode(
{
type: 'element',
tagName: 'pre',
properties: {},
children: [],
},
'children'
)
.openNode(
{
type: 'element',
tagName: 'code',
properties: {
className: [`code-${rawLang ?? 'text'}`],
},
children: [
{
type: 'text',
value: code,
},
],
},
'children'
)
.closeNode()
.closeNode();
},
},
};
export const CodeBlockHtmlAdapterExtension = BlockHtmlAdapterExtension(
codeBlockHtmlAdapterMatcher
);

View File

@@ -0,0 +1,4 @@
export * from './html.js';
export * from './markdown/index.js';
export * from './notion-html.js';
export * from './plain-text.js';

View File

@@ -0,0 +1,12 @@
import type { ExtensionType } from '@blocksuite/store';
import { CodeBlockMarkdownAdapterExtension } from './markdown.js';
import { CodeMarkdownPreprocessorExtension } from './preprocessor.js';
export * from './markdown.js';
export * from './preprocessor.js';
export const CodeBlockMarkdownAdapterExtensions: ExtensionType[] = [
CodeMarkdownPreprocessorExtension,
CodeBlockMarkdownAdapterExtension,
];

View File

@@ -0,0 +1,99 @@
import { CodeBlockSchema } from '@blocksuite/affine-model';
import {
BlockMarkdownAdapterExtension,
type BlockMarkdownAdapterMatcher,
CODE_BLOCK_WRAP_KEY,
IN_PARAGRAPH_NODE_CONTEXT_KEY,
type MarkdownAST,
} from '@blocksuite/affine-shared/adapters';
import type { DeltaInsert } from '@blocksuite/store';
import { nanoid } from '@blocksuite/store';
import type { Code, Html } from 'mdast';
const isCodeNode = (node: MarkdownAST): node is Code => node.type === 'code';
const isHtmlNode = (node: MarkdownAST): node is Html => node.type === 'html';
const isCodeOrHtmlNode = (node: MarkdownAST): node is Code | Html =>
isCodeNode(node) || isHtmlNode(node);
export const codeBlockMarkdownAdapterMatcher: BlockMarkdownAdapterMatcher = {
flavour: CodeBlockSchema.model.flavour,
toMatch: o => isCodeOrHtmlNode(o.node),
fromMatch: o => o.node.flavour === 'affine:code',
toBlockSnapshot: {
enter: (o, context) => {
if (!isCodeOrHtmlNode(o.node)) {
return;
}
const { walkerContext, configs } = context;
const wrap = configs.get(CODE_BLOCK_WRAP_KEY) === 'true';
let language = 'plain text';
switch (o.node.type) {
case 'code': {
if (o.node.lang) {
language = o.node.lang;
}
break;
}
case 'html': {
const inParagraphNode = !!walkerContext.getGlobalContext(
IN_PARAGRAPH_NODE_CONTEXT_KEY
);
// only handle top level html node
if (inParagraphNode) {
return;
}
language = 'html';
break;
}
}
walkerContext
.openNode(
{
type: 'block',
id: nanoid(),
flavour: 'affine:code',
props: {
language,
wrap,
text: {
'$blocksuite:internal:text$': true,
delta: [
{
insert: o.node.value,
},
],
},
},
children: [],
},
'children'
)
.closeNode();
},
},
fromBlockSnapshot: {
enter: (o, context) => {
const text = (o.node.props.text ?? { delta: [] }) as {
delta: DeltaInsert[];
};
const { walkerContext } = context;
walkerContext
.openNode(
{
type: 'code',
lang: (o.node.props.language as string) ?? null,
meta: null,
value: text.delta.map(delta => delta.insert).join(''),
},
'children'
)
.closeNode();
},
},
};
export const CodeBlockMarkdownAdapterExtension = BlockMarkdownAdapterExtension(
codeBlockMarkdownAdapterMatcher
);

View File

@@ -0,0 +1,76 @@
import {
type MarkdownAdapterPreprocessor,
MarkdownPreprocessorExtension,
} from '@blocksuite/affine-shared/adapters';
import { isValidUrl } from '@blocksuite/affine-shared/utils';
const codePreprocessor: MarkdownAdapterPreprocessor = {
name: 'code',
levels: ['slice'],
preprocess: content => {
let codeFence = '';
const lines = content
.split('\n')
.map(line => {
if (line.trimStart().startsWith('-')) {
return line;
}
let trimmedLine = line.trimStart();
if (!codeFence && trimmedLine.startsWith('```')) {
codeFence = trimmedLine.substring(
0,
trimmedLine.lastIndexOf('```') + 3
);
if (codeFence.split('').every(c => c === '`')) {
return line;
}
codeFence = '';
}
if (!codeFence && trimmedLine.startsWith('~~~')) {
codeFence = trimmedLine.substring(
0,
trimmedLine.lastIndexOf('~~~') + 3
);
if (codeFence.split('').every(c => c === '~')) {
return line;
}
codeFence = '';
}
if (
!!codeFence &&
trimmedLine.startsWith(codeFence) &&
trimmedLine.lastIndexOf(codeFence) === 0
) {
codeFence = '';
}
if (codeFence) {
return line;
}
trimmedLine = trimmedLine.trimEnd();
if (
!trimmedLine.startsWith('<') &&
!trimmedLine.endsWith('>') &&
!trimmedLine.includes(' ')
) {
// check if it is a url link and wrap it with the angle brackets
// sometimes the url includes emphasis `_` that will break URL parsing
//
// eg. /MuawcBMT1Mzvoar09-_66?mode=page&blockIds=rL2_GXbtLU2SsJVfCSmh_
// https://www.markdownguide.org/basic-syntax/#urls-and-email-addresses
const valid = isValidUrl(trimmedLine);
if (valid) {
return `<${trimmedLine}>`;
}
}
return line.replace(/^ /, '&#x20;');
})
.join('\n');
return lines;
},
};
export const CodeMarkdownPreprocessorExtension =
MarkdownPreprocessorExtension(codePreprocessor);

View File

@@ -0,0 +1,59 @@
import { CodeBlockSchema } from '@blocksuite/affine-model';
import {
BlockNotionHtmlAdapterExtension,
type BlockNotionHtmlAdapterMatcher,
CODE_BLOCK_WRAP_KEY,
HastUtils,
} from '@blocksuite/affine-shared/adapters';
import { nanoid } from '@blocksuite/store';
export const codeBlockNotionHtmlAdapterMatcher: BlockNotionHtmlAdapterMatcher =
{
flavour: CodeBlockSchema.model.flavour,
toMatch: o => HastUtils.isElement(o.node) && o.node.tagName === 'pre',
fromMatch: () => false,
toBlockSnapshot: {
enter: (o, context) => {
if (!HastUtils.isElement(o.node)) {
return;
}
const code = HastUtils.querySelector(o.node, 'code');
if (!code) {
return;
}
const { walkerContext, deltaConverter, configs } = context;
const wrap = configs.get(CODE_BLOCK_WRAP_KEY) === 'true';
const codeText =
code.children.length === 1 && code.children[0].type === 'text'
? code.children[0]
: { ...code, tag: 'div' };
walkerContext
.openNode(
{
type: 'block',
id: nanoid(),
flavour: CodeBlockSchema.model.flavour,
props: {
language: 'Plain Text',
wrap,
text: {
'$blocksuite:internal:text$': true,
delta: deltaConverter.astToDelta(codeText, {
trim: false,
pre: true,
}),
},
},
children: [],
},
'children'
)
.closeNode();
walkerContext.skipAllChildren();
},
},
fromBlockSnapshot: {},
};
export const CodeBlockNotionHtmlAdapterExtension =
BlockNotionHtmlAdapterExtension(codeBlockNotionHtmlAdapterMatcher);

View File

@@ -0,0 +1,26 @@
import { CodeBlockSchema } from '@blocksuite/affine-model';
import {
BlockPlainTextAdapterExtension,
type BlockPlainTextAdapterMatcher,
} from '@blocksuite/affine-shared/adapters';
import type { DeltaInsert } from '@blocksuite/store';
export const codeBlockPlainTextAdapterMatcher: BlockPlainTextAdapterMatcher = {
flavour: CodeBlockSchema.model.flavour,
toMatch: () => false,
fromMatch: o => o.node.flavour === CodeBlockSchema.model.flavour,
toBlockSnapshot: {},
fromBlockSnapshot: {
enter: (o, context) => {
const text = (o.node.props.text ?? { delta: [] }) as {
delta: DeltaInsert[];
};
const buffer = text.delta.map(delta => delta.insert).join('');
context.textBuffer.content += buffer;
context.textBuffer.content += '\n';
},
},
};
export const CodeBlockPlainTextAdapterExtension =
BlockPlainTextAdapterExtension(codeBlockPlainTextAdapterMatcher);

View File

@@ -0,0 +1,199 @@
import { deleteTextCommand } from '@blocksuite/affine-inline-preset';
import type { RichText } from '@blocksuite/affine-rich-text';
import {
HtmlAdapter,
pasteMiddleware,
PlainTextAdapter,
} from '@blocksuite/affine-shared/adapters';
import {
getBlockIndexCommand,
getBlockSelectionsCommand,
getTextSelectionCommand,
} from '@blocksuite/affine-shared/commands';
import { type Container, createIdentifier } from '@blocksuite/global/di';
import { DisposableGroup } from '@blocksuite/global/disposable';
import {
type BlockStdScope,
Clipboard,
type ClipboardAdapterConfig,
LifeCycleWatcher,
LifeCycleWatcherIdentifier,
StdIdentifier,
TextSelection,
type UIEventHandler,
} from '@blocksuite/std';
import type { ExtensionType } from '@blocksuite/store';
export const CodeClipboardAdapterConfigIdentifier =
createIdentifier<ClipboardAdapterConfig>('code-clipboard-adapter-config');
export function CodeClipboardAdapterConfigExtension(
config: ClipboardAdapterConfig
): ExtensionType {
return {
setup: di => {
di.addImpl(
CodeClipboardAdapterConfigIdentifier(config.mimeType),
() => config
);
},
};
}
const PlainTextClipboardConfig = CodeClipboardAdapterConfigExtension({
mimeType: 'text/plain',
adapter: PlainTextAdapter,
priority: 90,
});
const HtmlClipboardConfig = CodeClipboardAdapterConfigExtension({
mimeType: 'text/html',
adapter: HtmlAdapter,
priority: 80,
});
export class CodeBlockClipboard extends Clipboard {
static override readonly key = 'code-block-clipboard';
override get _adapters() {
const adapterConfigs = this.std.provider.getAll(
CodeClipboardAdapterConfigIdentifier
);
return Array.from(adapterConfigs.values());
}
}
export class CodeBlockClipboardController extends LifeCycleWatcher {
static override key = 'code-block-clipboard-controller';
private readonly _disposables = new DisposableGroup();
constructor(
std: BlockStdScope,
readonly clipboard: CodeBlockClipboard
) {
super(std);
}
static override setup(di: Container) {
di.add(
this as unknown as {
new (
std: BlockStdScope,
clipboard: CodeBlockClipboard
): CodeBlockClipboardController;
},
[StdIdentifier, CodeBlockClipboard]
);
di.addImpl(LifeCycleWatcherIdentifier(this.key), provider =>
provider.get(this)
);
}
protected _init = () => {
const paste = pasteMiddleware(this.std);
this.clipboard.use(paste);
this._disposables.add({
dispose: () => {
this.clipboard.unuse(paste);
},
});
};
onPaste: UIEventHandler = ctx => {
const e = ctx.get('clipboardState').raw;
e.preventDefault();
const textSelection = this.std.selection.find(TextSelection);
const plainText = e.clipboardData
?.getData('text/plain')
?.replace(/\r?\n|\r/g, '\n');
const selectedBlockId = textSelection?.from.blockId;
const codeBlock = selectedBlockId
? this.std.store.getBlock(selectedBlockId)?.model
: null;
if (plainText && codeBlock?.flavour === 'affine:code' && selectedBlockId) {
const richText = this.std.view
.getBlock(selectedBlockId)
?.querySelector<RichText>('rich-text');
const inlineEditor = richText?.inlineEditor;
const inlineRange = inlineEditor?.getInlineRange();
if (inlineEditor && inlineRange) {
inlineEditor.insertText(inlineRange, plainText);
inlineEditor.setInlineRange({
index: inlineRange.index + plainText.length,
length: 0,
});
return true;
}
}
this.std.store.captureSync();
this.std.command
.chain()
.try(cmd => [
cmd.pipe(getTextSelectionCommand).pipe((ctx, next) => {
const textSelection = ctx.currentTextSelection;
if (!textSelection) return;
const end = textSelection.to ?? textSelection.from;
next({ currentSelectionPath: end.blockId });
}),
cmd.pipe(getBlockSelectionsCommand).pipe((ctx, next) => {
const currentBlockSelections = ctx.currentBlockSelections;
if (!currentBlockSelections) return;
const blockSelection = currentBlockSelections.at(-1);
if (!blockSelection) return;
next({ currentSelectionPath: blockSelection.blockId });
}),
])
.pipe(getBlockIndexCommand)
.try(cmd => [cmd.pipe(getTextSelectionCommand).pipe(deleteTextCommand)])
.pipe((ctx, next) => {
if (!ctx.parentBlock) {
return;
}
this.clipboard
.paste(
e,
this.std.store,
ctx.parentBlock.model.id,
ctx.blockIndex ? ctx.blockIndex + 1 : 1
)
.catch(console.error);
return next();
})
.run();
return true;
};
override mounted() {
this._init();
// add paste event listener for code block
const subscription = this.std.view.viewUpdated.subscribe(
({ type, method, view }) => {
if (type !== 'block' || view.model.flavour !== 'affine:code') return;
if (method === 'add') {
view.handleEvent('paste', this.onPaste);
}
}
);
this._disposables.add(subscription);
}
override unmounted() {
this._disposables.dispose();
}
}
export function getCodeClipboardExtensions(): ExtensionType[] {
return [
PlainTextClipboardConfig,
HtmlClipboardConfig,
CodeBlockClipboard,
CodeBlockClipboardController,
];
}

View File

@@ -0,0 +1,19 @@
import { ConfigExtensionFactory } from '@blocksuite/std';
import type { BundledLanguageInfo, ThemeInput } from 'shiki';
export interface CodeBlockConfig {
theme?: {
dark?: ThemeInput;
light?: ThemeInput;
};
langs?: BundledLanguageInfo[];
/**
* Whether to show line numbers in the code block.
* @default true
*/
showLineNumbers?: boolean;
}
export const CodeBlockConfigExtension =
ConfigExtensionFactory<CodeBlockConfig>('affine:code');

View File

@@ -0,0 +1,50 @@
import { CommentInlineSpecExtension } from '@blocksuite/affine-inline-comment';
import { LatexInlineSpecExtension } from '@blocksuite/affine-inline-latex';
import { LinkInlineSpecExtension } from '@blocksuite/affine-inline-link';
import {
BackgroundInlineSpecExtension,
BoldInlineSpecExtension,
CodeInlineSpecExtension,
ColorInlineSpecExtension,
ItalicInlineSpecExtension,
StrikeInlineSpecExtension,
UnderlineInlineSpecExtension,
} from '@blocksuite/affine-inline-preset';
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import {
InlineManagerExtension,
InlineSpecExtension,
} from '@blocksuite/std/inline';
import { html } from 'lit';
import { z } from 'zod';
export const CodeBlockUnitSpecExtension =
InlineSpecExtension<AffineTextAttributes>({
name: 'code-block-unit',
schema: z.object({
'code-block-uint': z.undefined(),
}),
match: () => true,
renderer: ({ delta }) => {
return html`<affine-code-unit .delta=${delta}></affine-code-unit>`;
},
});
export const CodeBlockInlineManagerExtension =
InlineManagerExtension<AffineTextAttributes>({
id: 'CodeBlockInlineManager',
enableMarkdown: false,
specs: [
BoldInlineSpecExtension.identifier,
ItalicInlineSpecExtension.identifier,
UnderlineInlineSpecExtension.identifier,
StrikeInlineSpecExtension.identifier,
CodeInlineSpecExtension.identifier,
BackgroundInlineSpecExtension.identifier,
ColorInlineSpecExtension.identifier,
LatexInlineSpecExtension.identifier,
LinkInlineSpecExtension.identifier,
CodeBlockUnitSpecExtension.identifier,
CommentInlineSpecExtension.identifier,
],
});

View File

@@ -0,0 +1,115 @@
import { ColorScheme } from '@blocksuite/affine-model';
import { ThemeProvider } from '@blocksuite/affine-shared/services';
import { LifeCycleWatcher } from '@blocksuite/std';
import { type Signal, signal } from '@preact/signals-core';
import {
createHighlighterCore,
createOnigurumaEngine,
type HighlighterCore,
type MaybeGetter,
} from 'shiki';
import getWasm from 'shiki/wasm';
import { CodeBlockConfigExtension } from './code-block-config.js';
import {
CODE_BLOCK_DEFAULT_DARK_THEME,
CODE_BLOCK_DEFAULT_LIGHT_THEME,
} from './highlight/const.js';
export class CodeBlockHighlighter extends LifeCycleWatcher {
static override key = 'code-block-highlighter';
// Singleton highlighter instance
private static _sharedHighlighter: HighlighterCore | null = null;
private static _highlighterPromise: Promise<HighlighterCore> | null = null;
private static _refCount = 0;
private _darkThemeKey: string | undefined;
private _lightThemeKey: string | undefined;
highlighter$: Signal<HighlighterCore | null> = signal(null);
get themeKey() {
const theme = this.std.get(ThemeProvider).theme$.value;
return theme === ColorScheme.Dark
? this._darkThemeKey
: this._lightThemeKey;
}
private readonly _loadTheme = async (
highlighter: HighlighterCore
): Promise<void> => {
if (!CodeBlockHighlighter._isHighlighterInUse(highlighter)) {
return;
}
const config = this.std.getOptional(CodeBlockConfigExtension.identifier);
const darkTheme = config?.theme?.dark ?? CODE_BLOCK_DEFAULT_DARK_THEME;
const lightTheme = config?.theme?.light ?? CODE_BLOCK_DEFAULT_LIGHT_THEME;
this._darkThemeKey = (await normalizeGetter(darkTheme)).name;
this._lightThemeKey = (await normalizeGetter(lightTheme)).name;
if (!CodeBlockHighlighter._isHighlighterInUse(highlighter)) {
return;
}
await highlighter.loadTheme(darkTheme, lightTheme);
if (!CodeBlockHighlighter._isHighlighterInUse(highlighter)) {
return;
}
this.highlighter$.value = highlighter;
};
private static async _getOrCreateHighlighter(): Promise<HighlighterCore> {
if (CodeBlockHighlighter._sharedHighlighter) {
return CodeBlockHighlighter._sharedHighlighter;
}
if (!CodeBlockHighlighter._highlighterPromise) {
CodeBlockHighlighter._highlighterPromise = createHighlighterCore({
engine: createOnigurumaEngine(() => getWasm),
}).then(highlighter => {
CodeBlockHighlighter._sharedHighlighter = highlighter;
return highlighter;
});
}
return CodeBlockHighlighter._highlighterPromise;
}
override mounted(): void {
super.mounted();
CodeBlockHighlighter._refCount++;
CodeBlockHighlighter._getOrCreateHighlighter()
.then(this._loadTheme)
.catch(console.error);
}
override unmounted(): void {
CodeBlockHighlighter._refCount = Math.max(
0,
CodeBlockHighlighter._refCount - 1
);
this.highlighter$.value = null;
}
private static _isHighlighterInUse(highlighter: HighlighterCore) {
return (
CodeBlockHighlighter._refCount > 0 &&
CodeBlockHighlighter._sharedHighlighter === highlighter
);
}
}
/**
* https://github.com/shikijs/shiki/blob/933415cdc154fe74ccfb6bbb3eb6a7b7bf183e60/packages/core/src/internal.ts#L31
*/
export async function normalizeGetter<T>(p: MaybeGetter<T>): Promise<T> {
return Promise.resolve(typeof p === 'function' ? (p as any)() : p).then(
r => r.default || r
);
}

View File

@@ -0,0 +1,543 @@
import { CaptionedBlockComponent } from '@blocksuite/affine-components/caption';
import type { CodeBlockModel } from '@blocksuite/affine-model';
import { focusTextModel, type RichText } from '@blocksuite/affine-rich-text';
import {
BRACKET_PAIRS,
EDGELESS_TOP_CONTENTEDITABLE_SELECTOR,
} from '@blocksuite/affine-shared/consts';
import {
BlockElementCommentManager,
DocModeProvider,
EditorSettingProvider,
NotificationProvider,
} from '@blocksuite/affine-shared/services';
import { getViewportElement } from '@blocksuite/affine-shared/utils';
import { IS_MAC, IS_MOBILE } from '@blocksuite/global/env';
import { noop } from '@blocksuite/global/utils';
import type { BlockComponent } from '@blocksuite/std';
import { BlockSelection, TextSelection } from '@blocksuite/std';
import {
getInlineRangeProvider,
INLINE_ROOT_ATTR,
type InlineRangeProvider,
type InlineRootElement,
type VLine,
} from '@blocksuite/std/inline';
import { Slice } from '@blocksuite/store';
import { computed, effect, type Signal, signal } from '@preact/signals-core';
import { html, nothing, type TemplateResult } from 'lit';
import { query } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styleMap } from 'lit/directives/style-map.js';
import { bundledLanguagesInfo, type ThemedToken } from 'shiki';
import { CodeBlockConfigExtension } from './code-block-config.js';
import { CodeBlockInlineManagerExtension } from './code-block-inline.js';
import { CodeBlockHighlighter } from './code-block-service.js';
import { CodeBlockPreviewIdentifier } from './code-preview-extension.js';
import { codeBlockStyles } from './styles.js';
export class CodeBlockComponent extends CaptionedBlockComponent<CodeBlockModel> {
static override styles = codeBlockStyles;
private _inlineRangeProvider: InlineRangeProvider | null = null;
private readonly _localPreview$ = signal<boolean | null>(null);
preview$: Signal<boolean> = computed(() => {
const modelPreview = !!this.model.props.preview$.value;
if (this.store.readonly) {
return this._localPreview$.value ?? modelPreview;
}
return modelPreview;
});
collapsed$: Signal<boolean> = computed(
() => !!this.model.props.collapsed$.value
);
highlightTokens$: Signal<ThemedToken[][]> = signal([]);
languageName$: Signal<string> = computed(() => {
const lang = this.model.props.language$.value;
if (lang === null) {
return 'Plain Text';
}
const matchedInfo = this.langs.find(info => info.id === lang);
return matchedInfo ? matchedInfo.name : 'Plain Text';
});
get inlineEditor() {
const inlineRoot = this.querySelector<InlineRootElement>(
`[${INLINE_ROOT_ATTR}]`
);
return inlineRoot?.inlineEditor;
}
get inlineManager() {
return this.std.get(CodeBlockInlineManagerExtension.identifier);
}
get notificationService() {
return this.std.getOptional(NotificationProvider);
}
get readonly() {
return this.store.readonly;
}
get langs() {
return (
this.std.getOptional(CodeBlockConfigExtension.identifier)?.langs ??
bundledLanguagesInfo
);
}
get highlighter() {
return this.std.get(CodeBlockHighlighter);
}
/** Whether line numbers are currently shown for this block, accounting for the global setting and feature flags. */
get showLineNumbers(): boolean {
// Feature flag: mobile (or any other consumer) can hard-disable via CodeBlockConfigExtension.
const featureEnabled =
this.std.getOptional(CodeBlockConfigExtension.identifier)
?.showLineNumbers ?? true;
if (!featureEnabled) return false;
// Per-block prop overrides the global default; global defaults to true.
return this.model.props.lineNumber ?? this._showLineNumbersGlobal$.value;
}
override get topContenteditableElement() {
if (this.std.get(DocModeProvider).getEditorMode() === 'edgeless') {
return this.closest<BlockComponent>(
EDGELESS_TOP_CONTENTEDITABLE_SELECTOR
);
}
return this.rootComponent;
}
private _updateHighlightTokens() {
const modelLang = this.model.props.language$.value;
if (modelLang === null) {
this.highlightTokens$.value = [];
return;
}
const matchedInfo = this.langs.find(
info =>
info.id === modelLang ||
info.name === modelLang ||
info.aliases?.includes(modelLang)
);
if (matchedInfo) {
this.model.props.language$.value = matchedInfo.id;
const langImport = matchedInfo.import;
const lang = matchedInfo.id;
const highlighter = this.highlighter.highlighter$.value;
const theme = this.highlighter.themeKey;
if (!theme || !highlighter) {
this.highlightTokens$.value = [];
return;
}
noop(this.model.props.text.deltas$.value);
const code = this.model.props.text.toString();
const loadedLanguages = highlighter.getLoadedLanguages();
if (!loadedLanguages.includes(lang)) {
highlighter
.loadLanguage(langImport)
.then(() => {
this.highlightTokens$.value = highlighter.codeToTokensBase(code, {
lang,
theme,
});
})
.catch(console.error);
} else {
this.highlightTokens$.value = highlighter.codeToTokensBase(code, {
lang,
theme,
});
}
} else {
this.highlightTokens$.value = [];
// clear language if not found
this.model.props.language$.value = null;
}
}
/**
* Stable signal: true when the global editor setting enables line numbers.
* Defaults to true. Updated reactively by an effect in connectedCallback.
* Using a writable signal (not reassigned to computed) keeps the reference
* stable so any downstream computed/effect that captures it stays correct.
*/
private readonly _showLineNumbersGlobal$: Signal<boolean> = signal(true);
override connectedCallback() {
super.connectedCallback();
// Reactively sync the global line-number preference from EditorSettingProvider
// into the stable _showLineNumbersGlobal$ signal. Using effect() keeps the
// signal reference constant (no identity change) while still tracking updates.
const editorSetting = this.std.getOptional(EditorSettingProvider);
if (editorSetting) {
this.disposables.add(
effect(() => {
const val = (
editorSetting.setting$.value as Record<string, unknown>
)?.['codeBlockLineNumbers'];
this._showLineNumbersGlobal$.value = val !== false;
})
);
}
// set highlight options getter used by "exportToHtml"
this.disposables.add(
effect(() => {
this._updateHighlightTokens();
})
);
this.disposables.add(
effect(() => {
noop(this.highlightTokens$.value);
this._richTextElement?.inlineEditor?.render();
})
);
const selectionManager = this.host.selection;
const INDENT_SYMBOL = ' ';
const LINE_BREAK_SYMBOL = '\n';
const allIndexOf = (
text: string,
symbol: string,
start = 0,
end = text.length
) => {
const indexArr: number[] = [];
let i = start;
while (i < end) {
const index = text.indexOf(symbol, i);
if (index === -1 || index > end) {
break;
}
indexArr.push(index);
i = index + 1;
}
return indexArr;
};
// TODO: move to service for better performance
this.bindHotKey({
Backspace: ctx => {
const event = ctx.get('defaultState').event;
const textSelection = selectionManager.find(TextSelection);
if (!textSelection) {
event.preventDefault();
return;
}
const from = textSelection.from;
if (from.index === 0 && from.length === 0) {
event.preventDefault();
selectionManager.setGroup('note', [
selectionManager.create(BlockSelection, { blockId: this.blockId }),
]);
return true;
}
const inlineEditor = this.inlineEditor;
const inlineRange = inlineEditor?.getInlineRange();
if (!inlineRange || !inlineEditor) return;
const left = inlineEditor.yText.toString()[inlineRange.index - 1];
const right = inlineEditor.yText.toString()[inlineRange.index];
const leftBrackets = BRACKET_PAIRS.map(pair => pair.left);
if (BRACKET_PAIRS[leftBrackets.indexOf(left)]?.right === right) {
const index = inlineRange.index - 1;
inlineEditor.deleteText({
index: index,
length: 2,
});
inlineEditor.setInlineRange({
index: index,
length: 0,
});
event.preventDefault();
return true;
}
return;
},
Tab: ctx => {
if (this.store.readonly) return;
const state = ctx.get('keyboardState');
const event = state.raw;
const inlineEditor = this.inlineEditor;
if (!inlineEditor) return;
const inlineRange = inlineEditor.getInlineRange();
if (inlineRange) {
event.stopPropagation();
event.preventDefault();
const text = this.inlineEditor.yText.toString();
const index = text.lastIndexOf(
LINE_BREAK_SYMBOL,
inlineRange.index - 1
);
const indexArr = allIndexOf(
text,
LINE_BREAK_SYMBOL,
inlineRange.index,
inlineRange.index + inlineRange.length
)
.map(i => i + 1)
.reverse();
if (index !== -1) {
indexArr.push(index + 1);
} else {
indexArr.push(0);
}
indexArr.forEach(i => {
if (!this.inlineEditor) return;
this.inlineEditor.insertText(
{
index: i,
length: 0,
},
INDENT_SYMBOL
);
});
this.inlineEditor.setInlineRange({
index: inlineRange.index + 2,
length:
inlineRange.length + (indexArr.length - 1) * INDENT_SYMBOL.length,
});
return true;
}
return;
},
'Shift-Tab': ctx => {
const state = ctx.get('keyboardState');
const event = state.raw;
const inlineEditor = this.inlineEditor;
if (!inlineEditor) return;
const inlineRange = inlineEditor.getInlineRange();
if (inlineRange) {
event.stopPropagation();
event.preventDefault();
const text = this.inlineEditor.yText.toString();
const index = text.lastIndexOf(
LINE_BREAK_SYMBOL,
inlineRange.index - 1
);
let indexArr = allIndexOf(
text,
LINE_BREAK_SYMBOL,
inlineRange.index,
inlineRange.index + inlineRange.length
)
.map(i => i + 1)
.reverse();
if (index !== -1) {
indexArr.push(index + 1);
} else {
indexArr.push(0);
}
indexArr = indexArr.filter(
i => text.slice(i, i + 2) === INDENT_SYMBOL
);
indexArr.forEach(i => {
if (!this.inlineEditor) return;
this.inlineEditor.deleteText({
index: i,
length: 2,
});
});
if (indexArr.length > 0) {
this.inlineEditor.setInlineRange({
index:
inlineRange.index -
(indexArr[indexArr.length - 1] < inlineRange.index ? 2 : 0),
length:
inlineRange.length -
(indexArr.length - 1) * INDENT_SYMBOL.length,
});
}
return true;
}
return;
},
'Control-d': () => {
if (!IS_MAC) return;
return true;
},
Delete: () => {
return;
},
Enter: () => {
this.store.captureSync();
return true;
},
'Mod-Enter': () => {
const { model, std } = this;
if (!model || !std) return;
const inlineEditor = this.inlineEditor;
const inlineRange = inlineEditor?.getInlineRange();
if (!inlineRange || !inlineEditor) return;
const isEnd = model.props.text.length === inlineRange.index;
if (!isEnd) return;
const parent = this.store.getParent(model);
if (!parent) return;
const index = parent.children.indexOf(model);
if (index === -1) return;
const id = this.store.addBlock(
'affine:paragraph',
{},
parent,
index + 1
);
focusTextModel(std, id);
return true;
},
});
this._inlineRangeProvider = getInlineRangeProvider(this);
}
copyCode() {
const model = this.model;
const slice = Slice.fromModels(model.store, [model]);
this.std.clipboard
.copySlice(slice)
.then(() => {
this.notificationService?.toast('Copied to clipboard');
})
.catch(e => {
this.notificationService?.toast('Copied failed, something went wrong');
console.error(e);
});
}
get isCommentHighlighted() {
return (
this.std
.getOptional(BlockElementCommentManager)
?.isBlockCommentHighlighted(this.model) ?? false
);
}
override async getUpdateComplete() {
const result = await super.getUpdateComplete();
await this._richTextElement?.updateComplete;
return result;
}
override renderBlock(): TemplateResult<1> {
const showLineNumbers = this.showLineNumbers;
const preview = this.preview$.value;
const previewContext = this.std.getOptional(
CodeBlockPreviewIdentifier(this.model.props.language ?? '')
);
const shouldRenderPreview = preview && previewContext;
const collapsed = this.collapsed$.value;
return html`
<div
class=${classMap({
'affine-code-block-container': true,
'highlight-comment': this.isCommentHighlighted,
mobile: IS_MOBILE,
wrap: this.model.props.wrap,
'disable-line-numbers': !showLineNumbers,
collapsed,
})}
>
<rich-text
style=${styleMap({
display: shouldRenderPreview ? 'none' : undefined,
})}
.yText=${this.model.props.text.yText}
.inlineEventSource=${this.topContenteditableElement ?? nothing}
.undoManager=${this.store.history.undoManager}
.attributesSchema=${this.inlineManager.getSchema()}
.attributeRenderer=${this.inlineManager.getRenderer()}
.readonly=${this.store.readonly}
.inlineRangeProvider=${this._inlineRangeProvider}
.enableClipboard=${false}
.enableUndoRedo=${false}
.wrapText=${this.model.props.wrap}
.verticalScrollContainerGetter=${() => getViewportElement(this.host)}
.vLineRenderer=${(vLine: VLine) => {
return html`
<span contenteditable="false" class="line-number"
>${vLine.index + 1}</span
>
${vLine.renderVElements()}
`;
}}
>
</rich-text>
${
collapsed
? html`<div class="code-collapsed-fade" aria-hidden="true"></div>`
: nothing
}
<div
style=${styleMap({
display: shouldRenderPreview && !collapsed ? undefined : 'none',
})}
contenteditable="false"
class="affine-code-block-preview"
>
${shouldRenderPreview && previewContext?.renderer(this.model)}
</div>
${this.renderChildren(this.model)} ${Object.values(this.widgets)}
</div>
`;
}
setWrap(wrap: boolean) {
this.store.updateBlock(this.model, { wrap });
}
setCollapsed(collapsed: boolean) {
this.store.updateBlock(this.model, { collapsed });
}
@query('rich-text')
private accessor _richTextElement: RichText | null = null;
override accessor blockContainerStyles = {
margin: '18px 0',
};
override accessor useCaptionEditor = true;
override accessor useZeroWidth = true;
setPreviewState(preview: boolean) {
if (this.store.readonly) {
this._localPreview$.value = preview;
} else {
this.store.updateBlock(this.model, { preview });
}
}
}
declare global {
interface HTMLElementTagNameMap {
'affine-code': CodeBlockComponent;
}
}

View File

@@ -0,0 +1,7 @@
import { textKeymap } from '@blocksuite/affine-inline-preset';
import { CodeBlockSchema } from '@blocksuite/affine-model';
import { KeymapExtension } from '@blocksuite/std';
export const CodeKeymapExtension = KeymapExtension(textKeymap, {
flavour: CodeBlockSchema.model.flavour,
});

View File

@@ -0,0 +1,27 @@
import type { CodeBlockModel } from '@blocksuite/affine-model';
import { createIdentifier } from '@blocksuite/global/di';
import type { ExtensionType } from '@blocksuite/store';
import type { HTMLTemplateResult } from 'lit';
export type CodeBlockPreviewRenderer = (
model: CodeBlockModel
) => HTMLTemplateResult | null;
export type CodeBlockPreviewContext = {
renderer: CodeBlockPreviewRenderer;
lang: string;
};
export const CodeBlockPreviewIdentifier =
createIdentifier<CodeBlockPreviewContext>('CodeBlockPreview');
export function CodeBlockPreviewExtension(
lang: string,
renderer: CodeBlockPreviewRenderer
): ExtensionType {
return {
setup: di => {
di.addImpl(CodeBlockPreviewIdentifier(lang), { renderer, lang });
},
};
}

View File

@@ -0,0 +1,165 @@
import { createLitPortal } from '@blocksuite/affine-components/portal';
import type {
EditorIconButton,
MenuItemGroup,
} from '@blocksuite/affine-components/toolbar';
import { renderGroups } from '@blocksuite/affine-components/toolbar';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { WithDisposable } from '@blocksuite/global/lit';
import { noop } from '@blocksuite/global/utils';
import { MoreVerticalIcon } from '@blocksuite/icons/lit';
import { flip, offset } from '@floating-ui/dom';
import { effect } from '@preact/signals-core';
import { css, html, LitElement } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import type { CodeBlockToolbarContext } from '../context.js';
export class AffineCodeToolbar extends WithDisposable(LitElement) {
static override styles = css`
:host {
position: absolute;
width: 100%;
top: 0;
left: 0;
}
.code-toolbar-container {
width: auto;
height: 24px;
gap: 4px;
padding: 4px;
margin: 0;
display: flex;
}
.code-toolbar-button {
color: ${unsafeCSSVarV2('icon/primary')};
background-color: ${unsafeCSSVarV2('button/secondary')};
box-shadow: var(--affine-shadow-1);
border-radius: 4px;
}
`;
private _currentOpenMenu: AbortController | null = null;
private _popMenuAbortController: AbortController | null = null;
closeCurrentMenu = () => {
if (this._currentOpenMenu && !this._currentOpenMenu.signal.aborted) {
this._currentOpenMenu.abort();
this._currentOpenMenu = null;
}
};
private _toggleMoreMenu() {
if (
this._currentOpenMenu &&
!this._currentOpenMenu.signal.aborted &&
this._currentOpenMenu === this._popMenuAbortController
) {
this.closeCurrentMenu();
this._moreMenuOpen = false;
return;
}
this.closeCurrentMenu();
this._popMenuAbortController = new AbortController();
this._popMenuAbortController.signal.addEventListener('abort', () => {
this._moreMenuOpen = false;
this.onActiveStatusChange(false);
});
this.onActiveStatusChange(true);
this._currentOpenMenu = this._popMenuAbortController;
if (!this._moreButton) {
console.error(
'Failed to open more menu in code toolbar! Unexpected missing more button'
);
return;
}
createLitPortal({
template: html`
<affine-code-more-menu
.context=${this.context}
.moreGroups=${this.moreGroups}
></affine-code-more-menu>
`,
// should be greater than block-selection z-index as selection and popover wil share the same stacking context(editor-host)
portalStyles: {
zIndex: 'var(--affine-z-index-popover)',
},
container: this.context.host,
computePosition: {
referenceElement: this._moreButton,
placement: 'bottom-start',
middleware: [flip(), offset(4)],
autoUpdate: { animationFrame: true },
},
abortController: this._popMenuAbortController,
closeOnClickAway: true,
});
this._moreMenuOpen = true;
}
override disconnectedCallback() {
super.disconnectedCallback();
this.closeCurrentMenu();
}
override connectedCallback() {
super.connectedCallback();
// Mirror the collapsed$ signal from the block component into local @state
// so this LitElement re-renders when it changes.
this.disposables.add(
effect(() => {
this._collapsed = this.context.blockComponent.collapsed$.value;
})
);
}
override render() {
return html`
<editor-toolbar class="code-toolbar-container" data-without-bg>
${renderGroups(this.primaryGroups, this.context)}
<editor-icon-button
class="code-toolbar-button more"
data-testid="more"
aria-label="More"
.tooltip=${'More'}
.tooltipOffset=${4}
.iconSize=${'16px'}
.iconContainerPadding=${4}
.showTooltip=${!this._moreMenuOpen}
?disabled=${this.context.doc.readonly}
@click=${() => this._toggleMoreMenu()}
>
${MoreVerticalIcon()}
</editor-icon-button>
</editor-toolbar>
`;
}
@query('.code-toolbar-button.more')
private accessor _moreButton!: EditorIconButton;
@state()
private accessor _moreMenuOpen = false;
@state()
private accessor _collapsed = false;
@property({ attribute: false })
accessor context!: CodeBlockToolbarContext;
@property({ attribute: false })
accessor moreGroups!: MenuItemGroup<CodeBlockToolbarContext>[];
@property({ attribute: false })
accessor onActiveStatusChange: (active: boolean) => void = noop;
@property({ attribute: false })
accessor primaryGroups!: MenuItemGroup<CodeBlockToolbarContext>[];
}

View File

@@ -0,0 +1,168 @@
import {
type FilterableListItem,
type FilterableListOptions,
showPopFilterableList,
} from '@blocksuite/affine-components/filterable-list';
import { ArrowDownIcon } from '@blocksuite/affine-components/icons';
import {
DocModeProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
import { noop } from '@blocksuite/global/utils';
import { css, LitElement, nothing } from 'lit';
import { property, query } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
import { html } from 'lit/static-html.js';
import type { CodeBlockComponent } from '../..';
export class LanguageListButton extends WithDisposable(
SignalWatcher(LitElement)
) {
static override styles = css`
.lang-button {
display: flex;
gap: 4px;
padding: 2px 4px;
height: 28px;
}
.lang-button:hover {
background: ${unsafeCSSVarV2('layer/background/hoverOverlay')};
}
.lang-button[hover] {
background: ${unsafeCSSVarV2('layer/background/hoverOverlay')};
}
.lang-button-icon {
display: flex;
align-items: center;
color: ${unsafeCSSVarV2('icon/primary')};
svg {
height: 16px;
width: 16px;
}
}
`;
private _abortController?: AbortController;
private readonly _clickLangBtn = () => {
if (this.blockComponent.store.readonly) return;
if (this._abortController) {
// Close the language list if it's already opened.
this._abortController.abort();
return;
}
this._abortController = new AbortController();
this._abortController.signal.addEventListener('abort', () => {
this.onActiveStatusChange(false);
this._abortController = undefined;
});
this.onActiveStatusChange(true);
const options: FilterableListOptions = {
placeholder: 'Search for a language',
onSelect: item => {
const sortedBundledLanguages = this._sortedBundledLanguages;
const index = sortedBundledLanguages.indexOf(item);
if (index !== -1) {
sortedBundledLanguages.splice(index, 1);
sortedBundledLanguages.unshift(item);
}
this.blockComponent.store.transact(() => {
this.blockComponent.model.props.language$.value = item.name;
});
const std = this.blockComponent.std;
const mode =
std.getOptional(DocModeProvider)?.getEditorMode() ?? 'page';
const telemetryService = std.getOptional(TelemetryProvider);
if (!telemetryService) return;
telemetryService.track('codeBlockLanguageSelect', {
page: mode,
segment: 'code block',
module: 'language selector',
control: item.name,
});
},
active: item => item.name === this.blockComponent.model.props.language,
items: this._sortedBundledLanguages,
};
showPopFilterableList({
options,
referenceElement: this._langButton,
container: this.blockComponent.host,
abortController: this._abortController,
// stacking-context(editor-host)
portalStyles: {
zIndex: 'var(--affine-z-index-popover)',
},
});
};
private _sortedBundledLanguages: FilterableListItem[] = [];
override connectedCallback(): void {
super.connectedCallback();
const langList = localStorage.getItem('blocksuite:code-block:lang-list');
if (langList) {
this._sortedBundledLanguages = JSON.parse(langList);
} else {
this._sortedBundledLanguages = this.blockComponent.langs.map(lang => ({
label: lang.name,
name: lang.id,
aliases: lang.aliases,
}));
}
this.disposables.add(() => {
localStorage.setItem(
'blocksuite:code-block:lang-list',
JSON.stringify(this._sortedBundledLanguages)
);
});
}
override render() {
const textStyles = styleMap({
fontFamily: 'Inter',
fontSize: 'var(--affine-font-xs)',
fontStyle: 'normal',
fontWeight: '500',
lineHeight: '20px',
padding: '0 4px',
});
return html`<icon-button
class="lang-button"
data-testid="lang-button"
width="auto"
.text=${html`<div style=${textStyles}>
${this.blockComponent.languageName$.value}
</div>`}
height="24px"
@click=${this._clickLangBtn}
?disabled=${this.blockComponent.store.readonly}
>
<span class="lang-button-icon" slot="suffix">
${!this.blockComponent.store.readonly ? ArrowDownIcon : nothing}
</span>
</icon-button> `;
}
@query('.lang-button')
private accessor _langButton!: HTMLElement;
@property({ attribute: false })
accessor blockComponent!: CodeBlockComponent;
@property({ attribute: false })
accessor onActiveStatusChange: (active: boolean) => void = noop;
}

View File

@@ -0,0 +1,52 @@
import type { MenuItemGroup } from '@blocksuite/affine-components/toolbar';
import { renderGroups } from '@blocksuite/affine-components/toolbar';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
import { ShadowlessElement } from '@blocksuite/std';
import { html } from 'lit';
import { property } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
import type { CodeBlockToolbarContext } from '../context.js';
export class AffineCodeMoreMenu extends SignalWatcher(
WithDisposable(ShadowlessElement)
) {
override firstUpdated() {
this.disposables.add(
this.context.blockComponent.model.propsUpdated.subscribe(({ key }) => {
if (key === 'wrap' || key === 'lineNumber') {
this.requestUpdate();
}
})
);
}
override render() {
return html`
<editor-menu-content
data-show
class="more-popup-menu"
style=${styleMap({
'--content-padding': '8px',
'--packed-height': '4px',
})}
>
<div data-size="large" data-orientation="vertical">
${renderGroups(this.moreGroups, this.context)}
</div>
</editor-menu-content>
`;
}
@property({ attribute: false })
accessor context!: CodeBlockToolbarContext;
@property({ attribute: false })
accessor moreGroups!: MenuItemGroup<CodeBlockToolbarContext>[];
}
declare global {
interface HTMLElementTagNameMap {
'affine-code-more-menu': AffineCodeMoreMenu;
}
}

View File

@@ -0,0 +1,112 @@
import {
DocModeProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
import { css, html, LitElement, nothing } from 'lit';
import { property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import type { CodeBlockComponent } from '../../code-block';
import { CodeBlockPreviewIdentifier } from '../../code-preview-extension';
export class PreviewButton extends WithDisposable(SignalWatcher(LitElement)) {
static override styles = css`
:host {
margin-right: auto;
}
.preview-toggle-container {
display: flex;
padding: 2px;
align-items: flex-start;
gap: 4px;
border-radius: 4px;
background: ${unsafeCSSVarV2('segment/background')};
}
.toggle-button {
display: flex;
padding: 0px 4px;
justify-content: center;
align-items: center;
gap: 4px;
border-radius: 4px;
color: ${unsafeCSSVarV2('text/primary')};
font-family: Inter;
font-size: 12px;
font-style: normal;
font-weight: 500;
line-height: 20px;
}
.toggle-button:hover {
background: ${unsafeCSSVarV2('layer/background/hoverOverlay')};
}
.toggle-button.active {
background: ${unsafeCSSVarV2('segment/button')};
box-shadow:
var(--Shadow-buttonShadow-1-x, 0px) var(--Shadow-buttonShadow-1-y, 0px)
var(--Shadow-buttonShadow-1-blur, 1px) 0px
var(--Shadow-buttonShadow-1-color, rgba(0, 0, 0, 0.12)),
var(--Shadow-buttonShadow-2-x, 0px) var(--Shadow-buttonShadow-2-y, 1px)
var(--Shadow-buttonShadow-2-blur, 5px) 0px
var(--Shadow-buttonShadow-2-color, rgba(0, 0, 0, 0.12));
}
`;
private readonly _toggle = (value: boolean) => {
this.blockComponent.setPreviewState(value);
const std = this.blockComponent.std;
const mode = std.getOptional(DocModeProvider)?.getEditorMode() ?? 'page';
const telemetryService = std.getOptional(TelemetryProvider);
if (!telemetryService) return;
telemetryService.track('htmlBlockTogglePreview', {
page: mode,
segment: 'code block',
module: 'code toolbar container',
control: 'preview toggle button',
});
};
get preview() {
return this.blockComponent.preview$.value;
}
override render() {
const lang = this.blockComponent.model.props.language$.value ?? '';
const previewContext = this.blockComponent.std.getOptional(
CodeBlockPreviewIdentifier(lang)
);
if (!previewContext) return nothing;
return html`
<div class="preview-toggle-container">
<div
class=${classMap({
'toggle-button': true,
active: !this.preview,
})}
@click=${() => this._toggle(false)}
>
Code
</div>
<div
class=${classMap({
'toggle-button': true,
active: this.preview,
})}
@click=${() => this._toggle(true)}
>
Preview
</div>
</div>
`;
}
@property({ attribute: false })
accessor blockComponent!: CodeBlockComponent;
}

View File

@@ -0,0 +1,319 @@
import {
CancelWrapIcon,
CaptionIcon,
CollapseCodeIcon,
CopyIcon,
DeleteIcon,
DuplicateIcon,
ExpandCodeIcon,
WrapIcon,
} from '@blocksuite/affine-components/icons';
import type { MenuItemGroup } from '@blocksuite/affine-components/toolbar';
import { CommentProviderIdentifier } from '@blocksuite/affine-shared/services';
import { isInsidePageEditor } from '@blocksuite/affine-shared/utils';
import { noop, sleep } from '@blocksuite/global/utils';
import { CommentIcon, NumberedListIcon } from '@blocksuite/icons/lit';
import { BlockSelection } from '@blocksuite/std';
import { html } from 'lit';
import { ifDefined } from 'lit/directives/if-defined.js';
import { CodeBlockConfigExtension } from '../code-block-config.js';
import type { CodeBlockToolbarContext } from './context.js';
import { duplicateCodeBlock } from './utils.js';
export const PRIMARY_GROUPS: MenuItemGroup<CodeBlockToolbarContext>[] = [
{
type: 'primary',
items: [
{
type: 'change-lang',
generate: ({ blockComponent, setActive }) => {
const state = { active: false };
return {
action: noop,
render: () =>
html`<language-list-button
.blockComponent=${blockComponent}
.onActiveStatusChange=${async (active: boolean) => {
state.active = active;
if (!active) {
await sleep(1000);
if (state.active) return;
}
setActive(active);
}}
>
</language-list-button>`,
};
},
},
{
type: 'preview',
generate: ({ blockComponent }) => {
return {
action: noop,
render: () => html`
<preview-button .blockComponent=${blockComponent}>
</preview-button>
`,
};
},
},
{
type: 'copy-code',
label: 'Copy code',
icon: CopyIcon,
generate: ({ blockComponent }) => {
return {
action: () => {
blockComponent.copyCode();
},
render: item => html`
<editor-icon-button
class="code-toolbar-button copy-code"
aria-label=${ifDefined(item.label)}
.tooltip=${item.label}
.tooltipOffset=${4}
.iconSize=${'16px'}
.iconContainerPadding=${4}
@click=${(e: MouseEvent) => {
e.stopPropagation();
item.action();
}}
>
${item.icon}
</editor-icon-button>
`,
};
},
},
{
type: 'collapse',
when: ({ doc }) => !doc.readonly,
generate: ({ blockComponent }) => {
return {
action: () => {
blockComponent.setCollapsed(!blockComponent.collapsed$.value);
},
render: item => {
const collapsed = blockComponent.collapsed$.value;
const icon = collapsed ? ExpandCodeIcon : CollapseCodeIcon;
const label = collapsed ? 'Expand code' : 'Collapse code';
return html`
<editor-icon-button
class="code-toolbar-button collapse"
aria-label=${label}
.tooltip=${label}
.tooltipOffset=${4}
.iconSize=${'16px'}
.iconContainerPadding=${4}
@click=${(e: MouseEvent) => {
e.stopPropagation();
item.action();
}}
>
${icon}
</editor-icon-button>
`;
},
};
},
},
{
type: 'caption',
label: 'Caption',
icon: CaptionIcon,
when: ({ doc }) => !doc.readonly,
generate: ({ blockComponent }) => {
return {
action: () => {
blockComponent.captionEditor?.show();
},
render: item => html`
<editor-icon-button
class="code-toolbar-button caption"
aria-label=${ifDefined(item.label)}
.tooltip=${item.label}
.tooltipOffset=${4}
.iconSize=${'16px'}
.iconContainerPadding=${4}
@click=${(e: MouseEvent) => {
e.stopPropagation();
item.action();
}}
>
${item.icon}
</editor-icon-button>
`,
};
},
},
{
type: 'comment',
label: 'Comment',
tooltip: 'Comment',
icon: CommentIcon({
width: '20',
height: '20',
}),
when: ({ std }) => !!std.getOptional(CommentProviderIdentifier),
generate: ({ blockComponent }) => {
return {
action: () => {
const commentProvider = blockComponent.std.getOptional(
CommentProviderIdentifier
);
if (!commentProvider) return;
commentProvider.addComment([
new BlockSelection({
blockId: blockComponent.model.id,
}),
]);
},
render: item =>
html`<editor-icon-button
class="code-toolbar-button comment"
aria-label=${ifDefined(item.label)}
.tooltip=${item.label}
.tooltipOffset=${4}
.iconSize=${'16px'}
.iconContainerPadding=${4}
@click=${(e: MouseEvent) => {
e.stopPropagation();
item.action();
}}
>
${item.icon}
</editor-icon-button>`,
};
},
},
],
},
];
export const toggleGroup: MenuItemGroup<CodeBlockToolbarContext> = {
type: 'toggle',
items: [
{
type: 'wrap',
generate: ({ blockComponent }) => {
return {
action: () => {},
render: () => {
const wrapped = blockComponent.model.props.wrap;
const label = wrapped ? 'Cancel wrap' : 'Wrap';
const icon = wrapped ? CancelWrapIcon : WrapIcon;
return html`
<editor-menu-action
@click=${() => {
const currentWrap = blockComponent.model.props.wrap;
blockComponent.setWrap(!currentWrap);
}}
aria-label=${label}
>
${icon}
<span class="label">${label}</span>
<toggle-switch
style="margin-left: auto;"
.on="${wrapped}"
></toggle-switch>
</editor-menu-action>
`;
},
};
},
},
{
type: 'line-number',
when: ({ std }) =>
std.getOptional(CodeBlockConfigExtension.identifier)?.showLineNumbers ??
true,
generate: ({ blockComponent }) => {
return {
action: () => {},
render: () => {
const lineNumber = blockComponent.showLineNumbers;
const label = lineNumber ? 'Cancel line number' : 'Line number';
return html`
<editor-menu-action
@click=${() => {
blockComponent.store.updateBlock(blockComponent.model, {
lineNumber: !blockComponent.showLineNumbers,
});
}}
aria-label=${label}
>
${NumberedListIcon()}
<span class="label">${label}</span>
<toggle-switch
style="margin-left: auto;"
.on="${lineNumber}"
></toggle-switch>
</editor-menu-action>
`;
},
};
},
},
],
};
// Clipboard Group
export const clipboardGroup: MenuItemGroup<CodeBlockToolbarContext> = {
type: 'clipboard',
items: [
{
type: 'duplicate',
label: 'Duplicate',
icon: DuplicateIcon,
when: ({ doc }) => !doc.readonly,
action: ({ host, blockComponent, close }) => {
const codeId = duplicateCodeBlock(blockComponent.model);
host.updateComplete
.then(() => {
host.selection.setGroup('note', [
host.selection.create(BlockSelection, {
blockId: codeId,
}),
]);
if (isInsidePageEditor(host)) {
const duplicateElement = host.view.getBlock(codeId);
if (duplicateElement) {
duplicateElement.scrollIntoView({ block: 'nearest' });
}
}
})
.catch(console.error);
close();
},
},
],
};
// Delete Group
export const deleteGroup: MenuItemGroup<CodeBlockToolbarContext> = {
type: 'delete',
items: [
{
type: 'delete',
label: 'Delete',
icon: DeleteIcon,
when: ({ doc }) => !doc.readonly,
action: ({ doc, blockComponent, close }) => {
doc.deleteBlock(blockComponent.model);
close();
},
},
],
};
export const MORE_GROUPS: MenuItemGroup<CodeBlockToolbarContext>[] = [
toggleGroup,
clipboardGroup,
deleteGroup,
];

View File

@@ -0,0 +1,46 @@
import { MenuContext } from '@blocksuite/affine-components/toolbar';
import type { CodeBlockComponent } from '../code-block';
export class CodeBlockToolbarContext extends MenuContext {
override close = () => {
this.abortController.abort();
};
get doc() {
return this.blockComponent.store;
}
get host() {
return this.blockComponent.host;
}
get selectedBlockModels() {
if (this.blockComponent.model) return [this.blockComponent.model];
return [];
}
get std() {
return this.blockComponent.std;
}
constructor(
public blockComponent: CodeBlockComponent,
public abortController: AbortController,
public setActive: (active: boolean) => void
) {
super();
}
isEmpty() {
return false;
}
isMultiple() {
return false;
}
isSingle() {
return true;
}
}

View File

@@ -0,0 +1,173 @@
import { HoverController } from '@blocksuite/affine-components/hover';
import type {
AdvancedMenuItem,
MenuItemGroup,
} from '@blocksuite/affine-components/toolbar';
import {
cloneGroups,
getMoreMenuConfig,
} from '@blocksuite/affine-components/toolbar';
import type { CodeBlockModel } from '@blocksuite/affine-model';
import {
BlockSelection,
TextSelection,
WidgetComponent,
} from '@blocksuite/std';
import { limitShift, shift, size } from '@floating-ui/dom';
import { html } from 'lit';
import type { CodeBlockComponent } from '../code-block.js';
import { MORE_GROUPS, PRIMARY_GROUPS } from './config.js';
import { CodeBlockToolbarContext } from './context.js';
export const AFFINE_CODE_TOOLBAR_WIDGET = 'affine-code-toolbar-widget';
export class AffineCodeToolbarWidget extends WidgetComponent<
CodeBlockModel,
CodeBlockComponent
> {
private _hoverController: HoverController | null = null;
private _isActivated = false;
private readonly _setHoverController = () => {
this._hoverController = null;
this._hoverController = new HoverController(
this,
({ abortController }) => {
const codeBlock = this.block;
if (!codeBlock) {
return null;
}
const selection = this.host.selection;
const textSelection = selection.find(TextSelection);
if (
!!textSelection &&
(!!textSelection.to || !!textSelection.from.length)
) {
return null;
}
const blockSelections = selection.filter(BlockSelection);
if (
blockSelections.length > 1 ||
(blockSelections.length === 1 &&
blockSelections[0].blockId !== codeBlock.blockId)
) {
return null;
}
const setActive = (active: boolean) => {
this._isActivated = active;
if (!active && !this._hoverController?.isHovering) {
this._hoverController?.abort();
}
};
const context = new CodeBlockToolbarContext(
codeBlock,
abortController,
setActive
);
return {
template: html`<affine-code-toolbar
.context=${context}
.primaryGroups=${this.primaryGroups}
.moreGroups=${this.moreGroups}
.onActiveStatusChange=${setActive}
></affine-code-toolbar>`,
container: this.block,
// stacking-context(editor-host)
portalStyles: {
zIndex: 'var(--affine-z-index-popover)',
},
computePosition: {
referenceElement: codeBlock,
placement: 'top',
middleware: [
size({
apply({ rects, elements }) {
elements.floating.style.width = `${rects.reference.width}px`;
},
}),
shift({
crossAxis: true,
padding: {
bottom: 12,
right: 12,
},
limiter: limitShift(),
}),
],
autoUpdate: true,
},
};
},
{ allowMultiple: true }
);
const codeBlock = this.block;
if (!codeBlock) {
return;
}
this._hoverController.setReference(codeBlock);
this._hoverController.onAbort = () => {
// If the more menu is opened, don't close it.
if (this._isActivated) return;
this._hoverController?.abort();
return;
};
};
addMoretems = (
items: AdvancedMenuItem<CodeBlockToolbarContext>[],
index?: number,
type?: string
) => {
let group;
if (type) {
group = this.moreGroups.find(g => g.type === type);
}
if (!group) {
group = this.moreGroups[0];
}
if (index === undefined) {
group.items.push(...items);
return this;
}
group.items.splice(index, 0, ...items);
return this;
};
addPrimaryItems = (
items: AdvancedMenuItem<CodeBlockToolbarContext>[],
index?: number
) => {
if (index === undefined) {
this.primaryGroups[0].items.push(...items);
return this;
}
this.primaryGroups[0].items.splice(index, 0, ...items);
return this;
};
/*
* Caches the more menu items.
* Currently only supports configuring more menu.
*/
protected moreGroups: MenuItemGroup<CodeBlockToolbarContext>[] =
cloneGroups(MORE_GROUPS);
protected primaryGroups: MenuItemGroup<CodeBlockToolbarContext>[] =
cloneGroups(PRIMARY_GROUPS);
override firstUpdated() {
this.moreGroups = getMoreMenuConfig(this.std).configure(this.moreGroups);
this._setHoverController();
}
}

View File

@@ -0,0 +1,16 @@
import type { CodeBlockModel } from '@blocksuite/affine-model';
export const duplicateCodeBlock = (model: CodeBlockModel) => {
const keys = model.keys as (keyof (typeof model)['props'])[];
const values = keys.map(key => model.props[key]);
const blockProps = Object.fromEntries(keys.map((key, i) => [key, values[i]]));
const { text: _text, ...duplicateProps } = blockProps;
const newProps = {
flavour: model.flavour,
text: model.props.text.clone(),
...duplicateProps,
};
return model.store.addSiblingBlocks(model, [newProps])[0];
};

View File

@@ -0,0 +1,8 @@
import { type SlashMenuConfig } from '@blocksuite/affine-widget-slash-menu';
export const codeSlashMenuConfig: SlashMenuConfig = {
disableWhen: ({ model }) => {
return model.flavour === 'affine:code';
},
items: [],
};

View File

@@ -0,0 +1,30 @@
import { CodeBlockComponent } from './code-block';
import {
AFFINE_CODE_TOOLBAR_WIDGET,
AffineCodeToolbarWidget,
} from './code-toolbar';
import { AffineCodeToolbar } from './code-toolbar/components/code-toolbar';
import { LanguageListButton } from './code-toolbar/components/lang-button';
import { AffineCodeMoreMenu } from './code-toolbar/components/more-menu';
import { PreviewButton } from './code-toolbar/components/preview-button';
import { AffineCodeUnit } from './highlight/affine-code-unit';
export function effects() {
customElements.define('language-list-button', LanguageListButton);
customElements.define('affine-code-toolbar', AffineCodeToolbar);
customElements.define('affine-code-more-menu', AffineCodeMoreMenu);
customElements.define(AFFINE_CODE_TOOLBAR_WIDGET, AffineCodeToolbarWidget);
customElements.define('affine-code-unit', AffineCodeUnit);
customElements.define('affine-code', CodeBlockComponent);
customElements.define('preview-button', PreviewButton);
}
declare global {
interface HTMLElementTagNameMap {
'language-list-button': LanguageListButton;
'affine-code-toolbar': AffineCodeToolbar;
'affine-code-more-menu': AffineCodeMoreMenu;
'preview-button': PreviewButton;
[AFFINE_CODE_TOOLBAR_WIDGET]: AffineCodeToolbarWidget;
}
}

View File

@@ -0,0 +1,124 @@
import { affineTextStyles } from '@blocksuite/affine-shared/styles';
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import { ShadowlessElement } from '@blocksuite/std';
import { ZERO_WIDTH_FOR_EMPTY_LINE } from '@blocksuite/std/inline';
import type { DeltaInsert } from '@blocksuite/store';
import { html } from 'lit';
import { property } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
import type { ThemedToken } from 'shiki';
export class AffineCodeUnit extends ShadowlessElement {
get codeBlock() {
return this.closest('affine-code');
}
get vElement() {
return this.closest('v-element');
}
override render() {
if (this.delta.attributes?.link && this.codeBlock) {
return html`<affine-link
.std=${this.codeBlock.std}
.delta=${this.delta}
></affine-link>`;
}
let style = this.delta.attributes
? affineTextStyles(this.delta.attributes)
: {};
if (this.delta.attributes?.code) {
style = {
...style,
'font-size': 'calc(var(--affine-font-base) - 3px)',
padding: '0px 4px 2px',
};
}
const plainContent = html`<span style=${styleMap(style)}
><v-text .str=${this.delta.insert}></v-text
></span>`;
const codeBlock = this.codeBlock;
const vElement = this.vElement;
if (!codeBlock || !vElement) return plainContent;
const tokens = codeBlock.highlightTokens$.value;
if (tokens.length === 0) return plainContent;
const line = tokens[vElement.lineIndex];
if (!line) return plainContent;
// copy the tokens to avoid modifying the original tokens
const lineTokens = structuredClone(line);
if (lineTokens.length === 0) return plainContent;
const startOffset = vElement.startOffset;
const endOffset = vElement.endOffset;
const includedTokens: ThemedToken[] = [];
lineTokens.forEach(token => {
if (
(token.offset <= startOffset &&
token.offset + token.content.length >= startOffset) ||
(token.offset >= startOffset &&
token.offset + token.content.length <= endOffset) ||
(token.offset <= endOffset &&
token.offset + token.content.length >= endOffset)
) {
includedTokens.push(token);
}
});
if (includedTokens.length === 0) return plainContent;
if (includedTokens.length === 1) {
const token = includedTokens[0];
const content = token.content.slice(
startOffset - token.offset,
endOffset - token.offset
);
return html`<span
style=${styleMap({
color: token.color,
...style,
})}
><v-text .str=${content}></v-text
></span>`;
} else {
const firstToken = includedTokens[0];
const lastToken = includedTokens[includedTokens.length - 1];
const firstContent = firstToken.content.slice(
startOffset - firstToken.offset,
firstToken.content.length
);
const lastContent = lastToken.content.slice(
0,
endOffset - lastToken.offset
);
firstToken.content = firstContent;
lastToken.content = lastContent;
const vTexts = includedTokens.map(token => {
return html`<v-text
.str=${token.content}
style=${styleMap({
color: token.color,
...style,
})}
></v-text>`;
});
return html`<span>${vTexts}</span>`;
}
}
@property({ type: Object })
accessor delta: DeltaInsert<AffineTextAttributes> = {
insert: ZERO_WIDTH_FOR_EMPTY_LINE,
};
}
declare global {
interface HTMLElementTagNameMap {
'affine-code-unit': AffineCodeUnit;
}
}

View File

@@ -0,0 +1,4 @@
export const CODE_BLOCK_DEFAULT_DARK_THEME =
import('shiki/themes/dark-plus.mjs');
export const CODE_BLOCK_DEFAULT_LIGHT_THEME =
import('shiki/themes/light-plus.mjs');

View File

@@ -0,0 +1,10 @@
export * from './adapters';
export * from './clipboard';
export * from './code-block';
export * from './code-block-config';
export * from './code-block-service';
export * from './code-preview-extension';
export * from './code-toolbar';
export * from './highlight/const';
export * from './turbo/code-layout-handler';
export * from './turbo/code-painter.worker';

View File

@@ -0,0 +1,61 @@
import {
type CodeBlockModel,
CodeBlockSchema,
ParagraphBlockModel,
} from '@blocksuite/affine-model';
import { focusTextModel } from '@blocksuite/affine-rich-text';
import type { AffineTextAttributes } from '@blocksuite/affine-shared/types';
import { matchModels } from '@blocksuite/affine-shared/utils';
import type { BlockComponent } from '@blocksuite/std';
import { InlineMarkdownExtension } from '@blocksuite/std/inline';
export const CodeBlockMarkdownExtension =
InlineMarkdownExtension<AffineTextAttributes>({
name: 'code-block',
pattern: /^```([a-zA-Z0-9]*)\s$/,
action: ({ inlineEditor, inlineRange, prefixText, pattern }) => {
if (inlineEditor.yTextString.slice(0, inlineRange.index).includes('\n')) {
return;
}
const match = prefixText.match(pattern);
if (!match) return;
const language = match[1];
if (!inlineEditor.rootElement) return;
const blockComponent =
inlineEditor.rootElement.closest<BlockComponent>('[data-block-id]');
if (!blockComponent) return;
const { model, std, store } = blockComponent;
if (
matchModels(model, [ParagraphBlockModel]) &&
model.props.type === 'quote'
) {
return;
}
const parent = store.getParent(model);
if (!parent) return;
const index = parent.children.indexOf(model);
store.captureSync();
const codeId = store.addBlock<CodeBlockModel>(
CodeBlockSchema.model.flavour,
{ language },
parent,
index
);
if (model.text && model.text.length > prefixText.length) {
const text = model.text.clone();
store.addBlock('affine:paragraph', { text }, parent, index + 1);
text.delete(0, prefixText.length);
}
store.deleteBlock(model, { bringChildrenTo: parent });
focusTextModel(std, codeId);
},
});

View File

@@ -0,0 +1,19 @@
import {
type StoreExtensionContext,
StoreExtensionProvider,
} from '@blocksuite/affine-ext-loader';
import { CodeBlockSchemaExtension } from '@blocksuite/affine-model';
import { CodeBlockAdapterExtensions } from './adapters/extension';
import { CodeMarkdownPreprocessorExtension } from './adapters/markdown/preprocessor';
export class CodeStoreExtension extends StoreExtensionProvider {
override name = 'affine-code-block';
override setup(context: StoreExtensionContext) {
super.setup(context);
context.register(CodeBlockSchemaExtension);
context.register(CodeBlockAdapterExtensions);
context.register(CodeMarkdownPreprocessorExtension);
}
}

View File

@@ -0,0 +1,114 @@
import { scrollbarStyle } from '@blocksuite/affine-shared/styles';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { css } from 'lit';
export const codeBlockStyles = css`
affine-code {
display: block;
}
.affine-code-block-container {
font-size: var(--affine-font-xs);
line-height: var(--affine-line-height);
position: relative;
padding: 32px 20px;
background: var(--affine-background-code-block);
border-radius: 10px;
box-sizing: border-box;
}
.affine-code-block-container.mobile {
padding: 12px;
}
.affine-code-block-container.highlight-comment {
outline: 2px solid ${unsafeCSSVarV2('block/comment/highlightUnderline')};
}
${scrollbarStyle('.affine-code-block-container rich-text')}
/* In Chromium 121+, non-auto scrollbar-width/color override ::-webkit-scrollbar styles. */
@supports not selector(::-webkit-scrollbar) {
.affine-code-block-container rich-text {
scrollbar-width: thin;
scrollbar-color: ${unsafeCSSVarV2('icon/secondary', '#b1b1b1')}
transparent;
scrollbar-gutter: stable both-edges;
}
}
.affine-code-block-container .inline-editor {
font-family: var(--affine-font-code-family);
font-variant-ligatures: none;
}
.affine-code-block-container v-line {
position: relative;
display: inline-grid !important;
grid-template-columns: auto minmax(0, 1fr);
}
.affine-code-block-container.disable-line-numbers v-line {
grid-template-columns: unset;
}
.affine-code-block-container div:has(> v-line) {
display: grid;
}
.affine-code-block-container .line-number {
position: sticky;
text-align: left;
padding-right: 12px;
width: 32px;
word-break: break-word;
white-space: nowrap;
left: -0.5px;
z-index: 1;
background: var(--affine-background-code-block);
font-size: var(--affine-font-xs);
line-height: var(--affine-line-height);
color: var(--affine-text-secondary);
box-sizing: border-box;
user-select: none;
}
.affine-code-block-container.disable-line-numbers .line-number {
display: none;
}
affine-code .affine-code-block-preview {
padding: 12px;
}
/* ── Collapsed state ──────────────────────────────────────────────── */
/* Clamp the rich-text to the first 8 lines */
.affine-code-block-container.collapsed rich-text {
display: block;
max-height: calc(8 * var(--affine-line-height));
overflow: hidden;
}
/* Reduce bottom padding so the fade sits flush with the border */
.affine-code-block-container.collapsed {
padding-bottom: 0;
}
/* Gradient overlay that fades to the block background */
.affine-code-block-container .code-collapsed-fade {
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 80px;
background: linear-gradient(
to bottom,
transparent,
var(--affine-background-code-block)
);
border-radius: 0 0 10px 10px;
pointer-events: none;
z-index: 1;
}
`;

View File

@@ -0,0 +1,73 @@
import type { Rect } from '@blocksuite/affine-gfx-turbo-renderer';
import {
BlockLayoutHandlerExtension,
BlockLayoutHandlersIdentifier,
} from '@blocksuite/affine-gfx-turbo-renderer';
import type { Container } from '@blocksuite/global/di';
import type { EditorHost, GfxBlockComponent } from '@blocksuite/std';
import { clientToModelCoord, type ViewportRecord } from '@blocksuite/std/gfx';
import type { BlockModel } from '@blocksuite/store';
import type { CodeLayout } from './code-painter.worker';
export class CodeLayoutHandlerExtension extends BlockLayoutHandlerExtension<CodeLayout> {
readonly blockType = 'affine:code';
static override setup(di: Container) {
di.addImpl(
BlockLayoutHandlersIdentifier('code'),
CodeLayoutHandlerExtension
);
}
override queryLayout(
model: BlockModel,
host: EditorHost,
viewportRecord: ViewportRecord
): CodeLayout | null {
const component = host.std.view.getBlock(
model.id
) as GfxBlockComponent | null;
if (!component) return null;
const codeBlockElement = component.querySelector(
'.affine-code-block-container'
);
if (!codeBlockElement) return null;
const { zoom, viewScale } = viewportRecord;
const codeLayout: CodeLayout = {
type: 'affine:code',
blockId: model.id,
rect: { x: 0, y: 0, w: 0, h: 0 },
};
// Get the bounding rect of the code block
const clientRect = codeBlockElement.getBoundingClientRect();
if (!clientRect) return null;
// Convert client coordinates to model coordinates
const [modelX, modelY] = clientToModelCoord(viewportRecord, [
clientRect.x,
clientRect.y,
]);
codeLayout.rect = {
x: modelX,
y: modelY,
w: clientRect.width / zoom / viewScale,
h: clientRect.height / zoom / viewScale,
};
return codeLayout;
}
calculateBound(layout: CodeLayout) {
const rect: Rect = layout.rect;
return {
rect,
subRects: [rect],
};
}
}

Some files were not shown because too many files have changed in this diff Show More