refactor(editor): unify directories naming (#11516)

**Directory Structure Changes**

- Renamed multiple block-related directories by removing the "block-" prefix:
  - `block-attachment` → `attachment`
  - `block-bookmark` → `bookmark`
  - `block-callout` → `callout`
  - `block-code` → `code`
  - `block-data-view` → `data-view`
  - `block-database` → `database`
  - `block-divider` → `divider`
  - `block-edgeless-text` → `edgeless-text`
  - `block-embed` → `embed`
This commit is contained in:
Saul-Mirone
2025-04-07 12:34:40 +00:00
parent e1bd2047c4
commit 1f45cc5dec
893 changed files with 439 additions and 460 deletions
@@ -0,0 +1,55 @@
import { EmbedIframeBlockSchema } from '@blocksuite/affine-model';
import { BlockHtmlAdapterExtension } from '@blocksuite/affine-shared/adapters';
import { createEmbedBlockHtmlAdapterMatcher } from '../../common/adapters/html';
export const embedIframeBlockHtmlAdapterMatcher =
createEmbedBlockHtmlAdapterMatcher(EmbedIframeBlockSchema.model.flavour, {
fromBlockSnapshot: {
enter: (o, context) => {
const { walkerContext } = context;
// Parse as link
if (
typeof o.node.props.title !== 'string' ||
typeof o.node.props.url !== 'string'
) {
return;
}
walkerContext
.openNode(
{
type: 'element',
tagName: 'div',
properties: {
className: ['affine-paragraph-block-container'],
},
children: [],
},
'children'
)
.openNode(
{
type: 'element',
tagName: 'a',
properties: {
href: o.node.props.url,
},
children: [
{
type: 'text',
value: o.node.props.title,
},
],
},
'children'
)
.closeNode()
.closeNode();
},
},
});
export const EmbedIframeBlockHtmlAdapterExtension = BlockHtmlAdapterExtension(
embedIframeBlockHtmlAdapterMatcher
);
@@ -0,0 +1,15 @@
import type { ExtensionType } from '@blocksuite/store';
import { EmbedIframeBlockHtmlAdapterExtension } from './html';
import { EmbedIframeBlockMarkdownAdapterExtension } from './markdown';
import { EmbedIframeBlockPlainTextAdapterExtension } from './plain-text';
export * from './html';
export * from './markdown';
export * from './plain-text';
export const EmbedIframeBlockAdapterExtensions: ExtensionType[] = [
EmbedIframeBlockHtmlAdapterExtension,
EmbedIframeBlockMarkdownAdapterExtension,
EmbedIframeBlockPlainTextAdapterExtension,
];
@@ -0,0 +1,46 @@
import { EmbedIframeBlockSchema } from '@blocksuite/affine-model';
import { BlockMarkdownAdapterExtension } from '@blocksuite/affine-shared/adapters';
import { createEmbedBlockMarkdownAdapterMatcher } from '../../common/adapters/markdown.js';
export const embedIframeBlockMarkdownAdapterMatcher =
createEmbedBlockMarkdownAdapterMatcher(EmbedIframeBlockSchema.model.flavour, {
fromBlockSnapshot: {
enter: (o, context) => {
const { walkerContext } = context;
// Parse as link
if (
typeof o.node.props.title !== 'string' ||
typeof o.node.props.url !== 'string'
) {
return;
}
walkerContext
.openNode(
{
type: 'paragraph',
children: [],
},
'children'
)
.openNode(
{
type: 'link',
url: o.node.props.url,
children: [
{
type: 'text',
value: o.node.props.title,
},
],
},
'children'
)
.closeNode()
.closeNode();
},
},
});
export const EmbedIframeBlockMarkdownAdapterExtension =
BlockMarkdownAdapterExtension(embedIframeBlockMarkdownAdapterMatcher);
@@ -0,0 +1,31 @@
import { EmbedIframeBlockSchema } from '@blocksuite/affine-model';
import { BlockPlainTextAdapterExtension } from '@blocksuite/affine-shared/adapters';
import { createEmbedBlockPlainTextAdapterMatcher } from '../../common/adapters/plain-text';
export const embedIframeBlockPlainTextAdapterMatcher =
createEmbedBlockPlainTextAdapterMatcher(
EmbedIframeBlockSchema.model.flavour,
{
fromBlockSnapshot: {
enter: (o, context) => {
const { textBuffer } = context;
// Parse as link
if (
typeof o.node.props.title !== 'string' ||
typeof o.node.props.url !== 'string'
) {
return;
}
const buffer = `[${o.node.props.title}](${o.node.props.url})`;
if (buffer.length > 0) {
textBuffer.content += buffer;
textBuffer.content += '\n';
}
},
},
}
);
export const EmbedIframeBlockPlainTextAdapterExtension =
BlockPlainTextAdapterExtension(embedIframeBlockPlainTextAdapterMatcher);
@@ -0,0 +1,2 @@
export * from './insert-embed-iframe-with-url';
export * from './insert-empty-embed-iframe';
@@ -0,0 +1,109 @@
import {
EdgelessCRUDIdentifier,
SurfaceBlockComponent,
} from '@blocksuite/affine-block-surface';
import { EmbedIframeService } from '@blocksuite/affine-shared/services';
import { Bound, Vec } from '@blocksuite/global/gfx';
import {
BlockSelection,
type Command,
SurfaceSelection,
TextSelection,
} from '@blocksuite/std';
import { GfxControllerIdentifier } from '@blocksuite/std/gfx';
import {
EMBED_IFRAME_DEFAULT_HEIGHT_IN_SURFACE,
EMBED_IFRAME_DEFAULT_WIDTH_IN_SURFACE,
} from '../consts';
export const insertEmbedIframeWithUrlCommand: Command<
{ url: string },
{ blockId: string; flavour: string }
> = (ctx, next) => {
const { url, std } = ctx;
const embedIframeService = std.get(EmbedIframeService);
if (!embedIframeService || !embedIframeService.canEmbed(url)) {
return;
}
const config = embedIframeService.getConfig(url);
if (!config) {
return;
}
const { host } = std;
const selectionManager = host.selection;
let selectedBlockId: string | undefined;
const textSelection = selectionManager.find(TextSelection);
const blockSelection = selectionManager.find(BlockSelection);
const surfaceSelection = selectionManager.find(SurfaceSelection);
if (textSelection) {
selectedBlockId = textSelection.blockId;
} else if (blockSelection) {
selectedBlockId = blockSelection.blockId;
} else if (surfaceSelection && surfaceSelection.editing) {
selectedBlockId = surfaceSelection.blockId;
}
const flavour = 'affine:embed-iframe';
const props: Record<string, unknown> = { url };
// When there is a selected block, it means that the selection is in note or edgeless text
// we should insert the embed iframe block after the selected block and only need the url prop
let newBlockId: string | undefined;
if (selectedBlockId) {
const block = host.view.getBlock(selectedBlockId);
if (!block) return;
const parent = host.doc.getParent(block.model);
if (!parent) return;
const index = parent.children.indexOf(block.model);
newBlockId = host.doc.addBlock(flavour, props, parent, index + 1);
} else {
// When there is no selected block and in edgeless mode
// We should insert the embed iframe block to surface
// It means that not only the url prop but also the xywh prop is needed
const rootId = std.store.root?.id;
if (!rootId) return;
const edgelessRoot = std.view.getBlock(rootId);
if (!edgelessRoot) return;
const gfx = std.get(GfxControllerIdentifier);
const crud = std.get(EdgelessCRUDIdentifier);
gfx.viewport.smoothZoom(1);
const surfaceBlock = gfx.surfaceComponent;
if (!(surfaceBlock instanceof SurfaceBlockComponent)) return;
const options = config.options;
const { widthInSurface, heightInSurface } = options ?? {};
const width = widthInSurface ?? EMBED_IFRAME_DEFAULT_WIDTH_IN_SURFACE;
const height = heightInSurface ?? EMBED_IFRAME_DEFAULT_HEIGHT_IN_SURFACE;
const center = Vec.toVec(surfaceBlock.renderer.viewport.center);
const xywh = Bound.fromCenter(center, width, height).serialize();
newBlockId = crud.addBlock(
flavour,
{
...props,
xywh,
},
surfaceBlock.model
);
gfx.tool.setTool(
// @ts-expect-error FIXME: resolve after gfx tool refactor
'default'
);
gfx.selection.set({
elements: [newBlockId],
editing: false,
});
}
if (!newBlockId) {
return;
}
next({ blockId: newBlockId, flavour });
};
@@ -0,0 +1,55 @@
import type { EmbedIframeBlockProps } from '@blocksuite/affine-model';
import type { Command } from '@blocksuite/std';
import type { BlockModel } from '@blocksuite/store';
import type { EmbedLinkInputPopupOptions } from '../components/embed-iframe-link-input-popup';
import { EmbedIframeBlockComponent } from '../embed-iframe-block';
export const insertEmptyEmbedIframeCommand: Command<
{
place?: 'after' | 'before';
removeEmptyLine?: boolean;
selectedModels?: BlockModel[];
linkInputPopupOptions?: EmbedLinkInputPopupOptions;
},
{
insertedEmbedIframeBlockId: Promise<string>;
}
> = (ctx, next) => {
const { selectedModels, place, removeEmptyLine, std, linkInputPopupOptions } =
ctx;
if (!selectedModels?.length) return;
const targetModel =
place === 'before'
? selectedModels[0]
: selectedModels[selectedModels.length - 1];
const embedIframeBlockProps: Partial<EmbedIframeBlockProps> & {
flavour: 'affine:embed-iframe';
} = {
flavour: 'affine:embed-iframe',
};
const result = std.store.addSiblingBlocks(
targetModel,
[embedIframeBlockProps],
place
);
if (result.length === 0) return;
if (removeEmptyLine && targetModel.text?.length === 0) {
std.store.deleteBlock(targetModel);
}
next({
insertedEmbedIframeBlockId: std.host.updateComplete.then(async () => {
const blockComponent = std.view.getBlock(result[0]);
if (blockComponent instanceof EmbedIframeBlockComponent) {
await blockComponent.updateComplete;
blockComponent.toggleLinkInputPopup(linkInputPopupOptions);
}
return result[0];
}),
});
};
@@ -0,0 +1,342 @@
import { createLitPortal } from '@blocksuite/affine-components/portal';
import type { EmbedIframeBlockModel } from '@blocksuite/affine-model';
import {
DocModeProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { WithDisposable } from '@blocksuite/global/lit';
import { EditIcon, InformationIcon, ResetIcon } from '@blocksuite/icons/lit';
import type { BlockStdScope } from '@blocksuite/std';
import { flip, offset } from '@floating-ui/dom';
import { baseTheme } from '@toeverything/theme';
import { css, html, LitElement, nothing, unsafeCSS } from 'lit';
import { property, query } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styleMap } from 'lit/directives/style-map.js';
import { ERROR_CARD_DEFAULT_HEIGHT } from '../consts';
import type { EmbedIframeStatusCardOptions } from '../types';
const LINK_EDIT_POPUP_OFFSET = 12;
export class EmbedIframeErrorCard extends WithDisposable(LitElement) {
static override styles = css`
:host {
width: 100%;
height: 100%;
}
.affine-embed-iframe-error-card {
container: affine-embed-iframe-error-card / size;
display: flex;
box-sizing: border-box;
user-select: none;
padding: 12px;
gap: 12px;
overflow: hidden;
border-radius: 8px;
border: 1px solid ${unsafeCSSVarV2('layer/insideBorder/border')};
background: ${unsafeCSSVarV2('layer/background/secondary')};
font-family: ${unsafeCSS(baseTheme.fontSansFamily)};
user-select: none;
.error-content {
display: flex;
flex-direction: column;
gap: 4px;
.error-title {
display: flex;
align-items: center;
gap: 8px;
overflow: hidden;
.error-icon {
display: flex;
justify-content: center;
align-items: center;
color: ${unsafeCSSVarV2('status/error')};
}
.error-title-text {
color: ${unsafeCSSVarV2('text/primary')};
text-align: justify;
/* Client/smBold */
font-size: var(--affine-font-sm);
font-style: normal;
font-weight: 600;
line-height: 22px; /* 157.143% */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.error-message {
display: flex;
align-self: stretch;
color: ${unsafeCSSVarV2('text/secondary')};
overflow: hidden;
font-feature-settings:
'liga' off,
'clig' off;
text-overflow: ellipsis;
/* Client/xs */
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 400;
line-height: 20px; /* 166.667% */
}
.error-info {
display: flex;
align-items: center;
gap: 8px;
overflow: hidden;
.button {
display: flex;
padding: 0px 4px;
align-items: center;
border-radius: 4px;
cursor: pointer;
.icon {
display: flex;
justify-content: center;
align-items: center;
}
.text {
padding: 0px 4px;
font-size: var(--affine-font-xs);
font-style: normal;
font-weight: 500;
line-height: 20px; /* 166.667% */
}
}
.button.edit {
color: ${unsafeCSSVarV2('text/secondary')};
}
.button.retry {
color: ${unsafeCSSVarV2('text/emphasis')};
}
}
}
}
.affine-embed-iframe-error-card.horizontal {
flex-direction: row;
align-items: flex-start;
.error-content {
align-items: flex-start;
flex: 1 0 0;
.error-message {
height: 40px;
align-items: flex-start;
}
}
@container affine-embed-iframe-error-card (width < 480px) {
.error-banner {
display: none;
}
}
}
.affine-embed-iframe-error-card.vertical {
flex-direction: column-reverse;
align-items: center;
justify-content: center;
.error-content {
justify-content: center;
align-items: center;
.error-message {
justify-content: center;
align-items: center;
}
}
.icon-box {
svg {
transform: scale(1.6) translateY(-14px);
}
}
@container affine-embed-iframe-error-card (height < 300px) or (width < 300px) {
.error-banner {
display: none;
}
}
}
`;
private _editAbortController: AbortController | null = null;
private readonly _toggleEdit = (e: MouseEvent) => {
e.stopPropagation();
if (!this._editButton || this.readonly) {
return;
}
if (this._editAbortController) {
this._editAbortController.abort();
}
this._editAbortController = new AbortController();
createLitPortal({
template: html`<embed-iframe-link-edit-popup
.model=${this.model}
.abortController=${this._editAbortController}
.std=${this.std}
.inSurface=${this.inSurface}
></embed-iframe-link-edit-popup>`,
container: document.body,
computePosition: {
referenceElement: this._editButton,
placement: 'bottom-start',
middleware: [flip(), offset(LINK_EDIT_POPUP_OFFSET)],
autoUpdate: { animationFrame: true },
},
abortController: this._editAbortController,
closeOnClickAway: true,
});
};
private readonly _handleRetry = (e: MouseEvent) => {
e.stopPropagation();
this.onRetry();
// track retry event
this.telemetryService?.track('ReloadLink', {
type: 'embed iframe block',
page: this.editorMode === 'page' ? 'doc editor' : 'whiteboard editor',
segment: 'editor',
module: 'embed block',
control: 'reload button',
});
};
override render() {
const { layout, width, height } = this.options;
const cardClasses = classMap({
'affine-embed-iframe-error-card': true,
horizontal: layout === 'horizontal',
vertical: layout === 'vertical',
});
const cardWidth = width ? `${width}px` : '100%';
const cardHeight = height ? `${height}px` : '100%';
const cardStyle = styleMap({
width: cardWidth,
height: cardHeight,
});
return html`
<div class=${cardClasses} style=${cardStyle}>
<div class="error-content">
<div class="error-title">
<span class="error-icon">
${InformationIcon({ width: '16px', height: '16px' })}
</span>
<span class="error-title-text">This link couldnt be loaded.</span>
</div>
<div class="error-message">
${this.error?.message || 'Failed to load embedded content'}
</div>
<div class="error-info">
${this.readonly
? nothing
: html`
<div class="button edit" @click=${this._toggleEdit}>
<span class="icon"
>${EditIcon({ width: '16px', height: '16px' })}</span
>
<span class="text">Edit</span>
</div>
`}
<div class="button retry" @click=${this._handleRetry}>
<span class="icon"
>${ResetIcon({ width: '16px', height: '16px' })}</span
>
<span class="text">Reload</span>
</div>
</div>
</div>
<div class="error-banner">
<div class="icon-box">${EmbedIframeErrorIcon}</div>
</div>
</div>
`;
}
get host() {
return this.std.host;
}
get readonly() {
return this.model.doc.readonly;
}
get telemetryService() {
return this.std.getOptional(TelemetryProvider);
}
get editorMode() {
const docModeService = this.std.get(DocModeProvider);
const mode = docModeService.getEditorMode();
return mode ?? 'page';
}
@query('.button.edit')
accessor _editButton: HTMLElement | null = null;
@property({ attribute: false })
accessor error: Error | null = null;
@property({ attribute: false })
accessor onRetry!: () => void;
@property({ attribute: false })
accessor model!: EmbedIframeBlockModel;
@property({ attribute: false })
accessor std!: BlockStdScope;
@property({ attribute: false })
accessor inSurface = false;
@property({ attribute: false })
accessor options: EmbedIframeStatusCardOptions = {
layout: 'horizontal',
height: ERROR_CARD_DEFAULT_HEIGHT,
};
}
export const EmbedIframeErrorIcon = html`<svg
width="204"
height="102"
viewBox="0 0 204 102"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<g clip-path="url(#clip0_2676_106795)">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M94.6838 8.45092L106.173 31.9276L84.6593 57.0514L90.5888 64.9202C88.6083 64.6092 86.5089 65.0701 84.7813 66.3719L78.4802 71.1202C75.0967 73.6698 74.4207 78.4796 76.9704 81.8631C79.5201 85.2467 84.3299 85.9227 87.7134 83.373L89.4487 82.0654C90.3714 81.37 90.5558 80.0582 89.8604 79.1354C89.1651 78.2127 87.8533 78.0283 86.9305 78.7237L85.1952 80.0313C83.6573 81.1902 81.471 80.883 80.3121 79.345C79.1531 77.807 79.4604 75.6208 80.9984 74.4618L87.2995 69.7136C88.8375 68.5547 91.0237 68.8619 92.1827 70.3999C92.8645 71.3047 94.1389 71.4996 95.0582 70.8513L95.8982 71.966L94.6469 72.9089C93.109 74.0679 90.9227 73.7606 89.7638 72.2227C89.0684 71.2999 87.7566 71.1155 86.8339 71.8109C85.9111 72.5062 85.7267 73.818 86.4221 74.7408C88.9718 78.1243 93.7816 78.8003 97.1651 76.2506L98.4164 75.3077L99.8156 77.1646L86.8434 102.707L89.291 114.735L42.1397 108.108L56.3354 7.10072C56.6429 4.91308 58.6655 3.38889 60.8532 3.69634L94.6838 8.45092ZM122.987 12.4287L119.974 33.8672L95.4607 58.4925C98.7006 56.8928 102.722 57.7678 104.976 60.7594C107.526 64.1429 106.85 68.9527 103.466 71.5024L102.718 72.0665L105.949 78.0266L92.2105 103.461L92.9872 115.254L147.108 122.86L161.304 21.8531C161.611 19.6654 160.087 17.6428 157.899 17.3353L122.987 12.4287ZM100.701 68.3471L100.948 68.1607C102.486 67.0018 102.793 64.8155 101.634 63.2775C100.625 61.9381 98.8364 61.5321 97.3755 62.2152L100.701 68.3471ZM88.8231 36.502C84.6277 35.9124 80.7486 38.8354 80.159 43.0308L79.1885 49.9367C79.0277 51.0809 79.8249 52.1388 80.9691 52.2996C82.1133 52.4604 83.1712 51.6632 83.332 50.519L84.3025 43.6132C84.5705 41.7062 86.3337 40.3775 88.2407 40.6455L95.1466 41.6161C96.2908 41.7769 97.3487 40.9797 97.5095 39.8355C97.6703 38.6913 96.8731 37.6334 95.7289 37.4726L88.8231 36.502ZM115.065 40.1901C113.921 40.0293 112.863 40.8265 112.702 41.9707C112.542 43.1149 113.339 44.1728 114.483 44.3336L121.389 45.3042C123.296 45.5722 124.625 47.3354 124.357 49.2424L123.386 56.1483C123.225 57.2925 124.022 58.3504 125.167 58.5112C126.311 58.672 127.369 57.8748 127.529 56.7306L128.5 49.8247C129.09 45.6293 126.167 41.7503 121.971 41.1607L115.065 40.1901ZM123.031 73.7041C124.176 73.8649 124.973 74.9228 124.812 76.067L123.841 82.9728C123.252 87.1682 119.373 90.0913 115.177 89.5017L106.89 88.337C105.746 88.1762 104.949 87.1183 105.11 85.9741C105.27 84.8299 106.328 84.0327 107.473 84.1935L115.76 85.3582C117.667 85.6262 119.43 84.2975 119.698 82.3905L120.668 75.4847C120.829 74.3405 121.887 73.5433 123.031 73.7041Z"
fill="#E6E6E6"
/>
</g>
<defs>
<clipPath id="clip0_2676_106795">
<rect width="204" height="102" fill="white" />
</clipPath>
</defs>
</svg>`;
@@ -0,0 +1,132 @@
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { WithDisposable } from '@blocksuite/global/lit';
import { EmbedIcon } from '@blocksuite/icons/lit';
import { baseTheme } from '@toeverything/theme';
import { css, html, LitElement, unsafeCSS } from 'lit';
import { property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styleMap } from 'lit/directives/style-map.js';
import { IDLE_CARD_DEFAULT_HEIGHT } from '../consts';
import type { EmbedIframeStatusCardOptions } from '../types';
export class EmbedIframeIdleCard extends WithDisposable(LitElement) {
static override styles = css`
:host {
width: 100%;
height: 100%;
}
.affine-embed-iframe-idle-card {
container: affine-embed-iframe-idle-card / size;
box-sizing: border-box;
display: flex;
align-items: center;
padding: 12px;
gap: 8px;
border-radius: 8px;
background-color: ${unsafeCSSVarV2('layer/background/secondary')};
.icon {
display: flex;
justify-content: center;
align-items: center;
color: ${unsafeCSSVarV2('icon/secondary')};
flex-shrink: 0;
}
.text {
/* Client/base */
font-size: 15px;
font-style: normal;
font-weight: 400;
line-height: 24px; /* 160% */
font-family: ${unsafeCSS(baseTheme.fontSansFamily)};
color: ${unsafeCSSVarV2('text/secondary')};
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
}
.affine-embed-iframe-idle-card:hover {
cursor: pointer;
}
.affine-embed-iframe-idle-card.horizontal {
flex-direction: row;
.icon {
width: 24px;
height: 24px;
svg {
width: 24px;
height: 24px;
}
}
}
.affine-embed-iframe-idle-card.vertical {
flex-direction: column;
justify-content: center;
overflow: hidden;
gap: 12px;
.icon {
width: 176px;
height: 112px;
overflow-y: hidden;
svg {
width: 112px;
height: 112px;
transform: rotate(12deg) translateY(18%);
}
}
.text {
text-align: center;
white-space: normal;
word-break: break-word;
}
@container affine-embed-iframe-idle-card (height < 180px) {
.icon {
display: none;
}
}
}
`;
override render() {
const { layout, width, height } = this.options;
const cardClasses = classMap({
'affine-embed-iframe-idle-card': true,
horizontal: layout === 'horizontal',
vertical: layout === 'vertical',
});
const cardWidth = width ? `${width}px` : '100%';
const cardHeight = height ? `${height}px` : '100%';
const cardStyle = styleMap({
width: cardWidth,
height: cardHeight,
});
return html`
<div class=${cardClasses} style=${cardStyle}>
<span class="icon"> ${EmbedIcon()} </span>
<span class="text">
Embed anything (Google Drive, Google Docs, Spotify, Miro…)
</span>
</div>
`;
}
@property({ attribute: false })
accessor options: EmbedIframeStatusCardOptions = {
layout: 'horizontal',
height: IDLE_CARD_DEFAULT_HEIGHT,
};
}
@@ -0,0 +1,122 @@
import {
DocModeProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { SignalWatcher } from '@blocksuite/global/lit';
import { DoneIcon } from '@blocksuite/icons/lit';
import { css, html } from 'lit';
import { EmbedIframeLinkInputBase } from './embed-iframe-link-input-base';
export class EmbedIframeLinkEditPopup extends SignalWatcher(
EmbedIframeLinkInputBase
) {
static override styles = css`
.embed-iframe-link-edit-popup {
display: flex;
padding: 12px;
align-items: center;
gap: 12px;
color: var(--affine-text-primary-color);
border-radius: 8px;
border: 0.5px solid ${unsafeCSSVarV2('layer/insideBorder/border')};
background: ${unsafeCSSVarV2('layer/background/primary')};
box-shadow: ${unsafeCSSVar('overlayPanelShadow')};
.input-container {
display: flex;
width: 280px;
align-items: center;
border: 1px solid var(--affine-border-color);
border-radius: 4px;
padding: 0 8px;
background-color: var(--affine-background-color);
gap: 8px;
.input-label {
color: var(--affine-text-secondary-color);
font-size: 14px;
margin-right: 8px;
white-space: nowrap;
}
.link-input {
flex: 1;
border: none;
outline: none;
padding: 8px 0;
background: transparent;
font-size: 14px;
}
}
.input-container:focus-within {
border-color: var(--affine-blue-700);
outline: none;
}
.confirm-button {
cursor: pointer;
display: flex;
padding: 2px;
justify-content: center;
align-items: center;
color: ${unsafeCSSVarV2('icon/activated')};
}
.confirm-button[disabled] {
color: ${unsafeCSSVarV2('icon/primary')};
}
}
`;
protected override track(status: 'success' | 'failure') {
this.telemetryService?.track('EditLink', {
type: 'embed iframe block',
page: this.editorMode === 'page' ? 'doc editor' : 'whiteboard editor',
segment: 'editor',
module: 'embed block',
control: 'edit button',
other: status,
});
}
override render() {
const isInputEmpty = this.isInputEmpty();
const { url$ } = this.model.props;
return html`
<div class="embed-iframe-link-edit-popup">
<div class="input-container">
<span class="input-label">Link</span>
<input
class="link-input"
type="text"
spellcheck="false"
placeholder=${url$.value}
@input=${this.handleInput}
@keydown=${this.handleKeyDown}
/>
</div>
<div
class="confirm-button"
?disabled=${isInputEmpty}
@click=${this.onConfirm}
>
${DoneIcon({ width: '24px', height: '24px' })}
</div>
</div>
`;
}
get telemetryService() {
return this.std.getOptional(TelemetryProvider);
}
get editorMode() {
const docModeService = this.std.get(DocModeProvider);
const mode = docModeService.getEditorMode();
return mode ?? 'page';
}
}
@@ -0,0 +1,160 @@
import type { EmbedIframeBlockModel } from '@blocksuite/affine-model';
import {
EmbedIframeService,
NotificationProvider,
} from '@blocksuite/affine-shared/services';
import { isValidUrl, stopPropagation } from '@blocksuite/affine-shared/utils';
import { WithDisposable } from '@blocksuite/global/lit';
import { noop } from '@blocksuite/global/utils';
import {
BlockSelection,
type BlockStdScope,
SurfaceSelection,
} from '@blocksuite/std';
import { LitElement } from 'lit';
import { property, query, state } from 'lit/decorators.js';
export class EmbedIframeLinkInputBase extends WithDisposable(LitElement) {
// this method is used to track the event when the user inputs the link
// it should be overridden by the subclass
protected track(status: 'success' | 'failure') {
noop(status);
}
protected isInputEmpty() {
return this._linkInputValue.trim() === '';
}
protected tryToAddBookmark(url: string) {
if (!isValidUrl(url)) {
this.notificationService?.notify({
title: 'Invalid URL',
message: 'Please enter a valid URL',
accent: 'error',
onClose: function (): void {},
});
return;
}
const { model } = this;
const { parent } = model;
const index = parent?.children.indexOf(model);
const flavour = 'affine:bookmark';
this.store.transact(() => {
const blockId = this.store.addBlock(flavour, { url }, parent, index);
this.store.deleteBlock(model);
if (this.inSurface) {
this.std.selection.setGroup('gfx', [
this.std.selection.create(
SurfaceSelection,
blockId,
[blockId],
false
),
]);
} else {
this.std.selection.setGroup('note', [
this.std.selection.create(BlockSelection, { blockId }),
]);
}
});
this.abortController?.abort();
}
protected async onConfirm() {
if (this.isInputEmpty()) {
return;
}
try {
const embedIframeService = this.std.get(EmbedIframeService);
if (!embedIframeService) {
console.error('iframe EmbedIframeService not found');
this.track('failure');
return;
}
const url = this._linkInputValue;
const canEmbed = embedIframeService.canEmbed(url);
if (!canEmbed) {
console.log('iframe can not be embedded, add as a bookmark', url);
this.tryToAddBookmark(url);
return;
}
this.store.updateBlock(this.model, {
url: this._linkInputValue,
iframeUrl: '',
title: '',
description: '',
});
this.track('success');
} catch (error) {
this.track('failure');
this.notificationService?.notify({
title: 'Error in embed iframe creation',
message: error instanceof Error ? error.message : 'Please try again',
accent: 'error',
onClose: function (): void {},
});
} finally {
this.abortController?.abort();
}
}
protected handleInput = (e: InputEvent) => {
const target = e.target as HTMLInputElement;
this._linkInputValue = target.value;
};
protected handleKeyDown = async (e: KeyboardEvent) => {
e.stopPropagation();
if (e.key === 'Enter' && !e.isComposing) {
await this.onConfirm();
}
};
override connectedCallback() {
super.connectedCallback();
this.updateComplete
.then(() => {
requestAnimationFrame(() => {
this.input.focus();
});
})
.catch(console.error);
this.disposables.addFromEvent(this, 'cut', stopPropagation);
this.disposables.addFromEvent(this, 'copy', stopPropagation);
this.disposables.addFromEvent(this, 'paste', stopPropagation);
this.disposables.addFromEvent(this, 'pointerdown', stopPropagation);
}
get store() {
return this.model.doc;
}
get notificationService() {
return this.std.getOptional(NotificationProvider);
}
@state()
protected accessor _linkInputValue = '';
@query('input')
accessor input!: HTMLInputElement;
@property({ attribute: false })
accessor model!: EmbedIframeBlockModel;
@property({ attribute: false })
accessor std!: BlockStdScope;
@property({ attribute: false })
accessor abortController: AbortController | undefined = undefined;
@property({ attribute: false })
accessor inSurface = false;
}
@@ -0,0 +1,292 @@
import {
DocModeProvider,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import { unsafeCSSVar, unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { CloseIcon } from '@blocksuite/icons/lit';
import { baseTheme } from '@toeverything/theme';
import { css, html, nothing, unsafeCSS } from 'lit';
import { property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { EmbedIframeLinkInputBase } from './embed-iframe-link-input-base';
type EmbedLinkInputPopupVariant = 'default' | 'mobile';
export type EmbedLinkInputPopupOptions = {
showCloseButton?: boolean;
variant?: EmbedLinkInputPopupVariant;
title?: string;
description?: string;
placeholder?: string;
telemetrySegment?: string;
};
const DEFAULT_OPTIONS: EmbedLinkInputPopupOptions = {
showCloseButton: false,
variant: 'default',
title: 'Embed Link',
description: 'Works with links of Google Drive, Spotify…',
placeholder: 'Paste the Embed link...',
telemetrySegment: 'editor',
};
export class EmbedIframeLinkInputPopup extends EmbedIframeLinkInputBase {
static override styles = css`
.link-input-popup-main-wrapper {
box-sizing: border-box;
width: 340px;
padding: 12px;
border-radius: 8px;
background: ${unsafeCSSVarV2('layer/background/overlayPanel')};
box-shadow: ${unsafeCSSVar('overlayPanelShadow')};
font-family: ${unsafeCSS(baseTheme.fontSansFamily)};
}
.link-input-popup-content-wrapper {
display: flex;
flex-direction: column;
}
.popup-close-button {
position: absolute;
top: 12px;
right: 12px;
width: 24px;
height: 24px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
color: var(--affine-icon-color);
border-radius: 4px;
}
.popup-close-button:hover {
background-color: var(--affine-hover-color);
}
.title {
/* Client/h6 */
font-size: var(--affine-font-base);
font-style: normal;
font-weight: 500;
line-height: 24px;
color: ${unsafeCSSVarV2('text/primary')};
}
.description {
margin-top: 4px;
font-feature-settings:
'liga' off,
'clig' off;
font-size: var(--affine-font-sm);
font-style: normal;
font-weight: 400;
line-height: 22px;
color: ${unsafeCSSVarV2('text/secondary')};
}
.input-container {
width: 100%;
margin-top: 12px;
box-sizing: border-box;
.link-input {
box-sizing: border-box;
width: 100%;
padding: 4px 10px;
border-radius: 8px;
border: 1px solid ${unsafeCSSVarV2('layer/insideBorder/border')};
background: ${unsafeCSSVarV2('input/background')};
}
.link-input:focus {
border-color: var(--affine-blue-700);
box-shadow: var(--affine-active-shadow);
outline: none;
}
.link-input::placeholder {
color: ${unsafeCSSVarV2('text/placeholder')};
}
}
.button-container {
display: flex;
justify-content: center;
margin-top: 12px;
.confirm-button {
width: 100%;
height: 32px;
line-height: 32px;
text-align: center;
justify-content: center;
align-items: center;
border-radius: 8px;
background: ${unsafeCSSVarV2('button/primary')};
border: 1px solid ${unsafeCSSVarV2('layer/insideBorder/border')};
color: ${unsafeCSSVarV2('button/pureWhiteText')};
/* Client/xsMedium */
font-size: 12px;
font-style: normal;
font-weight: 500;
cursor: pointer;
}
.confirm-button[disabled] {
opacity: 0.5;
}
}
.link-input-popup-main-wrapper.mobile {
width: 360px;
border-radius: 22px;
padding: 12px 0;
.popup-close-button {
top: 20px;
right: 16px;
}
.link-input-popup-content-wrapper {
gap: 0;
.title {
padding: 10px 16px;
font-weight: 500;
}
.input-container {
padding: 4px 12px;
}
.link-input {
padding: 11px 10px;
font-size: 17px;
font-style: normal;
font-weight: 400;
letter-spacing: -0.43px;
}
.title,
.description {
font-size: 17px;
font-style: normal;
line-height: 22px; /* 129.412% */
letter-spacing: -0.43px;
}
.description {
font-weight: 400;
text-align: left;
order: 2;
padding: 11px 16px;
color: ${unsafeCSSVarV2('text/secondary')};
}
.input-container {
order: 1;
}
}
.description,
.input-container,
.button-container {
margin-top: 0;
}
.button-container {
padding: 4px 16px;
.confirm-button {
height: 40px;
line-height: 40px;
font-size: 17px;
font-style: normal;
font-weight: 400;
letter-spacing: -0.43px;
}
.confirm-button[disabled] {
opacity: 1;
background: ${unsafeCSSVarV2('button/disable')};
}
}
}
`;
private readonly _onClose = () => {
this.abortController?.abort();
};
protected override track(status: 'success' | 'failure') {
this.telemetryService?.track('CreateEmbedBlock', {
type: 'embed iframe block',
page: this.editorMode === 'page' ? 'doc editor' : 'whiteboard editor',
segment: this.options?.telemetrySegment ?? 'editor',
module: 'embed block',
control: 'confirm embed link',
other: status,
});
}
override render() {
const options = { ...DEFAULT_OPTIONS, ...this.options };
const { showCloseButton, variant, title, description, placeholder } =
options;
const modalMainWrapperClass = classMap({
'link-input-popup-main-wrapper': true,
mobile: variant === 'mobile',
});
return html`
<div class=${modalMainWrapperClass}>
${showCloseButton
? html`
<div class="popup-close-button" @click=${this._onClose}>
${CloseIcon({ width: '20', height: '20' })}
</div>
`
: nothing}
<div class="link-input-popup-content-wrapper">
<div class="title">${title}</div>
<div class="description">${description}</div>
<div class="input-container">
<input
class="link-input"
type="text"
placeholder=${ifDefined(placeholder)}
@input=${this.handleInput}
@keydown=${this.handleKeyDown}
/>
</div>
</div>
<div class="button-container">
<div
class="confirm-button"
@click=${this.onConfirm}
?disabled=${this.isInputEmpty()}
>
Confirm
</div>
</div>
</div>
`;
}
get telemetryService() {
return this.std.getOptional(TelemetryProvider);
}
get editorMode() {
const docModeService = this.std.get(DocModeProvider);
const mode = docModeService.getEditorMode();
return mode ?? 'page';
}
@property({ attribute: false })
accessor options: EmbedLinkInputPopupOptions | undefined = undefined;
}
@@ -0,0 +1,197 @@
import { ThemeProvider } from '@blocksuite/affine-shared/services';
import { unsafeCSSVarV2 } from '@blocksuite/affine-shared/theme';
import { EmbedIcon } from '@blocksuite/icons/lit';
import { type BlockStdScope } from '@blocksuite/std';
import { css, html, LitElement } from 'lit';
import { property } from 'lit/decorators.js';
import { classMap } from 'lit/directives/class-map.js';
import { styleMap } from 'lit/directives/style-map.js';
import { getEmbedCardIcons } from '../../common/utils';
import { LOADING_CARD_DEFAULT_HEIGHT } from '../consts';
import type { EmbedIframeStatusCardOptions } from '../types';
export class EmbedIframeLoadingCard extends LitElement {
static override styles = css`
:host {
width: 100%;
height: 100%;
}
.affine-embed-iframe-loading-card {
container: affine-embed-iframe-loading-card / size;
display: flex;
box-sizing: border-box;
border-radius: 8px;
user-select: none;
padding: 12px;
gap: 12px;
overflow: hidden;
border: 1px solid ${unsafeCSSVarV2('layer/insideBorder/border')};
background: ${unsafeCSSVarV2('layer/white')};
.loading-content {
display: flex;
gap: 8px;
align-self: stretch;
.loading-spinner {
display: flex;
width: 24px;
height: 24px;
justify-content: center;
align-items: center;
}
.loading-text {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
overflow: hidden;
color: ${unsafeCSSVarV2('text/primary')};
text-overflow: ellipsis;
/* Client/smMedium */
font-family: Inter;
font-size: var(--affine-font-sm);
font-style: normal;
font-weight: 500;
line-height: 22px; /* 157.143% */
}
}
.loading-banner {
display: flex;
box-sizing: border-box;
justify-content: center;
align-items: center;
flex-shrink: 0;
.icon-box {
display: flex;
transform: rotate(8deg);
justify-content: center;
align-items: center;
flex-shrink: 0;
border-radius: 4px 4px 0px 0px;
background: ${unsafeCSSVarV2('slashMenu/background')};
box-shadow: 0px 0px 5px 0px rgba(66, 65, 73, 0.17);
svg {
fill: black;
fill-opacity: 0.07;
}
}
}
@container affine-embed-iframe-loading-card (width < 360px) {
.loading-banner {
display: none;
}
}
}
.affine-embed-iframe-loading-card.horizontal {
flex-direction: row;
align-items: flex-start;
.loading-content {
flex: 1 0 0;
align-items: flex-start;
.loading-text {
flex: 1 0 0;
}
}
.loading-banner {
width: 204px;
padding: 3.139px 42.14px 0px 42.14px;
.icon-box {
width: 106px;
height: 106px;
svg {
width: 66px;
height: 66px;
}
}
}
}
.affine-embed-iframe-loading-card.vertical {
flex-direction: column-reverse;
align-items: center;
justify-content: center;
.loading-content {
justify-content: center;
font-size: 14px;
transform: translateX(-2%);
}
.loading-banner {
width: 340px;
padding: 5.23px 70.234px 0px 70.232px;
overflow-y: hidden;
.icon-box {
width: 176px;
height: 176px;
transform: rotate(8deg) translateY(15%);
svg {
width: 112px;
height: 112px;
}
}
}
@container affine-embed-iframe-loading-card (height < 240px) {
.loading-banner {
display: none;
}
}
}
`;
override render() {
const theme = this.std.get(ThemeProvider).theme;
const { LoadingIcon } = getEmbedCardIcons(theme);
const { layout, width, height } = this.options;
const cardClasses = classMap({
'affine-embed-iframe-loading-card': true,
horizontal: layout === 'horizontal',
vertical: layout === 'vertical',
});
const cardWidth = width ? `${width}px` : '100%';
const cardHeight = height ? `${height}px` : '100%';
const cardStyle = styleMap({
width: cardWidth,
height: cardHeight,
});
return html`
<div class=${cardClasses} style=${cardStyle}>
<div class="loading-content">
<div class="loading-spinner">${LoadingIcon}</div>
<div class="loading-text">Loading...</div>
</div>
<div class="loading-banner">
<div class="icon-box">${EmbedIcon()}</div>
</div>
</div>
`;
}
@property({ attribute: false })
accessor std!: BlockStdScope;
@property({ attribute: false })
accessor options: EmbedIframeStatusCardOptions = {
layout: 'horizontal',
height: LOADING_CARD_DEFAULT_HEIGHT,
};
}
@@ -0,0 +1,2 @@
export * from './providers';
export * from './toolbar';
@@ -0,0 +1,42 @@
import { EmbedIframeConfigExtension } from '@blocksuite/affine-shared/services';
import {
type EmbedIframeUrlValidationOptions,
validateEmbedIframeUrl,
} from '../../utils';
const EXCALIDRAW_DEFAULT_WIDTH_IN_SURFACE = 640;
const EXCALIDRAW_DEFAULT_HEIGHT_IN_SURFACE = 480;
const EXCALIDRAW_DEFAULT_HEIGHT_IN_NOTE = 480;
const EXCALIDRAW_DEFAULT_WIDTH_PERCENT = 100;
const excalidrawUrlValidationOptions: EmbedIframeUrlValidationOptions = {
protocols: ['https:'],
hostnames: ['excalidraw.com'],
};
const excalidrawConfig = {
name: 'excalidraw',
match: (url: string) =>
validateEmbedIframeUrl(url, excalidrawUrlValidationOptions),
buildOEmbedUrl: (url: string) => {
const match = validateEmbedIframeUrl(url, excalidrawUrlValidationOptions);
if (!match) {
return undefined;
}
return url;
},
useOEmbedUrlDirectly: true,
options: {
widthInSurface: EXCALIDRAW_DEFAULT_WIDTH_IN_SURFACE,
heightInSurface: EXCALIDRAW_DEFAULT_HEIGHT_IN_SURFACE,
heightInNote: EXCALIDRAW_DEFAULT_HEIGHT_IN_NOTE,
widthPercent: EXCALIDRAW_DEFAULT_WIDTH_PERCENT,
allow: 'clipboard-read; clipboard-write',
style: 'border: none; border-radius: 8px;',
allowFullscreen: true,
},
};
export const ExcalidrawEmbedConfig =
EmbedIframeConfigExtension(excalidrawConfig);
@@ -0,0 +1,81 @@
import { EmbedIframeConfigExtension } from '@blocksuite/affine-shared/services';
import {
type EmbedIframeUrlValidationOptions,
validateEmbedIframeUrl,
} from '../../utils';
const GOOGLE_DOCS_DEFAULT_WIDTH_IN_SURFACE = 800;
const GOOGLE_DOCS_DEFAULT_HEIGHT_IN_SURFACE = 600;
const GOOGLE_DOCS_DEFAULT_WIDTH_PERCENT = 100;
const GOOGLE_DOCS_DEFAULT_HEIGHT_IN_NOTE = 600;
const googleDocsUrlValidationOptions: EmbedIframeUrlValidationOptions = {
protocols: ['https:'],
hostnames: ['docs.google.com'],
};
/**
* Checks if the URL has a valid sharing parameter
* @param parsedUrl Parsed URL object
* @returns Boolean indicating if the URL has a valid sharing parameter
*/
function hasValidSharingParam(parsedUrl: URL): boolean {
const usp = parsedUrl.searchParams.get('usp');
return usp === 'sharing';
}
/**
* Validates if a URL is a valid Google Docs URL
* Valid format: https://docs.google.com/document/d/doc-id/edit?usp=sharing
* @param url The URL to validate
* @param strictMode Whether to strictly validate sharing parameters
* @returns Boolean indicating if the URL is a valid Google Docs URL
*/
function isValidGoogleDocsUrl(url: string, strictMode = true): boolean {
try {
if (!validateEmbedIframeUrl(url, googleDocsUrlValidationOptions)) {
return false;
}
const parsedUrl = new URL(url);
if (strictMode && !hasValidSharingParam(parsedUrl)) {
return false;
}
const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
return (
pathSegments[0] === 'document' &&
pathSegments[1] === 'd' &&
pathSegments.length >= 3 &&
!!pathSegments[2]
);
} catch (e) {
console.warn('Invalid Google Docs URL:', e);
return false;
}
}
const googleDocsConfig = {
name: 'google-docs',
match: (url: string) => isValidGoogleDocsUrl(url),
buildOEmbedUrl: (url: string) => {
if (!isValidGoogleDocsUrl(url)) {
return undefined;
}
return url;
},
useOEmbedUrlDirectly: true,
options: {
widthInSurface: GOOGLE_DOCS_DEFAULT_WIDTH_IN_SURFACE,
heightInSurface: GOOGLE_DOCS_DEFAULT_HEIGHT_IN_SURFACE,
widthPercent: GOOGLE_DOCS_DEFAULT_WIDTH_PERCENT,
heightInNote: GOOGLE_DOCS_DEFAULT_HEIGHT_IN_NOTE,
allowFullscreen: true,
style: 'border: none; border-radius: 8px;',
},
};
export const GoogleDocsEmbedConfig =
EmbedIframeConfigExtension(googleDocsConfig);
@@ -0,0 +1,197 @@
import { EmbedIframeConfigExtension } from '@blocksuite/affine-shared/services';
import {
type EmbedIframeUrlValidationOptions,
validateEmbedIframeUrl,
} from '../../utils';
const GOOGLE_DRIVE_DEFAULT_WIDTH_IN_SURFACE = 640;
const GOOGLE_DRIVE_DEFAULT_HEIGHT_IN_SURFACE = 480;
const GOOGLE_DRIVE_DEFAULT_WIDTH_PERCENT = 100;
const GOOGLE_DRIVE_DEFAULT_HEIGHT_IN_NOTE = 480;
const GOOGLE_DRIVE_EMBED_FOLDER_URL =
'https://drive.google.com/embeddedfolderview';
const GOOGLE_DRIVE_EMBED_FILE_URL = 'https://drive.google.com/file/d/';
const googleDriveUrlValidationOptions: EmbedIframeUrlValidationOptions = {
protocols: ['https:'],
hostnames: ['drive.google.com'],
};
/**
* Checks if the URL has a valid sharing parameter
* @param parsedUrl Parsed URL object
* @returns Boolean indicating if the URL has a valid sharing parameter
*/
function hasValidSharingParam(parsedUrl: URL): boolean {
const usp = parsedUrl.searchParams.get('usp');
return usp === 'sharing';
}
/**
* Check if the url is a valid google drive file url
* @param parsedUrl Parsed URL object
* @returns Boolean indicating if the URL is a valid Google Drive file URL
*/
function isValidGoogleDriveFileUrl(parsedUrl: URL): boolean {
const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
return (
pathSegments[0] === 'file' &&
pathSegments[1] === 'd' &&
pathSegments.length >= 3 &&
!!pathSegments[2]
);
}
/**
* Check if the url is a valid google drive folder url
* @param parsedUrl Parsed URL object
* @returns Boolean indicating if the URL is a valid Google Drive folder URL
*/
function isValidGoogleDriveFolderUrl(parsedUrl: URL): boolean {
const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
return (
pathSegments[0] === 'drive' &&
pathSegments[1] === 'folders' &&
pathSegments.length >= 3 &&
!!pathSegments[2]
);
}
/**
* Validates if a URL is a valid Google Drive path URL
* @param parsedUrl Parsed URL object
* @returns Boolean indicating if the URL is valid
*/
function isValidGoogleDrivePathUrl(parsedUrl: URL): boolean {
const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
// Should have at least 2 segments
if (pathSegments.length < 2) {
return false;
}
// Check for file pattern: /file/d/file-id/view
if (isValidGoogleDriveFileUrl(parsedUrl)) {
return true;
}
// Check for folder pattern: /drive/folders/folder-id
if (isValidGoogleDriveFolderUrl(parsedUrl)) {
return true;
}
return false;
}
/**
* Safely validates if a URL is a valid Google Drive URL
* https://drive.google.com/file/d/your-file-id/view?usp=sharing
* https://drive.google.com/drive/folders/your-folder-id?usp=sharing
* @param url The URL to validate
* @param strictMode Whether to strictly validate sharing parameters
* @returns Boolean indicating if the URL is a valid Google Drive URL
*/
function isValidGoogleDriveUrl(url: string, strictMode = true): boolean {
try {
if (!validateEmbedIframeUrl(url, googleDriveUrlValidationOptions)) {
return false;
}
const parsedUrl = new URL(url);
// Check sharing parameter if in strict mode
if (strictMode && !hasValidSharingParam(parsedUrl)) {
return false;
}
// Check hostname and path structure
return isValidGoogleDrivePathUrl(parsedUrl);
} catch (e) {
// URL parsing failed
console.warn('Invalid Google Drive URL:', e);
return false;
}
}
/**
* Build embed URL for Google Drive files
* @param fileId File ID
* @returns Embed URL
*/
function buildGoogleDriveFileEmbedUrl(fileId: string): string | undefined {
const embedUrl = new URL(
'preview',
`${GOOGLE_DRIVE_EMBED_FILE_URL}${fileId}/`
);
embedUrl.searchParams.set('usp', 'embed_googleplus');
return embedUrl.toString();
}
/**
* Build embed URL for Google Drive folders
* @param folderId Folder ID
* @returns Embed URL
*/
function buildGoogleDriveFolderEmbedUrl(folderId: string): string | undefined {
const embedUrl = new URL(GOOGLE_DRIVE_EMBED_FOLDER_URL);
embedUrl.searchParams.set('id', folderId);
embedUrl.hash = 'list';
return embedUrl.toString();
}
/**
* Build embed URL for Google Drive paths
* @param url The URL to embed
* @returns The embed URL
*/
function buildGoogleDriveEmbedUrl(url: string): string | undefined {
try {
const parsedUrl = new URL(url);
const pathSegments = parsedUrl.pathname.split('/').filter(Boolean);
// Should have at least 2 segments
if (pathSegments.length < 2) {
return undefined;
}
// Handle file URL: /file/d/file-id/view
if (isValidGoogleDriveFileUrl(parsedUrl)) {
return buildGoogleDriveFileEmbedUrl(pathSegments[2]);
}
// Handle folder URL: /drive/folders/folder-id
if (isValidGoogleDriveFolderUrl(parsedUrl)) {
return buildGoogleDriveFolderEmbedUrl(pathSegments[2]);
}
return undefined;
} catch (e) {
console.warn('Failed to parse Google Drive path URL:', e);
return undefined;
}
}
const googleDriveConfig = {
name: 'google-drive',
match: (url: string) => isValidGoogleDriveUrl(url),
buildOEmbedUrl: (url: string) => {
if (!isValidGoogleDriveUrl(url)) {
return undefined;
}
// If is a valid google drive url, build the embed url
return buildGoogleDriveEmbedUrl(url);
},
useOEmbedUrlDirectly: true,
options: {
widthInSurface: GOOGLE_DRIVE_DEFAULT_WIDTH_IN_SURFACE,
heightInSurface: GOOGLE_DRIVE_DEFAULT_HEIGHT_IN_SURFACE,
widthPercent: GOOGLE_DRIVE_DEFAULT_WIDTH_PERCENT,
heightInNote: GOOGLE_DRIVE_DEFAULT_HEIGHT_IN_NOTE,
allowFullscreen: true,
style: 'border: none; border-radius: 8px;',
},
};
export const GoogleDriveEmbedConfig =
EmbedIframeConfigExtension(googleDriveConfig);
@@ -0,0 +1,13 @@
import { ExcalidrawEmbedConfig } from './excalidraw';
import { GoogleDocsEmbedConfig } from './google-docs';
import { GoogleDriveEmbedConfig } from './google-drive';
import { MiroEmbedConfig } from './miro';
import { SpotifyEmbedConfig } from './spotify';
export const EmbedIframeConfigExtensions = [
SpotifyEmbedConfig,
GoogleDriveEmbedConfig,
MiroEmbedConfig,
ExcalidrawEmbedConfig,
GoogleDocsEmbedConfig,
];
@@ -0,0 +1,46 @@
import { EmbedIframeConfigExtension } from '@blocksuite/affine-shared/services';
import {
type EmbedIframeUrlValidationOptions,
validateEmbedIframeUrl,
} from '../../utils';
const MIRO_DEFAULT_WIDTH_IN_SURFACE = 640;
const MIRO_DEFAULT_HEIGHT_IN_SURFACE = 480;
const MIRO_DEFAULT_HEIGHT_IN_NOTE = 480;
const MIRO_DEFAULT_WIDTH_PERCENT = 100;
// https://developers.miro.com/reference/getembeddata
const miroEndpoint = 'https://miro.com/api/v1/oembed';
const miroUrlValidationOptions: EmbedIframeUrlValidationOptions = {
protocols: ['https:'],
hostnames: ['miro.com'],
};
const miroConfig = {
name: 'miro',
match: (url: string) => validateEmbedIframeUrl(url, miroUrlValidationOptions),
buildOEmbedUrl: (url: string) => {
const match = validateEmbedIframeUrl(url, miroUrlValidationOptions);
if (!match) {
return undefined;
}
const encodedUrl = encodeURIComponent(url);
const oEmbedUrl = `${miroEndpoint}?url=${encodedUrl}`;
return oEmbedUrl;
},
useOEmbedUrlDirectly: false,
options: {
widthInSurface: MIRO_DEFAULT_WIDTH_IN_SURFACE,
heightInSurface: MIRO_DEFAULT_HEIGHT_IN_SURFACE,
heightInNote: MIRO_DEFAULT_HEIGHT_IN_NOTE,
widthPercent: MIRO_DEFAULT_WIDTH_PERCENT,
allow: 'clipboard-read; clipboard-write',
style: 'border: none;',
allowFullscreen: true,
containerBorderRadius: 0,
},
};
export const MiroEmbedConfig = EmbedIframeConfigExtension(miroConfig);
@@ -0,0 +1,47 @@
import { EmbedIframeConfigExtension } from '@blocksuite/affine-shared/services';
import {
type EmbedIframeUrlValidationOptions,
validateEmbedIframeUrl,
} from '../../utils';
const SPOTIFY_DEFAULT_WIDTH_IN_SURFACE = 640;
const SPOTIFY_DEFAULT_HEIGHT_IN_SURFACE = 152;
const SPOTIFY_DEFAULT_HEIGHT_IN_NOTE = 152;
const SPOTIFY_DEFAULT_WIDTH_PERCENT = 100;
// https://developer.spotify.com/documentation/embeds/reference/oembed
const spotifyEndpoint = 'https://open.spotify.com/oembed';
const spotifyUrlValidationOptions: EmbedIframeUrlValidationOptions = {
protocols: ['https:'],
hostnames: ['open.spotify.com', 'spotify.link'],
};
const spotifyConfig = {
name: 'spotify',
match: (url: string) =>
validateEmbedIframeUrl(url, spotifyUrlValidationOptions),
buildOEmbedUrl: (url: string) => {
const match = validateEmbedIframeUrl(url, spotifyUrlValidationOptions);
if (!match) {
return undefined;
}
const encodedUrl = encodeURIComponent(url);
const oEmbedUrl = `${spotifyEndpoint}?url=${encodedUrl}`;
return oEmbedUrl;
},
useOEmbedUrlDirectly: false,
options: {
widthInSurface: SPOTIFY_DEFAULT_WIDTH_IN_SURFACE,
heightInSurface: SPOTIFY_DEFAULT_HEIGHT_IN_SURFACE,
heightInNote: SPOTIFY_DEFAULT_HEIGHT_IN_NOTE,
widthPercent: SPOTIFY_DEFAULT_WIDTH_PERCENT,
allow: 'autoplay; clipboard-write; encrypted-media; picture-in-picture',
style: 'border-radius: 8px;',
allowFullscreen: true,
containerBorderRadius: 12,
},
};
export const SpotifyEmbedConfig = EmbedIframeConfigExtension(spotifyConfig);
@@ -0,0 +1,37 @@
import { getSelectedModelsCommand } from '@blocksuite/affine-shared/commands';
import type { SlashMenuConfig } from '@blocksuite/affine-widget-slash-menu';
import { EmbedIcon } from '@blocksuite/icons/lit';
import { insertEmptyEmbedIframeCommand } from '../../commands/insert-empty-embed-iframe';
import { EmbedIframeTooltip } from './tooltip';
export const embedIframeSlashMenuConfig: SlashMenuConfig = {
items: [
{
name: 'Embed',
description: 'For Google Drive, and more.',
icon: EmbedIcon(),
tooltip: {
figure: EmbedIframeTooltip,
caption: 'Embed',
},
group: '4_Content & Media@5',
when: ({ model }) => {
return model.doc.schema.flavourSchemaMap.has('affine:embed-iframe');
},
action: ({ std }) => {
std.command
.chain()
.pipe(getSelectedModelsCommand)
.pipe(insertEmptyEmbedIframeCommand, {
place: 'after',
removeEmptyLine: true,
linkInputPopupOptions: {
telemetrySegment: 'slash menu',
},
})
.run();
},
},
],
};
File diff suppressed because one or more lines are too long
@@ -0,0 +1,485 @@
import { reassociateConnectorsCommand } from '@blocksuite/affine-block-surface';
import { toast } from '@blocksuite/affine-components/toast';
import {
BookmarkStyles,
EmbedIframeBlockModel,
} from '@blocksuite/affine-model';
import {
EMBED_CARD_HEIGHT,
EMBED_CARD_WIDTH,
} from '@blocksuite/affine-shared/consts';
import {
ActionPlacement,
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,
LinkedPageIcon,
OpenInNewIcon,
ResetIcon,
} from '@blocksuite/icons/lit';
import { BlockFlavourIdentifier, BlockSelection } from '@blocksuite/std';
import {
type ExtensionType,
Slice,
Text,
toDraftModel,
} 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 {
convertSelectedBlocksToLinkedDoc,
getTitleFromSelectedModels,
notifyDocCreated,
promptDocTitle,
} from '../../common/render-linked-doc';
import { EmbedIframeBlockComponent } from '../embed-iframe-block';
const trackBaseProps = {
category: 'embed iframe block',
};
const showWhenUrlExists = (ctx: ToolbarContext) => {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return false;
return !!model.props.url;
};
const openLinkAction = (id: string): ToolbarAction => {
return {
id,
when: showWhenUrlExists,
tooltip: 'Original',
icon: OpenInNewIcon(),
run(ctx) {
const component = ctx.getCurrentBlockByType(EmbedIframeBlockComponent);
component?.open();
ctx.track('OpenLink', {
...trackBaseProps,
control: 'open original link',
});
},
};
};
const captionAction = (id: string): ToolbarAction => {
return {
id,
when: showWhenUrlExists,
tooltip: 'Caption',
icon: CaptionIcon(),
run(ctx) {
const component = ctx.getCurrentBlockByType(EmbedIframeBlockComponent);
component?.captionEditor?.show();
ctx.track('OpenedCaptionEditor', {
...trackBaseProps,
control: 'add caption',
});
},
};
};
export const builtinToolbarConfig = {
actions: [
openLinkAction('a.open-link'),
{
id: 'c.conversions',
when: showWhenUrlExists,
actions: [
{
id: 'inline',
label: 'Inline view',
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { title, caption, url } = model.props;
if (!url) return;
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',
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { url, caption } = model.props;
if (!url) return;
const { parent } = model;
const index = parent?.children.indexOf(model);
const flavour = 'affine:bookmark';
const style =
BookmarkStyles.find(s => s !== 'vertical' && s !== 'cube') ??
BookmarkStyles[1];
const blockId = ctx.store.addBlock(
flavour,
{ url, caption, style },
parent,
index
);
ctx.store.deleteBlock(model);
// Selects new block
ctx.select('note', [
ctx.selection.create(BlockSelection, { blockId }),
]);
ctx.track('SelectedView', {
...trackBaseProps,
control: 'select view',
type: 'card view',
});
},
},
{
id: 'embed',
label: 'Embed view',
disabled: true,
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
const toggle = (e: CustomEvent<boolean>) => {
const opened = e.detail;
if (!opened) return;
ctx.track('OpenedViewSelector', {
...trackBaseProps,
control: 'switch view',
});
};
return html`${keyed(
model,
html`<affine-view-dropdown-menu
.actions=${actions}
.context=${ctx}
.toggle=${toggle}
.viewType$=${signal(actions[2].label)}
></affine-view-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
captionAction('d.caption'),
{
id: 'e.convert-to-linked-doc',
tooltip: 'Create Linked Doc',
icon: LinkedPageIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { store, std, selection, track } = ctx;
selection.clear();
const draftedModels = [model].map(toDraftModel);
const autofill = getTitleFromSelectedModels(draftedModels);
promptDocTitle(std, autofill)
.then(async title => {
if (title === null) return;
await convertSelectedBlocksToLinkedDoc(
std,
store,
draftedModels,
title
);
notifyDocCreated(std, store);
track('DocCreated', {
segment: 'doc',
page: 'doc editor',
module: 'toolbar',
control: 'create linked doc',
type: 'embed-linked-doc',
});
track('LinkedDocCreated', {
segment: 'doc',
page: 'doc editor',
module: 'toolbar',
control: 'create linked doc',
type: 'embed-linked-doc',
});
})
.catch(console.error);
},
},
{
placement: ActionPlacement.More,
id: 'a.clipboard',
actions: [
{
id: 'copy',
label: 'Copy',
icon: CopyIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const slice = Slice.fromModels(ctx.store, [model]);
ctx.clipboard
.copySlice(slice)
.then(() => toast(ctx.host, 'Copied to clipboard'))
.catch(console.error);
ctx.track('CopiedLink', {
...trackBaseProps,
control: 'copy link',
});
},
},
{
id: 'duplicate',
label: 'Duplicate',
icon: DuplicateIcon(),
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
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.reload',
label: 'Reload',
icon: ResetIcon(),
run(ctx) {
const component = ctx.getCurrentBlockByType(EmbedIframeBlockComponent);
component?.refreshData().catch(console.error);
ctx.track('ReloadLink', {
...trackBaseProps,
control: 'reload link',
});
},
},
{
placement: ActionPlacement.More,
id: 'c.delete',
label: 'Delete',
icon: DeleteIcon(),
variant: 'destructive',
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
ctx.store.deleteBlock(model);
// Clears
ctx.select('note');
ctx.reset();
},
},
],
} as const satisfies ToolbarModuleConfig;
export const builtinSurfaceToolbarConfig = {
actions: [
openLinkAction('a.open-link'),
{
id: 'c.conversions',
when: showWhenUrlExists,
actions: [
{
id: 'card',
label: 'Card view',
run(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return;
const { id: oldId, xywh, parent } = model;
const { url, caption } = model.props;
if (!url) return;
const style =
BookmarkStyles.find(s => s !== 'vertical' && s !== 'cube') ??
BookmarkStyles[1];
let flavour = 'affine:bookmark';
const bounds = Bound.deserialize(xywh);
bounds.w = EMBED_CARD_WIDTH[style];
bounds.h = EMBED_CARD_HEIGHT[style];
const newId = ctx.store.addBlock(
flavour,
{ url, caption, style, xywh: bounds.serialize() },
parent
);
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: 'card view',
});
},
},
{
id: 'embed',
label: 'Embed view',
disabled: true,
},
],
content(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return null;
const actions = this.actions.map(action => ({ ...action }));
const onToggle = (e: CustomEvent<boolean>) => {
if (!e.detail) return;
ctx.track('OpenedViewSelector', {
...trackBaseProps,
control: 'switch view',
});
};
return html`${keyed(
model,
html`<affine-view-dropdown-menu
@toggle=${onToggle}
.actions=${actions}
.context=${ctx}
.viewType$=${signal(actions[1].label)}
></affine-view-dropdown-menu>`
)}`;
},
} satisfies ToolbarActionGroup<ToolbarAction>,
captionAction('d.caption'),
{
id: 'e.scale',
content(ctx) {
const model = ctx.getCurrentModelByType(EmbedIframeBlockModel);
if (!model) return null;
const scale$ = computed(() => {
const scale = model.props.scale$.value ?? 1;
return Math.round(100 * scale);
});
const onSelect = (e: CustomEvent<number>) => {
e.stopPropagation();
const scale = e.detail / 100;
const bounds = Bound.deserialize(model.xywh);
const oldScale = model.props.scale ?? 1;
const ratio = scale / oldScale;
bounds.w *= ratio;
bounds.h *= ratio;
const xywh = bounds.serialize();
ctx.store.updateBlock(model, () => {
model.xywh = xywh;
model.props.scale = scale;
});
ctx.track('SelectedCardScale', {
...trackBaseProps,
control: 'select card scale',
});
};
const onToggle = (e: CustomEvent<boolean>) => {
e.stopPropagation();
const opened = e.detail;
if (!opened) return;
ctx.track('OpenedCardScaleSelector', {
...trackBaseProps,
control: 'switch card scale',
});
};
const format = (value: number) => `${value}%`;
return html`${keyed(
model,
html`<affine-size-dropdown-menu
@select=${onSelect}
@toggle=${onToggle}
.format=${format}
.size$=${scale$}
></affine-size-dropdown-menu>`
)}`;
},
},
],
when: ctx => ctx.getSurfaceModelsByType(EmbedIframeBlockModel).length > 0,
} 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,
}),
];
};
@@ -0,0 +1,12 @@
export const EMBED_IFRAME_DEFAULT_WIDTH_IN_SURFACE = 752;
export const EMBED_IFRAME_DEFAULT_HEIGHT_IN_SURFACE = 116;
export const EMBED_IFRAME_DEFAULT_CONTAINER_BORDER_RADIUS = 8;
export const DEFAULT_IFRAME_HEIGHT = 152;
export const DEFAULT_IFRAME_WIDTH = '100%';
export const LINK_CREATE_POPUP_OFFSET = 4;
export const IDLE_CARD_DEFAULT_HEIGHT = 48;
export const LOADING_CARD_DEFAULT_HEIGHT = 114;
export const ERROR_CARD_DEFAULT_HEIGHT = 114;
@@ -0,0 +1,37 @@
import { EdgelessClipboardConfig } from '@blocksuite/affine-block-surface';
import { type BlockSnapshot } from '@blocksuite/store';
export class EdgelessClipboardEmbedIframeConfig extends EdgelessClipboardConfig {
static override readonly key = 'affine:embed-iframe';
override createBlock(embedIframe: BlockSnapshot): string | null {
if (!this.surface) return null;
const {
xywh,
caption,
url,
title,
description,
iframeUrl,
scale,
width,
height,
} = embedIframe.props;
return this.crud.addBlock(
'affine:embed-iframe',
{
url,
iframeUrl,
xywh,
caption,
title,
description,
scale,
width,
height,
},
this.surface.model.id
);
}
}
@@ -0,0 +1,55 @@
import { EdgelessLegacySlotIdentifier } from '@blocksuite/affine-block-surface';
import { Bound } from '@blocksuite/global/gfx';
import { toGfxBlockComponent } from '@blocksuite/std';
import { styleMap } from 'lit/directives/style-map.js';
import { html } from 'lit/static-html.js';
import { EmbedIframeBlockComponent } from './embed-iframe-block';
export class EmbedEdgelessIframeBlockComponent extends toGfxBlockComponent(
EmbedIframeBlockComponent
) {
override selectedStyle$ = null;
override blockDraggable = false;
override accessor blockContainerStyles = {
margin: '0',
backgroundColor: 'transparent',
};
get edgelessSlots() {
return this.std.get(EdgelessLegacySlotIdentifier);
}
override connectedCallback() {
super.connectedCallback();
this.edgelessSlots.elementResizeStart.subscribe(() => {
this.isResizing$.value = true;
});
this.edgelessSlots.elementResizeEnd.subscribe(() => {
this.isResizing$.value = false;
});
}
override renderGfxBlock() {
const bound = Bound.deserialize(this.model.props.xywh$.value);
const scale = this.model.props.scale$.value;
const width = bound.w / scale;
const height = bound.h / scale;
const style = {
width: `${width}px`,
height: `${height}px`,
transformOrigin: '0 0',
transform: `scale(${scale})`,
};
return html`
<div class="edgeless-embed-iframe-block" style=${styleMap(style)}>
${this.renderPageContent()}
</div>
`;
}
}
@@ -0,0 +1,467 @@
import { SurfaceBlockModel } from '@blocksuite/affine-block-surface';
import {
CaptionedBlockComponent,
SelectedStyle,
} from '@blocksuite/affine-components/caption';
import { createLitPortal } from '@blocksuite/affine-components/portal';
import type { EmbedIframeBlockModel } from '@blocksuite/affine-model';
import {
type EmbedIframeData,
EmbedIframeService,
type IframeOptions,
LinkPreviewerService,
NotificationProvider,
} from '@blocksuite/affine-shared/services';
import { matchModels } from '@blocksuite/affine-shared/utils';
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
import { BlockSelection } from '@blocksuite/std';
import { flip, offset, shift } from '@floating-ui/dom';
import {
computed,
effect,
type ReadonlySignal,
signal,
} from '@preact/signals-core';
import { html } from 'lit';
import { query } from 'lit/decorators.js';
import { type ClassInfo, classMap } from 'lit/directives/class-map.js';
import { ifDefined } from 'lit/directives/if-defined.js';
import { styleMap } from 'lit/directives/style-map.js';
import type { EmbedLinkInputPopupOptions } from './components/embed-iframe-link-input-popup.js';
import {
DEFAULT_IFRAME_HEIGHT,
DEFAULT_IFRAME_WIDTH,
EMBED_IFRAME_DEFAULT_CONTAINER_BORDER_RADIUS,
ERROR_CARD_DEFAULT_HEIGHT,
IDLE_CARD_DEFAULT_HEIGHT,
LINK_CREATE_POPUP_OFFSET,
LOADING_CARD_DEFAULT_HEIGHT,
} from './consts.js';
import { embedIframeBlockStyles } from './style.js';
import type { EmbedIframeStatusCardOptions } from './types.js';
import { safeGetIframeSrc } from './utils.js';
export type EmbedIframeStatus = 'idle' | 'loading' | 'success' | 'error';
export class EmbedIframeBlockComponent extends CaptionedBlockComponent<EmbedIframeBlockModel> {
selectedStyle$: ReadonlySignal<ClassInfo> | null = computed<ClassInfo>(
() => ({
'selected-style': this.selected$.value,
})
);
blockDraggable = true;
static override styles = embedIframeBlockStyles;
readonly status$ = signal<EmbedIframeStatus>('idle');
readonly error$ = signal<Error | null>(null);
readonly isIdle$ = computed(() => this.status$.value === 'idle');
readonly isLoading$ = computed(() => this.status$.value === 'loading');
readonly hasError$ = computed(() => this.status$.value === 'error');
readonly isSuccess$ = computed(() => this.status$.value === 'success');
readonly isDraggingOnHost$ = signal(false);
readonly isResizing$ = signal(false);
// show overlay to prevent the iframe from capturing pointer events
// when the block is dragging, resizing, or not selected
readonly showOverlay$ = computed(
() =>
this.isSuccess$.value &&
(this.isDraggingOnHost$.value ||
this.isResizing$.value ||
!this.selected$.value)
);
// since different providers have different border radius
// we need to update the selected border radius when the iframe is loaded
readonly selectedBorderRadius$ = computed(() => {
if (
this.status$.value === 'success' &&
typeof this.iframeOptions?.containerBorderRadius === 'number'
) {
return this.iframeOptions.containerBorderRadius;
}
return EMBED_IFRAME_DEFAULT_CONTAINER_BORDER_RADIUS;
});
protected iframeOptions: IframeOptions | undefined = undefined;
get embedIframeService() {
return this.std.get(EmbedIframeService);
}
get linkPreviewService() {
return this.std.get(LinkPreviewerService);
}
get notificationService() {
return this.std.getOptional(NotificationProvider);
}
get inSurface() {
return matchModels(this.model.parent, [SurfaceBlockModel]);
}
get _horizontalCardHeight(): number {
switch (this.status$.value) {
case 'idle':
return IDLE_CARD_DEFAULT_HEIGHT;
case 'loading':
return LOADING_CARD_DEFAULT_HEIGHT;
case 'error':
return ERROR_CARD_DEFAULT_HEIGHT;
default:
return LOADING_CARD_DEFAULT_HEIGHT;
}
}
get _statusCardOptions(): EmbedIframeStatusCardOptions {
return this.inSurface
? { layout: 'vertical' }
: { layout: 'horizontal', height: this._horizontalCardHeight };
}
open = () => {
const link = this.model.props.url;
if (!link) {
this.notificationService?.notify({
title: 'No link found',
message: 'Please set a link to the block',
accent: 'warning',
onClose: function (): void {},
});
return;
}
window.open(link, '_blank');
};
refreshData = async () => {
try {
const { url } = this.model.props;
if (!url) {
this.status$.value = 'idle';
return;
}
// set loading status
this.status$.value = 'loading';
this.error$.value = null;
// get embed data
const embedIframeService = this.embedIframeService;
const linkPreviewService = this.linkPreviewService;
if (!embedIframeService || !linkPreviewService) {
throw new BlockSuiteError(
ErrorCode.ValueNotExists,
'EmbedIframeService or LinkPreviewerService not found'
);
}
// get embed data and preview data in a promise
const [embedData, previewData] = await Promise.all([
embedIframeService.getEmbedIframeData(url),
linkPreviewService.query(url),
]);
// if the embed data is not found, and the iframeUrl is not set, throw an error
const currentIframeUrl = this.model.props.iframeUrl;
if (!embedData && !currentIframeUrl) {
throw new BlockSuiteError(
ErrorCode.ValueNotExists,
'Failed to get embed data'
);
}
// update model
const iframeUrl = this._getIframeUrl(embedData) ?? currentIframeUrl;
this.doc.updateBlock(this.model, {
iframeUrl,
title: embedData?.title || previewData?.title,
description: embedData?.description || previewData?.description,
});
// update iframe options, to ensure the iframe is rendered with the correct options
this._updateIframeOptions(url);
// set success status
this.status$.value = 'success';
} catch (err) {
// set error status
this.status$.value = 'error';
this.error$.value = err instanceof Error ? err : new Error(String(err));
console.error('Failed to refresh iframe data:', err);
}
};
private _linkInputAbortController: AbortController | null = null;
toggleLinkInputPopup = (options?: EmbedLinkInputPopupOptions) => {
if (this.readonly) {
return;
}
// toggle create popup when ths block is in idle status and the url is not set
if (!this._blockContainer || !this.isIdle$.value || this.model.props.url) {
return;
}
if (this._linkInputAbortController) {
this._linkInputAbortController.abort();
}
this._linkInputAbortController = new AbortController();
createLitPortal({
template: html`<embed-iframe-link-input-popup
.model=${this.model}
.abortController=${this._linkInputAbortController}
.std=${this.std}
.inSurface=${this.inSurface}
.options=${options}
></embed-iframe-link-input-popup>`,
container: document.body,
computePosition: {
referenceElement: this._blockContainer,
placement: 'bottom',
middleware: [flip(), offset(LINK_CREATE_POPUP_OFFSET), shift()],
autoUpdate: { animationFrame: true },
},
abortController: this._linkInputAbortController,
closeOnClickAway: true,
});
};
/**
* Get the iframe url from the embed data, first check if iframe_url is set,
* if not, check if html is set and get the iframe src from html
* @param embedData - The embed data
* @returns The iframe url
*/
private readonly _getIframeUrl = (embedData: EmbedIframeData | null) => {
const { iframe_url, html } = embedData ?? {};
return iframe_url ?? (html && safeGetIframeSrc(html));
};
private readonly _updateIframeOptions = (url: string) => {
const config = this.embedIframeService?.getConfig(url);
if (config) {
this.iframeOptions = config.options;
}
};
private readonly _handleDoubleClick = () => {
this.open();
};
private readonly _selectBlock = () => {
const { selectionManager } = this;
const blockSelection = selectionManager.create(BlockSelection, {
blockId: this.blockId,
});
selectionManager.setGroup('note', [blockSelection]);
};
protected _handleClick = () => {
// when the block is in idle status and the url is not set, clear the selection
// and show the link input popup
if (this.isIdle$.value && !this.model.props.url) {
// when the block is in the surface, clear the surface selection
// otherwise, clear the block selection
this.selectionManager.clear([this.inSurface ? 'surface' : 'block']);
this.toggleLinkInputPopup();
return;
}
// We don't need to select the block when the block is in the surface
if (this.inSurface) {
return;
}
// otherwise, select the block
this._selectBlock();
};
private readonly _handleRetry = async () => {
await this.refreshData();
};
private readonly _renderIframe = () => {
const { iframeUrl } = this.model.props;
const {
widthPercent,
heightInNote,
style,
allow,
referrerpolicy,
scrolling,
allowFullscreen,
} = this.iframeOptions ?? {};
const width = `${widthPercent}%`;
// if the block is in the surface, use 100% as the height
// otherwise, use the heightInNote
const height = this.inSurface ? '100%' : heightInNote;
return html`
<iframe
width=${width ?? DEFAULT_IFRAME_WIDTH}
height=${height ?? DEFAULT_IFRAME_HEIGHT}
?allowfullscreen=${allowFullscreen}
loading="lazy"
frameborder="0"
src=${ifDefined(iframeUrl)}
allow=${ifDefined(allow)}
referrerpolicy=${ifDefined(referrerpolicy)}
scrolling=${ifDefined(scrolling)}
style=${ifDefined(style)}
></iframe>
`;
};
private readonly _renderContent = () => {
if (this.isIdle$.value) {
return html`<embed-iframe-idle-card
.options=${this._statusCardOptions}
></embed-iframe-idle-card>`;
}
if (this.isLoading$.value) {
return html`<embed-iframe-loading-card
.std=${this.std}
.options=${this._statusCardOptions}
></embed-iframe-loading-card>`;
}
if (this.hasError$.value) {
return html`<embed-iframe-error-card
.error=${this.error$.value}
.model=${this.model}
.onRetry=${this._handleRetry}
.std=${this.std}
.inSurface=${this.inSurface}
.options=${this._statusCardOptions}
></embed-iframe-error-card>`;
}
return this._renderIframe();
};
override connectedCallback() {
super.connectedCallback();
this.contentEditable = 'false';
// update the selected style when the block is in the note
this.disposables.add(
effect(() => {
if (this.inSurface) {
return;
}
// when the block is in idle status, use the background style
// otherwise, use the border style
if (this.status$.value === 'idle') {
this.selectedStyle = SelectedStyle.Background;
} else {
this.selectedStyle = SelectedStyle.Border;
}
})
);
// if the iframe url is not set, refresh the data to get the iframe url
if (!this.model.props.iframeUrl) {
this.doc.withoutTransact(() => {
this.refreshData().catch(console.error);
});
} else {
// update iframe options, to ensure the iframe is rendered with the correct options
this._updateIframeOptions(this.model.props.url);
this.status$.value = 'success';
}
// refresh data when original url changes
this.disposables.add(
this.model.propsUpdated.subscribe(({ key }) => {
if (key === 'url') {
this.refreshData().catch(console.error);
}
})
);
// subscribe the editor host global dragging event
// to show the overlay for the dragging area or other pointer events
this.handleEvent(
'dragStart',
() => {
this.isDraggingOnHost$.value = true;
},
{ global: true }
);
this.handleEvent(
'dragEnd',
() => {
this.isDraggingOnHost$.value = false;
},
{ global: true }
);
}
override disconnectedCallback() {
super.disconnectedCallback();
this._linkInputAbortController?.abort();
this._linkInputAbortController = null;
}
override renderBlock() {
const containerClasses = classMap({
'affine-embed-iframe-block-container': true,
...this.selectedStyle$?.value,
'in-surface': this.inSurface,
});
const containerStyles = styleMap({
borderRadius: `${this.selectedBorderRadius$.value}px`,
});
const overlayClasses = classMap({
'affine-embed-iframe-block-overlay': true,
show: this.showOverlay$.value,
});
return html`
<div
draggable=${this.blockDraggable ? 'true' : 'false'}
class=${containerClasses}
style=${containerStyles}
@click=${this._handleClick}
@dblclick=${this._handleDoubleClick}
>
${this._renderContent()}
<!-- overlay to prevent the iframe from capturing pointer events -->
<div class=${overlayClasses}></div>
</div>
`;
}
override accessor blockContainerStyles = {
margin: '18px 0',
backgroundColor: 'transparent',
};
get readonly() {
return this.doc.readonly;
}
get selectionManager() {
return this.host.selection;
}
override accessor useCaptionEditor = true;
override accessor useZeroWidth = true;
override accessor selectedStyle = SelectedStyle.Border;
@query('.affine-embed-iframe-block-container')
accessor _blockContainer: HTMLElement | null = null;
}
@@ -0,0 +1,23 @@
import { EmbedIframeBlockSchema } from '@blocksuite/affine-model';
import { SlashMenuConfigExtension } from '@blocksuite/affine-widget-slash-menu';
import { BlockViewExtension, FlavourExtension } from '@blocksuite/std';
import type { ExtensionType } from '@blocksuite/store';
import { literal } from 'lit/static-html.js';
import { EmbedIframeBlockAdapterExtensions } from './adapters';
import { embedIframeSlashMenuConfig } from './configs/slash-menu/slash-menu';
import { createBuiltinToolbarConfigExtension } from './configs/toolbar';
const flavour = EmbedIframeBlockSchema.model.flavour;
export const EmbedIframeBlockSpec: ExtensionType[] = [
FlavourExtension(flavour),
BlockViewExtension(flavour, model => {
return model.parent?.flavour === 'affine:surface'
? literal`affine-embed-edgeless-iframe-block`
: literal`affine-embed-iframe-block`;
}),
EmbedIframeBlockAdapterExtensions,
createBuiltinToolbarConfigExtension(flavour),
SlashMenuConfigExtension(flavour, embedIframeSlashMenuConfig),
].flat();
@@ -0,0 +1,11 @@
export * from './adapters';
export * from './commands';
export * from './configs';
export {
EMBED_IFRAME_DEFAULT_HEIGHT_IN_SURFACE,
EMBED_IFRAME_DEFAULT_WIDTH_IN_SURFACE,
} from './consts';
export * from './edgeless-clipboard-config';
export * from './embed-iframe-block';
export * from './embed-iframe-spec';
export { canEmbedAsIframe } from './utils';
@@ -0,0 +1,29 @@
import { css } from 'lit';
export const embedIframeBlockStyles = css`
.affine-embed-iframe-block-container {
display: flex;
width: 100%;
border-radius: 8px;
user-select: none;
align-items: center;
justify-content: center;
position: relative;
}
.affine-embed-iframe-block-container.in-surface {
height: 100%;
}
.affine-embed-iframe-block-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: none;
}
.affine-embed-iframe-block-overlay.show {
display: block;
}
`;
@@ -0,0 +1,16 @@
/**
* The options for the embed iframe status card
* layout: the layout of the card, horizontal or vertical
* width: the width of the card, if not set, the card width will be 100%
* height: the height of the card, if not set, the card height will be 100%
* @example
* {
* layout: 'horizontal',
* height: 114,
* }
*/
export type EmbedIframeStatusCardOptions = {
layout: 'horizontal' | 'vertical';
width?: number;
height?: number;
};
@@ -0,0 +1,75 @@
import { EmbedIframeService } from '@blocksuite/affine-shared/services';
import type { BlockStdScope } from '@blocksuite/std';
/**
* The options for the embed iframe url validation
*/
export interface EmbedIframeUrlValidationOptions {
protocols: string[]; // Allowed protocols, e.g. ['https']
hostnames: string[]; // Allowed hostnames, e.g. ['docs.google.com']
}
/**
* Validate the url is allowed to embed in the iframe
* @param url URL to validate
* @param options Validation options
* @returns Whether the url is valid
*/
export function validateEmbedIframeUrl(
url: string,
options: EmbedIframeUrlValidationOptions
): boolean {
try {
const parsedUrl = new URL(url);
const { protocols, hostnames } = options;
return (
protocols.includes(parsedUrl.protocol) &&
hostnames.includes(parsedUrl.hostname)
);
} catch (e) {
console.warn(`Invalid embed iframe url: ${url}`, e);
return false;
}
}
/**
* Safely extracts the src URL from an iframe HTML string
* @param htmlString The iframe HTML string to parse
* @param options Optional validation configuration
* @returns The validated src URL or undefined if validation fails
*/
export function safeGetIframeSrc(htmlString: string): string | undefined {
try {
// Create a DOMParser instance
const parser = new DOMParser();
// Parse the HTML string
const doc = parser.parseFromString(htmlString, 'text/html');
// Get the iframe element
const iframe = doc.querySelector('iframe');
if (!iframe) {
return undefined;
}
// Get the src attribute
const src = iframe.getAttribute('src');
if (!src) {
return undefined;
}
return src;
} catch {
return undefined;
}
}
/**
* Check if the url can be embedded as an iframe
* @param std The block std scope
* @param url The url to check
* @returns Whether the url can be embedded as an iframe
*/
export function canEmbedAsIframe(std: BlockStdScope, url: string) {
const embedIframeService = std.get(EmbedIframeService);
return embedIframeService.canEmbed(url);
}