mirror of
https://github.com/toeverything/AFFiNE.git
synced 2026-08-18 02:21:51 +08:00
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:
@@ -0,0 +1,97 @@
|
||||
import { isFrameBlock } from '@blocksuite/affine-block-frame';
|
||||
import {
|
||||
getSurfaceComponent,
|
||||
isNoteBlock,
|
||||
} from '@blocksuite/affine-block-surface';
|
||||
import type {
|
||||
EdgelessTextBlockModel,
|
||||
EmbedSyncedDocModel,
|
||||
FrameBlockModel,
|
||||
ImageBlockModel,
|
||||
NoteBlockModel,
|
||||
ShapeElementModel,
|
||||
} from '@blocksuite/affine-model';
|
||||
import { getElementsWithoutGroup } from '@blocksuite/affine-shared/utils';
|
||||
import { getCommonBoundWithRotation } from '@blocksuite/global/gfx';
|
||||
import type { BlockComponent } from '@blocksuite/std';
|
||||
import { GfxControllerIdentifier, type GfxModel } from '@blocksuite/std/gfx';
|
||||
import groupBy from 'lodash-es/groupBy';
|
||||
|
||||
import { createElementsFromClipboardDataCommand } from '../clipboard/command.js';
|
||||
import { getSortedCloneElements, prepareCloneData } from './clone-utils.js';
|
||||
import {
|
||||
isEdgelessTextBlock,
|
||||
isEmbedSyncedDocBlock,
|
||||
isImageBlock,
|
||||
} from './query.js';
|
||||
|
||||
const offset = 10;
|
||||
export async function duplicate(
|
||||
edgeless: BlockComponent,
|
||||
elements: GfxModel[],
|
||||
select = true
|
||||
) {
|
||||
const gfx = edgeless.std.get(GfxControllerIdentifier);
|
||||
|
||||
const surface = getSurfaceComponent(edgeless.std);
|
||||
if (!surface) return;
|
||||
|
||||
const copyElements = getSortedCloneElements(elements);
|
||||
const totalBound = getCommonBoundWithRotation(copyElements);
|
||||
totalBound.x += totalBound.w + offset;
|
||||
|
||||
const snapshot = prepareCloneData(copyElements, edgeless.std);
|
||||
const [_, { createdElementsPromise }] = edgeless.std.command.exec(
|
||||
createElementsFromClipboardDataCommand,
|
||||
{
|
||||
elementsRawData: snapshot,
|
||||
pasteCenter: totalBound.center,
|
||||
}
|
||||
);
|
||||
if (!createdElementsPromise) return;
|
||||
const { canvasElements, blockModels } = await createdElementsPromise;
|
||||
|
||||
const newElements = [...canvasElements, ...blockModels];
|
||||
|
||||
surface.fitToViewport(totalBound);
|
||||
|
||||
if (select) {
|
||||
gfx.selection.set({
|
||||
elements: newElements.map(e => e.id),
|
||||
editing: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
export const splitElements = (elements: GfxModel[]) => {
|
||||
const { notes, frames, shapes, images, edgelessTexts, embedSyncedDocs } =
|
||||
groupBy(getElementsWithoutGroup(elements), element => {
|
||||
if (isNoteBlock(element)) {
|
||||
return 'notes';
|
||||
} else if (isFrameBlock(element)) {
|
||||
return 'frames';
|
||||
} else if (isImageBlock(element)) {
|
||||
return 'images';
|
||||
} else if (isEdgelessTextBlock(element)) {
|
||||
return 'edgelessTexts';
|
||||
} else if (isEmbedSyncedDocBlock(element)) {
|
||||
return 'embedSyncedDocs';
|
||||
}
|
||||
return 'shapes';
|
||||
}) as {
|
||||
notes: NoteBlockModel[];
|
||||
shapes: ShapeElementModel[];
|
||||
frames: FrameBlockModel[];
|
||||
images: ImageBlockModel[];
|
||||
edgelessTexts: EdgelessTextBlockModel[];
|
||||
embedSyncedDocs: EmbedSyncedDocModel[];
|
||||
};
|
||||
|
||||
return {
|
||||
notes: notes ?? [],
|
||||
shapes: shapes ?? [],
|
||||
frames: frames ?? [],
|
||||
images: images ?? [],
|
||||
edgelessTexts: edgelessTexts ?? [],
|
||||
embedSyncedDocs: embedSyncedDocs ?? [],
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,237 @@
|
||||
import type {
|
||||
FrameBlockProps,
|
||||
NodeDetail,
|
||||
SerializedConnectorElement,
|
||||
SerializedGroupElement,
|
||||
SerializedMindmapElement,
|
||||
} from '@blocksuite/affine-model';
|
||||
import {
|
||||
ConnectorElementModel,
|
||||
GroupElementModel,
|
||||
MindmapElementModel,
|
||||
} from '@blocksuite/affine-model';
|
||||
import type { BlockStdScope } from '@blocksuite/std';
|
||||
import {
|
||||
getTopElements,
|
||||
GfxBlockElementModel,
|
||||
type GfxModel,
|
||||
type GfxPrimitiveElementModel,
|
||||
isGfxGroupCompatibleModel,
|
||||
type SerializedElement,
|
||||
} from '@blocksuite/std/gfx';
|
||||
import type { BlockSnapshot, Transformer } from '@blocksuite/store';
|
||||
|
||||
/**
|
||||
* return all elements in the tree of the elements
|
||||
*/
|
||||
export function getSortedCloneElements(elements: GfxModel[]) {
|
||||
const set = new Set<GfxModel>();
|
||||
elements.forEach(element => {
|
||||
// this element subtree has been added
|
||||
if (set.has(element)) return;
|
||||
|
||||
set.add(element);
|
||||
if (isGfxGroupCompatibleModel(element)) {
|
||||
element.descendantElements.forEach(descendant => set.add(descendant));
|
||||
}
|
||||
});
|
||||
return sortEdgelessElements([...set]);
|
||||
}
|
||||
|
||||
export function prepareCloneData(elements: GfxModel[], std: BlockStdScope) {
|
||||
elements = sortEdgelessElements(elements);
|
||||
const job = std.store.getTransformer();
|
||||
const res = elements.map(element => {
|
||||
const data = serializeElement(element, elements, job);
|
||||
return data;
|
||||
});
|
||||
return res.filter((d): d is SerializedElement | BlockSnapshot => !!d);
|
||||
}
|
||||
|
||||
export function serializeElement(
|
||||
element: GfxModel,
|
||||
elements: GfxModel[],
|
||||
job: Transformer
|
||||
) {
|
||||
if (element instanceof GfxBlockElementModel) {
|
||||
const snapshot = job.blockToSnapshot(element);
|
||||
if (!snapshot) {
|
||||
return;
|
||||
}
|
||||
return { ...snapshot };
|
||||
} else if (element instanceof ConnectorElementModel) {
|
||||
return serializeConnector(element, elements);
|
||||
} else {
|
||||
return element.serialize();
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeConnector(
|
||||
connector: ConnectorElementModel,
|
||||
elements: GfxModel[]
|
||||
) {
|
||||
const sourceId = connector.source?.id;
|
||||
const targetId = connector.target?.id;
|
||||
const serialized = connector.serialize();
|
||||
// if the source or target element not to be cloned
|
||||
// transfer connector position to absolute path
|
||||
if (sourceId && elements.every(s => s.id !== sourceId)) {
|
||||
serialized.source = { position: connector.absolutePath[0] };
|
||||
}
|
||||
if (targetId && elements.every(s => s.id !== targetId)) {
|
||||
serialized.target = {
|
||||
position: connector.absolutePath[connector.absolutePath.length - 1],
|
||||
};
|
||||
}
|
||||
return serialized;
|
||||
}
|
||||
|
||||
/**
|
||||
* There are interdependencies between elements,
|
||||
* so they must be added in a certain order
|
||||
* @param elements edgeless model list
|
||||
* @returns sorted edgeless model list
|
||||
*/
|
||||
export function sortEdgelessElements(elements: GfxModel[]) {
|
||||
// Since each element has a parent-child relationship, and from-to connector relationship
|
||||
// the child element must be added before the parent element
|
||||
// and the connected elements must be added before the connector element
|
||||
// To achieve this, we do a post-order traversal of the tree
|
||||
|
||||
if (elements.length === 0) return [];
|
||||
const result: GfxModel[] = [];
|
||||
|
||||
const topElements = getTopElements(elements);
|
||||
|
||||
// the connector element must be added after the connected elements
|
||||
const moveConnectorToEnd = (elements: GfxModel[]) => {
|
||||
const connectors = elements.filter(
|
||||
element => element instanceof ConnectorElementModel
|
||||
);
|
||||
const rest = elements.filter(
|
||||
element => !(element instanceof ConnectorElementModel)
|
||||
);
|
||||
return [...rest, ...connectors];
|
||||
};
|
||||
|
||||
const traverse = (element: GfxModel) => {
|
||||
if (isGfxGroupCompatibleModel(element)) {
|
||||
moveConnectorToEnd(element.childElements).forEach(child =>
|
||||
traverse(child)
|
||||
);
|
||||
}
|
||||
result.push(element);
|
||||
};
|
||||
|
||||
moveConnectorToEnd(topElements).forEach(element => traverse(element));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* map connector source & target ids
|
||||
* @param props serialized element props
|
||||
* @param ids old element id to new element id map
|
||||
* @returns updated element props
|
||||
*/
|
||||
export function mapConnectorIds(
|
||||
props: SerializedConnectorElement,
|
||||
ids: Map<string, string>
|
||||
) {
|
||||
if (props.source.id) {
|
||||
props.source.id = ids.get(props.source.id);
|
||||
}
|
||||
if (props.target.id) {
|
||||
props.target.id = ids.get(props.target.id);
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
/**
|
||||
* map group children ids
|
||||
* @param props serialized element props
|
||||
* @param ids old element id to new element id map
|
||||
* @returns updated element props
|
||||
*/
|
||||
export function mapGroupIds(
|
||||
props: SerializedGroupElement,
|
||||
ids: Map<string, string>
|
||||
) {
|
||||
if (props.children) {
|
||||
const newMap: Record<string, boolean> = {};
|
||||
for (const [key, value] of Object.entries(props.children)) {
|
||||
const newKey = ids.get(key);
|
||||
if (newKey) {
|
||||
newMap[newKey] = value;
|
||||
}
|
||||
}
|
||||
props.children = newMap;
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
/**
|
||||
* map frame children ids
|
||||
* @param props frame block props
|
||||
* @param ids old element id to new element id map
|
||||
* @returns updated frame block props
|
||||
*/
|
||||
export function mapFrameIds(props: FrameBlockProps, ids: Map<string, string>) {
|
||||
const oldChildIds = props.childElementIds
|
||||
? Object.keys(props.childElementIds)
|
||||
: [];
|
||||
const newChildIds: Record<string, boolean> = {};
|
||||
oldChildIds.forEach(oldId => {
|
||||
const newIds = ids.get(oldId);
|
||||
if (newIds) newChildIds[newIds] = true;
|
||||
});
|
||||
props.childElementIds = newChildIds;
|
||||
|
||||
return props;
|
||||
}
|
||||
|
||||
/**
|
||||
* map mindmap children & parent ids
|
||||
* @param props serialized element props
|
||||
* @param ids old element id to new element id map
|
||||
* @returns updated element props
|
||||
*/
|
||||
export function mapMindmapIds(
|
||||
props: SerializedMindmapElement,
|
||||
ids: Map<string, string>
|
||||
) {
|
||||
if (props.children) {
|
||||
const newMap: Record<string, NodeDetail> = {};
|
||||
for (const [key, value] of Object.entries(props.children)) {
|
||||
const newKey = ids.get(key);
|
||||
if (value.parent) {
|
||||
const newParent = ids.get(value.parent);
|
||||
value.parent = newParent;
|
||||
}
|
||||
if (newKey) {
|
||||
newMap[newKey] = value;
|
||||
}
|
||||
}
|
||||
props.children = newMap;
|
||||
}
|
||||
return props;
|
||||
}
|
||||
|
||||
export function getElementProps(
|
||||
element: GfxPrimitiveElementModel,
|
||||
ids: Map<string, string>
|
||||
) {
|
||||
if (element instanceof ConnectorElementModel) {
|
||||
const props = element.serialize();
|
||||
return mapConnectorIds(props, ids);
|
||||
}
|
||||
if (element instanceof GroupElementModel) {
|
||||
const props = element.serialize();
|
||||
return mapGroupIds(props, ids);
|
||||
}
|
||||
if (element instanceof MindmapElementModel) {
|
||||
const props = element.serialize();
|
||||
return mapMindmapIds(props, ids);
|
||||
}
|
||||
return element.serialize();
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { EdgelessCRUDIdentifier } from '@blocksuite/affine-block-surface';
|
||||
|
||||
import type { EdgelessRootService } from '../edgeless-root-service.js';
|
||||
|
||||
/**
|
||||
* move connectors from origin to target
|
||||
* @param originId origin element id
|
||||
* @param targetId target element id
|
||||
* @param service edgeless root service
|
||||
*/
|
||||
export function moveConnectors(
|
||||
originId: string,
|
||||
targetId: string,
|
||||
service: EdgelessRootService
|
||||
) {
|
||||
const connectors = service.surface.getConnectors(originId);
|
||||
const crud = service.std.get(EdgelessCRUDIdentifier);
|
||||
connectors.forEach(connector => {
|
||||
if (connector.source.id === originId) {
|
||||
crud.updateElement(connector.id, {
|
||||
source: { ...connector.source, id: targetId },
|
||||
});
|
||||
}
|
||||
if (connector.target.id === originId) {
|
||||
crud.updateElement(connector.id, {
|
||||
target: { ...connector.target, id: targetId },
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
export const DEFAULT_NOTE_CHILD_FLAVOUR = 'affine:paragraph';
|
||||
export const DEFAULT_NOTE_CHILD_TYPE = 'text';
|
||||
export const DEFAULT_NOTE_TIP = 'Text';
|
||||
|
||||
export const FIT_TO_SCREEN_PADDING = 100;
|
||||
|
||||
export const ATTACHED_DISTANCE = 20;
|
||||
|
||||
export const SurfaceColor = '#6046FE';
|
||||
export const NoteColor = '#1E96EB';
|
||||
export const BlendColor = '#7D91FF';
|
||||
|
||||
export const AI_CHAT_BLOCK_MIN_WIDTH = 260;
|
||||
export const AI_CHAT_BLOCK_MIN_HEIGHT = 160;
|
||||
export const AI_CHAT_BLOCK_MAX_WIDTH = 320;
|
||||
export const AI_CHAT_BLOCK_MAX_HEIGHT = 300;
|
||||
|
||||
export const EMBED_IFRAME_BLOCK_MIN_WIDTH = 218;
|
||||
export const EMBED_IFRAME_BLOCK_MIN_HEIGHT = 44;
|
||||
export const EMBED_IFRAME_BLOCK_MAX_WIDTH = 3400;
|
||||
export const EMBED_IFRAME_BLOCK_MAX_HEIGHT = 2200;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { isNoteBlock } from '@blocksuite/affine-block-surface';
|
||||
import type { Connectable } from '@blocksuite/affine-model';
|
||||
import type { GfxModel } from '@blocksuite/std/gfx';
|
||||
|
||||
import type { EdgelessRootBlockComponent } from '../index.js';
|
||||
import { isConnectable } from './query.js';
|
||||
|
||||
/**
|
||||
* Use deleteElementsV2 instead.
|
||||
* @deprecated
|
||||
*/
|
||||
export function deleteElements(
|
||||
edgeless: EdgelessRootBlockComponent,
|
||||
elements: GfxModel[]
|
||||
) {
|
||||
const set = new Set(elements);
|
||||
const { service } = edgeless;
|
||||
|
||||
elements.forEach(element => {
|
||||
if (isConnectable(element)) {
|
||||
const connectors = service.getConnectors(element as Connectable);
|
||||
connectors.forEach(connector => set.add(connector));
|
||||
}
|
||||
});
|
||||
|
||||
set.forEach(element => {
|
||||
if (isNoteBlock(element)) {
|
||||
const children = edgeless.doc.root?.children ?? [];
|
||||
// FIXME: should always keep at least 1 note
|
||||
if (children.length > 1) {
|
||||
edgeless.doc.deleteBlock(element);
|
||||
}
|
||||
} else {
|
||||
service.removeElement(element.id);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
// TODO(@fundon): move to pen module
|
||||
export const drawingCursor = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none'%3E%3Cg filter='url(%23filter0_d_5033_225305)'%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M16.138 6.9046C16.6785 6.36513 17.5553 6.36513 18.0958 6.9046C18.6358 7.44353 18.6358 8.31689 18.0958 8.85582L17.3186 9.63134L15.3621 7.67873L16.138 6.9046ZM14.6542 8.38506L16.6107 10.3377L8.96075 17.9707L6.61523 18.384L6.94908 16.461C7.00206 16.1558 7.14823 15.8745 7.36749 15.6557L14.6542 8.38506Z' fill='black'/%3E%3Cpath fill-rule='evenodd' clip-rule='evenodd' d='M18.095 6.9046C17.5545 6.36513 16.6777 6.36513 16.1372 6.9046L15.3613 7.67873L17.3178 9.63134L18.095 8.85582C18.635 8.31689 18.635 7.44353 18.095 6.9046ZM18.8014 9.56366C19.7328 8.63405 19.7329 7.12641 18.8014 6.1968C17.8705 5.26773 16.3616 5.26773 15.4307 6.1968L6.66035 14.9478C6.29491 15.3124 6.05131 15.7813 5.96301 16.2899L5.50738 18.9145C5.47951 19.075 5.53158 19.239 5.6469 19.354C5.76223 19.469 5.92636 19.5207 6.08678 19.4924L9.28847 18.9282C9.38935 18.9104 9.48233 18.8621 9.55485 18.7898L17.671 10.6918L18.8014 9.56366ZM16.6099 10.3377L14.6534 8.38506L7.36668 15.6557C7.14741 15.8745 7.00125 16.1558 6.94827 16.461L6.61442 18.384L8.95993 17.9707L16.6099 10.3377Z' fill='white'/%3E%3C/g%3E%3Cdefs%3E%3Cfilter id='filter0_d_5033_225305' x='-1.8' y='-0.8' width='27.6' height='27.6' filterUnits='userSpaceOnUse' color-interpolation-filters='sRGB'%3E%3CfeFlood flood-opacity='0' result='BackgroundImageFix'/%3E%3CfeColorMatrix in='SourceAlpha' type='matrix' values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0' result='hardAlpha'/%3E%3CfeOffset dy='1'/%3E%3CfeGaussianBlur stdDeviation='0.9'/%3E%3CfeColorMatrix type='matrix' values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.65 0'/%3E%3CfeBlend mode='normal' in2='BackgroundImageFix' result='effect1_dropShadow_5033_225305'/%3E%3CfeBlend mode='normal' in='SourceGraphic' in2='effect1_dropShadow_5033_225305' result='shape'/%3E%3C/filter%3E%3C/defs%3E%3C/svg%3E") 4 20, crosshair`;
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { ShapeToolOption } from '@blocksuite/affine-gfx-shape';
|
||||
import { ShapeType } from '@blocksuite/affine-model';
|
||||
|
||||
const shapeMap: Record<ShapeToolOption['shapeName'], number> = {
|
||||
[ShapeType.Rect]: 0,
|
||||
[ShapeType.Ellipse]: 1,
|
||||
[ShapeType.Diamond]: 2,
|
||||
[ShapeType.Triangle]: 3,
|
||||
roundedRect: 4,
|
||||
};
|
||||
const shapes = Object.keys(shapeMap) as ShapeToolOption['shapeName'][];
|
||||
|
||||
export function getNextShapeType(cur: ShapeToolOption['shapeName']) {
|
||||
return shapes[(shapeMap[cur] + 1) % shapes.length];
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import type { IVec } from '@blocksuite/global/gfx';
|
||||
import type { PointerEventState } from '@blocksuite/std';
|
||||
import type { Viewport } from '@blocksuite/std/gfx';
|
||||
|
||||
const PANNING_DISTANCE = 30;
|
||||
|
||||
export function calPanDelta(
|
||||
viewport: Viewport,
|
||||
e: PointerEventState,
|
||||
edgeDistance = 20
|
||||
): IVec | null {
|
||||
// Get viewport edge
|
||||
const { left, top } = viewport;
|
||||
const { width, height } = viewport;
|
||||
// Get pointer position
|
||||
let { x, y } = e;
|
||||
const { containerOffset } = e;
|
||||
x += containerOffset.x;
|
||||
y += containerOffset.y;
|
||||
// Check if pointer is near viewport edge
|
||||
const nearLeft = x < left + edgeDistance;
|
||||
const nearRight = x > left + width - edgeDistance;
|
||||
const nearTop = y < top + edgeDistance;
|
||||
const nearBottom = y > top + height - edgeDistance;
|
||||
// If pointer is not near viewport edge, return false
|
||||
if (!(nearLeft || nearRight || nearTop || nearBottom)) return null;
|
||||
|
||||
// Calculate move delta
|
||||
let deltaX = 0;
|
||||
let deltaY = 0;
|
||||
|
||||
// Use PANNING_DISTANCE to limit the max delta, avoid panning too fast
|
||||
if (nearLeft) {
|
||||
deltaX = Math.max(-PANNING_DISTANCE, x - (left + edgeDistance));
|
||||
} else if (nearRight) {
|
||||
deltaX = Math.min(PANNING_DISTANCE, x - (left + width - edgeDistance));
|
||||
}
|
||||
|
||||
if (nearTop) {
|
||||
deltaY = Math.max(-PANNING_DISTANCE, y - (top + edgeDistance));
|
||||
} else if (nearBottom) {
|
||||
deltaY = Math.min(PANNING_DISTANCE, y - (top + height - edgeDistance));
|
||||
}
|
||||
|
||||
return [deltaX, deltaY];
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
import type { CanvasElementWithText } from '@blocksuite/affine-block-surface';
|
||||
import {
|
||||
type AttachmentBlockModel,
|
||||
type BookmarkBlockModel,
|
||||
type Connectable,
|
||||
ConnectorElementModel,
|
||||
type EdgelessTextBlockModel,
|
||||
type EmbedBlockModel,
|
||||
type EmbedFigmaModel,
|
||||
type EmbedGithubModel,
|
||||
type EmbedHtmlModel,
|
||||
type EmbedLinkedDocModel,
|
||||
type EmbedLoomModel,
|
||||
type EmbedSyncedDocModel,
|
||||
type EmbedYoutubeModel,
|
||||
type ImageBlockModel,
|
||||
ShapeElementModel,
|
||||
TextElementModel,
|
||||
} from '@blocksuite/affine-model';
|
||||
import {
|
||||
getElementsWithoutGroup,
|
||||
isTopLevelBlock,
|
||||
} from '@blocksuite/affine-shared/utils';
|
||||
import type { PointLocation } from '@blocksuite/global/gfx';
|
||||
import { Bound } from '@blocksuite/global/gfx';
|
||||
import type {
|
||||
GfxModel,
|
||||
GfxPrimitiveElementModel,
|
||||
GfxToolsFullOptionValue,
|
||||
Viewport,
|
||||
} from '@blocksuite/std/gfx';
|
||||
import type { BlockModel } from '@blocksuite/store';
|
||||
|
||||
import { drawingCursor } from './cursors';
|
||||
|
||||
export function isEdgelessTextBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EdgelessTextBlockModel {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:edgeless-text'
|
||||
);
|
||||
}
|
||||
|
||||
export function isImageBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is ImageBlockModel {
|
||||
return (
|
||||
!!element && 'flavour' in element && element.flavour === 'affine:image'
|
||||
);
|
||||
}
|
||||
|
||||
export function isAttachmentBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is AttachmentBlockModel {
|
||||
return (
|
||||
!!element && 'flavour' in element && element.flavour === 'affine:attachment'
|
||||
);
|
||||
}
|
||||
|
||||
export function isBookmarkBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is BookmarkBlockModel {
|
||||
return (
|
||||
!!element && 'flavour' in element && element.flavour === 'affine:bookmark'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbeddedBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedBlockModel {
|
||||
return (
|
||||
!!element && 'flavour' in element && /affine:embed-*/.test(element.flavour)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: Remove this function after the edgeless refactor completed
|
||||
* This function is used to check if the block is an AI chat block for edgeless selected rect
|
||||
* Should not be used in the future
|
||||
* Related issue: https://linear.app/affine-design/issue/BS-1009/
|
||||
* @deprecated
|
||||
*/
|
||||
export function isAIChatBlock(element: BlockModel | GfxModel | null) {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-ai-chat'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* TODO: Remove this function after the edgeless refactor completed
|
||||
* This function is used to check if the block is an EmbedIframeBlock for edgeless selected rect
|
||||
* Should not be used in the future
|
||||
* Related issue: https://linear.app/affine-design/issue/BS-2841/
|
||||
* @deprecated
|
||||
*/
|
||||
export function isEmbedIframeBlock(element: BlockModel | GfxModel | null) {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-iframe'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbeddedLinkBlock(element: BlockModel | GfxModel | null) {
|
||||
return (
|
||||
isEmbeddedBlock(element) &&
|
||||
!isEmbedSyncedDocBlock(element) &&
|
||||
!isEmbedLinkedDocBlock(element)
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedGithubBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedGithubModel {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-github'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedYoutubeBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedYoutubeModel {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-youtube'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedLoomBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedLoomModel {
|
||||
return (
|
||||
!!element && 'flavour' in element && element.flavour === 'affine:embed-loom'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedFigmaBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedFigmaModel {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-figma'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedLinkedDocBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedLinkedDocModel {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-linked-doc'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedSyncedDocBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedSyncedDocModel {
|
||||
return (
|
||||
!!element &&
|
||||
'flavour' in element &&
|
||||
element.flavour === 'affine:embed-synced-doc'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmbedHtmlBlock(
|
||||
element: BlockModel | GfxModel | null
|
||||
): element is EmbedHtmlModel {
|
||||
return (
|
||||
!!element && 'flavour' in element && element.flavour === 'affine:embed-html'
|
||||
);
|
||||
}
|
||||
|
||||
export function isCanvasElement(
|
||||
selectable: GfxModel | BlockModel | null
|
||||
): selectable is GfxPrimitiveElementModel {
|
||||
return !isTopLevelBlock(selectable);
|
||||
}
|
||||
|
||||
export function isCanvasElementWithText(
|
||||
element: GfxModel
|
||||
): element is CanvasElementWithText {
|
||||
return (
|
||||
element instanceof TextElementModel || element instanceof ShapeElementModel
|
||||
);
|
||||
}
|
||||
|
||||
export function isConnectable(
|
||||
element: GfxModel | null
|
||||
): element is Connectable {
|
||||
return !!element && element.connectable;
|
||||
}
|
||||
|
||||
export function getSelectionBoxBound(viewport: Viewport, bound: Bound) {
|
||||
const { w, h } = bound;
|
||||
const [x, y] = viewport.toViewCoord(bound.x, bound.y);
|
||||
return new DOMRect(x, y, w * viewport.zoom, h * viewport.zoom);
|
||||
}
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/CSS/cursor
|
||||
export function getCursorMode(edgelessTool: GfxToolsFullOptionValue | null) {
|
||||
if (!edgelessTool) {
|
||||
return 'default';
|
||||
}
|
||||
switch (edgelessTool.type) {
|
||||
case 'default':
|
||||
return 'default';
|
||||
case 'pan':
|
||||
return edgelessTool.panning ? 'grabbing' : 'grab';
|
||||
case 'brush':
|
||||
case 'highlighter':
|
||||
return drawingCursor;
|
||||
case 'eraser':
|
||||
case 'shape':
|
||||
case 'connector':
|
||||
case 'frame':
|
||||
return 'crosshair';
|
||||
case 'text':
|
||||
return 'text';
|
||||
default:
|
||||
return 'default';
|
||||
}
|
||||
}
|
||||
|
||||
export type SelectableProps = {
|
||||
bound: Bound;
|
||||
rotate: number;
|
||||
path?: PointLocation[];
|
||||
};
|
||||
|
||||
export function getSelectableBounds(
|
||||
selected: GfxModel[]
|
||||
): Map<string, SelectableProps> {
|
||||
const bounds = new Map();
|
||||
getElementsWithoutGroup(selected).forEach(ele => {
|
||||
const bound = Bound.deserialize(ele.xywh);
|
||||
const props: SelectableProps = {
|
||||
bound,
|
||||
rotate: ele.rotate,
|
||||
};
|
||||
|
||||
if (isCanvasElement(ele) && ele instanceof ConnectorElementModel) {
|
||||
props.path = ele.absolutePath.map(p => p.clone());
|
||||
}
|
||||
|
||||
bounds.set(ele.id, props);
|
||||
});
|
||||
|
||||
return bounds;
|
||||
}
|
||||
@@ -0,0 +1,762 @@
|
||||
import { Overlay } from '@blocksuite/affine-block-surface';
|
||||
import {
|
||||
ConnectorElementModel,
|
||||
MindmapElementModel,
|
||||
} from '@blocksuite/affine-model';
|
||||
import { almostEqual, Bound, Point } from '@blocksuite/global/gfx';
|
||||
import type { GfxModel } from '@blocksuite/std/gfx';
|
||||
|
||||
interface Distance {
|
||||
horiz?: {
|
||||
/**
|
||||
* the minimum x moving distance to align with other bound
|
||||
*/
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* the indices of the align position
|
||||
*/
|
||||
alignPositionIndices: number[];
|
||||
};
|
||||
|
||||
vert?: {
|
||||
/**
|
||||
* the minimum y moving distance to align with other bound
|
||||
*/
|
||||
distance: number;
|
||||
|
||||
/**
|
||||
* the indices of the align position
|
||||
*/
|
||||
alignPositionIndices: number[];
|
||||
};
|
||||
}
|
||||
|
||||
const ALIGN_THRESHOLD = 8;
|
||||
const DISTRIBUTION_LINE_OFFSET = 1;
|
||||
const STROKE_WIDTH = 2;
|
||||
|
||||
export class SnapOverlay extends Overlay {
|
||||
static override overlayName: string = 'snap-manager';
|
||||
|
||||
private _skippedElements: Set<GfxModel> = new Set();
|
||||
|
||||
private _referenceBounds: {
|
||||
vertical: Bound[];
|
||||
horizontal: Bound[];
|
||||
all: Bound[];
|
||||
} = {
|
||||
vertical: [],
|
||||
horizontal: [],
|
||||
all: [],
|
||||
};
|
||||
|
||||
/**
|
||||
* This variable contains reference lines that are
|
||||
* generated by the 'Distribute Alignment' function. This alignment is achieved
|
||||
* by evenly distributing elements based on specified alignment rules.
|
||||
* These lines serve as a guide for achieving equal spacing or distribution
|
||||
* among multiple graphics or design elements.
|
||||
*/
|
||||
private _distributedAlignLines: [Point, Point][] = [];
|
||||
|
||||
/**
|
||||
* This variable holds reference lines that are calculated
|
||||
* based on the self-alignment of the graphics. This alignment is determined
|
||||
* according to various aspects of the graphic itself, such as the center, edges,
|
||||
* corners, etc. It essentially represents the guidelines for the positioning
|
||||
* and alignment within the individual graphic elements.
|
||||
*/
|
||||
private _intraGraphicAlignLines: {
|
||||
horizontal: [Point, Point][];
|
||||
vertical: [Point, Point][];
|
||||
} = {
|
||||
horizontal: [],
|
||||
vertical: [],
|
||||
};
|
||||
|
||||
override clear() {
|
||||
this._referenceBounds = {
|
||||
vertical: [],
|
||||
horizontal: [],
|
||||
all: [],
|
||||
};
|
||||
this._intraGraphicAlignLines = {
|
||||
horizontal: [],
|
||||
vertical: [],
|
||||
};
|
||||
this._distributedAlignLines = [];
|
||||
this._skippedElements.clear();
|
||||
|
||||
super.clear();
|
||||
}
|
||||
|
||||
private _alignDistributeHorizontally(
|
||||
rst: { dx: number; dy: number },
|
||||
bound: Bound,
|
||||
threshold: number,
|
||||
viewport: { zoom: number }
|
||||
) {
|
||||
const wBoxes: Bound[] = [];
|
||||
this._referenceBounds.horizontal.forEach(box => {
|
||||
if (box.isHorizontalCross(bound)) {
|
||||
wBoxes.push(box);
|
||||
}
|
||||
});
|
||||
|
||||
wBoxes.sort((a, b) => a.center[0] - b.center[0]);
|
||||
|
||||
let dif = Infinity;
|
||||
let min = Infinity;
|
||||
let aveDis = Number.MAX_SAFE_INTEGER;
|
||||
let curBound!: {
|
||||
leftIdx: number;
|
||||
rightIdx: number;
|
||||
spacing: number;
|
||||
points: [Point, Point][];
|
||||
};
|
||||
for (let i = 0; i < wBoxes.length; i++) {
|
||||
for (let j = i + 1; j < wBoxes.length; j++) {
|
||||
let lb = wBoxes[i],
|
||||
rb = wBoxes[j];
|
||||
// it means these bound need to be horizontally across
|
||||
if (!lb.isHorizontalCross(rb) || lb.isIntersectWithBound(rb)) continue;
|
||||
|
||||
let switchFlag = false;
|
||||
// exchange lb and rb to make sure lb is on the left of rb
|
||||
if (rb.maxX < lb.minX) {
|
||||
const temp = rb;
|
||||
rb = lb;
|
||||
lb = temp;
|
||||
switchFlag = true;
|
||||
}
|
||||
|
||||
let _centerX = 0;
|
||||
const updateDif = () => {
|
||||
dif = Math.abs(bound.center[0] - _centerX);
|
||||
const curAveDis =
|
||||
(Math.abs(lb.center[0] - bound.center[0]) +
|
||||
Math.abs(rb.center[0] - bound.center[0])) /
|
||||
2;
|
||||
if (
|
||||
dif <= threshold &&
|
||||
(dif < min || (almostEqual(dif, min) && curAveDis < aveDis))
|
||||
) {
|
||||
min = dif;
|
||||
aveDis = curAveDis;
|
||||
rst.dx = _centerX - bound.center[0];
|
||||
/**
|
||||
* calculate points to draw
|
||||
*/
|
||||
const ys = [lb.minY, lb.maxY, rb.minY, rb.maxY].sort(
|
||||
(a, b) => a - b
|
||||
);
|
||||
const y = (ys[1] + ys[2]) / 2;
|
||||
const offset = DISTRIBUTION_LINE_OFFSET / viewport.zoom;
|
||||
const xs = [
|
||||
_centerX - bound.w / 2,
|
||||
_centerX + bound.w / 2,
|
||||
rb.minX,
|
||||
rb.maxX,
|
||||
lb.minX,
|
||||
lb.maxX,
|
||||
].sort((a, b) => a - b);
|
||||
|
||||
curBound = {
|
||||
leftIdx: switchFlag ? j : i,
|
||||
rightIdx: switchFlag ? i : j,
|
||||
spacing: xs[2] - xs[1],
|
||||
points: [
|
||||
[new Point(xs[1] + offset, y), new Point(xs[2] - offset, y)],
|
||||
[new Point(xs[3] + offset, y), new Point(xs[4] - offset, y)],
|
||||
],
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* align between left and right bound
|
||||
*/
|
||||
if (lb.horizontalDistance(rb) > bound.w) {
|
||||
_centerX = (lb.maxX + rb.minX) / 2;
|
||||
updateDif();
|
||||
}
|
||||
|
||||
/**
|
||||
* align to the left bounds
|
||||
*/
|
||||
_centerX = lb.minX - (rb.minX - lb.maxX) - bound.w / 2;
|
||||
updateDif();
|
||||
|
||||
/** align right */
|
||||
_centerX = rb.minX - lb.maxX + rb.maxX + bound.w / 2;
|
||||
updateDif();
|
||||
}
|
||||
}
|
||||
|
||||
// find the boxes that has same spacing
|
||||
if (curBound) {
|
||||
const { leftIdx, rightIdx, spacing, points } = curBound;
|
||||
|
||||
this._distributedAlignLines.push(...points);
|
||||
|
||||
{
|
||||
let curLeftBound = wBoxes[leftIdx];
|
||||
|
||||
for (let i = leftIdx - 1; i >= 0; i--) {
|
||||
if (almostEqual(wBoxes[i].maxX, curLeftBound.minX - spacing)) {
|
||||
const targetBound = wBoxes[i];
|
||||
const ys = [
|
||||
targetBound.minY,
|
||||
targetBound.maxY,
|
||||
curLeftBound.minY,
|
||||
curLeftBound.maxY,
|
||||
].sort((a, b) => a - b);
|
||||
const y = (ys[1] + ys[2]) / 2;
|
||||
|
||||
this._distributedAlignLines.push([
|
||||
new Point(wBoxes[i].maxX, y),
|
||||
new Point(curLeftBound.minX, y),
|
||||
]);
|
||||
|
||||
curLeftBound = wBoxes[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let curRightBound = wBoxes[rightIdx];
|
||||
|
||||
for (let i = rightIdx + 1; i < wBoxes.length; i++) {
|
||||
if (almostEqual(wBoxes[i].minX, curRightBound.maxX + spacing)) {
|
||||
const targetBound = wBoxes[i];
|
||||
const ys = [
|
||||
targetBound.minY,
|
||||
targetBound.maxY,
|
||||
curRightBound.minY,
|
||||
curRightBound.maxY,
|
||||
].sort((a, b) => a - b);
|
||||
const y = (ys[1] + ys[2]) / 2;
|
||||
|
||||
this._distributedAlignLines.push([
|
||||
new Point(curRightBound.maxX, y),
|
||||
new Point(wBoxes[i].minX, y),
|
||||
]);
|
||||
|
||||
curRightBound = wBoxes[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _alignDistributeVertically(
|
||||
rst: { dx: number; dy: number },
|
||||
bound: Bound,
|
||||
threshold: number,
|
||||
viewport: { zoom: number }
|
||||
) {
|
||||
const hBoxes: Bound[] = [];
|
||||
this._referenceBounds.vertical.forEach(box => {
|
||||
if (box.isVerticalCross(bound)) {
|
||||
hBoxes.push(box);
|
||||
}
|
||||
});
|
||||
|
||||
hBoxes.sort((a, b) => a.center[0] - b.center[0]);
|
||||
|
||||
let dif = Infinity;
|
||||
let min = Infinity;
|
||||
let aveDis = Number.MAX_SAFE_INTEGER;
|
||||
let curBound!: {
|
||||
upperIdx: number;
|
||||
lowerIdx: number;
|
||||
spacing: number;
|
||||
points: [Point, Point][];
|
||||
};
|
||||
for (let i = 0; i < hBoxes.length; i++) {
|
||||
for (let j = i + 1; j < hBoxes.length; j++) {
|
||||
let ub = hBoxes[i],
|
||||
db = hBoxes[j];
|
||||
if (!ub.isVerticalCross(db) || ub.isIntersectWithBound(db)) continue;
|
||||
|
||||
let switchFlag = false;
|
||||
if (db.maxY < ub.minX) {
|
||||
const temp = ub;
|
||||
ub = db;
|
||||
db = temp;
|
||||
switchFlag = true;
|
||||
}
|
||||
|
||||
/** align middle */
|
||||
let _centerY = 0;
|
||||
const updateDiff = () => {
|
||||
dif = Math.abs(bound.center[1] - _centerY);
|
||||
const curAveDis =
|
||||
(Math.abs(ub.center[1] - bound.center[1]) +
|
||||
Math.abs(db.center[1] - bound.center[1])) /
|
||||
2;
|
||||
|
||||
if (
|
||||
dif <= threshold &&
|
||||
(dif < min || (almostEqual(dif, min) && curAveDis < aveDis))
|
||||
) {
|
||||
min = dif;
|
||||
rst.dy = _centerY - bound.center[1];
|
||||
/**
|
||||
* calculate points to draw
|
||||
*/
|
||||
const xs = [ub.minX, ub.maxX, db.minX, db.maxX].sort(
|
||||
(a, b) => a - b
|
||||
);
|
||||
const x = (xs[1] + xs[2]) / 2;
|
||||
const offset = DISTRIBUTION_LINE_OFFSET / viewport.zoom;
|
||||
const ys = [
|
||||
_centerY - bound.h / 2,
|
||||
_centerY + bound.h / 2,
|
||||
db.minY,
|
||||
db.maxY,
|
||||
ub.minY,
|
||||
ub.maxY,
|
||||
].sort((a, b) => a - b);
|
||||
|
||||
curBound = {
|
||||
upperIdx: switchFlag ? j : i,
|
||||
lowerIdx: switchFlag ? i : j,
|
||||
spacing: ys[2] - ys[1],
|
||||
points: [
|
||||
[new Point(x, ys[1] + offset), new Point(x, ys[2] - offset)],
|
||||
[new Point(x, ys[3] + offset), new Point(x, ys[4] - offset)],
|
||||
],
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
if (ub.verticalDistance(db) > bound.h) {
|
||||
_centerY = (ub.maxY + db.minY) / 2;
|
||||
updateDiff();
|
||||
}
|
||||
|
||||
/** align upper */
|
||||
_centerY = ub.minY - (db.minY - ub.maxY) - bound.h / 2;
|
||||
updateDiff();
|
||||
/** align lower */
|
||||
_centerY = db.minY - ub.maxY + db.maxY + bound.h / 2;
|
||||
updateDiff();
|
||||
}
|
||||
}
|
||||
|
||||
// find the boxes that has same spacing
|
||||
if (curBound) {
|
||||
const { upperIdx, lowerIdx, spacing, points } = curBound;
|
||||
|
||||
this._distributedAlignLines.push(...points);
|
||||
|
||||
{
|
||||
let curUpperBound = hBoxes[upperIdx];
|
||||
|
||||
for (let i = upperIdx - 1; i >= 0; i--) {
|
||||
if (almostEqual(hBoxes[i].maxY, curUpperBound.minY - spacing)) {
|
||||
const targetBound = hBoxes[i];
|
||||
const xs = [
|
||||
targetBound.minX,
|
||||
targetBound.maxX,
|
||||
curUpperBound.minX,
|
||||
curUpperBound.maxX,
|
||||
].sort((a, b) => a - b);
|
||||
const x = (xs[1] + xs[2]) / 2;
|
||||
|
||||
this._distributedAlignLines.push([
|
||||
new Point(x, hBoxes[i].maxY),
|
||||
new Point(x, curUpperBound.minY),
|
||||
]);
|
||||
|
||||
curUpperBound = hBoxes[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let curLowerBound = hBoxes[lowerIdx];
|
||||
|
||||
for (let i = lowerIdx + 1; i < hBoxes.length; i++) {
|
||||
if (almostEqual(hBoxes[i].minY, curLowerBound.maxY + spacing)) {
|
||||
const targetBound = hBoxes[i];
|
||||
const xs = [
|
||||
targetBound.minX,
|
||||
targetBound.maxX,
|
||||
curLowerBound.minX,
|
||||
curLowerBound.maxX,
|
||||
].sort((a, b) => a - b);
|
||||
const x = (xs[1] + xs[2]) / 2;
|
||||
|
||||
this._distributedAlignLines.push([
|
||||
new Point(x, curLowerBound.maxY),
|
||||
new Point(x, hBoxes[i].minY),
|
||||
]);
|
||||
|
||||
curLowerBound = hBoxes[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _calculateClosestDistances(bound: Bound, other: Bound): Distance {
|
||||
// Calculate center-to-center and center-to-side distances
|
||||
const centerXDistance = other.center[0] - bound.center[0];
|
||||
const centerYDistance = other.center[1] - bound.center[1];
|
||||
|
||||
// Calculate center-to-side distances
|
||||
const leftDistance = other.minX - bound.center[0];
|
||||
const rightDistance = other.maxX - bound.center[0];
|
||||
const topDistance = other.minY - bound.center[1];
|
||||
const bottomDistance = other.maxY - bound.center[1];
|
||||
|
||||
// Calculate side-to-side distances
|
||||
const leftToLeft = other.minX - bound.minX;
|
||||
const leftToRight = other.maxX - bound.minX;
|
||||
const rightToLeft = other.minX - bound.maxX;
|
||||
const rightToRight = other.maxX - bound.maxX;
|
||||
|
||||
const topToTop = other.minY - bound.minY;
|
||||
const topToBottom = other.maxY - bound.minY;
|
||||
const bottomToTop = other.minY - bound.maxY;
|
||||
const bottomToBottom = other.maxY - bound.maxY;
|
||||
|
||||
// calculate side-to-center distances
|
||||
const rightToCenter = other.center[0] - bound.maxX;
|
||||
const leftToCenter = other.center[0] - bound.minX;
|
||||
const topToCenter = other.center[1] - bound.minY;
|
||||
const bottomToCenter = other.center[1] - bound.maxY;
|
||||
|
||||
const xDistances = [
|
||||
centerXDistance,
|
||||
leftDistance,
|
||||
rightDistance,
|
||||
leftToLeft,
|
||||
leftToRight,
|
||||
rightToLeft,
|
||||
rightToRight,
|
||||
rightToCenter,
|
||||
leftToCenter,
|
||||
];
|
||||
|
||||
const yDistances = [
|
||||
centerYDistance,
|
||||
topDistance,
|
||||
bottomDistance,
|
||||
topToTop,
|
||||
topToBottom,
|
||||
bottomToTop,
|
||||
bottomToBottom,
|
||||
topToCenter,
|
||||
bottomToCenter,
|
||||
];
|
||||
|
||||
// Get absolute distances
|
||||
const xDistancesAbs = xDistances.map(Math.abs);
|
||||
const yDistancesAbs = yDistances.map(Math.abs);
|
||||
|
||||
// Get closest distances
|
||||
const closestX = Math.min(...xDistancesAbs);
|
||||
const closestY = Math.min(...yDistancesAbs);
|
||||
|
||||
const threshold = ALIGN_THRESHOLD / this.gfx.viewport.zoom;
|
||||
|
||||
// the x and y distances will be useful for locating the align point
|
||||
return {
|
||||
horiz:
|
||||
closestX <= threshold
|
||||
? {
|
||||
distance: xDistances[xDistancesAbs.indexOf(closestX)],
|
||||
get alignPositionIndices() {
|
||||
const indices: number[] = [];
|
||||
xDistancesAbs.forEach(
|
||||
(val, idx) => almostEqual(val, closestX) && indices.push(idx)
|
||||
);
|
||||
return indices;
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
vert:
|
||||
closestY <= threshold
|
||||
? {
|
||||
distance: yDistances[yDistancesAbs.indexOf(closestY)],
|
||||
get alignPositionIndices() {
|
||||
const indices: number[] = [];
|
||||
yDistancesAbs.forEach(
|
||||
(val, idx) => almostEqual(val, closestY) && indices.push(idx)
|
||||
);
|
||||
return indices;
|
||||
},
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update horizontal moving distance `rst.dx` to align with other bound.
|
||||
* Also, update the align points to draw.
|
||||
* @param rst
|
||||
* @param bound
|
||||
* @param other
|
||||
* @param distance
|
||||
*/
|
||||
private _updateXAlignPoint(
|
||||
rst: { dx: number; dy: number },
|
||||
bound: Bound,
|
||||
other: Bound,
|
||||
distance: Distance
|
||||
) {
|
||||
if (!distance.horiz) return;
|
||||
|
||||
const { distance: dx, alignPositionIndices: distanceIndices } =
|
||||
distance.horiz;
|
||||
const offset = STROKE_WIDTH / this.gfx.viewport.zoom / 2;
|
||||
const alignXPosition = [
|
||||
other.center[0],
|
||||
other.minX + offset,
|
||||
other.maxX - offset,
|
||||
bound.minX + dx + offset,
|
||||
bound.minX + dx + offset,
|
||||
bound.maxX + dx - offset,
|
||||
bound.maxX + dx - offset,
|
||||
other.center[0] - offset,
|
||||
other.center[0] + offset,
|
||||
];
|
||||
|
||||
rst.dx = dx;
|
||||
|
||||
const dy = distance.vert?.distance ?? 0;
|
||||
const top = Math.min(bound.minY + dy, other.minY);
|
||||
const down = Math.max(bound.maxY + dy, other.maxY);
|
||||
|
||||
this._intraGraphicAlignLines.horizontal = distanceIndices.map(
|
||||
idx =>
|
||||
[
|
||||
new Point(alignXPosition[idx], top),
|
||||
new Point(alignXPosition[idx], down),
|
||||
] as [Point, Point]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update vertical moving distance `rst.dy` to align with other bound.
|
||||
* Also, update the align points to draw.
|
||||
* @param rst
|
||||
* @param bound
|
||||
* @param other
|
||||
* @param distance
|
||||
*/
|
||||
private _updateYAlignPoint(
|
||||
rst: { dx: number; dy: number },
|
||||
bound: Bound,
|
||||
other: Bound,
|
||||
distance: Distance
|
||||
) {
|
||||
if (!distance.vert) return;
|
||||
|
||||
const { distance: dy, alignPositionIndices } = distance.vert;
|
||||
const offset = STROKE_WIDTH / this.gfx.viewport.zoom / 2;
|
||||
const alignXPosition = [
|
||||
other.center[1] - offset,
|
||||
other.minY + offset,
|
||||
other.maxY - offset,
|
||||
bound.minY + dy + offset,
|
||||
bound.minY + dy + offset,
|
||||
bound.maxY + dy - offset,
|
||||
bound.maxY + dy - offset,
|
||||
other.center[1] + offset,
|
||||
other.center[1] - offset,
|
||||
];
|
||||
|
||||
rst.dy = dy;
|
||||
|
||||
const dx = distance.horiz?.distance ?? 0;
|
||||
const left = Math.min(bound.minX + dx, other.minX);
|
||||
const right = Math.max(bound.maxX + dx, other.maxX);
|
||||
|
||||
this._intraGraphicAlignLines.vertical = alignPositionIndices.map(
|
||||
idx =>
|
||||
[
|
||||
new Point(left, alignXPosition[idx]),
|
||||
new Point(right, alignXPosition[idx]),
|
||||
] as [Point, Point]
|
||||
);
|
||||
}
|
||||
|
||||
align(bound: Bound): { dx: number; dy: number } {
|
||||
const rst = { dx: 0, dy: 0 };
|
||||
const threshold = ALIGN_THRESHOLD / this.gfx.viewport.zoom;
|
||||
|
||||
const { viewport } = this.gfx;
|
||||
|
||||
this._intraGraphicAlignLines = {
|
||||
horizontal: [],
|
||||
vertical: [],
|
||||
};
|
||||
this._distributedAlignLines = [];
|
||||
this._updateAlignCandidates(bound);
|
||||
|
||||
for (const other of this._referenceBounds.all) {
|
||||
const closestDistances = this._calculateClosestDistances(bound, other);
|
||||
|
||||
if (
|
||||
closestDistances.horiz &&
|
||||
(!this._intraGraphicAlignLines.horizontal.length ||
|
||||
Math.abs(closestDistances.horiz.distance) < Math.abs(rst.dx))
|
||||
) {
|
||||
this._updateXAlignPoint(rst, bound, other, closestDistances);
|
||||
}
|
||||
|
||||
if (
|
||||
closestDistances.vert &&
|
||||
(!this._intraGraphicAlignLines.vertical.length ||
|
||||
Math.abs(closestDistances.vert.distance) < Math.abs(rst.dy))
|
||||
) {
|
||||
this._updateYAlignPoint(rst, bound, other, closestDistances);
|
||||
}
|
||||
}
|
||||
|
||||
// point align priority is higher than distribute align
|
||||
if (rst.dx === 0) {
|
||||
this._alignDistributeHorizontally(rst, bound, threshold, viewport);
|
||||
}
|
||||
|
||||
if (rst.dy === 0) {
|
||||
this._alignDistributeVertically(rst, bound, threshold, viewport);
|
||||
}
|
||||
|
||||
this._renderer?.refresh();
|
||||
|
||||
return rst;
|
||||
}
|
||||
|
||||
override render(ctx: CanvasRenderingContext2D) {
|
||||
if (
|
||||
this._intraGraphicAlignLines.vertical.length === 0 &&
|
||||
this._intraGraphicAlignLines.horizontal.length === 0 &&
|
||||
this._distributedAlignLines.length === 0
|
||||
)
|
||||
return;
|
||||
const { viewport } = this.gfx;
|
||||
const strokeWidth = STROKE_WIDTH / viewport.zoom;
|
||||
|
||||
ctx.strokeStyle = '#8B5CF6';
|
||||
ctx.lineWidth = strokeWidth;
|
||||
ctx.beginPath();
|
||||
|
||||
[
|
||||
...this._intraGraphicAlignLines.horizontal,
|
||||
...this._intraGraphicAlignLines.vertical,
|
||||
].forEach(line => {
|
||||
let d = '';
|
||||
if (line[0].x === line[1].x) {
|
||||
const x = line[0].x;
|
||||
const minY = Math.min(line[0].y, line[1].y);
|
||||
const maxY = Math.max(line[0].y, line[1].y);
|
||||
d = `M${x},${minY}L${x},${maxY}`;
|
||||
} else {
|
||||
const y = line[0].y;
|
||||
const minX = Math.min(line[0].x, line[1].x);
|
||||
const maxX = Math.max(line[0].x, line[1].x);
|
||||
d = `M${minX},${y}L${maxX},${y}`;
|
||||
}
|
||||
ctx.stroke(new Path2D(d));
|
||||
});
|
||||
|
||||
ctx.strokeStyle = '#CC4187';
|
||||
this._distributedAlignLines.forEach(line => {
|
||||
const bar = 10 / viewport.zoom;
|
||||
let d = '';
|
||||
if (line[0].x === line[1].x) {
|
||||
const x = line[0].x;
|
||||
const minY = Math.min(line[0].y, line[1].y);
|
||||
const maxY = Math.max(line[0].y, line[1].y);
|
||||
d = `M${x},${minY}L${x},${maxY}
|
||||
M${x - bar},${minY}L${x + bar},${minY}
|
||||
M${x - bar},${maxY}L${x + bar},${maxY} `;
|
||||
} else {
|
||||
const y = line[0].y;
|
||||
const minX = Math.min(line[0].x, line[1].x);
|
||||
const maxX = Math.max(line[0].x, line[1].x);
|
||||
d = `M${minX},${y}L${maxX},${y}
|
||||
M${minX},${y - bar}L${minX},${y + bar}
|
||||
M${maxX},${y - bar}L${maxX},${y + bar}`;
|
||||
}
|
||||
ctx.stroke(new Path2D(d));
|
||||
});
|
||||
}
|
||||
|
||||
private _isSkippedElement(element: GfxModel) {
|
||||
return (
|
||||
element instanceof ConnectorElementModel ||
|
||||
element.group instanceof MindmapElementModel
|
||||
);
|
||||
}
|
||||
|
||||
private _updateAlignCandidates(movingBound: Bound) {
|
||||
movingBound = movingBound.expand(ALIGN_THRESHOLD * this.gfx.viewport.zoom);
|
||||
|
||||
const viewportBound = this.gfx.viewport.viewportBounds;
|
||||
const horizAreaBound = new Bound(
|
||||
Math.min(movingBound.x, viewportBound.x),
|
||||
movingBound.y,
|
||||
Math.max(movingBound.w, viewportBound.w),
|
||||
movingBound.h
|
||||
);
|
||||
const vertAreaBound = new Bound(
|
||||
movingBound.x,
|
||||
Math.min(movingBound.y, viewportBound.y),
|
||||
movingBound.w,
|
||||
Math.max(movingBound.h, viewportBound.h)
|
||||
);
|
||||
|
||||
const { _skippedElements: skipped } = this;
|
||||
const vertCandidates = this.gfx.grid.search(vertAreaBound, {
|
||||
useSet: true,
|
||||
});
|
||||
const horizCandidates = this.gfx.grid.search(horizAreaBound, {
|
||||
useSet: true,
|
||||
});
|
||||
const verticalBounds: Bound[] = [];
|
||||
const horizBounds: Bound[] = [];
|
||||
const allBounds: Bound[] = [];
|
||||
|
||||
vertCandidates.forEach(candidate => {
|
||||
if (skipped.has(candidate) || this._isSkippedElement(candidate)) return;
|
||||
verticalBounds.push(candidate.elementBound);
|
||||
allBounds.push(candidate.elementBound);
|
||||
});
|
||||
|
||||
horizCandidates.forEach(candidate => {
|
||||
if (skipped.has(candidate) || this._isSkippedElement(candidate)) return;
|
||||
horizBounds.push(candidate.elementBound);
|
||||
allBounds.push(candidate.elementBound);
|
||||
});
|
||||
|
||||
this._referenceBounds = {
|
||||
horizontal: horizBounds,
|
||||
vertical: verticalBounds,
|
||||
all: allBounds,
|
||||
};
|
||||
}
|
||||
|
||||
setMovingElements(
|
||||
movingElements: GfxModel[],
|
||||
excludes: GfxModel[] = []
|
||||
): Bound {
|
||||
if (movingElements.length === 0) return new Bound();
|
||||
|
||||
const skipped = new Set(movingElements);
|
||||
excludes.forEach(e => skipped.add(e));
|
||||
|
||||
this._skippedElements = skipped;
|
||||
|
||||
return movingElements.reduce(
|
||||
(prev, element) => prev.unite(element.elementBound),
|
||||
movingElements[0].elementBound
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user