mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-08-19 02:51:47 +08:00
refactor(editor): extract root block (#10356)
Closes: [BS-2207](https://linear.app/affine-design/issue/BS-2207/move-root-block-to-affineblock-root)
This commit is contained in:
+664
@@ -0,0 +1,664 @@
|
||||
import { insertEdgelessTextCommand } from '@blocksuite/affine-block-edgeless-text';
|
||||
import {
|
||||
CanvasElementType,
|
||||
EdgelessCRUDIdentifier,
|
||||
} from '@blocksuite/affine-block-surface';
|
||||
import { FontFamilyIcon } from '@blocksuite/affine-components/icons';
|
||||
import type {
|
||||
Connection,
|
||||
ConnectorElementModel,
|
||||
ShapeElementModel,
|
||||
} from '@blocksuite/affine-model';
|
||||
import {
|
||||
DEFAULT_NOTE_WIDTH,
|
||||
DefaultTheme,
|
||||
FontFamily,
|
||||
FontStyle,
|
||||
FontWeight,
|
||||
getShapeName,
|
||||
GroupElementModel,
|
||||
NoteBlockModel,
|
||||
ShapeStyle,
|
||||
TextElementModel,
|
||||
} from '@blocksuite/affine-model';
|
||||
import {
|
||||
EditPropsStore,
|
||||
FeatureFlagService,
|
||||
ThemeProvider,
|
||||
} from '@blocksuite/affine-shared/services';
|
||||
import { captureEventTarget } from '@blocksuite/affine-shared/utils';
|
||||
import { type BlockStdScope, stdContext } from '@blocksuite/block-std';
|
||||
import { GfxControllerIdentifier } from '@blocksuite/block-std/gfx';
|
||||
import type { XYWH } from '@blocksuite/global/utils';
|
||||
import {
|
||||
assertInstanceOf,
|
||||
Bound,
|
||||
clamp,
|
||||
normalizeDegAngle,
|
||||
serializeXYWH,
|
||||
toDegree,
|
||||
Vec,
|
||||
WithDisposable,
|
||||
} from '@blocksuite/global/utils';
|
||||
import { FrameIcon, PageIcon } from '@blocksuite/icons/lit';
|
||||
import { consume } from '@lit/context';
|
||||
import { baseTheme } from '@toeverything/theme';
|
||||
import { css, html, LitElement, nothing, unsafeCSS } from 'lit';
|
||||
import { property } from 'lit/decorators.js';
|
||||
import { repeat } from 'lit/directives/repeat.js';
|
||||
import { styleMap } from 'lit/directives/style-map.js';
|
||||
import * as Y from 'yjs';
|
||||
|
||||
import type { EdgelessRootBlockComponent } from '../../edgeless-root-block.js';
|
||||
import {
|
||||
SHAPE_OVERLAY_HEIGHT,
|
||||
SHAPE_OVERLAY_WIDTH,
|
||||
} from '../../utils/consts.js';
|
||||
import {
|
||||
mountShapeTextEditor,
|
||||
mountTextElementEditor,
|
||||
} from '../../utils/text.js';
|
||||
import { ShapeComponentConfig } from '../toolbar/shape/shape-menu-config.js';
|
||||
import {
|
||||
type AUTO_COMPLETE_TARGET_TYPE,
|
||||
AutoCompleteFrameOverlay,
|
||||
AutoCompleteNoteOverlay,
|
||||
AutoCompleteShapeOverlay,
|
||||
AutoCompleteTextOverlay,
|
||||
capitalizeFirstLetter,
|
||||
createShapeElement,
|
||||
DEFAULT_NOTE_OVERLAY_HEIGHT,
|
||||
DEFAULT_TEXT_HEIGHT,
|
||||
DEFAULT_TEXT_WIDTH,
|
||||
Direction,
|
||||
isShape,
|
||||
PANEL_HEIGHT,
|
||||
PANEL_WIDTH,
|
||||
type TARGET_SHAPE_TYPE,
|
||||
} from './utils.js';
|
||||
|
||||
export class EdgelessAutoCompletePanel extends WithDisposable(LitElement) {
|
||||
static override styles = css`
|
||||
.auto-complete-panel-container {
|
||||
position: absolute;
|
||||
display: flex;
|
||||
width: 136px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 8px 0;
|
||||
gap: 8px;
|
||||
border-radius: 8px;
|
||||
background: var(--affine-background-overlay-panel-color);
|
||||
box-shadow: var(--affine-shadow-2);
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.row-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 120px;
|
||||
height: 28px;
|
||||
padding: 4px 0;
|
||||
text-align: center;
|
||||
border-radius: 8px;
|
||||
font-family: ${unsafeCSS(baseTheme.fontSansFamily)};
|
||||
font-size: 12px;
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
border: 1px solid var(--affine-border-color, #e3e2e4);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
`;
|
||||
|
||||
private _overlay:
|
||||
| AutoCompleteShapeOverlay
|
||||
| AutoCompleteNoteOverlay
|
||||
| AutoCompleteFrameOverlay
|
||||
| AutoCompleteTextOverlay
|
||||
| null = null;
|
||||
|
||||
get gfx() {
|
||||
return this.std.get(GfxControllerIdentifier);
|
||||
}
|
||||
|
||||
constructor(
|
||||
position: [number, number],
|
||||
edgeless: EdgelessRootBlockComponent,
|
||||
currentSource: ShapeElementModel | NoteBlockModel,
|
||||
connector: ConnectorElementModel
|
||||
) {
|
||||
super();
|
||||
this.position = position;
|
||||
this.edgeless = edgeless;
|
||||
this.currentSource = currentSource;
|
||||
this.connector = connector;
|
||||
}
|
||||
|
||||
get crud() {
|
||||
return this.std.get(EdgelessCRUDIdentifier);
|
||||
}
|
||||
|
||||
private _addFrame() {
|
||||
const bound = this._generateTarget(this.connector)?.nextBound;
|
||||
if (!bound) return;
|
||||
|
||||
const { h } = bound;
|
||||
const w = h / 0.75;
|
||||
const target = this._getTargetXYWH(w, h);
|
||||
if (!target) return;
|
||||
|
||||
const { xywh, position } = target;
|
||||
|
||||
const edgeless = this.edgeless;
|
||||
const { service, surfaceBlockModel } = edgeless;
|
||||
const frameMgr = service.frame;
|
||||
const frameIndex = service.frames.length + 1;
|
||||
const props = this.std.get(EditPropsStore).applyLastProps('affine:frame', {
|
||||
title: new Y.Text(`Frame ${frameIndex}`),
|
||||
xywh: serializeXYWH(...xywh),
|
||||
presentationIndex: frameMgr.generatePresentationIndex(),
|
||||
});
|
||||
const id = this.crud.addBlock('affine:frame', props, surfaceBlockModel);
|
||||
edgeless.doc.captureSync();
|
||||
const frame = this.crud.getElementById(id);
|
||||
if (!frame) return;
|
||||
|
||||
this.connector.target = {
|
||||
id,
|
||||
position,
|
||||
};
|
||||
|
||||
edgeless.service.selection.set({
|
||||
elements: [frame.id],
|
||||
editing: false,
|
||||
});
|
||||
}
|
||||
|
||||
private _addNote() {
|
||||
const { doc } = this.edgeless;
|
||||
const target = this._getTargetXYWH(
|
||||
DEFAULT_NOTE_WIDTH,
|
||||
DEFAULT_NOTE_OVERLAY_HEIGHT
|
||||
);
|
||||
if (!target) return;
|
||||
|
||||
const { xywh, position } = target;
|
||||
const id = this.crud.addBlock(
|
||||
'affine:note',
|
||||
{
|
||||
xywh: serializeXYWH(...xywh),
|
||||
},
|
||||
doc.root?.id
|
||||
);
|
||||
const note = doc.getBlock(id)?.model;
|
||||
assertInstanceOf(note, NoteBlockModel);
|
||||
doc.addBlock('affine:paragraph', { type: 'text' }, id);
|
||||
const group = this.currentSource.group;
|
||||
|
||||
if (group instanceof GroupElementModel) {
|
||||
group.addChild(note);
|
||||
}
|
||||
this.connector.target = {
|
||||
id,
|
||||
position: position as [number, number],
|
||||
};
|
||||
this.crud.updateElement(this.connector.id, {
|
||||
target: { id, position },
|
||||
});
|
||||
this.edgeless.service.selection.set({
|
||||
elements: [id],
|
||||
editing: false,
|
||||
});
|
||||
}
|
||||
|
||||
private _addShape(targetType: TARGET_SHAPE_TYPE) {
|
||||
const edgeless = this.edgeless;
|
||||
const result = this._generateTarget(this.connector);
|
||||
if (!result) return;
|
||||
|
||||
const currentSource = this.currentSource;
|
||||
const { nextBound, position } = result;
|
||||
const id = createShapeElement(edgeless, currentSource, targetType);
|
||||
if (!id) return;
|
||||
|
||||
this.crud.updateElement(id, { xywh: nextBound.serialize() });
|
||||
this.crud.updateElement(this.connector.id, {
|
||||
target: { id, position },
|
||||
});
|
||||
|
||||
mountShapeTextEditor(
|
||||
this.crud.getElementById(id) as ShapeElementModel,
|
||||
this.edgeless
|
||||
);
|
||||
this.gfx.selection.set({
|
||||
elements: [id],
|
||||
editing: true,
|
||||
});
|
||||
edgeless.doc.captureSync();
|
||||
}
|
||||
|
||||
private _addText() {
|
||||
const target = this._getTargetXYWH(DEFAULT_TEXT_WIDTH, DEFAULT_TEXT_HEIGHT);
|
||||
if (!target) return;
|
||||
const { xywh, position } = target;
|
||||
const bound = Bound.fromXYWH(xywh);
|
||||
|
||||
const textFlag = this.edgeless.doc
|
||||
.get(FeatureFlagService)
|
||||
.getFlag('enable_edgeless_text');
|
||||
if (textFlag) {
|
||||
const [_, { textId }] = this.edgeless.std.command.exec(
|
||||
insertEdgelessTextCommand,
|
||||
{
|
||||
x: bound.x,
|
||||
y: bound.y,
|
||||
}
|
||||
);
|
||||
if (!textId) return;
|
||||
|
||||
const textElement = this.crud.getElementById(textId);
|
||||
if (!textElement) return;
|
||||
|
||||
this.crud.updateElement(this.connector.id, {
|
||||
target: { id: textId, position },
|
||||
});
|
||||
if (this.currentSource.group instanceof GroupElementModel) {
|
||||
this.currentSource.group.addChild(textElement);
|
||||
}
|
||||
|
||||
this.gfx.selection.set({
|
||||
elements: [textId],
|
||||
editing: false,
|
||||
});
|
||||
this.edgeless.doc.captureSync();
|
||||
} else {
|
||||
const textId = this.crud.addElement(CanvasElementType.TEXT, {
|
||||
xywh: bound.serialize(),
|
||||
text: new Y.Text(),
|
||||
textAlign: 'left',
|
||||
fontSize: 24,
|
||||
fontFamily: FontFamily.Inter,
|
||||
color: DefaultTheme.textColor,
|
||||
fontWeight: FontWeight.Regular,
|
||||
fontStyle: FontStyle.Normal,
|
||||
});
|
||||
if (!textId) return;
|
||||
const textElement = this.crud.getElementById(textId);
|
||||
assertInstanceOf(textElement, TextElementModel);
|
||||
|
||||
this.crud.updateElement(this.connector.id, {
|
||||
target: { id: textId, position },
|
||||
});
|
||||
if (this.currentSource.group instanceof GroupElementModel) {
|
||||
this.currentSource.group.addChild(textElement);
|
||||
}
|
||||
|
||||
this.gfx.selection.set({
|
||||
elements: [textId],
|
||||
editing: false,
|
||||
});
|
||||
this.edgeless.doc.captureSync();
|
||||
|
||||
mountTextElementEditor(textElement, this.edgeless);
|
||||
}
|
||||
}
|
||||
|
||||
private _autoComplete(targetType: AUTO_COMPLETE_TARGET_TYPE) {
|
||||
this._removeOverlay();
|
||||
if (!this._connectorExist()) return;
|
||||
|
||||
switch (targetType) {
|
||||
case 'text':
|
||||
this._addText();
|
||||
break;
|
||||
case 'note':
|
||||
this._addNote();
|
||||
break;
|
||||
case 'frame':
|
||||
this._addFrame();
|
||||
break;
|
||||
default:
|
||||
this._addShape(targetType);
|
||||
}
|
||||
|
||||
this.remove();
|
||||
}
|
||||
|
||||
private _connectorExist() {
|
||||
return !!this.crud.getElementById(this.connector.id);
|
||||
}
|
||||
|
||||
private _generateTarget(connector: ConnectorElementModel) {
|
||||
const { currentSource } = this;
|
||||
let w = SHAPE_OVERLAY_WIDTH;
|
||||
let h = SHAPE_OVERLAY_HEIGHT;
|
||||
if (isShape(currentSource)) {
|
||||
const bound = Bound.deserialize(currentSource.xywh);
|
||||
w = bound.w;
|
||||
h = bound.h;
|
||||
}
|
||||
const point = connector.target.position;
|
||||
if (!point) return;
|
||||
|
||||
const len = connector.path.length;
|
||||
const angle = normalizeDegAngle(
|
||||
toDegree(Vec.angle(connector.path[len - 2], connector.path[len - 1]))
|
||||
);
|
||||
let nextBound: Bound;
|
||||
let position: Connection['position'];
|
||||
// direction of the connector target arrow
|
||||
let direction: Direction;
|
||||
|
||||
if (angle >= 45 && angle <= 135) {
|
||||
nextBound = new Bound(point[0] - w / 2, point[1], w, h);
|
||||
position = [0.5, 0];
|
||||
direction = Direction.Bottom;
|
||||
} else if (angle >= 135 && angle <= 225) {
|
||||
nextBound = new Bound(point[0] - w, point[1] - h / 2, w, h);
|
||||
position = [1, 0.5];
|
||||
direction = Direction.Left;
|
||||
} else if (angle >= 225 && angle <= 315) {
|
||||
nextBound = new Bound(point[0] - w / 2, point[1] - h, w, h);
|
||||
position = [0.5, 1];
|
||||
direction = Direction.Top;
|
||||
} else {
|
||||
nextBound = new Bound(point[0], point[1] - h / 2, w, h);
|
||||
position = [0, 0.5];
|
||||
direction = Direction.Right;
|
||||
}
|
||||
|
||||
return { nextBound, position, direction };
|
||||
}
|
||||
|
||||
private _getCurrentSourceInfo(): {
|
||||
style: ShapeStyle;
|
||||
type: AUTO_COMPLETE_TARGET_TYPE;
|
||||
} {
|
||||
const { currentSource } = this;
|
||||
if (isShape(currentSource)) {
|
||||
const { shapeType, shapeStyle, radius } = currentSource;
|
||||
return {
|
||||
style: shapeStyle,
|
||||
type: getShapeName(shapeType, radius),
|
||||
};
|
||||
}
|
||||
return {
|
||||
style: ShapeStyle.General,
|
||||
type: 'note',
|
||||
};
|
||||
}
|
||||
|
||||
private _getPanelPosition() {
|
||||
const { viewport } = this.edgeless.service;
|
||||
const { boundingClientRect: viewportRect, zoom } = viewport;
|
||||
const result = this._getTargetXYWH(PANEL_WIDTH / zoom, PANEL_HEIGHT / zoom);
|
||||
const pos = result ? result.xywh.slice(0, 2) : this.position;
|
||||
const coord = viewport.toViewCoord(pos[0], pos[1]);
|
||||
const { width, height } = viewportRect;
|
||||
|
||||
coord[0] = clamp(coord[0], 20, width - 20 - PANEL_WIDTH);
|
||||
coord[1] = clamp(coord[1], 20, height - 20 - PANEL_HEIGHT);
|
||||
|
||||
return coord;
|
||||
}
|
||||
|
||||
private _getTargetXYWH(width: number, height: number) {
|
||||
const result = this._generateTarget(this.connector);
|
||||
if (!result) return null;
|
||||
|
||||
const { nextBound: bound, direction, position } = result;
|
||||
if (!bound) return null;
|
||||
|
||||
const { w, h } = bound;
|
||||
let x = bound.x;
|
||||
let y = bound.y;
|
||||
|
||||
switch (direction) {
|
||||
case Direction.Right:
|
||||
y += h / 2 - height / 2;
|
||||
break;
|
||||
case Direction.Bottom:
|
||||
x -= width / 2 - w / 2;
|
||||
break;
|
||||
case Direction.Left:
|
||||
y += h / 2 - height / 2;
|
||||
x -= width - w;
|
||||
break;
|
||||
case Direction.Top:
|
||||
x -= width / 2 - w / 2;
|
||||
y += h - height;
|
||||
break;
|
||||
}
|
||||
|
||||
const xywh = [x, y, width, height] as XYWH;
|
||||
|
||||
return { xywh, position };
|
||||
}
|
||||
|
||||
private _removeOverlay() {
|
||||
if (this._overlay)
|
||||
this.edgeless.surface.renderer.removeOverlay(this._overlay);
|
||||
}
|
||||
|
||||
private _showFrameOverlay() {
|
||||
const bound = this._generateTarget(this.connector)?.nextBound;
|
||||
if (!bound) return;
|
||||
|
||||
const { h } = bound;
|
||||
const w = h / 0.75;
|
||||
const xywh = this._getTargetXYWH(w, h)?.xywh;
|
||||
if (!xywh) return;
|
||||
|
||||
const strokeColor = this.std
|
||||
.get(ThemeProvider)
|
||||
.getCssVariableColor('--affine-black-30');
|
||||
this._overlay = new AutoCompleteFrameOverlay(this.gfx, xywh, strokeColor);
|
||||
this.edgeless.surface.renderer.addOverlay(this._overlay);
|
||||
}
|
||||
|
||||
private _showNoteOverlay() {
|
||||
const xywh = this._getTargetXYWH(
|
||||
DEFAULT_NOTE_WIDTH,
|
||||
DEFAULT_NOTE_OVERLAY_HEIGHT
|
||||
)?.xywh;
|
||||
if (!xywh) return;
|
||||
|
||||
const background = this.edgeless.std
|
||||
.get(ThemeProvider)
|
||||
.getColorValue(
|
||||
this.edgeless.std.get(EditPropsStore).lastProps$.value['affine:note']
|
||||
.background,
|
||||
DefaultTheme.noteBackgrounColor,
|
||||
true
|
||||
);
|
||||
this._overlay = new AutoCompleteNoteOverlay(this.gfx, xywh, background);
|
||||
this.edgeless.surface.renderer.addOverlay(this._overlay);
|
||||
}
|
||||
|
||||
private _showOverlay(targetType: AUTO_COMPLETE_TARGET_TYPE) {
|
||||
this._removeOverlay();
|
||||
if (!this._connectorExist()) return;
|
||||
|
||||
switch (targetType) {
|
||||
case 'text':
|
||||
this._showTextOverlay();
|
||||
break;
|
||||
case 'note':
|
||||
this._showNoteOverlay();
|
||||
break;
|
||||
case 'frame':
|
||||
this._showFrameOverlay();
|
||||
break;
|
||||
default:
|
||||
this._showShapeOverlay(targetType);
|
||||
}
|
||||
|
||||
this.edgeless.surface.refresh();
|
||||
}
|
||||
|
||||
private _showShapeOverlay(targetType: TARGET_SHAPE_TYPE) {
|
||||
const bound = this._generateTarget(this.connector)?.nextBound;
|
||||
if (!bound) return;
|
||||
|
||||
const { x, y, w, h } = bound;
|
||||
const xywh = [x, y, w, h] as XYWH;
|
||||
const { shapeStyle, strokeColor, fillColor, strokeWidth, roughness } =
|
||||
this.edgeless.std.get(EditPropsStore).lastProps$.value[
|
||||
`shape:${targetType}`
|
||||
];
|
||||
|
||||
const stroke = this.edgeless.std
|
||||
.get(ThemeProvider)
|
||||
.getColorValue(strokeColor, DefaultTheme.shapeStrokeColor, true);
|
||||
const fill = this.edgeless.std
|
||||
.get(ThemeProvider)
|
||||
.getColorValue(fillColor, DefaultTheme.shapeFillColor, true);
|
||||
|
||||
const options = {
|
||||
seed: 666,
|
||||
roughness: roughness,
|
||||
strokeLineDash: [0, 0],
|
||||
stroke,
|
||||
strokeWidth,
|
||||
fill,
|
||||
};
|
||||
|
||||
this._overlay = new AutoCompleteShapeOverlay(
|
||||
this.gfx,
|
||||
xywh,
|
||||
targetType,
|
||||
options,
|
||||
shapeStyle
|
||||
);
|
||||
|
||||
this.edgeless.surface.renderer.addOverlay(this._overlay);
|
||||
}
|
||||
|
||||
private _showTextOverlay() {
|
||||
const xywh = this._getTargetXYWH(
|
||||
DEFAULT_TEXT_WIDTH,
|
||||
DEFAULT_TEXT_HEIGHT
|
||||
)?.xywh;
|
||||
if (!xywh) return;
|
||||
|
||||
this._overlay = new AutoCompleteTextOverlay(this.gfx, xywh);
|
||||
this.edgeless.surface.renderer.addOverlay(this._overlay);
|
||||
}
|
||||
|
||||
override connectedCallback() {
|
||||
super.connectedCallback();
|
||||
this.edgeless.handleEvent('click', ctx => {
|
||||
const { target } = ctx.get('pointerState').raw;
|
||||
const element = captureEventTarget(target);
|
||||
const clickAway = !element?.closest('edgeless-auto-complete-panel');
|
||||
if (clickAway) this.remove();
|
||||
});
|
||||
}
|
||||
|
||||
override disconnectedCallback() {
|
||||
super.disconnectedCallback();
|
||||
this._removeOverlay();
|
||||
}
|
||||
|
||||
override firstUpdated() {
|
||||
this.disposables.add(
|
||||
this.edgeless.service.viewport.viewportUpdated.on(() =>
|
||||
this.requestUpdate()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
override render() {
|
||||
const position = this._getPanelPosition();
|
||||
if (!position) return nothing;
|
||||
|
||||
const style = styleMap({
|
||||
left: `${position[0]}px`,
|
||||
top: `${position[1]}px`,
|
||||
});
|
||||
const { style: currentSourceStyle, type: currentSourceType } =
|
||||
this._getCurrentSourceInfo();
|
||||
|
||||
const shapeButtons = repeat(
|
||||
ShapeComponentConfig,
|
||||
({ name, generalIcon, scribbledIcon, tooltip }) => html`
|
||||
<edgeless-tool-icon-button
|
||||
.tooltip=${tooltip}
|
||||
.iconSize=${'20px'}
|
||||
@pointerenter=${() => this._showOverlay(name)}
|
||||
@pointerleave=${() => this._removeOverlay()}
|
||||
@click=${() => this._autoComplete(name)}
|
||||
>
|
||||
${currentSourceStyle === 'General' ? generalIcon : scribbledIcon}
|
||||
</edgeless-tool-icon-button>
|
||||
`
|
||||
);
|
||||
|
||||
return html`<div class="auto-complete-panel-container" style=${style}>
|
||||
${shapeButtons}
|
||||
|
||||
<edgeless-tool-icon-button
|
||||
.tooltip=${'Text'}
|
||||
.iconSize=${'20px'}
|
||||
@pointerenter=${() => this._showOverlay('text')}
|
||||
@pointerleave=${() => this._removeOverlay()}
|
||||
@click=${() => this._autoComplete('text')}
|
||||
>
|
||||
${FontFamilyIcon}
|
||||
</edgeless-tool-icon-button>
|
||||
<edgeless-tool-icon-button
|
||||
.tooltip=${'Note'}
|
||||
.iconSize=${'20px'}
|
||||
@pointerenter=${() => this._showOverlay('note')}
|
||||
@pointerleave=${() => this._removeOverlay()}
|
||||
@click=${() => this._autoComplete('note')}
|
||||
>
|
||||
${PageIcon()}
|
||||
</edgeless-tool-icon-button>
|
||||
<edgeless-tool-icon-button
|
||||
.tooltip=${'Frame'}
|
||||
.iconSize=${'20px'}
|
||||
@pointerenter=${() => this._showOverlay('frame')}
|
||||
@pointerleave=${() => this._removeOverlay()}
|
||||
@click=${() => this._autoComplete('frame')}
|
||||
>
|
||||
${FrameIcon()}
|
||||
</edgeless-tool-icon-button>
|
||||
|
||||
<edgeless-tool-icon-button
|
||||
.iconContainerPadding=${0}
|
||||
.tooltip=${capitalizeFirstLetter(currentSourceType)}
|
||||
@pointerenter=${() => this._showOverlay(currentSourceType)}
|
||||
@pointerleave=${() => this._removeOverlay()}
|
||||
@click=${() => this._autoComplete(currentSourceType)}
|
||||
>
|
||||
<div class="row-button">Add a same object</div>
|
||||
</edgeless-tool-icon-button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor connector: ConnectorElementModel;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor currentSource: ShapeElementModel | NoteBlockModel;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor edgeless: EdgelessRootBlockComponent;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor position: [number, number];
|
||||
|
||||
@consume({
|
||||
context: stdContext,
|
||||
})
|
||||
accessor std!: BlockStdScope;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'edgeless-auto-complete-panel': EdgelessAutoCompletePanel;
|
||||
}
|
||||
}
|
||||
+757
@@ -0,0 +1,757 @@
|
||||
import {
|
||||
CanvasElementType,
|
||||
type ConnectionOverlay,
|
||||
ConnectorPathGenerator,
|
||||
EdgelessCRUDIdentifier,
|
||||
isNoteBlock,
|
||||
Overlay,
|
||||
OverlayIdentifier,
|
||||
type RoughCanvas,
|
||||
} from '@blocksuite/affine-block-surface';
|
||||
import type {
|
||||
Connection,
|
||||
ConnectorElementModel,
|
||||
NoteBlockModel,
|
||||
ShapeType,
|
||||
} from '@blocksuite/affine-model';
|
||||
import {
|
||||
DEFAULT_NOTE_HEIGHT,
|
||||
DefaultTheme,
|
||||
LayoutType,
|
||||
MindmapElementModel,
|
||||
ShapeElementModel,
|
||||
shapeMethods,
|
||||
} from '@blocksuite/affine-model';
|
||||
import { handleNativeRangeAtPoint } from '@blocksuite/affine-shared/utils';
|
||||
import { type BlockStdScope, stdContext } from '@blocksuite/block-std';
|
||||
import { GfxControllerIdentifier } from '@blocksuite/block-std/gfx';
|
||||
import type { Bound, IVec } from '@blocksuite/global/utils';
|
||||
import {
|
||||
assertExists,
|
||||
DisposableGroup,
|
||||
Vec,
|
||||
WithDisposable,
|
||||
} from '@blocksuite/global/utils';
|
||||
import {
|
||||
ArrowUpBigIcon,
|
||||
PlusIcon,
|
||||
SiblingNodeIcon,
|
||||
SubNodeIcon,
|
||||
} from '@blocksuite/icons/lit';
|
||||
import { consume } from '@lit/context';
|
||||
import { css, html, LitElement, nothing } from 'lit';
|
||||
import { property, state } from 'lit/decorators.js';
|
||||
import { classMap } from 'lit/directives/class-map.js';
|
||||
import { styleMap } from 'lit/directives/style-map.js';
|
||||
|
||||
import type { EdgelessRootBlockComponent } from '../../edgeless-root-block.js';
|
||||
import { mountShapeTextEditor } from '../../utils/text.js';
|
||||
import type { SelectedRect } from '../rects/edgeless-selected-rect.js';
|
||||
import { EdgelessAutoCompletePanel } from './auto-complete-panel.js';
|
||||
import {
|
||||
createEdgelessElement,
|
||||
Direction,
|
||||
getPosition,
|
||||
isShape,
|
||||
MAIN_GAP,
|
||||
nextBound,
|
||||
} from './utils.js';
|
||||
|
||||
class AutoCompleteOverlay extends Overlay {
|
||||
linePoints: IVec[] = [];
|
||||
|
||||
renderShape: ((ctx: CanvasRenderingContext2D) => void) | null = null;
|
||||
|
||||
stroke = '';
|
||||
|
||||
override render(ctx: CanvasRenderingContext2D, _rc: RoughCanvas) {
|
||||
if (this.linePoints.length && this.renderShape) {
|
||||
ctx.setLineDash([2, 2]);
|
||||
ctx.strokeStyle = this.stroke;
|
||||
ctx.beginPath();
|
||||
this.linePoints.forEach((p, index) => {
|
||||
if (index === 0) ctx.moveTo(p[0], p[1]);
|
||||
else ctx.lineTo(p[0], p[1]);
|
||||
});
|
||||
ctx.stroke();
|
||||
|
||||
this.renderShape(ctx);
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class EdgelessAutoComplete extends WithDisposable(LitElement) {
|
||||
static override styles = css`
|
||||
.edgeless-auto-complete-container {
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
pointer-events: none;
|
||||
}
|
||||
.edgeless-auto-complete-arrow-wrapper {
|
||||
width: 72px;
|
||||
height: 44px;
|
||||
position: absolute;
|
||||
z-index: 1;
|
||||
pointer-events: auto;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.edgeless-auto-complete-arrow-wrapper.hidden {
|
||||
display: none;
|
||||
}
|
||||
.edgeless-auto-complete-arrow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 19px;
|
||||
cursor: pointer;
|
||||
pointer-events: auto;
|
||||
transition:
|
||||
background 0.3s linear,
|
||||
box-shadow 0.2s linear;
|
||||
}
|
||||
.edgeless-auto-complete-arrow-wrapper.mindmap {
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
}
|
||||
|
||||
.edgeless-auto-complete-arrow-wrapper:hover
|
||||
> .edgeless-auto-complete-arrow {
|
||||
border: 1px solid var(--affine-border-color);
|
||||
box-shadow: var(--affine-shadow-1);
|
||||
background: var(--affine-white);
|
||||
}
|
||||
|
||||
.edgeless-auto-complete-arrow-wrapper
|
||||
> .edgeless-auto-complete-arrow:hover {
|
||||
border: 1px solid var(--affine-white-10);
|
||||
box-shadow: var(--affine-shadow-1);
|
||||
background: var(--affine-primary-color);
|
||||
}
|
||||
|
||||
.edgeless-auto-complete-arrow-wrapper.mindmap
|
||||
> .edgeless-auto-complete-arrow {
|
||||
border: 1px solid var(--affine-border-color);
|
||||
box-shadow: var(--affine-shadow-1);
|
||||
background: var(--affine-white);
|
||||
|
||||
transition:
|
||||
background 0.3s linear,
|
||||
color 0.2s linear;
|
||||
}
|
||||
|
||||
.edgeless-auto-complete-arrow-wrapper.mindmap
|
||||
> .edgeless-auto-complete-arrow:hover {
|
||||
border: 1px solid var(--affine-white-10);
|
||||
box-shadow: var(--affine-shadow-1);
|
||||
background: var(--affine-primary-color);
|
||||
}
|
||||
|
||||
.edgeless-auto-complete-arrow svg {
|
||||
fill: #77757d;
|
||||
color: #77757d;
|
||||
}
|
||||
.edgeless-auto-complete-arrow:hover svg {
|
||||
fill: #ffffff;
|
||||
color: #ffffff;
|
||||
}
|
||||
`;
|
||||
|
||||
private _autoCompleteOverlay!: AutoCompleteOverlay;
|
||||
|
||||
private readonly _onPointerDown = (e: PointerEvent, type: Direction) => {
|
||||
const viewportRect = this.gfx.viewport.boundingClientRect;
|
||||
const start = this.gfx.viewport.toModelCoord(
|
||||
e.clientX - viewportRect.left,
|
||||
e.clientY - viewportRect.top
|
||||
);
|
||||
|
||||
if (!this.edgeless.dispatcher) return;
|
||||
|
||||
let connector: ConnectorElementModel | null;
|
||||
|
||||
this._disposables.addFromEvent(document, 'pointermove', e => {
|
||||
const point = this.gfx.viewport.toModelCoord(
|
||||
e.clientX - viewportRect.left,
|
||||
e.clientY - viewportRect.top
|
||||
);
|
||||
if (Vec.dist(start, point) > 8 && !this._isMoving) {
|
||||
if (!this.canShowAutoComplete) return;
|
||||
this._isMoving = true;
|
||||
const { startPosition } = getPosition(type);
|
||||
connector = this._addConnector(
|
||||
{
|
||||
id: this.current.id,
|
||||
position: startPosition,
|
||||
},
|
||||
{
|
||||
position: point,
|
||||
}
|
||||
);
|
||||
}
|
||||
if (this._isMoving) {
|
||||
assertExists(connector);
|
||||
const otherSideId = connector.source.id;
|
||||
|
||||
connector.target = this.connectionOverlay.renderConnector(
|
||||
point,
|
||||
otherSideId ? [otherSideId] : []
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
this._disposables.addFromEvent(document, 'pointerup', e => {
|
||||
if (!this._isMoving) {
|
||||
this._generateElementOnClick(type);
|
||||
} else if (connector && !connector.target.id) {
|
||||
this.edgeless.service.selection.clear();
|
||||
this._createAutoCompletePanel(e, connector);
|
||||
}
|
||||
|
||||
this._isMoving = false;
|
||||
this.connectionOverlay.clear();
|
||||
this._disposables.dispose();
|
||||
this._disposables = new DisposableGroup();
|
||||
});
|
||||
};
|
||||
|
||||
private _pathGenerator!: ConnectorPathGenerator;
|
||||
|
||||
private _timer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
get canShowAutoComplete() {
|
||||
const { current } = this;
|
||||
return isShape(current) || isNoteBlock(current);
|
||||
}
|
||||
|
||||
get connectionOverlay() {
|
||||
return this.std.get(OverlayIdentifier('connection')) as ConnectionOverlay;
|
||||
}
|
||||
|
||||
get crud() {
|
||||
return this.std.get(EdgelessCRUDIdentifier);
|
||||
}
|
||||
|
||||
get gfx() {
|
||||
return this.std.get(GfxControllerIdentifier);
|
||||
}
|
||||
|
||||
private _addConnector(source: Connection, target: Connection) {
|
||||
const id = this.crud.addElement(CanvasElementType.CONNECTOR, {
|
||||
source,
|
||||
target,
|
||||
});
|
||||
if (!id) return null;
|
||||
return this.crud.getElementById(id) as ConnectorElementModel;
|
||||
}
|
||||
|
||||
private _addMindmapNode(target: 'sibling' | 'child') {
|
||||
const mindmap = this.current.group;
|
||||
|
||||
if (!(mindmap instanceof MindmapElementModel)) return;
|
||||
|
||||
const parent =
|
||||
target === 'sibling'
|
||||
? (mindmap.getParentNode(this.current.id) ?? this.current)
|
||||
: this.current;
|
||||
|
||||
const parentNode = mindmap.getNode(parent.id);
|
||||
|
||||
if (!parentNode) return;
|
||||
|
||||
const newNode = mindmap.addNode(
|
||||
parentNode.id,
|
||||
target === 'sibling' ? this.current.id : undefined,
|
||||
undefined,
|
||||
undefined
|
||||
);
|
||||
|
||||
if (parentNode.detail.collapsed) {
|
||||
mindmap.toggleCollapse(parentNode);
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
mountShapeTextEditor(
|
||||
this.crud.getElementById(newNode) as ShapeElementModel,
|
||||
this.edgeless
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private _computeLine(
|
||||
type: Direction,
|
||||
curShape: ShapeElementModel,
|
||||
nextBound: Bound
|
||||
) {
|
||||
const startBound = this.current.elementBound;
|
||||
const { startPosition, endPosition } = getPosition(type);
|
||||
const nextShape = {
|
||||
xywh: nextBound.serialize(),
|
||||
rotate: curShape.rotate,
|
||||
shapeType: curShape.shapeType,
|
||||
};
|
||||
const startPoint = curShape.getRelativePointLocation(startPosition);
|
||||
const endPoint = curShape.getRelativePointLocation.call(
|
||||
nextShape,
|
||||
endPosition
|
||||
);
|
||||
|
||||
return this._pathGenerator.generateOrthogonalConnectorPath({
|
||||
startBound,
|
||||
endBound: nextBound,
|
||||
startPoint,
|
||||
endPoint,
|
||||
});
|
||||
}
|
||||
|
||||
private _computeNextBound(type: Direction) {
|
||||
if (isShape(this.current)) {
|
||||
const connectedShapes = this._getConnectedElements(this.current).filter(
|
||||
e => e instanceof ShapeElementModel
|
||||
) as ShapeElementModel[];
|
||||
return nextBound(type, this.current, connectedShapes);
|
||||
} else {
|
||||
const bound = this.current.elementBound;
|
||||
switch (type) {
|
||||
case Direction.Right: {
|
||||
bound.x += bound.w + MAIN_GAP;
|
||||
break;
|
||||
}
|
||||
case Direction.Bottom: {
|
||||
bound.y += bound.h + MAIN_GAP;
|
||||
break;
|
||||
}
|
||||
case Direction.Left: {
|
||||
bound.x -= bound.w + MAIN_GAP;
|
||||
break;
|
||||
}
|
||||
case Direction.Top: {
|
||||
bound.y -= bound.h + MAIN_GAP;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return bound;
|
||||
}
|
||||
}
|
||||
|
||||
private _createAutoCompletePanel(
|
||||
e: PointerEvent,
|
||||
connector: ConnectorElementModel
|
||||
) {
|
||||
if (!this.canShowAutoComplete) return;
|
||||
|
||||
const position = this.edgeless.service.viewport.toModelCoord(
|
||||
e.clientX,
|
||||
e.clientY
|
||||
);
|
||||
const autoCompletePanel = new EdgelessAutoCompletePanel(
|
||||
position,
|
||||
this.edgeless,
|
||||
this.current,
|
||||
connector
|
||||
);
|
||||
|
||||
this.edgeless.append(autoCompletePanel);
|
||||
}
|
||||
|
||||
private _generateElementOnClick(type: Direction) {
|
||||
const { doc, service } = this.edgeless;
|
||||
const bound = this._computeNextBound(type);
|
||||
const id = createEdgelessElement(this.edgeless, this.current, bound);
|
||||
if (!id) return;
|
||||
if (isShape(this.current)) {
|
||||
const { startPosition, endPosition } = getPosition(type);
|
||||
this._addConnector(
|
||||
{
|
||||
id: this.current.id,
|
||||
position: startPosition,
|
||||
},
|
||||
{
|
||||
id,
|
||||
position: endPosition,
|
||||
}
|
||||
);
|
||||
|
||||
mountShapeTextEditor(
|
||||
this.crud.getElementById(id) as ShapeElementModel,
|
||||
this.edgeless
|
||||
);
|
||||
} else {
|
||||
const model = doc.getBlockById(id);
|
||||
assertExists(model);
|
||||
const [x, y] = service.viewport.toViewCoord(
|
||||
bound.center[0],
|
||||
bound.y + DEFAULT_NOTE_HEIGHT / 2
|
||||
);
|
||||
requestAnimationFrame(() => {
|
||||
handleNativeRangeAtPoint(x, y);
|
||||
});
|
||||
}
|
||||
|
||||
this.edgeless.service.selection.set({
|
||||
elements: [id],
|
||||
editing: true,
|
||||
});
|
||||
this.removeOverlay();
|
||||
}
|
||||
|
||||
private _getConnectedElements(element: ShapeElementModel) {
|
||||
const service = this.edgeless.service;
|
||||
|
||||
return service.getConnectors(element.id).reduce((prev, current) => {
|
||||
if (current.target.id === element.id && current.source.id) {
|
||||
prev.push(
|
||||
this.crud.getElementById(current.source.id) as ShapeElementModel
|
||||
);
|
||||
}
|
||||
if (current.source.id === element.id && current.target.id) {
|
||||
prev.push(
|
||||
this.crud.getElementById(current.target.id) as ShapeElementModel
|
||||
);
|
||||
}
|
||||
|
||||
return prev;
|
||||
}, [] as ShapeElementModel[]);
|
||||
}
|
||||
|
||||
private _getMindmapButtons() {
|
||||
const mindmap = this.current.group as MindmapElementModel;
|
||||
const mindmapDirection =
|
||||
this.current instanceof ShapeElementModel &&
|
||||
mindmap instanceof MindmapElementModel
|
||||
? mindmap.getLayoutDir(this.current.id)
|
||||
: null;
|
||||
const isRoot = mindmap?.tree.id === this.current.id;
|
||||
const mindmapNode = mindmap.getNode(this.current.id);
|
||||
|
||||
let buttons: [
|
||||
Direction,
|
||||
'child' | 'sibling',
|
||||
LayoutType.LEFT | LayoutType.RIGHT,
|
||||
][] = [];
|
||||
|
||||
switch (mindmapDirection) {
|
||||
case LayoutType.LEFT:
|
||||
buttons = [[Direction.Left, 'child', LayoutType.LEFT]];
|
||||
|
||||
if (!isRoot) {
|
||||
buttons.push([Direction.Bottom, 'sibling', mindmapDirection]);
|
||||
}
|
||||
break;
|
||||
case LayoutType.RIGHT:
|
||||
buttons = [[Direction.Right, 'child', LayoutType.RIGHT]];
|
||||
|
||||
if (!isRoot) {
|
||||
buttons.push([Direction.Bottom, 'sibling', mindmapDirection]);
|
||||
}
|
||||
break;
|
||||
case LayoutType.BALANCE:
|
||||
buttons = [
|
||||
[Direction.Right, 'child', LayoutType.RIGHT],
|
||||
[Direction.Left, 'child', LayoutType.LEFT],
|
||||
];
|
||||
break;
|
||||
default:
|
||||
buttons = [];
|
||||
}
|
||||
|
||||
return buttons.length
|
||||
? {
|
||||
mindmapNode,
|
||||
buttons,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
private _initOverlay() {
|
||||
const { surface } = this.edgeless;
|
||||
this._autoCompleteOverlay = new AutoCompleteOverlay(this.gfx);
|
||||
surface.renderer.addOverlay(this._autoCompleteOverlay);
|
||||
}
|
||||
|
||||
private _renderArrow() {
|
||||
const isShape = this.current instanceof ShapeElementModel;
|
||||
const { selectedRect } = this;
|
||||
const { zoom } = this.edgeless.service.viewport;
|
||||
const width = 72;
|
||||
const height = 44;
|
||||
|
||||
// Auto-complete arrows for shape and note are different
|
||||
// Shape: right, bottom, left, top
|
||||
// Note: right, left
|
||||
const arrowDirections = isShape
|
||||
? [Direction.Right, Direction.Bottom, Direction.Left, Direction.Top]
|
||||
: [Direction.Right, Direction.Left];
|
||||
const arrowMargin = isShape ? height / 2 : height * (2 / 3);
|
||||
const Arrows = arrowDirections.map(type => {
|
||||
let transform = '';
|
||||
|
||||
const iconSize = { width: '16px', height: '16px' };
|
||||
const icon = (isShape ? ArrowUpBigIcon : PlusIcon)(iconSize);
|
||||
|
||||
switch (type) {
|
||||
case Direction.Top:
|
||||
transform += `translate(${
|
||||
selectedRect.width / 2
|
||||
}px, ${-arrowMargin}px)`;
|
||||
break;
|
||||
case Direction.Right:
|
||||
transform += `translate(${selectedRect.width + arrowMargin}px, ${
|
||||
selectedRect.height / 2
|
||||
}px)`;
|
||||
|
||||
isShape && (transform += `rotate(90deg)`);
|
||||
break;
|
||||
case Direction.Bottom:
|
||||
transform += `translate(${selectedRect.width / 2}px, ${
|
||||
selectedRect.height + arrowMargin
|
||||
}px)`;
|
||||
isShape && (transform += `rotate(180deg)`);
|
||||
break;
|
||||
case Direction.Left:
|
||||
transform += `translate(${-arrowMargin}px, ${
|
||||
selectedRect.height / 2
|
||||
}px)`;
|
||||
isShape && (transform += `rotate(-90deg)`);
|
||||
break;
|
||||
}
|
||||
transform += `translate(${-width / 2}px, ${-height / 2}px)`;
|
||||
const arrowWrapperClasses = classMap({
|
||||
'edgeless-auto-complete-arrow-wrapper': true,
|
||||
hidden: !isShape && type === Direction.Left && zoom >= 1.5,
|
||||
});
|
||||
|
||||
return html`<div
|
||||
class=${arrowWrapperClasses}
|
||||
style=${styleMap({
|
||||
transform,
|
||||
transformOrigin: 'left top',
|
||||
})}
|
||||
>
|
||||
<div
|
||||
class="edgeless-auto-complete-arrow"
|
||||
@mouseenter=${() => {
|
||||
this._timer = setTimeout(() => {
|
||||
if (this.current instanceof ShapeElementModel) {
|
||||
const bound = this._computeNextBound(type);
|
||||
const path = this._computeLine(type, this.current, bound);
|
||||
this._showNextShape(
|
||||
this.current,
|
||||
bound,
|
||||
path,
|
||||
this.current.shapeType
|
||||
);
|
||||
}
|
||||
}, 300);
|
||||
}}
|
||||
@mouseleave=${() => {
|
||||
this.removeOverlay();
|
||||
}}
|
||||
@pointerdown=${(e: PointerEvent) => {
|
||||
this._onPointerDown(e, type);
|
||||
}}
|
||||
>
|
||||
${icon}
|
||||
</div>
|
||||
</div>`;
|
||||
});
|
||||
|
||||
return Arrows;
|
||||
}
|
||||
|
||||
private _renderMindMapButtons() {
|
||||
const mindmapButtons = this._getMindmapButtons();
|
||||
|
||||
if (!mindmapButtons) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { selectedRect } = this;
|
||||
const { zoom } = this.edgeless.service.viewport;
|
||||
const size = 26;
|
||||
const buttonMargin =
|
||||
(mindmapButtons.mindmapNode?.children.length ?? 0) > 0
|
||||
? size / 2 + 32 * zoom
|
||||
: size / 2 + 6;
|
||||
const verticalMargin = size / 2 + 6;
|
||||
|
||||
return mindmapButtons.buttons.map(type => {
|
||||
let transform = '';
|
||||
|
||||
const [position, target, layout] = type;
|
||||
const isLeftLayout = layout === LayoutType.LEFT;
|
||||
const icon = (target === 'child' ? SubNodeIcon : SiblingNodeIcon)({
|
||||
width: '16px',
|
||||
height: '16px',
|
||||
});
|
||||
|
||||
switch (position) {
|
||||
case Direction.Bottom:
|
||||
transform += `translate(${selectedRect.width / 2}px, ${
|
||||
selectedRect.height + verticalMargin
|
||||
}px)`;
|
||||
isLeftLayout && (transform += `scale(-1)`);
|
||||
break;
|
||||
case Direction.Right:
|
||||
transform += `translate(${selectedRect.width + buttonMargin}px, ${
|
||||
selectedRect.height / 2
|
||||
}px)`;
|
||||
break;
|
||||
case Direction.Left:
|
||||
transform += `translate(${-buttonMargin}px, ${
|
||||
selectedRect.height / 2
|
||||
}px)`;
|
||||
|
||||
transform += `scale(-1)`;
|
||||
break;
|
||||
}
|
||||
|
||||
transform += `translate(${-size / 2}px, ${-size / 2}px)`;
|
||||
|
||||
const arrowWrapperClasses = classMap({
|
||||
'edgeless-auto-complete-arrow-wrapper': true,
|
||||
hidden: position === Direction.Left && zoom >= 1.5,
|
||||
mindmap: true,
|
||||
});
|
||||
|
||||
return html`<div
|
||||
class=${arrowWrapperClasses}
|
||||
style=${styleMap({
|
||||
transform,
|
||||
transformOrigin: 'left top',
|
||||
})}
|
||||
>
|
||||
<div
|
||||
class="edgeless-auto-complete-arrow"
|
||||
@pointerdown=${() => {
|
||||
this._addMindmapNode(target);
|
||||
}}
|
||||
>
|
||||
${icon}
|
||||
</div>
|
||||
</div>`;
|
||||
});
|
||||
}
|
||||
|
||||
private _showNextShape(
|
||||
current: ShapeElementModel,
|
||||
bound: Bound,
|
||||
path: IVec[],
|
||||
targetType: ShapeType
|
||||
) {
|
||||
const { surface } = this.edgeless;
|
||||
|
||||
this._autoCompleteOverlay.stroke = surface.renderer.getColorValue(
|
||||
current.strokeColor,
|
||||
DefaultTheme.shapeStrokeColor,
|
||||
true
|
||||
);
|
||||
this._autoCompleteOverlay.linePoints = path;
|
||||
this._autoCompleteOverlay.renderShape = ctx => {
|
||||
shapeMethods[targetType].draw(ctx, { ...bound, rotate: current.rotate });
|
||||
};
|
||||
surface.refresh();
|
||||
}
|
||||
|
||||
override connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
this._pathGenerator = new ConnectorPathGenerator({
|
||||
getElementById: id => this.crud.getElementById(id),
|
||||
});
|
||||
this._initOverlay();
|
||||
}
|
||||
|
||||
override firstUpdated() {
|
||||
const { _disposables, edgeless } = this;
|
||||
|
||||
_disposables.add(
|
||||
this.gfx.selection.slots.updated.on(() => {
|
||||
this._autoCompleteOverlay.linePoints = [];
|
||||
this._autoCompleteOverlay.renderShape = null;
|
||||
})
|
||||
);
|
||||
|
||||
_disposables.add(() => this.removeOverlay());
|
||||
|
||||
_disposables.add(
|
||||
edgeless.host.event.add('pointerMove', ctx => {
|
||||
const evt = ctx.get('pointerState');
|
||||
const [x, y] = edgeless.gfx.viewport.toModelCoord(evt.x, evt.y);
|
||||
const elm = edgeless.gfx.getElementByPoint(x, y);
|
||||
|
||||
if (!elm) {
|
||||
this._isHover = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this._isHover = elm === this.current ? true : false;
|
||||
})
|
||||
);
|
||||
|
||||
this.edgeless.handleEvent('dragStart', () => {
|
||||
this._isMoving = true;
|
||||
});
|
||||
this.edgeless.handleEvent('dragEnd', () => {
|
||||
this._isMoving = false;
|
||||
});
|
||||
}
|
||||
|
||||
removeOverlay() {
|
||||
this._timer && clearTimeout(this._timer);
|
||||
this.edgeless.surface.renderer.removeOverlay(this._autoCompleteOverlay);
|
||||
}
|
||||
|
||||
override render() {
|
||||
const isShape = this.current instanceof ShapeElementModel;
|
||||
const isMindMap = this.current.group instanceof MindmapElementModel;
|
||||
|
||||
if (this._isMoving || (this._isHover && !isShape)) {
|
||||
this.removeOverlay();
|
||||
return nothing;
|
||||
}
|
||||
const { selectedRect } = this;
|
||||
|
||||
return html`<div
|
||||
class="edgeless-auto-complete-container"
|
||||
style=${styleMap({
|
||||
top: selectedRect.top + 'px',
|
||||
left: selectedRect.left + 'px',
|
||||
width: selectedRect.width + 'px',
|
||||
height: selectedRect.height + 'px',
|
||||
transform: `rotate(${selectedRect.rotate}deg)`,
|
||||
})}
|
||||
>
|
||||
${isMindMap ? this._renderMindMapButtons() : this._renderArrow()}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
@state()
|
||||
private accessor _isHover = true;
|
||||
|
||||
@state()
|
||||
private accessor _isMoving = false;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor current!: ShapeElementModel | NoteBlockModel;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor edgeless!: EdgelessRootBlockComponent;
|
||||
|
||||
@property({ attribute: false })
|
||||
accessor selectedRect!: SelectedRect;
|
||||
|
||||
@consume({
|
||||
context: stdContext,
|
||||
})
|
||||
accessor std!: BlockStdScope;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface HTMLElementTagNameMap {
|
||||
'edgeless-auto-complete': EdgelessAutoComplete;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
import {
|
||||
type Options,
|
||||
Overlay,
|
||||
type RoughCanvas,
|
||||
} from '@blocksuite/affine-block-surface';
|
||||
import {
|
||||
type Connection,
|
||||
getShapeRadius,
|
||||
getShapeType,
|
||||
GroupElementModel,
|
||||
type NoteBlockModel,
|
||||
ShapeElementModel,
|
||||
type ShapeName,
|
||||
type ShapeStyle,
|
||||
} from '@blocksuite/affine-model';
|
||||
import type { GfxController, GfxModel } from '@blocksuite/block-std/gfx';
|
||||
import { BlockSuiteError, ErrorCode } from '@blocksuite/global/exceptions';
|
||||
import type { XYWH } from '@blocksuite/global/utils';
|
||||
import { assertType, Bound, normalizeDegAngle } from '@blocksuite/global/utils';
|
||||
import * as Y from 'yjs';
|
||||
|
||||
import type { EdgelessRootBlockComponent } from '../../edgeless-root-block.js';
|
||||
import { type Shape, ShapeFactory } from '../../utils/tool-overlay.js';
|
||||
|
||||
export enum Direction {
|
||||
Right,
|
||||
Bottom,
|
||||
Left,
|
||||
Top,
|
||||
}
|
||||
|
||||
export const PANEL_WIDTH = 136;
|
||||
export const PANEL_HEIGHT = 108;
|
||||
|
||||
export const MAIN_GAP = 100;
|
||||
export const SECOND_GAP = 20;
|
||||
export const DEFAULT_NOTE_OVERLAY_HEIGHT = 110;
|
||||
export const DEFAULT_TEXT_WIDTH = 116;
|
||||
export const DEFAULT_TEXT_HEIGHT = 24;
|
||||
|
||||
export type TARGET_SHAPE_TYPE = ShapeName;
|
||||
export type AUTO_COMPLETE_TARGET_TYPE =
|
||||
| TARGET_SHAPE_TYPE
|
||||
| 'text'
|
||||
| 'note'
|
||||
| 'frame';
|
||||
|
||||
class AutoCompleteTargetOverlay extends Overlay {
|
||||
xywh: XYWH;
|
||||
|
||||
constructor(gfx: GfxController, xywh: XYWH) {
|
||||
super(gfx);
|
||||
this.xywh = xywh;
|
||||
}
|
||||
|
||||
override render(_ctx: CanvasRenderingContext2D, _rc: RoughCanvas) {}
|
||||
}
|
||||
|
||||
export class AutoCompleteTextOverlay extends AutoCompleteTargetOverlay {
|
||||
constructor(gfx: GfxController, xywh: XYWH) {
|
||||
super(gfx, xywh);
|
||||
}
|
||||
|
||||
override render(ctx: CanvasRenderingContext2D, _rc: RoughCanvas) {
|
||||
const [x, y, w, h] = this.xywh;
|
||||
|
||||
ctx.globalAlpha = 0.4;
|
||||
ctx.strokeStyle = '#1e96eb';
|
||||
ctx.lineWidth = 1;
|
||||
ctx.strokeRect(x, y, w, h);
|
||||
|
||||
// fill text placeholder
|
||||
ctx.font = '15px sans-serif';
|
||||
ctx.fillStyle = '#C0BFC1';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText("Type '/' to insert", x + w / 2, y + h / 2);
|
||||
}
|
||||
}
|
||||
|
||||
export class AutoCompleteNoteOverlay extends AutoCompleteTargetOverlay {
|
||||
private readonly _background: string;
|
||||
|
||||
constructor(gfx: GfxController, xywh: XYWH, background: string) {
|
||||
super(gfx, xywh);
|
||||
this._background = background;
|
||||
}
|
||||
|
||||
override render(ctx: CanvasRenderingContext2D, _rc: RoughCanvas) {
|
||||
const [x, y, w, h] = this.xywh;
|
||||
|
||||
ctx.globalAlpha = 0.4;
|
||||
ctx.fillStyle = this._background;
|
||||
ctx.strokeStyle = 'rgba(0, 0, 0, 0.10)';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, y, w, h, 8);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.stroke();
|
||||
|
||||
// fill text placeholder
|
||||
ctx.font = '15px sans-serif';
|
||||
ctx.fillStyle = 'black';
|
||||
ctx.textAlign = 'left';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText("Type '/' for command", x + 24, y + h / 2);
|
||||
}
|
||||
}
|
||||
|
||||
export class AutoCompleteFrameOverlay extends AutoCompleteTargetOverlay {
|
||||
private readonly _strokeColor;
|
||||
|
||||
constructor(gfx: GfxController, xywh: XYWH, strokeColor: string) {
|
||||
super(gfx, xywh);
|
||||
this._strokeColor = strokeColor;
|
||||
}
|
||||
|
||||
override render(ctx: CanvasRenderingContext2D, _rc: RoughCanvas) {
|
||||
const [x, y, w, h] = this.xywh;
|
||||
// frame title background
|
||||
const titleWidth = 72;
|
||||
const titleHeight = 30;
|
||||
const titleY = y - titleHeight - 10;
|
||||
|
||||
ctx.globalAlpha = 0.4;
|
||||
ctx.fillStyle = 'rgba(0, 0, 0, 0.8)';
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, titleY, titleWidth, titleHeight, 4);
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
|
||||
// fill title text
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.font = '14px sans-serif';
|
||||
ctx.fillStyle = 'white';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText('Frame', x + titleWidth / 2, titleY + titleHeight / 2);
|
||||
|
||||
// frame stroke
|
||||
ctx.globalAlpha = 0.4;
|
||||
ctx.strokeStyle = this._strokeColor;
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, y, w, h, 8);
|
||||
ctx.closePath();
|
||||
ctx.stroke();
|
||||
}
|
||||
}
|
||||
|
||||
export class AutoCompleteShapeOverlay extends Overlay {
|
||||
private readonly _shape: Shape;
|
||||
|
||||
constructor(
|
||||
gfx: GfxController,
|
||||
xywh: XYWH,
|
||||
type: TARGET_SHAPE_TYPE,
|
||||
options: Options,
|
||||
shapeStyle: ShapeStyle
|
||||
) {
|
||||
super(gfx);
|
||||
this._shape = ShapeFactory.createShape(xywh, type, options, shapeStyle);
|
||||
}
|
||||
|
||||
override render(ctx: CanvasRenderingContext2D, rc: RoughCanvas) {
|
||||
ctx.globalAlpha = 0.4;
|
||||
this._shape.draw(ctx, rc);
|
||||
}
|
||||
}
|
||||
|
||||
export function nextBound(
|
||||
type: Direction,
|
||||
curShape: ShapeElementModel,
|
||||
elements: ShapeElementModel[]
|
||||
) {
|
||||
const bound = Bound.deserialize(curShape.xywh);
|
||||
const { x, y, w, h } = bound;
|
||||
let nextBound: Bound;
|
||||
let angle = 0;
|
||||
switch (type) {
|
||||
case Direction.Right:
|
||||
angle = 0;
|
||||
break;
|
||||
case Direction.Bottom:
|
||||
angle = 90;
|
||||
break;
|
||||
case Direction.Left:
|
||||
angle = 180;
|
||||
break;
|
||||
case Direction.Top:
|
||||
angle = 270;
|
||||
break;
|
||||
}
|
||||
angle = normalizeDegAngle(angle + curShape.rotate);
|
||||
|
||||
if (angle >= 45 && angle <= 135) {
|
||||
nextBound = new Bound(x, y + h + MAIN_GAP, w, h);
|
||||
} else if (angle >= 135 && angle <= 225) {
|
||||
nextBound = new Bound(x - w - MAIN_GAP, y, w, h);
|
||||
} else if (angle >= 225 && angle <= 315) {
|
||||
nextBound = new Bound(x, y - h - MAIN_GAP, w, h);
|
||||
} else {
|
||||
nextBound = new Bound(x + w + MAIN_GAP, y, w, h);
|
||||
}
|
||||
|
||||
function isValidBound(bound: Bound) {
|
||||
return !elements.some(a => bound.isOverlapWithBound(a.elementBound));
|
||||
}
|
||||
|
||||
let count = 0;
|
||||
function findValidBound() {
|
||||
count++;
|
||||
const number = Math.ceil(count / 2);
|
||||
const next = nextBound.clone();
|
||||
switch (type) {
|
||||
case Direction.Right:
|
||||
case Direction.Left:
|
||||
next.y =
|
||||
count % 2 === 1
|
||||
? nextBound.y - (h + SECOND_GAP) * number
|
||||
: nextBound.y + (h + SECOND_GAP) * number;
|
||||
break;
|
||||
case Direction.Bottom:
|
||||
case Direction.Top:
|
||||
next.x =
|
||||
count % 2 === 1
|
||||
? nextBound.x - (w + SECOND_GAP) * number
|
||||
: nextBound.x + (w + SECOND_GAP) * number;
|
||||
break;
|
||||
}
|
||||
if (isValidBound(next)) return next;
|
||||
return findValidBound();
|
||||
}
|
||||
|
||||
return isValidBound(nextBound) ? nextBound : findValidBound();
|
||||
}
|
||||
|
||||
export function getPosition(type: Direction) {
|
||||
let startPosition: Connection['position'];
|
||||
let endPosition: Connection['position'];
|
||||
|
||||
switch (type) {
|
||||
case Direction.Right:
|
||||
startPosition = [1, 0.5];
|
||||
endPosition = [0, 0.5];
|
||||
break;
|
||||
case Direction.Bottom:
|
||||
startPosition = [0.5, 1];
|
||||
endPosition = [0.5, 0];
|
||||
break;
|
||||
case Direction.Left:
|
||||
startPosition = [0, 0.5];
|
||||
endPosition = [1, 0.5];
|
||||
break;
|
||||
case Direction.Top:
|
||||
startPosition = [0.5, 0];
|
||||
endPosition = [0.5, 1];
|
||||
break;
|
||||
}
|
||||
return { startPosition, endPosition };
|
||||
}
|
||||
|
||||
export function isShape(element: unknown): element is ShapeElementModel {
|
||||
return element instanceof ShapeElementModel;
|
||||
}
|
||||
|
||||
export function capitalizeFirstLetter(str: string) {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
|
||||
export function createEdgelessElement(
|
||||
edgeless: EdgelessRootBlockComponent,
|
||||
current: ShapeElementModel | NoteBlockModel,
|
||||
bound: Bound
|
||||
) {
|
||||
let id;
|
||||
const { service } = edgeless;
|
||||
const { crud } = service;
|
||||
|
||||
let element: GfxModel | null = null;
|
||||
|
||||
if (isShape(current)) {
|
||||
id = crud.addElement(current.type, {
|
||||
...current.serialize(),
|
||||
text: new Y.Text(),
|
||||
xywh: bound.serialize(),
|
||||
});
|
||||
if (!id) return null;
|
||||
element = crud.getElementById(id);
|
||||
} else {
|
||||
const { doc } = edgeless;
|
||||
id = doc.addBlock(
|
||||
'affine:note',
|
||||
{
|
||||
background: current.background,
|
||||
displayMode: current.displayMode,
|
||||
edgeless: current.edgeless,
|
||||
xywh: bound.serialize(),
|
||||
},
|
||||
edgeless.model.id
|
||||
);
|
||||
const note = doc.getBlock(id)?.model;
|
||||
if (!note) {
|
||||
throw new BlockSuiteError(
|
||||
ErrorCode.GfxBlockElementError,
|
||||
'Note block is not found after creation'
|
||||
);
|
||||
}
|
||||
assertType<NoteBlockModel>(note);
|
||||
doc.updateBlock(note, () => {
|
||||
note.edgeless.collapse = true;
|
||||
});
|
||||
doc.addBlock('affine:paragraph', {}, note.id);
|
||||
|
||||
element = note;
|
||||
}
|
||||
|
||||
if (!element) {
|
||||
throw new BlockSuiteError(
|
||||
ErrorCode.GfxBlockElementError,
|
||||
'Element is not found after creation'
|
||||
);
|
||||
}
|
||||
|
||||
const group = current.group;
|
||||
if (group instanceof GroupElementModel) {
|
||||
group.addChild(element);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
export function createShapeElement(
|
||||
edgeless: EdgelessRootBlockComponent,
|
||||
current: ShapeElementModel | NoteBlockModel,
|
||||
targetType: TARGET_SHAPE_TYPE
|
||||
) {
|
||||
const { crud } = edgeless.service;
|
||||
const id = crud.addElement('shape', {
|
||||
shapeType: getShapeType(targetType),
|
||||
radius: getShapeRadius(targetType),
|
||||
text: new Y.Text(),
|
||||
});
|
||||
if (!id) return null;
|
||||
const element = crud.getElementById(id);
|
||||
const group = current.group;
|
||||
if (group instanceof GroupElementModel && element) {
|
||||
group.addChild(element);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
Reference in New Issue
Block a user