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,43 @@
import {
type ClipboardConfigCreationContext,
EdgelessClipboardConfig,
} from '@blocksuite/affine-block-surface';
import { type BlockSnapshot, fromJSON } from '@blocksuite/store';
export class EdgelessClipboardFrameConfig extends EdgelessClipboardConfig {
static override readonly key = 'affine:frame';
override createBlock(
frame: BlockSnapshot,
context: ClipboardConfigCreationContext
): string | null {
if (!this.surface) return null;
const { oldToNewIdMap, newPresentationIndexes } = context;
const { xywh, title, background, childElementIds } = frame.props;
const newChildElementIds: Record<string, boolean> = {};
if (typeof childElementIds === 'object' && childElementIds !== null) {
Object.keys(childElementIds).forEach(oldId => {
const newId = oldToNewIdMap.get(oldId);
if (newId) {
newChildElementIds[newId] = true;
}
});
}
const frameId = this.crud.addBlock(
'affine:frame',
{
xywh,
background,
title: fromJSON(title),
childElementIds: newChildElementIds,
presentationIndex: newPresentationIndexes.get(frame.id),
},
this.surface.model.id
);
return frameId;
}
}
@@ -0,0 +1,9 @@
export const FrameConfig: {
name: string;
wh: [number, number];
}[] = [
{ name: '1:1', wh: [1200, 1200] },
{ name: '4:3', wh: [1600, 1200] },
{ name: '16:9', wh: [1600, 900] },
{ name: '2:1', wh: [1600, 800] },
];
@@ -0,0 +1,33 @@
import { menu } from '@blocksuite/affine-components/context-menu';
import type { DenseMenuBuilder } from '@blocksuite/affine-widget-edgeless-toolbar';
import { FrameIcon } from '@blocksuite/icons/lit';
import { EdgelessFrameManagerIdentifier } from '../frame-manager.js';
import { FrameConfig } from './config.js';
export const buildFrameDenseMenu: DenseMenuBuilder = (edgeless, gfx) =>
menu.subMenu({
name: 'Frame',
prefix: FrameIcon({ width: '20px', height: '20px' }),
select: () => gfx.tool.setTool({ type: 'frame' }),
isSelected: gfx.tool.currentToolName$.peek() === 'frame',
options: {
items: [
menu.action({
name: 'Custom',
select: () => gfx.tool.setTool({ type: 'frame' }),
}),
...FrameConfig.map(config =>
menu.action({
name: `Slide ${config.name}`,
select: () => {
const frame = edgeless.std.get(EdgelessFrameManagerIdentifier);
// @ts-expect-error FIXME: resolve after gfx tool refactor
gfx.tool.setTool('default');
frame.createFrameOnViewportCenter(config.wh);
},
})
),
],
},
});
@@ -0,0 +1,104 @@
import { EdgelessToolbarToolMixin } from '@blocksuite/affine-widget-edgeless-toolbar';
import type { GfxToolsFullOptionValue } from '@blocksuite/std/gfx';
import { css, html, LitElement } from 'lit';
import { repeat } from 'lit/directives/repeat.js';
import { EdgelessFrameManagerIdentifier } from '../frame-manager.js';
import { FrameConfig } from './config.js';
export class EdgelessFrameMenu extends EdgelessToolbarToolMixin(LitElement) {
static override styles = css`
:host {
position: absolute;
display: flex;
z-index: -1;
}
.menu-content {
display: flex;
align-items: center;
justify-content: center;
gap: 14px;
}
.frame-add-button {
width: 40px;
height: 24px;
border-radius: 4px;
border: 1px solid var(--affine-border-color);
color: var(--affine-text-primary-color);
line-height: 20px;
font-weight: 400;
font-size: 12px;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
position: relative;
}
.frame-add-button::before {
content: '';
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
border-radius: 3px;
background: transparent;
transition: background-color 0.23s ease;
pointer-events: none;
}
.frame-add-button:hover::before {
background: var(--affine-hover-color);
}
.custom {
width: 60px;
background: var(--affine-hover-color);
}
.divider {
width: 1px;
height: 20px;
background: var(--affine-border-color);
transform: scaleX(0.5);
}
`;
override type: GfxToolsFullOptionValue['type'] = 'frame';
get frameManager() {
return this.edgeless.std.get(EdgelessFrameManagerIdentifier);
}
override render() {
const { gfx, frameManager } = this;
return html`
<edgeless-slide-menu .showNext=${false}>
<div class="menu-content">
<div class="frame-add-button custom">Custom</div>
<div class="divider"></div>
${repeat(
FrameConfig,
item => item.name,
(item, index) => html`
<div
@click=${() => {
// @ts-expect-error FIXME: resolve after gfx tool refactor
gfx.tool.setTool('default');
frameManager.createFrameOnViewportCenter(item.wh);
}}
class="frame-add-button ${index}"
data-name="${item.name}"
data-w="${item.wh[0]}"
data-h="${item.wh[1]}"
>
${item.name}
</div>
`
)}
</div>
</edgeless-slide-menu>
`;
}
}
@@ -0,0 +1,48 @@
import { QuickToolMixin } from '@blocksuite/affine-widget-edgeless-toolbar';
import { FrameIcon } from '@blocksuite/icons/lit';
import type { GfxToolsFullOptionValue } from '@blocksuite/std/gfx';
import { css, html, LitElement } from 'lit';
export class EdgelessFrameToolButton extends QuickToolMixin(LitElement) {
static override styles = css`
:host {
display: flex;
}
`;
override type: GfxToolsFullOptionValue['type'] = 'frame';
private _toggleFrameMenu() {
if (this.tryDisposePopper()) return;
const menu = this.createPopper('edgeless-frame-menu', this);
menu.element.edgeless = this.edgeless;
}
override render() {
const type = this.edgelessTool?.type;
return html`
<edgeless-tool-icon-button
class="edgeless-frame-button"
.tooltip=${this.popper
? ''
: html`<affine-tooltip-content-with-shortcut
data-tip="${'Frame'}"
data-shortcut="${'F'}"
></affine-tooltip-content-with-shortcut>`}
.tooltipOffset=${17}
.iconSize=${'24px'}
.active=${type === 'frame'}
.iconContainerPadding=${6}
@click=${() => {
// don't update tool before toggling menu
this._toggleFrameMenu();
this.setEdgelessTool({ type: 'frame' });
}}
>
${FrameIcon()}
<toolbar-arrow-up-icon></toolbar-arrow-up-icon>
</edgeless-tool-icon-button>
`;
}
}
@@ -0,0 +1,5 @@
export * from './config';
export * from './frame-dense-menu';
export * from './frame-menu';
export * from './frame-tool-button';
export * from './quick-tool';
@@ -0,0 +1,484 @@
import { EdgelessLegacySlotIdentifier } from '@blocksuite/affine-block-surface';
import { toast } from '@blocksuite/affine-components/toast';
import type { FrameBlockModel } from '@blocksuite/affine-model';
import {
EditPropsStore,
ViewportElementProvider,
} from '@blocksuite/affine-shared/services';
import { EdgelessToolbarToolMixin } from '@blocksuite/affine-widget-edgeless-toolbar';
import { Bound, clamp } from '@blocksuite/global/gfx';
import { SignalWatcher } from '@blocksuite/global/lit';
import {
EndPointArrowIcon,
ExpandCloseIcon,
ExpandFullIcon,
StartPointArrowIcon,
StopAiIcon,
} from '@blocksuite/icons/lit';
import type { BlockComponent } from '@blocksuite/std';
import type { GfxToolsFullOptionValue } from '@blocksuite/std/gfx';
import { effect } from '@preact/signals-core';
import { cssVar } from '@toeverything/theme';
import { css, html, LitElement, nothing, type PropertyValues } from 'lit';
import { property, state } from 'lit/decorators.js';
import {
EdgelessFrameManagerIdentifier,
isFrameBlock,
type NavigatorMode,
} from '../frame-manager';
export class PresentationToolbar extends EdgelessToolbarToolMixin(
SignalWatcher(LitElement)
) {
static override styles = css`
:host {
align-items: inherit;
width: 100%;
height: 100%;
gap: 8px;
padding-right: 2px;
}
.full-divider {
width: 8px;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.full-divider::after {
content: '';
width: 1px;
height: 100%;
background: var(--affine-border-color);
transform: scaleX(0.5);
}
.config-buttons {
display: flex;
gap: 10px;
}
.edgeless-frame-navigator {
width: 140px;
display: flex;
align-items: center;
justify-content: center;
}
.edgeless-frame-navigator.dense {
width: auto;
}
.edgeless-frame-navigator-title {
display: inline-block;
cursor: pointer;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
padding-right: 8px;
}
.edgeless-frame-navigator-count {
color: var(--affine-text-secondary-color);
white-space: nowrap;
}
.edgeless-frame-navigator-stop {
border: none;
cursor: pointer;
padding: 4px;
border-radius: 8px;
position: relative;
overflow: hidden;
svg {
display: block;
width: 24px;
height: 24px;
color: white;
}
}
.edgeless-frame-navigator-stop::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: transparent;
border-radius: inherit;
}
.edgeless-frame-navigator-stop:hover::before {
background: var(--affine-hover-color);
}
`;
private _cachedIndex = -1;
private _timer?: ReturnType<typeof setTimeout>;
override type: GfxToolsFullOptionValue['type'] = 'frameNavigator';
private get _cachedPresentHideToolbar() {
return !!this.edgeless.std
.get(EditPropsStore)
.getStorage('presentHideToolbar');
}
private set _cachedPresentHideToolbar(value) {
this.edgeless.std
.get(EditPropsStore)
.setStorage('presentHideToolbar', !!value);
}
private get _frames(): FrameBlockModel[] {
return this.edgeless.std.get(EdgelessFrameManagerIdentifier).frames;
}
get dense() {
return this.containerWidth < 554;
}
get host() {
return this.edgeless.host;
}
get slots() {
return this.edgeless.std.get(EdgelessLegacySlotIdentifier);
}
constructor(edgeless: BlockComponent) {
super();
this.edgeless = edgeless;
}
private _bindHotKey() {
const handleKeyIfFrameNavigator = (action: () => void) => () => {
if (this.edgelessTool.type === 'frameNavigator') {
action();
}
};
this.edgeless.bindHotKey(
{
ArrowLeft: handleKeyIfFrameNavigator(() => this._previousFrame()),
ArrowRight: handleKeyIfFrameNavigator(() => this._nextFrame()),
Escape: handleKeyIfFrameNavigator(() => this._exitPresentation()),
},
{
global: true,
}
);
}
private _exitPresentation() {
// When exit presentation mode, we need to set the tool to default or pan
// And exit fullscreen
const tool = this.edgeless.doc.readonly
? { type: 'pan', panning: false }
: { type: 'default' };
// @ts-expect-error FIXME: resolve after gfx tool refactor
this.setEdgelessTool(tool);
if (document.fullscreenElement) {
document.exitFullscreen().catch(console.error);
}
}
private _moveToCurrentFrame() {
const current = this._currentFrameIndex;
const viewport = this.gfx.viewport;
const frame = this._frames[current];
if (frame) {
let bound = Bound.deserialize(frame.xywh);
if (this._navigatorMode === 'fill') {
const vb = viewport.viewportBounds;
const center = bound.center;
let w, h;
if (vb.w / vb.h > bound.w / bound.h) {
w = bound.w;
h = (w * vb.h) / vb.w;
} else {
h = bound.h;
w = (h * vb.w) / vb.h;
}
bound = Bound.fromCenter(center, w, h);
}
viewport.setViewportByBound(bound, [0, 0, 0, 0], false);
this.slots.navigatorFrameChanged.next(
this._frames[this._currentFrameIndex]
);
}
}
private _nextFrame() {
const frames = this._frames;
const min = 0;
const max = frames.length - 1;
if (this._currentFrameIndex === frames.length - 1) {
toast(this.host, 'You have reached the last frame');
} else {
this._currentFrameIndex = clamp(this._currentFrameIndex + 1, min, max);
}
}
private _previousFrame() {
const frames = this._frames;
const min = 0;
const max = frames.length - 1;
if (this._currentFrameIndex === 0) {
toast(this.host, 'You have reached the first frame');
} else {
this._currentFrameIndex = clamp(this._currentFrameIndex - 1, min, max);
}
}
/**
* Toggle fullscreen, but keep edgeless tool to frameNavigator
* If already fullscreen, exit fullscreen
* If not fullscreen, enter fullscreen
*/
private _toggleFullScreen() {
if (document.fullscreenElement) {
document.exitFullscreen().catch(console.error);
this._fullScreenMode = false;
} else {
const { viewportElement } = this.edgeless.std.get(
ViewportElementProvider
);
launchIntoFullscreen(viewportElement);
this._fullScreenMode = true;
}
}
override connectedCallback(): void {
super.connectedCallback();
const { _disposables } = this;
_disposables.add(
effect(() => {
const currentTool = this.gfx.tool.currentToolOption$.value;
const selection = this.gfx.selection;
if (currentTool?.type === 'frameNavigator') {
this._cachedIndex = this._currentFrameIndex;
this._navigatorMode = currentTool.mode ?? this._navigatorMode;
if (isFrameBlock(selection.selectedElements[0])) {
this._cachedIndex = this._frames.findIndex(
frame => frame.id === selection.selectedElements[0].id
);
}
if (this._frames.length === 0)
toast(
this.host,
'The presentation requires at least 1 frame. You can firstly create a frame.',
5000
);
this._toggleFullScreen();
}
this.requestUpdate();
})
);
}
override firstUpdated() {
const { _disposables } = this;
this._bindHotKey();
_disposables.add(
this.slots.navigatorSettingUpdated.subscribe(({ fillScreen }) => {
if (fillScreen !== undefined) {
this._navigatorMode = fillScreen ? 'fill' : 'fit';
}
})
);
_disposables.addFromEvent(document, 'fullscreenchange', () => {
if (document.fullscreenElement) {
// When enter fullscreen, we need to set current frame to the cached index
this._timer = setTimeout(() => {
this._currentFrameIndex = this._cachedIndex;
}, 400);
} else {
// When exit fullscreen, we need to clear the timer
clearTimeout(this._timer);
if (
this.edgelessTool.type === 'frameNavigator' &&
this._fullScreenMode
) {
const tool = this.edgeless.doc.readonly
? { type: 'pan', panning: false }
: { type: 'default' };
// @ts-expect-error FIXME: resolve after gfx tool refactor
this.setEdgelessTool(tool);
}
}
setTimeout(() => this._moveToCurrentFrame(), 400);
this.slots.fullScreenToggled.next();
});
this._navigatorMode =
this.edgeless.std.get(EditPropsStore).getStorage('presentFillScreen') ===
true
? 'fill'
: 'fit';
}
override render() {
const current = this._currentFrameIndex;
const frames = this._frames;
const frame = frames[current];
return html`
<style>
:host {
display: flex;
}
</style>
<edgeless-tool-icon-button
.iconContainerPadding=${0}
.tooltip=${'Previous'}
.iconSize=${'24px'}
@click=${() => this._previousFrame()}
>
${StartPointArrowIcon()}
</edgeless-tool-icon-button>
<div class="edgeless-frame-navigator ${this.dense ? 'dense' : ''}">
${this.dense
? nothing
: html`<span
style="color: ${cssVar('textPrimaryColor')}"
class="edgeless-frame-navigator-title"
@click=${() => this._moveToCurrentFrame()}
>
${frame?.props.title ?? 'no frame'}
</span>`}
<span class="edgeless-frame-navigator-count">
${frames.length === 0 ? 0 : current + 1} / ${frames.length}
</span>
</div>
<edgeless-tool-icon-button
.tooltip=${'Next'}
@click=${() => this._nextFrame()}
.iconContainerPadding=${0}
.iconSize=${'24px'}
>
${EndPointArrowIcon()}
</edgeless-tool-icon-button>
<div class="full-divider"></div>
<div class="config-buttons">
<edgeless-tool-icon-button
.tooltip=${document.fullscreenElement
? 'Exit Full Screen'
: 'Enter Full Screen'}
@click=${() => this._toggleFullScreen()}
.iconContainerPadding=${0}
.iconContainerWidth=${'24px'}
.iconSize=${'24px'}
>
${document.fullscreenElement ? ExpandCloseIcon() : ExpandFullIcon()}
</edgeless-tool-icon-button>
${this.dense
? nothing
: html`<edgeless-frame-order-button
.popperShow=${this.frameMenuShow}
.setPopperShow=${this.setFrameMenuShow}
.edgeless=${this.edgeless}
>
</edgeless-frame-order-button>`}
<edgeless-navigator-setting-button
.edgeless=${this.edgeless}
.hideToolbar=${this._cachedPresentHideToolbar}
.onHideToolbarChange=${(hideToolbar: boolean) => {
this._cachedPresentHideToolbar = hideToolbar;
}}
.popperShow=${this.settingMenuShow}
.setPopperShow=${this.setSettingMenuShow}
.includeFrameOrder=${this.dense}
>
</edgeless-navigator-setting-button>
</div>
<div class="full-divider"></div>
<button
class="edgeless-frame-navigator-stop"
@click=${this._exitPresentation}
style="background: ${cssVar('warningColor')}"
>
${StopAiIcon()}
</button>
`;
}
protected override updated(changedProperties: PropertyValues) {
if (
changedProperties.has('_currentFrameIndex') &&
this.edgelessTool.type === 'frameNavigator'
) {
this._moveToCurrentFrame();
}
}
@state({
hasChanged() {
return true;
},
})
private accessor _currentFrameIndex = 0;
private accessor _fullScreenMode = true;
@state()
private accessor _navigatorMode: NavigatorMode = 'fit';
@property({ attribute: false })
accessor containerWidth = 1920;
@property({ type: Boolean })
accessor frameMenuShow = false;
@property()
accessor setFrameMenuShow: (show: boolean) => void = () => {};
@property()
accessor setSettingMenuShow: (show: boolean) => void = () => {};
@property({ type: Boolean })
accessor settingMenuShow = false;
}
function launchIntoFullscreen(element: Element) {
if (element.requestFullscreen) {
element.requestFullscreen().catch(console.error);
} else if (
'mozRequestFullScreen' in element &&
element.mozRequestFullScreen instanceof Function
) {
// Firefox
element.mozRequestFullScreen();
} else if (
'webkitRequestFullscreen' in element &&
element.webkitRequestFullscreen instanceof Function
) {
// Chrome, Safari and Opera
element.webkitRequestFullscreen();
} else if (
'msRequestFullscreen' in element &&
element.msRequestFullscreen instanceof Function
) {
// IE/Edge
element.msRequestFullscreen();
}
}
@@ -0,0 +1,15 @@
import { QuickToolExtension } from '@blocksuite/affine-widget-edgeless-toolbar';
import { html } from 'lit';
import { buildFrameDenseMenu } from './frame-dense-menu';
export const frameQuickTool = QuickToolExtension('frame', ({ block, gfx }) => {
return {
type: 'frame',
content: html`<edgeless-frame-tool-button
.edgeless=${block}
></edgeless-frame-tool-button>`,
menu: buildFrameDenseMenu(block, gfx),
enable: !block.doc.readonly,
};
});
@@ -0,0 +1,37 @@
import { EdgelessFrameMenu, EdgelessFrameToolButton } from './edgeless-toolbar';
import { PresentationToolbar } from './edgeless-toolbar/presentation-toolbar';
import { FrameBlockComponent } from './frame-block';
import { EdgelessFrameOrderButton } from './present/frame-order-button';
import { EdgelessFrameOrderMenu } from './present/frame-order-menu';
import { EdgelessNavigatorSettingButton } from './present/navigator-setting-button';
import { EdgelessPresentButton } from './present/present-button';
export function effects() {
customElements.define('affine-frame', FrameBlockComponent);
customElements.define('edgeless-frame-tool-button', EdgelessFrameToolButton);
customElements.define('edgeless-frame-menu', EdgelessFrameMenu);
customElements.define(
'edgeless-frame-order-button',
EdgelessFrameOrderButton
);
customElements.define('edgeless-frame-order-menu', EdgelessFrameOrderMenu);
customElements.define(
'edgeless-navigator-setting-button',
EdgelessNavigatorSettingButton
);
customElements.define('edgeless-present-button', EdgelessPresentButton);
customElements.define('presentation-toolbar', PresentationToolbar);
}
declare global {
interface HTMLElementTagNameMap {
'affine-frame': FrameBlockComponent;
'edgeless-frame-tool-button': EdgelessFrameToolButton;
'edgeless-frame-menu': EdgelessFrameMenu;
'edgeless-frame-order-button': EdgelessFrameOrderButton;
'edgeless-frame-order-menu': EdgelessFrameOrderMenu;
'edgeless-navigator-setting-button': EdgelessNavigatorSettingButton;
'edgeless-present-button': EdgelessPresentButton;
'presentation-toolbar': PresentationToolbar;
}
}
@@ -0,0 +1,107 @@
import { DefaultTheme, type FrameBlockModel } from '@blocksuite/affine-model';
import { ThemeProvider } from '@blocksuite/affine-shared/services';
import { Bound } from '@blocksuite/global/gfx';
import { GfxBlockComponent } from '@blocksuite/std';
import type { SelectedContext } from '@blocksuite/std/gfx';
import { cssVarV2 } from '@toeverything/theme/v2';
import { html } from 'lit';
import { state } from 'lit/decorators.js';
import { styleMap } from 'lit/directives/style-map.js';
export class FrameBlockComponent extends GfxBlockComponent<FrameBlockModel> {
override connectedCallback() {
super.connectedCallback();
this._disposables.add(
this.doc.slots.blockUpdated.subscribe(({ type, id }) => {
if (id === this.model.id && type === 'update') {
this.requestUpdate();
}
})
);
this._disposables.add(
this.gfx.viewport.viewportUpdated.subscribe(() => {
this.requestUpdate();
})
);
}
/**
* Due to potentially very large frame sizes, CSS scaling can cause iOS Safari to crash.
* To mitigate this issue, we combine size calculations within the rendering rect.
*/
override getCSSTransform(): string {
return '';
}
override getRenderingRect() {
const viewport = this.gfx.viewport;
const { translateX, translateY, zoom } = viewport;
const { xywh, rotate } = this.model;
const bound = Bound.deserialize(xywh);
const scaledX = bound.x * zoom + translateX;
const scaledY = bound.y * zoom + translateY;
return {
x: scaledX,
y: scaledY,
w: bound.w * zoom,
h: bound.h * zoom,
rotate,
zIndex: this.toZIndex(),
};
}
override onSelected(context: SelectedContext): void {
const { x, y } = context.position;
if (
!context.fallback &&
// if the frame is selected by title, then ignore it because the title selection is handled by the title widget
(this.model.externalBound?.containsPoint([x, y]) ||
// otherwise if the frame has title, then ignore it because in this case the frame cannot be selected by frame body
this.model.props.title.length)
) {
return;
}
super.onSelected(context);
}
override renderGfxBlock() {
const { model, showBorder, std } = this;
const backgroundColor = std
.get(ThemeProvider)
.generateColorProperty(model.props.background, DefaultTheme.transparent);
const _isNavigator =
this.gfx.tool.currentToolName$.value === 'frameNavigator';
const frameIndex = this.gfx.layer.getZIndex(model);
return html`
<div
class="affine-frame-container"
style=${styleMap({
zIndex: `${frameIndex}`,
backgroundColor,
height: '100%',
width: '100%',
borderRadius: '2px',
border:
_isNavigator || !showBorder
? 'none'
: `1px solid ${cssVarV2('edgeless/frame/border/default')}`,
})}
></div>
`;
}
@state()
accessor showBorder = true;
}
declare global {
interface HTMLElementTagNameMap {
'affine-frame': FrameBlockComponent;
}
}
@@ -0,0 +1,88 @@
import { OverlayIdentifier } from '@blocksuite/affine-block-surface';
import {
type FrameBlockModel,
MindmapElementModel,
} from '@blocksuite/affine-model';
import {
type DragExtensionInitializeContext,
type ExtensionDragEndContext,
type ExtensionDragMoveContext,
type ExtensionDragStartContext,
getTopElements,
GfxExtensionIdentifier,
TransformExtension,
} from '@blocksuite/std/gfx';
import {
type EdgelessFrameManager,
type FrameOverlay,
isFrameBlock,
} from './frame-manager';
export class FrameHighlightManager extends TransformExtension {
static override key = 'frame-highlight-manager';
get frameMgr() {
return this.std.getOptional(
GfxExtensionIdentifier('frame-manager')
) as EdgelessFrameManager;
}
get frameHighlightOverlay() {
return this.std.getOptional(OverlayIdentifier('frame')) as FrameOverlay;
}
override onDragInitialize(_: DragExtensionInitializeContext): {
onDragStart?: (context: ExtensionDragStartContext) => void;
onDragMove?: (context: ExtensionDragMoveContext) => void;
onDragEnd?: (context: ExtensionDragEndContext) => void;
clear?: () => void;
} {
if (!this.frameMgr || !this.frameHighlightOverlay) {
return {};
}
let hoveredFrame: FrameBlockModel | null = null;
const { frameMgr, frameHighlightOverlay } = this;
let draggedFrames: FrameBlockModel[] = [];
return {
onDragStart(context) {
draggedFrames = context.elements
.map(elem => elem.model)
.filter(model => isFrameBlock(model));
},
onDragMove(context) {
const { dragLastPos } = context;
hoveredFrame = frameMgr.getFrameFromPoint(
[dragLastPos.x, dragLastPos.y],
draggedFrames
);
if (hoveredFrame && !hoveredFrame.isLocked()) {
frameHighlightOverlay.highlight(hoveredFrame);
} else {
frameHighlightOverlay.clear();
}
},
onDragEnd(context) {
const topElements = getTopElements(
context.elements.map(elem =>
elem.model.group instanceof MindmapElementModel
? elem.model.group
: elem.model
)
);
if (hoveredFrame) {
frameMgr.addElementsToFrame(hoveredFrame, topElements);
} else {
topElements.forEach(elem => frameMgr.removeFromParentFrame(elem));
}
frameHighlightOverlay.clear();
},
};
}
}
@@ -0,0 +1,488 @@
import type { SurfaceBlockModel } from '@blocksuite/affine-block-surface';
import { Overlay } from '@blocksuite/affine-block-surface';
import type { FrameBlockModel } from '@blocksuite/affine-model';
import { EditPropsStore } from '@blocksuite/affine-shared/services';
import { DisposableGroup } from '@blocksuite/global/disposable';
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
import {
Bound,
deserializeXYWH,
type IVec,
type SerializedXYWH,
} from '@blocksuite/global/gfx';
import {
generateKeyBetweenV2,
getTopElements,
GfxBlockElementModel,
type GfxController,
GfxExtension,
GfxExtensionIdentifier,
type GfxModel,
isGfxGroupCompatibleModel,
renderableInEdgeless,
} from '@blocksuite/std/gfx';
import { type BlockModel, Text } from '@blocksuite/store';
import * as Y from 'yjs';
const FRAME_PADDING = 40;
export type NavigatorMode = 'fill' | 'fit';
export class FrameOverlay extends Overlay {
static override overlayName: string = 'frame';
private _disposable = new DisposableGroup();
private _frame: FrameBlockModel | null = null;
private _innerElements = new Set<GfxModel>();
private readonly _prevXYWH: SerializedXYWH | null = null;
private get _frameManager() {
return this.gfx.std.get(EdgelessFrameManagerIdentifier);
}
constructor(gfx: GfxController) {
super(gfx);
}
private _reset() {
this._disposable.dispose();
this._disposable = new DisposableGroup();
this._frame = null;
this._innerElements.clear();
}
override clear() {
if (this._frame === null && this._innerElements.size === 0) return;
this._reset();
this._renderer?.refresh();
}
highlight(
frame: FrameBlockModel,
highlightElementsInBound = false,
highlightOutline = true
) {
if (!highlightElementsInBound && !highlightOutline) return;
let needRefresh = false;
if (highlightOutline && this._prevXYWH !== frame.xywh) {
needRefresh = true;
}
let innerElements = new Set<GfxModel>();
if (highlightElementsInBound) {
innerElements = new Set(
getTopElements(
this._frameManager.getElementsInFrameBound(frame)
).concat(
this._frameManager.getChildElementsInFrame(frame).filter(child => {
return frame.intersectsBound(child.elementBound);
})
)
);
if (!areSetsEqual(this._innerElements, innerElements)) {
needRefresh = true;
}
}
if (!needRefresh) return;
this._reset();
if (highlightOutline) this._frame = frame;
if (highlightElementsInBound) this._innerElements = innerElements;
const subscription = frame.deleted.subscribe(() => {
subscription.unsubscribe();
this.clear();
});
this._disposable.add(subscription);
this._renderer?.refresh();
}
override render(ctx: CanvasRenderingContext2D): void {
ctx.beginPath();
ctx.strokeStyle = '#1E96EB';
ctx.lineWidth = 2 / this.gfx.viewport.zoom;
const radius = 2 / this.gfx.viewport.zoom;
if (this._frame) {
const { x, y, w, h } = this._frame.elementBound;
ctx.roundRect(x, y, w, h, radius);
ctx.stroke();
}
this._innerElements.forEach(element => {
const [x, y, w, h] = deserializeXYWH(element.xywh);
ctx.translate(x + w / 2, y + h / 2);
ctx.rotate((element.rotate * Math.PI) / 180);
ctx.roundRect(-w / 2, -h / 2, w, h, radius);
ctx.translate(-x - w / 2, -y - h / 2);
ctx.stroke();
});
}
}
export const EdgelessFrameManagerIdentifier =
GfxExtensionIdentifier<EdgelessFrameManager>('frame-manager');
export class EdgelessFrameManager extends GfxExtension {
static override key = 'frame-manager';
private readonly _disposable = new DisposableGroup();
/**
* Get all sorted frames by presentation orderer,
* the legacy frame that uses `index` as presentation order
* will be put at the beginning of the array.
*/
get frames() {
return Object.values(this.gfx.doc.blocks.value)
.map(({ model }) => model)
.filter(isFrameBlock)
.sort(EdgelessFrameManager.framePresentationComparator);
}
constructor(gfx: GfxController) {
super(gfx);
this._watchElementAdded();
}
static framePresentationComparator<
T extends
| FrameBlockModel
| { props: { index: string; presentationIndex?: string } },
>(a: T, b: T) {
function stringCompare(a: string, b: string) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
const isModel = (
x:
| FrameBlockModel
| { props: { index: string; presentationIndex?: string } }
): x is FrameBlockModel => {
return 'presentationIndex$' in x;
};
if (
isModel(a) &&
isModel(b) &&
a.props.presentationIndex$.value &&
b.props.presentationIndex$.value
) {
return stringCompare(
a.props.presentationIndex$.value,
b.props.presentationIndex$.value
);
} else if (a.props.presentationIndex && b.props.presentationIndex) {
return stringCompare(
a.props.presentationIndex,
b.props.presentationIndex
);
} else if (a.props.presentationIndex) {
return -1;
} else if (b.props.presentationIndex) {
return 1;
} else {
return stringCompare(a.props.index, b.props.index);
}
}
private _addChildrenToLegacyFrame(frame: FrameBlockModel) {
if (frame.props.childElementIds !== undefined) return;
const elements = this.getElementsInFrameBound(frame);
const childElements = elements.filter(
element => this.getParentFrame(element) === null && element !== frame
);
frame.addChildren(childElements);
}
private _addFrameBlock(bound: Bound) {
const surfaceModel = this.gfx.surface as SurfaceBlockModel;
const props = this.gfx.std
.get(EditPropsStore)
.applyLastProps('affine:frame', {
title: new Text(new Y.Text(`Frame ${this.frames.length + 1}`)),
xywh: bound.serialize(),
index: this.gfx.layer.generateIndex(true),
presentationIndex: this.generatePresentationIndex(),
});
const id = this.gfx.doc.addBlock('affine:frame', props, surfaceModel);
const frameModel = this.gfx.getElementById(id);
if (!frameModel || !isFrameBlock(frameModel)) {
throw new BlockSuiteError(
ErrorCode.GfxBlockElementError,
'Frame model is not found'
);
}
return frameModel;
}
private _watchElementAdded() {
if (!this.gfx.surface) {
return;
}
const { surface: surfaceModel, doc } = this.gfx;
this._disposable.add(
surfaceModel.elementAdded.subscribe(({ id, local }) => {
const element = surfaceModel.getElementById(id);
if (element && local) {
const frame = this.getFrameFromPoint(element.elementBound.center);
// if the container created with a frame, skip it.
if (
isGfxGroupCompatibleModel(element) &&
frame &&
element.hasChild(frame)
) {
return;
}
// new element may intended to be added to other group
// so we need to wait for the next microtask to check if the element can be added to the frame
queueMicrotask(() => {
if (!element.group && frame) {
this.addElementsToFrame(frame, [element]);
}
});
}
})
);
this._disposable.add(
doc.slots.blockUpdated.subscribe(payload => {
if (
payload.type === 'add' &&
payload.model instanceof GfxBlockElementModel &&
renderableInEdgeless(doc, surfaceModel, payload.model)
) {
const frame = this.getFrameFromPoint(
payload.model.elementBound.center,
isFrameBlock(payload.model) ? [payload.model] : []
);
if (!frame) return;
if (
isFrameBlock(payload.model) &&
payload.model.containsBound(frame.elementBound)
) {
return;
}
this.addElementsToFrame(frame, [payload.model]);
}
})
);
}
/**
* Reset parent of elements to the frame
*/
addElementsToFrame(frame: FrameBlockModel, elements: GfxModel[]) {
if (frame.isLocked()) return;
if (frame.props.childElementIds === undefined) {
this._addChildrenToLegacyFrame(frame);
}
elements = elements.filter(
el => el !== frame && !frame.childElements.includes(el)
);
if (elements.length === 0) return;
frame.addChildren(elements);
}
createFrameOnBound(bound: Bound) {
const frameModel = this._addFrameBlock(bound);
this.addElementsToFrame(
frameModel,
getTopElements(this.getElementsInFrameBound(frameModel))
);
this.gfx.doc.captureSync();
this.gfx.selection.set({
elements: [frameModel.id],
editing: false,
});
return frameModel;
}
createFrameOnElements(elements: GfxModel[]) {
// make sure all elements are in the same level
for (const element of elements) {
if (element.group !== elements[0].group) return;
}
const parentFrameBound = this.getParentFrame(elements[0])?.elementBound;
let bound = this.gfx.selection.selectedBound;
if (parentFrameBound?.contains(bound)) {
bound.x -= Math.min(0.5 * (bound.x - parentFrameBound.x), FRAME_PADDING);
bound.y -= Math.min(0.5 * (bound.y - parentFrameBound.y), FRAME_PADDING);
bound.w += Math.min(
0.5 * (parentFrameBound.x + parentFrameBound.w - bound.x - bound.w),
FRAME_PADDING
);
bound.h += Math.min(
0.5 * (parentFrameBound.y + parentFrameBound.h - bound.y - bound.h),
FRAME_PADDING
);
} else {
bound = bound.expand(FRAME_PADDING);
}
const frameModel = this._addFrameBlock(bound);
this.addElementsToFrame(frameModel, getTopElements(elements));
this.gfx.doc.captureSync();
this.gfx.selection.set({
elements: [frameModel.id],
editing: false,
});
return frameModel;
}
createFrameOnSelected() {
return this.createFrameOnElements(this.gfx.selection.selectedElements);
}
createFrameOnViewportCenter(wh: [number, number]) {
const center = this.gfx.viewport.center;
const bound = new Bound(
center.x - wh[0] / 2,
center.y - wh[1] / 2,
wh[0],
wh[1]
);
this.createFrameOnBound(bound);
}
generatePresentationIndex() {
const before =
this.frames[this.frames.length - 1]?.props.presentationIndex ?? null;
return generateKeyBetweenV2(before, null);
}
/**
* Get all elements in the frame, there are three cases:
* 1. The frame doesn't have `childElements`, return all elements in the frame bound but not owned by another frame.
* 2. Return all child elements of the frame if `childElements` exists.
*/
getChildElementsInFrame(frame: FrameBlockModel): GfxModel[] {
if (frame.props.childElementIds === undefined) {
return this.getElementsInFrameBound(frame).filter(
element => this.getParentFrame(element) !== null
);
}
const childElements = frame.childIds
.map(id => this.gfx.getElementById(id))
.filter(element => element !== null);
return childElements as GfxModel[];
}
/**
* Get all elements in the frame bound,
* whatever the element already has another parent frame or not.
*/
getElementsInFrameBound(frame: FrameBlockModel, fullyContained = true) {
const bound = Bound.deserialize(frame.xywh);
const elements: GfxModel[] = this.gfx.grid
.search(bound, { strict: fullyContained })
.filter(element => element !== frame);
return elements;
}
/**
* Get most top frame from the point.
*/
getFrameFromPoint([x, y]: IVec, ignoreFrames: FrameBlockModel[] = []) {
for (let i = this.frames.length - 1; i >= 0; i--) {
const frame = this.frames[i];
if (frame.includesPoint(x, y, {}) && !ignoreFrames.includes(frame)) {
return frame;
}
}
return null;
}
getParentFrame(element: GfxModel) {
const container = element.group;
return container && isFrameBlock(container) ? container : null;
}
/**
* This method will populate `presentationIndex` for all legacy frames,
* and keep the orderer of the legacy frames.
*/
refreshLegacyFrameOrder() {
const frames = this.frames.splice(0, this.frames.length);
let splitIndex = frames.findIndex(frame => frame.props.presentationIndex);
if (splitIndex === 0) return;
if (splitIndex === -1) splitIndex = frames.length;
let afterPreIndex =
frames[splitIndex]?.props.presentationIndex ||
generateKeyBetweenV2(null, null);
for (let index = splitIndex - 1; index >= 0; index--) {
const preIndex = generateKeyBetweenV2(null, afterPreIndex);
frames[index].props.presentationIndex = preIndex;
afterPreIndex = preIndex;
}
}
removeAllChildrenFromFrame(frame: FrameBlockModel) {
this.gfx.doc.transact(() => {
frame.props.childElementIds = {};
});
}
removeFromParentFrame(element: GfxModel) {
const parentFrame = this.getParentFrame(element);
// oxlint-disable-next-line unicorn/prefer-dom-node-remove
parentFrame?.removeChild(element);
}
override unmounted(): void {
this._disposable.dispose();
}
}
function areSetsEqual<T>(setA: Set<T>, setB: Set<T>) {
if (setA.size !== setB.size) return false;
for (const a of setA) if (!setB.has(a)) return false;
return true;
}
export function isFrameBlock(element: unknown): element is FrameBlockModel {
return !!element && (element as BlockModel).flavour === 'affine:frame';
}
@@ -0,0 +1,14 @@
import { FrameBlockSchema } from '@blocksuite/affine-model';
import { BlockViewExtension } from '@blocksuite/std';
import type { ExtensionType } from '@blocksuite/store';
import { literal } from 'lit/static-html.js';
import { EdgelessFrameManager, FrameOverlay } from './frame-manager';
const flavour = FrameBlockSchema.model.flavour;
export const FrameBlockSpec: ExtensionType[] = [
BlockViewExtension(flavour, literal`affine-frame`),
FrameOverlay,
EdgelessFrameManager,
];
@@ -0,0 +1,106 @@
import { OverlayIdentifier } from '@blocksuite/affine-block-surface';
import type { FrameBlockModel } from '@blocksuite/affine-model';
import {
EditPropsStore,
TelemetryProvider,
} from '@blocksuite/affine-shared/services';
import type { IPoint, IVec } from '@blocksuite/global/gfx';
import { Bound, Vec } from '@blocksuite/global/gfx';
import type { PointerEventState } from '@blocksuite/std';
import { BaseTool, getTopElements } from '@blocksuite/std/gfx';
import { Text } from '@blocksuite/store';
import * as Y from 'yjs';
import {
EdgelessFrameManagerIdentifier,
type FrameOverlay,
} from './frame-manager';
export class FrameTool extends BaseTool {
static override toolName = 'frame';
private _frame: FrameBlockModel | null = null;
private _startPoint: IVec | null = null;
get frameManager() {
return this.std.get(EdgelessFrameManagerIdentifier);
}
get frameOverlay() {
return this.std.get(OverlayIdentifier('frame')) as FrameOverlay;
}
private _toModelCoord(p: IPoint): IVec {
return this.gfx.viewport.toModelCoord(p.x, p.y);
}
override dragEnd(): void {
if (this._frame) {
const frame = this._frame;
frame.pop('xywh');
// @ts-expect-error TODO: refactor gfx tool
this.gfx.tool.setTool('default');
this.gfx.selection.set({
elements: [frame.id],
editing: false,
});
this.frameManager.addElementsToFrame(
frame,
getTopElements(this.frameManager.getElementsInFrameBound(frame))
);
}
this._frame = null;
this._startPoint = null;
this.frameOverlay.clear();
}
override dragMove(e: PointerEventState): void {
if (!this._startPoint) return;
const currentPoint = this._toModelCoord(e.point);
if (Vec.dist(this._startPoint, currentPoint) < 8 && !this._frame) return;
if (!this._frame) {
const frames = this.gfx.layer.blocks.filter(
block => block.flavour === 'affine:frame'
) as FrameBlockModel[];
const props = this.std
.get(EditPropsStore)
.applyLastProps('affine:frame', {
title: new Text(new Y.Text(`Frame ${frames.length + 1}`)),
xywh: Bound.fromPoints([this._startPoint, currentPoint]).serialize(),
index: this.gfx.layer.generateIndex(true),
presentationIndex: this.frameManager.generatePresentationIndex(),
});
const id = this.doc.addBlock('affine:frame', props, this.gfx.surface);
this.std.getOptional(TelemetryProvider)?.track('CanvasElementAdded', {
control: 'canvas:draw',
page: 'whiteboard editor',
module: 'toolbar',
segment: 'toolbar',
type: 'frame',
});
this._frame = this.gfx.getElementById(id) as FrameBlockModel;
this._frame.stash('xywh');
return;
}
this.gfx.doc.updateBlock(this._frame, {
xywh: Bound.fromPoints([this._startPoint, currentPoint]).serialize(),
});
this.frameOverlay.highlight(this._frame, true);
}
override dragStart(e: PointerEventState): void {
this.doc.captureSync();
const { point } = e;
this._startPoint = this._toModelCoord(point);
}
}
@@ -0,0 +1,195 @@
import { EdgelessCRUDIdentifier } from '@blocksuite/affine-block-surface';
import {
packColor,
type PickColorEvent,
} from '@blocksuite/affine-components/color-picker';
import { toast } from '@blocksuite/affine-components/toast';
import {
DEFAULT_NOTE_HEIGHT,
DefaultTheme,
FrameBlockModel,
FrameBlockSchema,
NoteBlockModel,
NoteBlockSchema,
NoteDisplayMode,
resolveColor,
SurfaceRefBlockSchema,
} from '@blocksuite/affine-model';
import {
type ToolbarContext,
type ToolbarModuleConfig,
ToolbarModuleExtension,
} from '@blocksuite/affine-shared/services';
import {
getMostCommonResolvedValue,
matchModels,
} from '@blocksuite/affine-shared/utils';
import { mountFrameTitleEditor } from '@blocksuite/affine-widget-frame-title';
import { Bound } from '@blocksuite/global/gfx';
import { EditIcon, PageIcon, UngroupIcon } from '@blocksuite/icons/lit';
import { type BlockComponent, BlockFlavourIdentifier } from '@blocksuite/std';
import { GfxControllerIdentifier } from '@blocksuite/std/gfx';
import type { ExtensionType } from '@blocksuite/store';
import { html } from 'lit';
import { EdgelessFrameManagerIdentifier } from './frame-manager';
function getRootBlock(ctx: ToolbarContext): BlockComponent | null {
const rootModel = ctx.store.root;
if (!rootModel) return null;
return ctx.view.getBlock(rootModel.id);
}
const builtinSurfaceToolbarConfig = {
actions: [
{
id: 'a.insert-into-page',
label: 'Insert into Page',
showLabel: true,
tooltip: 'Insert into Page',
icon: PageIcon(),
when: ctx => ctx.getSurfaceModelsByType(FrameBlockModel).length === 1,
run(ctx) {
const model = ctx.getCurrentModelByType(FrameBlockModel);
if (!model) return;
const rootModel = ctx.store.root;
if (!rootModel) return;
const { id: frameId, xywh } = model;
let lastNoteId = rootModel.children
.filter(
note =>
matchModels(note, [NoteBlockModel]) &&
note.props.displayMode !== NoteDisplayMode.EdgelessOnly
)
.pop()?.id;
if (!lastNoteId) {
const bounds = Bound.deserialize(xywh);
bounds.y += bounds.h;
bounds.h = DEFAULT_NOTE_HEIGHT;
lastNoteId = ctx.store.addBlock(
NoteBlockSchema.model.flavour,
{ xywh: bounds.serialize() },
rootModel.id
);
}
ctx.store.addBlock(
SurfaceRefBlockSchema.model.flavour,
{ reference: frameId, refFlavour: NoteBlockSchema.model.flavour },
lastNoteId
);
toast(ctx.host, 'Frame has been inserted into doc');
},
},
{
id: 'b.rename',
tooltip: 'Rename',
icon: EditIcon(),
when: ctx => ctx.getSurfaceModelsByType(FrameBlockModel).length === 1,
run(ctx) {
const model = ctx.getCurrentModelByType(FrameBlockModel);
if (!model) return;
const rootBlock = getRootBlock(ctx);
if (!rootBlock) return;
mountFrameTitleEditor(model, rootBlock);
},
},
{
id: 'b.ungroup',
tooltip: 'Ungroup',
icon: UngroupIcon(),
run(ctx) {
const models = ctx.getSurfaceModelsByType(FrameBlockModel);
if (!models.length) return;
const crud = ctx.std.get(EdgelessCRUDIdentifier);
const gfx = ctx.std.get(GfxControllerIdentifier);
ctx.store.captureSync();
const frameManager = ctx.std.get(EdgelessFrameManagerIdentifier);
for (const model of models) {
frameManager.removeAllChildrenFromFrame(model);
}
for (const model of models) {
crud.removeElement(model.id);
}
gfx.selection.clear();
},
},
{
id: 'c.color-picker',
content(ctx) {
const models = ctx.getSurfaceModelsByType(FrameBlockModel);
if (!models.length) return null;
const enableCustomColor = ctx.features.getFlag('enable_color_picker');
const theme = ctx.theme.edgeless$.value;
const field = 'background';
const firstModel = models[0];
const background =
getMostCommonResolvedValue(
models.map(model => model.props),
field,
background => resolveColor(background, theme)
) ?? DefaultTheme.transparent;
const onPick = (e: PickColorEvent) => {
if (e.type === 'pick') {
const color = e.detail.value;
for (const model of models) {
const props = packColor(field, color);
ctx.std
.get(EdgelessCRUDIdentifier)
.updateElement(model.id, props);
}
return;
}
for (const model of models) {
model[e.type === 'start' ? 'stash' : 'pop'](field);
}
};
return html`
<edgeless-color-picker-button
class="background"
.label="${'Background'}"
.pick=${onPick}
.color=${background}
.theme=${theme}
.originalColor=${firstModel.props.background}
.enableCustomColor=${enableCustomColor}
>
</edgeless-color-picker-button>
`;
},
},
],
when: ctx => ctx.getSurfaceModelsByType(FrameBlockModel).length > 0,
} as const satisfies ToolbarModuleConfig;
const createFrameToolbarConfig = (flavour: string): ExtensionType => {
const name = flavour.split(':').pop();
return ToolbarModuleExtension({
id: BlockFlavourIdentifier(`affine:surface:${name}`),
config: builtinSurfaceToolbarConfig,
});
};
export const frameToolbarExtension = createFrameToolbarConfig(
FrameBlockSchema.model.flavour
);
@@ -0,0 +1,23 @@
import type { FrameTool } from './frame-tool';
import type { PresentTool, PresentToolOption } from './preset-tool';
export * from './edgeless-clipboard-config';
export * from './edgeless-toolbar';
export * from './frame-block';
export * from './frame-highlight-manager';
export * from './frame-manager';
export * from './frame-spec';
export * from './frame-tool';
export * from './frame-toolbar';
export * from './preset-tool';
declare module '@blocksuite/std/gfx' {
interface GfxToolsMap {
frameNavigator: PresentTool;
frame: FrameTool;
}
interface GfxToolsOption {
frameNavigator: PresentToolOption;
}
}
@@ -0,0 +1,82 @@
import type { FrameBlockModel } from '@blocksuite/affine-model';
import { createButtonPopper } from '@blocksuite/affine-shared/utils';
import { WithDisposable } from '@blocksuite/global/lit';
import { LayerIcon } from '@blocksuite/icons/lit';
import type { BlockComponent } from '@blocksuite/std';
import { css, html, LitElement } from 'lit';
import { property, query } from 'lit/decorators.js';
import type { EdgelessFrameOrderMenu } from './frame-order-menu.js';
export class EdgelessFrameOrderButton extends WithDisposable(LitElement) {
static override styles = css`
edgeless-frame-order-menu {
display: none;
}
edgeless-frame-order-menu[data-show] {
display: initial;
}
`;
private _edgelessFrameOrderPopper: ReturnType<
typeof createButtonPopper
> | null = null;
override disconnectedCallback() {
super.disconnectedCallback();
this._edgelessFrameOrderPopper?.dispose();
}
override firstUpdated() {
this._edgelessFrameOrderPopper = createButtonPopper({
reference: this._edgelessFrameOrderButton,
popperElement: this._edgelessFrameOrderMenu,
stateUpdated: ({ display }) => this.setPopperShow(display === 'show'),
mainAxis: 22,
});
}
protected override render() {
const { readonly } = this.edgeless.doc;
return html`
<style>
.edgeless-frame-order-button svg {
color: ${readonly ? 'var(--affine-text-disable-color)' : 'inherit'};
}
</style>
<edgeless-tool-icon-button
class="edgeless-frame-order-button"
.iconSize=${'24px'}
.tooltip=${this.popperShow ? '' : 'Frame Order'}
@click=${() => {
if (readonly) return;
this._edgelessFrameOrderPopper?.toggle();
}}
.iconContainerPadding=${0}
>
${LayerIcon()}
</edgeless-tool-icon-button>
<edgeless-frame-order-menu .edgeless=${this.edgeless}>
</edgeless-frame-order-menu>
`;
}
@query('.edgeless-frame-order-button')
private accessor _edgelessFrameOrderButton!: HTMLElement;
@query('edgeless-frame-order-menu')
private accessor _edgelessFrameOrderMenu!: EdgelessFrameOrderMenu;
@property({ attribute: false })
accessor edgeless!: BlockComponent;
@property({ attribute: false })
accessor frames!: FrameBlockModel[];
@property({ attribute: false })
accessor popperShow = false;
@property({ attribute: false })
accessor setPopperShow: (show: boolean) => void = () => {};
}
@@ -0,0 +1,265 @@
import { EdgelessCRUDIdentifier } from '@blocksuite/affine-block-surface';
import { DisposableGroup } from '@blocksuite/global/disposable';
import { SignalWatcher, WithDisposable } from '@blocksuite/global/lit';
import type { BlockComponent } from '@blocksuite/std';
import { generateKeyBetweenV2 } from '@blocksuite/std/gfx';
import { css, html, LitElement, nothing } from 'lit';
import { property, query, state } from 'lit/decorators.js';
import { repeat } from 'lit/directives/repeat.js';
import { EdgelessFrameManagerIdentifier } from '../frame-manager';
export class EdgelessFrameOrderMenu extends SignalWatcher(
WithDisposable(LitElement)
) {
static override styles = css`
:host {
position: relative;
}
.edgeless-frame-order-items-container {
max-height: 281px;
border-radius: 8px;
padding: 8px;
background: var(--affine-background-overlay-panel-color);
box-shadow: var(--affine-menu-shadow);
overflow: auto;
display: flex;
flex-direction: column;
gap: 4px;
}
.edgeless-frame-order-items-container.embed {
padding: 0;
background: unset;
box-shadow: unset;
border-radius: 0;
}
.item {
box-sizing: border-box;
width: 256px;
border-radius: 4px;
padding: 4px;
display: flex;
gap: 4px;
align-items: center;
cursor: grab;
}
.draggable:hover {
background-color: var(--affine-hover-color);
}
.item:hover .drag-indicator {
opacity: 1;
}
.drag-indicator {
cursor: pointer;
width: 4px;
height: 12px;
border-radius: 1px;
opacity: 0.2;
background: var(--affine-placeholder-color);
margin-right: 2px;
}
.title {
font-size: 14px;
font-weight: 400;
height: 22px;
line-height: 22px;
color: var(--affine-text-primary-color);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.clone {
visibility: hidden;
position: absolute;
z-index: 1;
left: 8px;
height: 30px;
border: 1px solid var(--affine-border-color);
box-shadow: var(--affine-menu-shadow);
background-color: var(--affine-white);
pointer-events: none;
}
.indicator-line {
visibility: hidden;
position: absolute;
z-index: 1;
left: 8px;
background-color: var(--affine-primary-color);
height: 1px;
width: 90%;
}
`;
get crud() {
return this.edgeless.std.get(EdgelessCRUDIdentifier);
}
private get _frameMgr() {
return this.edgeless.std.get(EdgelessFrameManagerIdentifier);
}
private get _frames() {
return this._frameMgr.frames;
}
private _bindEvent() {
const { _disposables } = this;
_disposables.addFromEvent(this._container, 'wheel', e => {
e.stopPropagation();
});
_disposables.addFromEvent(this._container, 'pointerdown', e => {
const ele = e.target as HTMLElement;
const draggable = ele.closest('.draggable');
if (!draggable) return;
const clone = this._clone;
const indicatorLine = this._indicatorLine;
clone.style.visibility = 'visible';
const rect = draggable.getBoundingClientRect();
const index = Number(draggable.getAttribute('index'));
this._curIndex = index;
let newIndex = -1;
const containerRect = this._container.getBoundingClientRect();
const start = containerRect.top + 8;
const end = containerRect.bottom;
const shiftX = e.clientX - rect.left;
const shiftY = e.clientY - rect.top;
function moveAt(x: number, y: number) {
clone.style.left = x - containerRect.left - shiftX + 'px';
clone.style.top = y - containerRect.top - shiftY + 'px';
}
function isInsideContainer(e: PointerEvent) {
return e.clientY >= start && e.clientY <= end;
}
moveAt(e.clientX, e.clientY);
this._disposables.addFromEvent(document, 'pointermove', e => {
indicatorLine.style.visibility = 'visible';
moveAt(e.clientX, e.clientY);
if (isInsideContainer(e)) {
const relativeY = e.pageY + this._container.scrollTop - start;
let top = 0;
if (relativeY < rect.height / 2) {
newIndex = 0;
top = this.embed ? -2 : 4;
} else {
newIndex = Math.ceil(
(relativeY - rect.height / 2) / (rect.height + 10)
);
top =
(this.embed ? -2 : 7.5) +
newIndex * rect.height +
(newIndex - 0.5) * 4;
}
indicatorLine.style.top = top - this._container.scrollTop + 'px';
return;
}
newIndex = -1;
});
this._disposables.addFromEvent(document, 'pointerup', () => {
clone.style.visibility = 'hidden';
indicatorLine.style.visibility = 'hidden';
if (
newIndex >= 0 &&
newIndex <= this._frames.length &&
newIndex !== index &&
newIndex !== index + 1
) {
const frameMgr = this._frameMgr;
// Legacy compatibility
frameMgr.refreshLegacyFrameOrder();
const before =
this._frames[newIndex - 1]?.props.presentationIndex || null;
const after = this._frames[newIndex]?.props.presentationIndex || null;
const frame = this._frames[index];
this.crud.updateElement(frame.id, {
presentationIndex: generateKeyBetweenV2(before, after),
});
this.edgeless.doc.captureSync();
this.requestUpdate();
}
this._disposables.dispose();
this._disposables = new DisposableGroup();
this._bindEvent();
});
});
}
override disconnectedCallback(): void {
super.disconnectedCallback();
this._disposables.dispose();
}
override firstUpdated() {
this._bindEvent();
}
override render() {
const frame = this._frames[this._curIndex];
return html`
<div
class="edgeless-frame-order-items-container ${this.embed
? 'embed'
: ''}"
@click=${(e: MouseEvent) => e.stopPropagation()}
>
${repeat(
this._frames,
frame => frame.id,
(frame, index) => html`
<div class="item draggable" id=${frame.id} index=${index}>
<div class="drag-indicator"></div>
<div class="title">${frame.props.title.toString()}</div>
</div>
`
)}
<div class="indicator-line"></div>
<div class="clone item">
${frame
? html`<div class="drag-indicator"></div>
<div class="index">${this._curIndex + 1}</div>
<div class="title">${frame.props.title.toString()}</div>`
: nothing}
</div>
</div>
`;
}
@query('.clone')
private accessor _clone!: HTMLDivElement;
@query('.edgeless-frame-order-items-container')
private accessor _container!: HTMLDivElement;
@state()
private accessor _curIndex = -1;
@query('.indicator-line')
private accessor _indicatorLine!: HTMLDivElement;
@property({ attribute: false })
accessor edgeless!: BlockComponent;
@property({ attribute: false })
accessor embed = false;
}
@@ -0,0 +1,196 @@
import { EdgelessLegacySlotIdentifier } from '@blocksuite/affine-block-surface';
import { EditPropsStore } from '@blocksuite/affine-shared/services';
import { createButtonPopper } from '@blocksuite/affine-shared/utils';
import { WithDisposable } from '@blocksuite/global/lit';
import { SettingsIcon } from '@blocksuite/icons/lit';
import type { BlockComponent } from '@blocksuite/std';
import { css, html, LitElement, nothing } from 'lit';
import { property, query, state } from 'lit/decorators.js';
export class EdgelessNavigatorSettingButton extends WithDisposable(LitElement) {
static override styles = css`
.navigator-setting-menu {
display: none;
padding: 8px;
border-radius: 8px;
font-size: 12px;
font-weight: 500;
background-color: var(--affine-background-overlay-panel-color);
box-shadow: var(--affine-menu-shadow);
color: var(--affine-text-primary-color);
}
.navigator-setting-menu[data-show] {
display: flex;
flex-direction: column;
gap: 4px;
}
.item-container {
padding: 4px 12px;
display: flex;
justify-content: space-between;
align-items: center;
min-width: 264px;
width: 100%;
box-sizing: border-box;
}
.item-container.header {
height: 34px;
}
.text {
padding: 0px 4px;
line-height: 22px;
font-size: var(--affine-font-sm);
color: var(--affine-text-primary-color);
}
.text.title {
font-weight: 500;
line-height: 20px;
font-size: var(--affine-font-xs);
color: var(--affine-text-secondary-color);
}
.divider {
width: 100%;
height: 16px;
display: flex;
align-items: center;
}
.divider::before {
content: '';
width: 100%;
height: 1px;
background: var(--affine-border-color);
}
`;
private _navigatorSettingPopper?: ReturnType<
typeof createButtonPopper
> | null = null;
private readonly _onBlackBackgroundChange = (checked: boolean) => {
this.blackBackground = checked;
const slots = this.edgeless.std.get(EdgelessLegacySlotIdentifier);
slots.navigatorSettingUpdated.next({
blackBackground: this.blackBackground,
});
};
private _tryRestoreSettings() {
const blackBackground = this.edgeless.std
.get(EditPropsStore)
.getStorage('presentBlackBackground');
this.blackBackground = blackBackground ?? true;
}
override connectedCallback() {
super.connectedCallback();
this._tryRestoreSettings();
}
override disconnectedCallback(): void {
this._navigatorSettingPopper?.dispose();
this._navigatorSettingPopper = null;
}
override firstUpdated() {
this._navigatorSettingPopper = createButtonPopper({
reference: this._navigatorSettingButton,
popperElement: this._navigatorSettingMenu,
stateUpdated: ({ display }) => this.setPopperShow(display === 'show'),
mainAxis: 22,
});
}
override render() {
return html`
<edgeless-tool-icon-button
class="navigator-setting-button"
.tooltip=${this.popperShow ? '' : 'Settings'}
.iconSize=${'24px'}
@click=${() => {
this._navigatorSettingPopper?.toggle();
}}
.iconContainerPadding=${0}
>
${SettingsIcon()}
</edgeless-tool-icon-button>
<div
class="navigator-setting-menu"
@click=${(e: MouseEvent) => {
e.stopPropagation();
}}
>
<div class="item-container header">
<div class="text title">Playback Settings</div>
</div>
<div class="item-container">
<div class="text">Black background</div>
<toggle-switch
.subscribe=${this.blackBackground}
.onChange=${this._onBlackBackgroundChange}
>
</toggle-switch>
</div>
<div class="item-container">
<div class="text">Hide toolbar</div>
<toggle-switch
.subscribe=${this.hideToolbar}
.onChange=${(checked: boolean) => {
this.onHideToolbarChange && this.onHideToolbarChange(checked);
}}
>
</toggle-switch>
</div>
${this.includeFrameOrder
? html` <div class="divider"></div>
<div class="item-container header">
<div class="text title">Frame Order</div>
</div>
<edgeless-frame-order-menu
.edgeless=${this.edgeless}
.embed=${true}
></edgeless-frame-order-menu>`
: nothing}
</div>
`;
}
@query('.navigator-setting-button')
private accessor _navigatorSettingButton!: HTMLElement;
@query('.navigator-setting-menu')
private accessor _navigatorSettingMenu!: HTMLElement;
@state()
accessor blackBackground = true;
@property({ attribute: false })
accessor edgeless!: BlockComponent;
@property({ attribute: false })
accessor hideToolbar = false;
@property({ attribute: false })
accessor includeFrameOrder = false;
@property({ attribute: false })
accessor onHideToolbarChange: undefined | ((hideToolbar: boolean) => void) =
undefined;
@property({ attribute: false })
accessor popperShow = false;
@property({ attribute: false })
accessor setPopperShow: (show: boolean) => void = () => {};
}
@@ -0,0 +1,41 @@
import {
EdgelessToolbarToolMixin,
QuickToolMixin,
} from '@blocksuite/affine-widget-edgeless-toolbar';
import { PresentationIcon } from '@blocksuite/icons/lit';
import type { GfxToolsFullOptionValue } from '@blocksuite/std/gfx';
import { css, html, LitElement } from 'lit';
export class EdgelessPresentButton extends QuickToolMixin(
EdgelessToolbarToolMixin(LitElement)
) {
static override styles = css`
:host {
display: flex;
}
.edgeless-note-button {
display: flex;
position: relative;
}
`;
override type: GfxToolsFullOptionValue['type'] = 'frameNavigator';
override render() {
return html`<edgeless-tool-icon-button
class="edgeless-frame-navigator-button"
.tooltip=${'Present'}
.tooltipOffset=${17}
.iconContainerPadding=${6}
.iconSize=${'24px'}
@click=${() => {
this.setEdgelessTool({
type: 'frameNavigator',
});
}}
>
${PresentationIcon()}
</edgeless-tool-icon-button>
</div>`;
}
}
@@ -0,0 +1,11 @@
import { BaseTool } from '@blocksuite/std/gfx';
import type { NavigatorMode } from './frame-manager';
export type PresentToolOption = {
mode?: NavigatorMode;
};
export class PresentTool extends BaseTool<PresentToolOption> {
static override toolName: string = 'frameNavigator';
}