diff --git a/packages/common/src/algorithms/a-star.ts b/packages/common/src/algorithms/a-star.ts index 5a60824bb..71864e5d4 100644 --- a/packages/common/src/algorithms/a-star.ts +++ b/packages/common/src/algorithms/a-star.ts @@ -30,7 +30,7 @@ export class AStar { if (currentPoint[0] === end[0] && currentPoint[1] === end[1]) { break; } - current.node.adjacentNodes.forEach(next => { + current.node.adjacentNodes.forEach((next) => { let newCost = costSoFar.get(current!.node)! + this.heuristic(next.data, current!.node.data); const previousNode = this.cameFrom.get(current!.node); // Inflection point weight, if an inflection point occurs, cost + 1 to avoid the inflection point path diff --git a/packages/common/src/plugins/with-group.spec.ts b/packages/common/src/plugins/with-group.spec.ts index 43351813e..7338f8dfd 100644 --- a/packages/common/src/plugins/with-group.spec.ts +++ b/packages/common/src/plugins/with-group.spec.ts @@ -149,14 +149,14 @@ describe('with group plugin', () => { it('should remove the group if there is only one element left within after deletion', () => { addSelectedElement(board, [board.children[0]]); deleteFragment(board); - const group = board.children.find(item => item.id === board.children[0].groupId); + const group = board.children.find((item) => item.id === board.children[0].groupId); expect(group).toBe(undefined); }); it('should update element groupId if there is only one element left within after deletion', () => { addSelectedElement(board, [board.children[4]]); deleteFragment(board); - const group = board.children.find(item => item.id === board.children[4].groupId); + const group = board.children.find((item) => item.id === board.children[4].groupId); expect(group).toBe(undefined); expect(board.children[3].groupId).toBe(group2[group2.length - 1].id); diff --git a/packages/common/src/plugins/with-resize.ts b/packages/common/src/plugins/with-resize.ts index c3f8ef9e5..afa910850 100644 --- a/packages/common/src/plugins/with-resize.ts +++ b/packages/common/src/plugins/with-resize.ts @@ -52,7 +52,7 @@ export const withResize = PlaitBoard.findPath(board, el)) + ? resizeHitTestRef.element.map((el) => PlaitBoard.findPath(board, el)) : PlaitBoard.findPath(board, resizeHitTestRef.element); resizeRef = { path, diff --git a/packages/common/src/text/types.ts b/packages/common/src/text/types.ts index b342fb29f..11bdf0f95 100644 --- a/packages/common/src/text/types.ts +++ b/packages/common/src/text/types.ts @@ -1,9 +1,9 @@ import { BaseElement } from 'slate'; -export type ElementSize = { +export type ElementSize = { width: number; height: number; -} +}; export enum Alignment { left = 'left', diff --git a/packages/common/src/transforms/align.ts b/packages/common/src/transforms/align.ts index 6bdbe7723..c18ae0510 100644 --- a/packages/common/src/transforms/align.ts +++ b/packages/common/src/transforms/align.ts @@ -60,7 +60,7 @@ export const alignRight = (board: PlaitBoard) => { function setOffset(board: PlaitBoard, getOffset: (outerRectangle: RectangleClient, rectangle: RectangleClient) => Point) { const elements = getHighestSelectedElements(board); const outerRectangle = getRectangleByElements(board, elements, false); - elements.forEach(element => { + elements.forEach((element) => { if (!element.points && !PlaitGroupElement.isGroup(element)) return; const rectangle = board.getRectangle(element)!; const offset = getOffset(outerRectangle, rectangle); @@ -70,8 +70,8 @@ function setOffset(board: PlaitBoard, getOffset: (outerRectangle: RectangleClien } else if (element.points) { updateElements = [element]; } - updateElements.forEach(item => { - const newPoints = item.points!.map(p => [p[0] + offset[0], p[1] + offset[1]]) as Point[]; + updateElements.forEach((item) => { + const newPoints = item.points!.map((p) => [p[0] + offset[0], p[1] + offset[1]]) as Point[]; const path = PlaitBoard.findPath(board, item); Transforms.setNode( board, @@ -98,14 +98,14 @@ const distribute = (board: PlaitBoard, isHorizontal: boolean) => { const axis = isHorizontal ? 'x' : 'y'; const side = isHorizontal ? 'width' : 'height'; const highestSelectedElements = getHighestSelectedElements(board); - const refs = highestSelectedElements.map(element => { + const refs = highestSelectedElements.map((element) => { return { element, rectangle: board.getRectangle(element)! }; }); const outerRectangle = getRectangleByElements(board, highestSelectedElements, false); const minRectangleRef = refs.sort((a, b) => a.rectangle[axis] - b.rectangle[axis])[0]; const maxRectangleRef = refs.sort((a, b) => b.rectangle[axis] + b.rectangle[side] - (a.rectangle[axis] + a.rectangle[side]))[0]; - const minIndex = refs.findIndex(ref => ref === minRectangleRef); - const maxIndex = refs.findIndex(ref => ref === maxRectangleRef); + const minIndex = refs.findIndex((ref) => ref === minRectangleRef); + const maxIndex = refs.findIndex((ref) => ref === maxRectangleRef); let distributeRefs = refs.filter((element, index) => index !== minIndex && index !== maxIndex); const sum = distributeRefs.reduce((accumulator, current) => current.rectangle[side] + accumulator, 0); const offset = @@ -118,7 +118,7 @@ const distribute = (board: PlaitBoard, isHorizontal: boolean) => { const moveAxis = isHorizontal ? 0 : 1; moveOffset[moveAxis] = position - rectangle[axis]; const path = PlaitBoard.findPath(board, distributeRefs[i].element); - const newPoints = distributeRefs[i].element.points!.map(p => [p[0] + moveOffset[0], p[1] + moveOffset[1]]) as Point[]; + const newPoints = distributeRefs[i].element.points!.map((p) => [p[0] + moveOffset[0], p[1] + moveOffset[1]]) as Point[]; Transforms.setNode( board, { diff --git a/packages/common/src/transforms/property.ts b/packages/common/src/transforms/property.ts index 603026484..905303e7e 100644 --- a/packages/common/src/transforms/property.ts +++ b/packages/common/src/transforms/property.ts @@ -9,7 +9,7 @@ export interface SetOptions { export const setProperty = (board: PlaitBoard, properties: Partial, options?: SetOptions) => { const selectedElements = getSelectedElements(board) as T[]; - selectedElements.forEach(element => { + selectedElements.forEach((element) => { if (options?.match && !options?.match(element)) return; const path = PlaitBoard.findPath(board, element); const memorizeKey = options?.getMemorizeKey ? options?.getMemorizeKey(element) : ''; diff --git a/packages/common/src/utils/clipboard.ts b/packages/common/src/utils/clipboard.ts index ec4f8fdb0..87a7da3dc 100644 --- a/packages/common/src/utils/clipboard.ts +++ b/packages/common/src/utils/clipboard.ts @@ -6,13 +6,13 @@ export const buildClipboardData = ( startPoint: Point, elementBuilder?: (element: PlaitElement) => PlaitElement | undefined ) => { - return elements.map(element => { + return elements.map((element) => { const newElement = elementBuilder && elementBuilder(element); if (newElement) { return newElement; } if (element.points) { - const points = element.points.map(point => [point[0] - startPoint[0], point[1] - startPoint[1]]); + const points = element.points.map((point) => [point[0] - startPoint[0], point[1] - startPoint[1]]); return { ...element, points }; } return element; @@ -26,14 +26,14 @@ export const insertClipboardData = ( elementHandler?: (element: PlaitElement, idsMap: Record) => void ) => { const idsMap: Record = {}; - elements.forEach(element => { + elements.forEach((element) => { idsMap[element.id] = idCreator(); }); - elements.forEach(element => { + elements.forEach((element) => { element.id = idsMap[element.id]; elementHandler && elementHandler(element, idsMap); if (element.points) { - element.points = element.points.map(point => [startPoint[0] + point[0], startPoint[1] + point[1]]) as [Point, Point]; + element.points = element.points.map((point) => [startPoint[0] + point[0], startPoint[1] + point[1]]) as [Point, Point]; } Transforms.insertNode(board, element, [board.children.length]); }); diff --git a/packages/common/src/utils/default-orthogonal-routing.ts b/packages/common/src/utils/default-orthogonal-routing.ts index 4e9e99e8d..94e8eae8b 100644 --- a/packages/common/src/utils/default-orthogonal-routing.ts +++ b/packages/common/src/utils/default-orthogonal-routing.ts @@ -1,8 +1,8 @@ // Credits to xyflow // https://github.com/xyflow/xyflow/blob/main/packages/system/src/utils/edges/smoothstep-edge.ts -import { Direction, Point } from "@plait/core"; -import { getDirectionFactor } from "./direction"; +import { Direction, Point } from '@plait/core'; +import { getDirectionFactor } from './direction'; export const getPoints = (source: Point, sourcePosition: Direction, target: Point, targetPosition: Direction, offset: number) => { const sourceDirectionFactors = getDirectionFactor(sourcePosition); @@ -99,4 +99,4 @@ function getEdgeCenter({ const centerY = targetY < sourceY ? targetY + yOffset : targetY - yOffset; return [centerX, centerY, xOffset, yOffset]; -} \ No newline at end of file +} diff --git a/packages/common/src/utils/elbow-line-route.ts b/packages/common/src/utils/elbow-line-route.ts index 983e306c0..710fdb4b3 100644 --- a/packages/common/src/utils/elbow-line-route.ts +++ b/packages/common/src/utils/elbow-line-route.ts @@ -48,7 +48,11 @@ export const generateElbowLineRoute = (options: ElbowLineRouteOptions, board?: P const isHitY = RectangleClient.isHitY(options.sourceOuterRectangle, options.targetOuterRectangle); const centerX = isHitX ? undefined : RectangleClient.getGapCenter(options.sourceOuterRectangle, options.targetOuterRectangle, true); const centerY = isHitY ? undefined : RectangleClient.getGapCenter(options.sourceOuterRectangle, options.targetOuterRectangle, false); - route = routeAdjust(route, { centerX, centerY, sourceRectangle: options.sourceRectangle, targetRectangle: options.targetRectangle }, board); + route = routeAdjust( + route, + { centerX, centerY, sourceRectangle: options.sourceRectangle, targetRectangle: options.targetRectangle }, + board + ); return route; }; @@ -61,7 +65,11 @@ export const routeAdjust = (path: Point[], options: RouteAdjustOptions, board?: const optionsX = getAdjustOptions(path, centerX, true); const resultX = optionsX.pointOfHit && - adjust(path, { parallelPaths: optionsX.parallelPaths, pointOfHit: optionsX.pointOfHit, sourceRectangle, targetRectangle }, board); + adjust( + path, + { parallelPaths: optionsX.parallelPaths, pointOfHit: optionsX.pointOfHit, sourceRectangle, targetRectangle }, + board + ); if (resultX) { path = resultX; } @@ -70,7 +78,11 @@ export const routeAdjust = (path: Point[], options: RouteAdjustOptions, board?: const optionsY = getAdjustOptions(path, centerY, false); const resultY = optionsY.pointOfHit && - adjust(path, { parallelPaths: optionsY.parallelPaths, pointOfHit: optionsY.pointOfHit, sourceRectangle, targetRectangle }, board); + adjust( + path, + { parallelPaths: optionsY.parallelPaths, pointOfHit: optionsY.pointOfHit, sourceRectangle, targetRectangle }, + board + ); if (resultY) { path = resultY; } @@ -81,7 +93,7 @@ export const routeAdjust = (path: Point[], options: RouteAdjustOptions, board?: const adjust = (route: Point[], options: AdjustOptions, board?: PlaitBoard): null | Point[] => { const { parallelPaths, pointOfHit, sourceRectangle, targetRectangle } = options; let result = null; - parallelPaths.forEach(parallelPath => { + parallelPaths.forEach((parallelPath) => { // Construct a rectangle const tempRectPoints = [pointOfHit, parallelPath[0], parallelPath[1]]; // directly use getCornerPoints will bring the precision issue (eg: 263.6923375175286 - 57.130859375) @@ -94,7 +106,7 @@ const adjust = (route: Point[], options: AdjustOptions, board?: PlaitBoard): nul const indexRangeInPath: number[] = []; const indexRangeInCorner: number[] = []; route.forEach((point, index) => { - const cornerResult = tempCorners.findIndex(corner => Point.isEquals(point, corner)); + const cornerResult = tempCorners.findIndex((corner) => Point.isEquals(point, corner)); if (cornerResult !== -1) { indexRangeInPath.push(index); indexRangeInCorner.push(cornerResult); @@ -153,7 +165,7 @@ export const getGraphPoints = (options: ElbowLineRouteOptions) => { const y: number[] = []; let result: Point[] = []; - [sourceOuterRectangle, targetOuterRectangle].forEach(rectangle => { + [sourceOuterRectangle, targetOuterRectangle].forEach((rectangle) => { x.push(rectangle.x, rectangle.x + rectangle.width / 2, rectangle.x + rectangle.width); y.push(rectangle.y, rectangle.y + rectangle.height / 2, rectangle.y + rectangle.height); }); @@ -181,7 +193,7 @@ export const getGraphPoints = (options: ElbowLineRouteOptions) => { } } } - result = removeDuplicatePoints(result).filter(point => { + result = removeDuplicatePoints(result).filter((point) => { const isInSource = RectangleClient.isPointInRectangle(sourceOuterRectangle, point); const isInTarget = RectangleClient.isPointInRectangle(targetOuterRectangle, point); return !isInSource && !isInTarget; @@ -193,7 +205,7 @@ export const createGraph = (points: Point[]) => { const graph = new PointGraph(); const Xs: number[] = []; const Ys: number[] = []; - points.forEach(p => { + points.forEach((p) => { const x = p[0], y = p[1]; if (Xs.indexOf(x) < 0) Xs.push(x); diff --git a/packages/common/src/utils/image.ts b/packages/common/src/utils/image.ts index 47bdbb4e6..15eeedb07 100644 --- a/packages/common/src/utils/image.ts +++ b/packages/common/src/utils/image.ts @@ -53,7 +53,7 @@ function getImageSize(file: File, defaultImageWidth: number): Promise<{ width: n const image = new Image(); image.src = URL.createObjectURL(file); - image.onload = function() { + image.onload = function () { const width = defaultImageWidth; const height = (defaultImageWidth * image.naturalHeight) / image.naturalWidth; resolve( diff --git a/packages/common/src/utils/line-path.ts b/packages/common/src/utils/line-path.ts index c1f41dce0..046c7ce56 100644 --- a/packages/common/src/utils/line-path.ts +++ b/packages/common/src/utils/line-path.ts @@ -53,8 +53,8 @@ export function getRatioByPoint(points: Point[], point: Point) { export const removeDuplicatePoints = (points: Point[]) => { const newArray: Point[] = []; - points.forEach(point => { - const index = newArray.findIndex(otherPoint => { + points.forEach((point) => { + const index = newArray.findIndex((otherPoint) => { return Point.isEquals(point, otherPoint); }); if (index === -1) newArray.push(point); diff --git a/packages/common/src/utils/text.ts b/packages/common/src/utils/text.ts index ee2b6c3c8..9a28ac07f 100644 --- a/packages/common/src/utils/text.ts +++ b/packages/common/src/utils/text.ts @@ -26,7 +26,7 @@ export const getFirstTextManage = (element: PlaitElement) => { }; export const getTextEditorsByElement: TextInterface['getTextEditorsByElement'] = (element: PlaitElement) => { - return getTextManages(element).map(manage => { + return getTextManages(element).map((manage) => { return manage.editor; }); }; @@ -42,7 +42,7 @@ export const getFirstTextEditor: TextInterface['getFirstTextEditor'] = (element: export const findFirstTextEditor: TextInterface['findFirstTextEditor'] = (board: PlaitBoard) => { const selectedElements = getSelectedElements(board); let firstEditor: Editor | null = null; - selectedElements.forEach(element => { + selectedElements.forEach((element) => { const editors = getTextEditorsByElement(element); if (!firstEditor && editors && editors.length > 0) { firstEditor = editors[0]; @@ -53,12 +53,12 @@ export const findFirstTextEditor: TextInterface['findFirstTextEditor'] = (board: export const getElementsText = (elements: PlaitElement[]) => { return elements - .map(item => { + .map((item) => { try { const editors = getTextEditorsByElement(item); if (editors.length) { return editors - .map(editor => { + .map((editor) => { const textsEntry = Node.texts(editor); return Array.from(textsEntry).reduce((total, text) => (total += text[0].text), ''); }) @@ -69,7 +69,7 @@ export const getElementsText = (elements: PlaitElement[]) => { return ''; } }) - .filter(item => item) + .filter((item) => item) .join(' '); }; @@ -77,14 +77,14 @@ export const getTextEditors: TextInterface['getTextEditors'] = (board: PlaitBoar const selectedElements = elements || getSelectedElements(board); if (selectedElements.length) { const textManages: TextManage[] = []; - selectedElements.forEach(item => { + selectedElements.forEach((item) => { textManages.push(...getTextManages(item)); }); - const editingTextManage = textManages.find(textManage => textManage.isEditing); + const editingTextManage = textManages.find((textManage) => textManage.isEditing); if (editingTextManage) { return [editingTextManage.editor]; } - return textManages.map(item => { + return textManages.map((item) => { return item.editor; }); } @@ -94,10 +94,10 @@ export const getTextEditors: TextInterface['getTextEditors'] = (board: PlaitBoar export const getEditingTextEditor: TextInterface['getEditingTextEditor'] = (board: PlaitBoard, elements?: PlaitElement[]) => { const selectedElements = elements || getSelectedElements(board); const textManages: TextManage[] = []; - selectedElements.forEach(item => { + selectedElements.forEach((item) => { textManages.push(...getTextManages(item)); }); - const editingTextManage = textManages.find(textManage => textManage.isEditing); + const editingTextManage = textManages.find((textManage) => textManage.isEditing); if (editingTextManage) { return editingTextManage.editor; } diff --git a/packages/common/src/utils/vector.spec.ts b/packages/common/src/utils/vector.spec.ts index 3b79af169..97d31a4d8 100644 --- a/packages/common/src/utils/vector.spec.ts +++ b/packages/common/src/utils/vector.spec.ts @@ -35,8 +35,8 @@ describe('vector', () => { let start = [0, 0] as Point; let end = [40, 30] as Point; const unitVector = getUnitVectorByPointAndPoint(start, end); - expect(unitVector[0]).toEqual(4/5); - expect(unitVector[1]).toEqual(3/5) + expect(unitVector[0]).toEqual(4 / 5); + expect(unitVector[1]).toEqual(3 / 5); }); }); describe('get point on vector by vector and vector component', () => { diff --git a/packages/core/src/context.ts b/packages/core/src/context.ts index 518071684..eb4b3005a 100644 --- a/packages/core/src/context.ts +++ b/packages/core/src/context.ts @@ -4,7 +4,7 @@ export class PlaitBoardContext { private uploadingFiles: ImageEntry[] = []; getUploadingFile(url: string) { - return this.uploadingFiles.find(file => file.url === url); + return this.uploadingFiles.find((file) => file.url === url); } setUploadingFile(file: ImageEntry) { @@ -12,6 +12,6 @@ export class PlaitBoardContext { } removeUploadingFile(fileEntry: ImageEntry) { - this.uploadingFiles = this.uploadingFiles.filter(file => file.url !== fileEntry.url); + this.uploadingFiles = this.uploadingFiles.filter((file) => file.url !== fileEntry.url); } } diff --git a/packages/core/src/core/element/element-ref.ts b/packages/core/src/core/element/element-ref.ts index 5ce447806..3b99d7ae9 100644 --- a/packages/core/src/core/element/element-ref.ts +++ b/packages/core/src/core/element/element-ref.ts @@ -1,6 +1,4 @@ /** * store the instance ref for element */ -export interface PlaitElementRef { -} - +export interface PlaitElementRef {} diff --git a/packages/core/src/core/list-render.spec.ts b/packages/core/src/core/list-render.spec.ts index f1d3090e1..971e779a1 100644 --- a/packages/core/src/core/list-render.spec.ts +++ b/packages/core/src/core/list-render.spec.ts @@ -1,18 +1,12 @@ describe('mountElementG', () => { describe('default', () => { - it('container g should have correct position', () => { - - }); - it('children element should have a root container g', () => { - - }); - it(`children element's g should have been before of it's parent element container g`, () => { - - }); + it('container g should have correct position', () => {}); + it('children element should have a root container g', () => {}); + it(`children element's g should have been before of it's parent element container g`, () => {}); it(`should add to correct position when insert a element`, () => {}); it(`should add to correct position when insert a child element`, () => {}); - it(`should add to correct position when insert a element at start position`, () => {}) - it(`should add to correct position when insert a child element at start position`, () => {}) + it(`should add to correct position when insert a element at start position`, () => {}); + it(`should add to correct position when insert a child element at start position`, () => {}); }); describe('move', () => { it('should move container g to correct when move element', () => {}); diff --git a/packages/core/src/core/list-render.ts b/packages/core/src/core/list-render.ts index 56885e0ac..8ff8b0c5f 100644 --- a/packages/core/src/core/list-render.ts +++ b/packages/core/src/core/list-render.ts @@ -75,7 +75,7 @@ export class ListRender { currentIndexForFirstElement = record.currentIndex; } }); - diffResult.forEachOperation(record => { + diffResult.forEachOperation((record) => { // removed if (record.currentIndex === null) { const componentRef = this.instances[record.previousIndex as number]; @@ -168,7 +168,7 @@ const getContext = ( board: board, selected: isSelected, index, - hasThemeChanged: !!board.operations?.find(op => op.type === 'set_theme') + hasThemeChanged: !!board.operations?.find((op) => op.type === 'set_theme') }; return context; }; diff --git a/packages/core/src/differs/default_iterable_differ.ts b/packages/core/src/differs/default_iterable_differ.ts index b1ac9f7c2..47170782b 100644 --- a/packages/core/src/differs/default_iterable_differ.ts +++ b/packages/core/src/differs/default_iterable_differ.ts @@ -6,666 +6,646 @@ * found in the LICENSE file at https://angular.io/license */ -import {isListLikeIterable, iterateListLike} from '../utils/iterable'; - -import {IterableChangeRecord, IterableChanges, IterableDiffer, CustomIterable, TrackByFunction} from './iterable_differs'; +import { isListLikeIterable, iterateListLike } from '../utils/iterable'; +import { IterableChangeRecord, IterableChanges, IterableDiffer, CustomIterable, TrackByFunction } from './iterable_differs'; const trackByIdentity = (index: number, item: any) => item; export type Writable = { - -readonly[K in keyof T]: T[K]; + -readonly [K in keyof T]: T[K]; }; export class DefaultIterableDiffer implements IterableDiffer, IterableChanges { - public readonly length: number = 0; - public readonly collection!: V[]|Iterable|null; - // Keeps track of the used records at any point in time (during & across `_check()` calls) - private _linkedRecords: _DuplicateMap|null = null; - // Keeps track of the removed records at any point in time during `_check()` calls. - private _unlinkedRecords: _DuplicateMap|null = null; - private _previousItHead: IterableChangeRecord_|null = null; - private _itHead: IterableChangeRecord_|null = null; - private _itTail: IterableChangeRecord_|null = null; - private _additionsHead: IterableChangeRecord_|null = null; - private _additionsTail: IterableChangeRecord_|null = null; - private _movesHead: IterableChangeRecord_|null = null; - private _movesTail: IterableChangeRecord_|null = null; - private _removalsHead: IterableChangeRecord_|null = null; - private _removalsTail: IterableChangeRecord_|null = null; - // Keeps track of records where custom track by is the same, but item identity has changed - private _identityChangesHead: IterableChangeRecord_|null = null; - private _identityChangesTail: IterableChangeRecord_|null = null; - private _trackByFn: TrackByFunction; - - constructor(trackByFn?: TrackByFunction) { - this._trackByFn = trackByFn || trackByIdentity; - } - - forEachItem(fn: (record: IterableChangeRecord_) => void) { - let record: IterableChangeRecord_|null; - for (record = this._itHead; record !== null; record = record._next) { - fn(record); - } - } - - forEachOperation( - fn: (item: IterableChangeRecord, previousIndex: number|null, currentIndex: number|null) => - void) { - let nextIt = this._itHead; - let nextRemove = this._removalsHead; - let addRemoveOffset = 0; - let moveOffsets: number[]|null = null; - while (nextIt || nextRemove) { - // Figure out which is the next record to process - // Order: remove, add, move - const record: IterableChangeRecord = !nextRemove || - nextIt && - nextIt.currentIndex! < - getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets) ? - nextIt! : - nextRemove; - const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets); - const currentIndex = record.currentIndex; - - // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary - if (record === nextRemove) { - addRemoveOffset--; - nextRemove = nextRemove._nextRemoved; - } else { - nextIt = nextIt!._next; - if (record.previousIndex == null) { - addRemoveOffset++; + public readonly length: number = 0; + public readonly collection!: V[] | Iterable | null; + // Keeps track of the used records at any point in time (during & across `_check()` calls) + private _linkedRecords: _DuplicateMap | null = null; + // Keeps track of the removed records at any point in time during `_check()` calls. + private _unlinkedRecords: _DuplicateMap | null = null; + private _previousItHead: IterableChangeRecord_ | null = null; + private _itHead: IterableChangeRecord_ | null = null; + private _itTail: IterableChangeRecord_ | null = null; + private _additionsHead: IterableChangeRecord_ | null = null; + private _additionsTail: IterableChangeRecord_ | null = null; + private _movesHead: IterableChangeRecord_ | null = null; + private _movesTail: IterableChangeRecord_ | null = null; + private _removalsHead: IterableChangeRecord_ | null = null; + private _removalsTail: IterableChangeRecord_ | null = null; + // Keeps track of records where custom track by is the same, but item identity has changed + private _identityChangesHead: IterableChangeRecord_ | null = null; + private _identityChangesTail: IterableChangeRecord_ | null = null; + private _trackByFn: TrackByFunction; + + constructor(trackByFn?: TrackByFunction) { + this._trackByFn = trackByFn || trackByIdentity; + } + + forEachItem(fn: (record: IterableChangeRecord_) => void) { + let record: IterableChangeRecord_ | null; + for (record = this._itHead; record !== null; record = record._next) { + fn(record); + } + } + + forEachOperation(fn: (item: IterableChangeRecord, previousIndex: number | null, currentIndex: number | null) => void) { + let nextIt = this._itHead; + let nextRemove = this._removalsHead; + let addRemoveOffset = 0; + let moveOffsets: number[] | null = null; + while (nextIt || nextRemove) { + // Figure out which is the next record to process + // Order: remove, add, move + const record: IterableChangeRecord = + !nextRemove || (nextIt && nextIt.currentIndex! < getPreviousIndex(nextRemove, addRemoveOffset, moveOffsets)) + ? nextIt! + : nextRemove; + const adjPreviousIndex = getPreviousIndex(record, addRemoveOffset, moveOffsets); + const currentIndex = record.currentIndex; + + // consume the item, and adjust the addRemoveOffset and update moveDistance if necessary + if (record === nextRemove) { + addRemoveOffset--; + nextRemove = nextRemove._nextRemoved; + } else { + nextIt = nextIt!._next; + if (record.previousIndex == null) { + addRemoveOffset++; + } else { + // INVARIANT: currentIndex < previousIndex + if (!moveOffsets) moveOffsets = []; + const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset; + const localCurrentIndex = currentIndex! - addRemoveOffset; + if (localMovePreviousIndex != localCurrentIndex) { + for (let i = 0; i < localMovePreviousIndex; i++) { + const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0); + const index = offset + i; + if (localCurrentIndex <= index && index < localMovePreviousIndex) { + moveOffsets[i] = offset + 1; + } + } + const previousIndex = record.previousIndex; + moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex; + } + } + } + + if (adjPreviousIndex !== currentIndex) { + fn(record, adjPreviousIndex, currentIndex); + } + } + } + + forEachPreviousItem(fn: (record: IterableChangeRecord_) => void) { + let record: IterableChangeRecord_ | null; + for (record = this._previousItHead; record !== null; record = record._nextPrevious) { + fn(record); + } + } + + forEachAddedItem(fn: (record: IterableChangeRecord_) => void) { + let record: IterableChangeRecord_ | null; + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + fn(record); + } + } + + forEachMovedItem(fn: (record: IterableChangeRecord_) => void) { + let record: IterableChangeRecord_ | null; + for (record = this._movesHead; record !== null; record = record._nextMoved) { + fn(record); + } + } + + forEachRemovedItem(fn: (record: IterableChangeRecord_) => void) { + let record: IterableChangeRecord_ | null; + for (record = this._removalsHead; record !== null; record = record._nextRemoved) { + fn(record); + } + } + + forEachIdentityChange(fn: (record: IterableChangeRecord_) => void) { + let record: IterableChangeRecord_ | null; + for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) { + fn(record); + } + } + + diff(collection: CustomIterable | null | undefined): DefaultIterableDiffer | null { + if (collection == null) collection = []; + if (!isListLikeIterable(collection)) { + throw new Error('Exception: Error trying to diff. Only arrays and iterables are allowed'); + } + + if (this.check(collection)) { + return this; } else { - // INVARIANT: currentIndex < previousIndex - if (!moveOffsets) moveOffsets = []; - const localMovePreviousIndex = adjPreviousIndex - addRemoveOffset; - const localCurrentIndex = currentIndex! - addRemoveOffset; - if (localMovePreviousIndex != localCurrentIndex) { - for (let i = 0; i < localMovePreviousIndex; i++) { - const offset = i < moveOffsets.length ? moveOffsets[i] : (moveOffsets[i] = 0); - const index = offset + i; - if (localCurrentIndex <= index && index < localMovePreviousIndex) { - moveOffsets[i] = offset + 1; - } + return null; + } + } + + onDestroy() {} + + check(collection: CustomIterable): boolean { + this._reset(); + + let record: IterableChangeRecord_ | null = this._itHead; + let mayBeDirty: boolean = false; + let index: number; + let item: V; + let itemTrackBy: any; + if (Array.isArray(collection)) { + (this as Writable).length = collection.length; + + for (let index = 0; index < this.length; index++) { + item = collection[index]; + itemTrackBy = this._trackByFn(index, item); + if (record === null || !Object.is(record.trackById, itemTrackBy)) { + record = this._mismatch(record, item, itemTrackBy, index); + mayBeDirty = true; + } else { + if (mayBeDirty) { + record = this._verifyReinsertion(record, item, itemTrackBy, index); + } + if (!Object.is(record.item, item)) this._addIdentityChange(record, item); + } + + record = record._next; } - const previousIndex = record.previousIndex; - moveOffsets[previousIndex] = localCurrentIndex - localMovePreviousIndex; - } + } else { + index = 0; + iterateListLike(collection, (item: V) => { + itemTrackBy = this._trackByFn(index, item); + if (record === null || !Object.is(record.trackById, itemTrackBy)) { + record = this._mismatch(record, item, itemTrackBy, index); + mayBeDirty = true; + } else { + if (mayBeDirty) { + record = this._verifyReinsertion(record, item, itemTrackBy, index); + } + if (!Object.is(record.item, item)) this._addIdentityChange(record, item); + } + record = record._next; + index++; + }); + (this as Writable).length = index; } - } - if (adjPreviousIndex !== currentIndex) { - fn(record, adjPreviousIndex, currentIndex); - } + this._truncate(record); + (this as Writable).collection = collection; + return this.isDirty; + } + + /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity + * changes. + */ + get isDirty(): boolean { + return ( + this._additionsHead !== null || this._movesHead !== null || this._removalsHead !== null || this._identityChangesHead !== null + ); + } + + /** + * Reset the state of the change objects to show no changes. This means set previousKey to + * currentKey, and clear all of the queues (additions, moves, removals). + * Set the previousIndexes of moved and added items to their currentIndexes + * Reset the list of additions, moves and removals + * + * @internal + */ + _reset() { + if (this.isDirty) { + let record: IterableChangeRecord_ | null; + + for (record = this._previousItHead = this._itHead; record !== null; record = record._next) { + record._nextPrevious = record._next; + } + + for (record = this._additionsHead; record !== null; record = record._nextAdded) { + record.previousIndex = record.currentIndex; + } + this._additionsHead = this._additionsTail = null; + + for (record = this._movesHead; record !== null; record = record._nextMoved) { + record.previousIndex = record.currentIndex; + } + this._movesHead = this._movesTail = null; + this._removalsHead = this._removalsTail = null; + this._identityChangesHead = this._identityChangesTail = null; + } } - } - forEachPreviousItem(fn: (record: IterableChangeRecord_) => void) { - let record: IterableChangeRecord_|null; - for (record = this._previousItHead; record !== null; record = record._nextPrevious) { - fn(record); + /** + * This is the core function which handles differences between collections. + * + * - `record` is the record which we saw at this position last time. If null then it is a new + * item. + * - `item` is the current item in the collection + * - `index` is the position of the item in the collection + * + * @internal + */ + _mismatch(record: IterableChangeRecord_ | null, item: V, itemTrackBy: any, index: number): IterableChangeRecord_ { + // The previous record after which we will append the current one. + let previousRecord: IterableChangeRecord_ | null; + + if (record === null) { + previousRecord = this._itTail; + } else { + previousRecord = record._prev; + // Remove the record from the collection since we know it does not match the item. + this._remove(record); + } + + // See if we have evicted the item, which used to be at some anterior position of _itHead list. + record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); + if (record !== null) { + // It is an item which we have evicted earlier: reinsert it back into the list. + // But first we need to check if identity changed, so we can update in view if necessary. + if (!Object.is(record.item, item)) this._addIdentityChange(record, item); + + this._reinsertAfter(record, previousRecord, index); + } else { + // Attempt to see if the item is at some posterior position of _itHead list. + record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index); + if (record !== null) { + // We have the item in _itHead at/after `index` position. We need to move it forward in the + // collection. + // But first we need to check if identity changed, so we can update in view if necessary. + if (!Object.is(record.item, item)) this._addIdentityChange(record, item); + + this._moveAfter(record, previousRecord, index); + } else { + // It is a new item: add it. + record = this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index); + } + } + return record; } - } - forEachAddedItem(fn: (record: IterableChangeRecord_) => void) { - let record: IterableChangeRecord_|null; - for (record = this._additionsHead; record !== null; record = record._nextAdded) { - fn(record); + /** + * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty) + * + * Use case: `[a, a]` => `[b, a, a]` + * + * If we did not have this check then the insertion of `b` would: + * 1) evict first `a` + * 2) insert `b` at `0` index. + * 3) leave `a` at index `1` as is. <-- this is wrong! + * 3) reinsert `a` at index 2. <-- this is wrong! + * + * The correct behavior is: + * 1) evict first `a` + * 2) insert `b` at `0` index. + * 3) reinsert `a` at index 1. + * 3) move `a` at from `1` to `2`. + * + * + * Double check that we have not evicted a duplicate item. We need to check if the item type may + * have already been removed: + * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted + * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a + * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a' + * at the end. + * + * @internal + */ + _verifyReinsertion(record: IterableChangeRecord_, item: V, itemTrackBy: any, index: number): IterableChangeRecord_ { + let reinsertRecord: IterableChangeRecord_ | null = + this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); + if (reinsertRecord !== null) { + record = this._reinsertAfter(reinsertRecord, record._prev!, index); + } else if (record.currentIndex != index) { + record.currentIndex = index; + this._addToMoves(record, index); + } + return record; } - } - forEachMovedItem(fn: (record: IterableChangeRecord_) => void) { - let record: IterableChangeRecord_|null; - for (record = this._movesHead; record !== null; record = record._nextMoved) { - fn(record); + /** + * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection + * + * - `record` The first excess {@link IterableChangeRecord_}. + * + * @internal + */ + _truncate(record: IterableChangeRecord_ | null) { + // Anything after that needs to be removed; + while (record !== null) { + const nextRecord: IterableChangeRecord_ | null = record._next; + this._addToRemovals(this._unlink(record)); + record = nextRecord; + } + if (this._unlinkedRecords !== null) { + this._unlinkedRecords.clear(); + } + + if (this._additionsTail !== null) { + this._additionsTail._nextAdded = null; + } + if (this._movesTail !== null) { + this._movesTail._nextMoved = null; + } + if (this._itTail !== null) { + this._itTail._next = null; + } + if (this._removalsTail !== null) { + this._removalsTail._nextRemoved = null; + } + if (this._identityChangesTail !== null) { + this._identityChangesTail._nextIdentityChange = null; + } } - } - forEachRemovedItem(fn: (record: IterableChangeRecord_) => void) { - let record: IterableChangeRecord_|null; - for (record = this._removalsHead; record !== null; record = record._nextRemoved) { - fn(record); + /** @internal */ + _reinsertAfter(record: IterableChangeRecord_, prevRecord: IterableChangeRecord_ | null, index: number): IterableChangeRecord_ { + if (this._unlinkedRecords !== null) { + this._unlinkedRecords.remove(record); + } + const prev = record._prevRemoved; + const next = record._nextRemoved; + + if (prev === null) { + this._removalsHead = next; + } else { + prev._nextRemoved = next; + } + if (next === null) { + this._removalsTail = prev; + } else { + next._prevRemoved = prev; + } + + this._insertAfter(record, prevRecord, index); + this._addToMoves(record, index); + return record; } - } - forEachIdentityChange(fn: (record: IterableChangeRecord_) => void) { - let record: IterableChangeRecord_|null; - for (record = this._identityChangesHead; record !== null; record = record._nextIdentityChange) { - fn(record); + /** @internal */ + _moveAfter(record: IterableChangeRecord_, prevRecord: IterableChangeRecord_ | null, index: number): IterableChangeRecord_ { + this._unlink(record); + this._insertAfter(record, prevRecord, index); + this._addToMoves(record, index); + return record; } - } - diff(collection: CustomIterable|null|undefined): DefaultIterableDiffer|null { - if (collection == null) collection = []; - if (!isListLikeIterable(collection)) { - throw new Error('Exception: Error trying to diff. Only arrays and iterables are allowed'); + /** @internal */ + _addAfter(record: IterableChangeRecord_, prevRecord: IterableChangeRecord_ | null, index: number): IterableChangeRecord_ { + this._insertAfter(record, prevRecord, index); + + if (this._additionsTail === null) { + // assert(this._additionsHead === null); + this._additionsTail = this._additionsHead = record; + } else { + // assert(_additionsTail._nextAdded === null); + // assert(record._nextAdded === null); + this._additionsTail = this._additionsTail._nextAdded = record; + } + return record; } - if (this.check(collection)) { - return this; - } else { - return null; + /** @internal */ + _insertAfter(record: IterableChangeRecord_, prevRecord: IterableChangeRecord_ | null, index: number): IterableChangeRecord_ { + const next: IterableChangeRecord_ | null = prevRecord === null ? this._itHead : prevRecord._next; + record._next = next; + record._prev = prevRecord; + if (next === null) { + this._itTail = record; + } else { + next._prev = record; + } + if (prevRecord === null) { + this._itHead = record; + } else { + prevRecord._next = record; + } + + if (this._linkedRecords === null) { + this._linkedRecords = new _DuplicateMap(); + } + this._linkedRecords.put(record); + + record.currentIndex = index; + return record; } - } - onDestroy() {} + /** @internal */ + _remove(record: IterableChangeRecord_): IterableChangeRecord_ { + return this._addToRemovals(this._unlink(record)); + } - check(collection: CustomIterable): boolean { - this._reset(); + /** @internal */ + _unlink(record: IterableChangeRecord_): IterableChangeRecord_ { + if (this._linkedRecords !== null) { + this._linkedRecords.remove(record); + } - let record: IterableChangeRecord_|null = this._itHead; - let mayBeDirty: boolean = false; - let index: number; - let item: V; - let itemTrackBy: any; - if (Array.isArray(collection)) { - (this as Writable).length = collection.length; + const prev = record._prev; + const next = record._next; - for (let index = 0; index < this.length; index++) { - item = collection[index]; - itemTrackBy = this._trackByFn(index, item); - if (record === null || !Object.is(record.trackById, itemTrackBy)) { - record = this._mismatch(record, item, itemTrackBy, index); - mayBeDirty = true; + if (prev === null) { + this._itHead = next; } else { - if (mayBeDirty) { - record = this._verifyReinsertion(record, item, itemTrackBy, index); - } - if (!Object.is(record.item, item)) this._addIdentityChange(record, item); - } - - record = record._next; - } - } else { - index = 0; - iterateListLike(collection, (item: V) => { - itemTrackBy = this._trackByFn(index, item); - if (record === null || !Object.is(record.trackById, itemTrackBy)) { - record = this._mismatch(record, item, itemTrackBy, index); - mayBeDirty = true; + prev._next = next; + } + if (next === null) { + this._itTail = prev; } else { - if (mayBeDirty) { - record = this._verifyReinsertion(record, item, itemTrackBy, index); - } - if (!Object.is(record.item, item)) this._addIdentityChange(record, item); - } - record = record._next; - index++; - }); - (this as Writable).length = index; - } - - this._truncate(record); - (this as Writable).collection = collection; - return this.isDirty; - } - - /* CollectionChanges is considered dirty if it has any additions, moves, removals, or identity - * changes. - */ - get isDirty(): boolean { - return this._additionsHead !== null || this._movesHead !== null || - this._removalsHead !== null || this._identityChangesHead !== null; - } - - /** - * Reset the state of the change objects to show no changes. This means set previousKey to - * currentKey, and clear all of the queues (additions, moves, removals). - * Set the previousIndexes of moved and added items to their currentIndexes - * Reset the list of additions, moves and removals - * - * @internal - */ - _reset() { - if (this.isDirty) { - let record: IterableChangeRecord_|null; - - for (record = this._previousItHead = this._itHead; record !== null; record = record._next) { - record._nextPrevious = record._next; - } - - for (record = this._additionsHead; record !== null; record = record._nextAdded) { - record.previousIndex = record.currentIndex; - } - this._additionsHead = this._additionsTail = null; - - for (record = this._movesHead; record !== null; record = record._nextMoved) { - record.previousIndex = record.currentIndex; - } - this._movesHead = this._movesTail = null; - this._removalsHead = this._removalsTail = null; - this._identityChangesHead = this._identityChangesTail = null; - } - } - - /** - * This is the core function which handles differences between collections. - * - * - `record` is the record which we saw at this position last time. If null then it is a new - * item. - * - `item` is the current item in the collection - * - `index` is the position of the item in the collection - * - * @internal - */ - _mismatch(record: IterableChangeRecord_|null, item: V, itemTrackBy: any, index: number): - IterableChangeRecord_ { - // The previous record after which we will append the current one. - let previousRecord: IterableChangeRecord_|null; - - if (record === null) { - previousRecord = this._itTail; - } else { - previousRecord = record._prev; - // Remove the record from the collection since we know it does not match the item. - this._remove(record); - } - - // See if we have evicted the item, which used to be at some anterior position of _itHead list. - record = this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); - if (record !== null) { - // It is an item which we have evicted earlier: reinsert it back into the list. - // But first we need to check if identity changed, so we can update in view if necessary. - if (!Object.is(record.item, item)) this._addIdentityChange(record, item); - - this._reinsertAfter(record, previousRecord, index); - } else { - // Attempt to see if the item is at some posterior position of _itHead list. - record = this._linkedRecords === null ? null : this._linkedRecords.get(itemTrackBy, index); - if (record !== null) { - // We have the item in _itHead at/after `index` position. We need to move it forward in the - // collection. - // But first we need to check if identity changed, so we can update in view if necessary. - if (!Object.is(record.item, item)) this._addIdentityChange(record, item); - - this._moveAfter(record, previousRecord, index); - } else { - // It is a new item: add it. - record = - this._addAfter(new IterableChangeRecord_(item, itemTrackBy), previousRecord, index); - } - } - return record; - } - - /** - * This check is only needed if an array contains duplicates. (Short circuit of nothing dirty) - * - * Use case: `[a, a]` => `[b, a, a]` - * - * If we did not have this check then the insertion of `b` would: - * 1) evict first `a` - * 2) insert `b` at `0` index. - * 3) leave `a` at index `1` as is. <-- this is wrong! - * 3) reinsert `a` at index 2. <-- this is wrong! - * - * The correct behavior is: - * 1) evict first `a` - * 2) insert `b` at `0` index. - * 3) reinsert `a` at index 1. - * 3) move `a` at from `1` to `2`. - * - * - * Double check that we have not evicted a duplicate item. We need to check if the item type may - * have already been removed: - * The insertion of b will evict the first 'a'. If we don't reinsert it now it will be reinserted - * at the end. Which will show up as the two 'a's switching position. This is incorrect, since a - * better way to think of it is as insert of 'b' rather then switch 'a' with 'b' and then add 'a' - * at the end. - * - * @internal - */ - _verifyReinsertion(record: IterableChangeRecord_, item: V, itemTrackBy: any, index: number): - IterableChangeRecord_ { - let reinsertRecord: IterableChangeRecord_|null = - this._unlinkedRecords === null ? null : this._unlinkedRecords.get(itemTrackBy, null); - if (reinsertRecord !== null) { - record = this._reinsertAfter(reinsertRecord, record._prev!, index); - } else if (record.currentIndex != index) { - record.currentIndex = index; - this._addToMoves(record, index); - } - return record; - } - - /** - * Get rid of any excess {@link IterableChangeRecord_}s from the previous collection - * - * - `record` The first excess {@link IterableChangeRecord_}. - * - * @internal - */ - _truncate(record: IterableChangeRecord_|null) { - // Anything after that needs to be removed; - while (record !== null) { - const nextRecord: IterableChangeRecord_|null = record._next; - this._addToRemovals(this._unlink(record)); - record = nextRecord; - } - if (this._unlinkedRecords !== null) { - this._unlinkedRecords.clear(); - } - - if (this._additionsTail !== null) { - this._additionsTail._nextAdded = null; - } - if (this._movesTail !== null) { - this._movesTail._nextMoved = null; - } - if (this._itTail !== null) { - this._itTail._next = null; - } - if (this._removalsTail !== null) { - this._removalsTail._nextRemoved = null; - } - if (this._identityChangesTail !== null) { - this._identityChangesTail._nextIdentityChange = null; - } - } - - /** @internal */ - _reinsertAfter( - record: IterableChangeRecord_, prevRecord: IterableChangeRecord_|null, - index: number): IterableChangeRecord_ { - if (this._unlinkedRecords !== null) { - this._unlinkedRecords.remove(record); - } - const prev = record._prevRemoved; - const next = record._nextRemoved; - - if (prev === null) { - this._removalsHead = next; - } else { - prev._nextRemoved = next; - } - if (next === null) { - this._removalsTail = prev; - } else { - next._prevRemoved = prev; - } - - this._insertAfter(record, prevRecord, index); - this._addToMoves(record, index); - return record; - } - - /** @internal */ - _moveAfter( - record: IterableChangeRecord_, prevRecord: IterableChangeRecord_|null, - index: number): IterableChangeRecord_ { - this._unlink(record); - this._insertAfter(record, prevRecord, index); - this._addToMoves(record, index); - return record; - } - - /** @internal */ - _addAfter( - record: IterableChangeRecord_, prevRecord: IterableChangeRecord_|null, - index: number): IterableChangeRecord_ { - this._insertAfter(record, prevRecord, index); - - if (this._additionsTail === null) { - // assert(this._additionsHead === null); - this._additionsTail = this._additionsHead = record; - } else { - // assert(_additionsTail._nextAdded === null); - // assert(record._nextAdded === null); - this._additionsTail = this._additionsTail._nextAdded = record; - } - return record; - } - - /** @internal */ - _insertAfter( - record: IterableChangeRecord_, prevRecord: IterableChangeRecord_|null, - index: number): IterableChangeRecord_ { - - const next: IterableChangeRecord_|null = - prevRecord === null ? this._itHead : prevRecord._next; - record._next = next; - record._prev = prevRecord; - if (next === null) { - this._itTail = record; - } else { - next._prev = record; - } - if (prevRecord === null) { - this._itHead = record; - } else { - prevRecord._next = record; - } - - if (this._linkedRecords === null) { - this._linkedRecords = new _DuplicateMap(); + next._prev = prev; + } + + return record; + } + + /** @internal */ + _addToMoves(record: IterableChangeRecord_, toIndex: number): IterableChangeRecord_ { + if (record.previousIndex === toIndex) { + return record; + } + + if (this._movesTail === null) { + this._movesTail = this._movesHead = record; + } else { + this._movesTail = this._movesTail._nextMoved = record; + } + + return record; } - this._linkedRecords.put(record); - record.currentIndex = index; - return record; - } + private _addToRemovals(record: IterableChangeRecord_): IterableChangeRecord_ { + if (this._unlinkedRecords === null) { + this._unlinkedRecords = new _DuplicateMap(); + } + this._unlinkedRecords.put(record); + record.currentIndex = null; + record._nextRemoved = null; - /** @internal */ - _remove(record: IterableChangeRecord_): IterableChangeRecord_ { - return this._addToRemovals(this._unlink(record)); - } - - /** @internal */ - _unlink(record: IterableChangeRecord_): IterableChangeRecord_ { - if (this._linkedRecords !== null) { - this._linkedRecords.remove(record); - } - - const prev = record._prev; - const next = record._next; - - if (prev === null) { - this._itHead = next; - } else { - prev._next = next; - } - if (next === null) { - this._itTail = prev; - } else { - next._prev = prev; - } - - return record; - } - - /** @internal */ - _addToMoves(record: IterableChangeRecord_, toIndex: number): IterableChangeRecord_ { - if (record.previousIndex === toIndex) { - return record; - } - - if (this._movesTail === null) { - this._movesTail = this._movesHead = record; - } else { - this._movesTail = this._movesTail._nextMoved = record; - } - - return record; - } - - private _addToRemovals(record: IterableChangeRecord_): IterableChangeRecord_ { - if (this._unlinkedRecords === null) { - this._unlinkedRecords = new _DuplicateMap(); - } - this._unlinkedRecords.put(record); - record.currentIndex = null; - record._nextRemoved = null; - - if (this._removalsTail === null) { - this._removalsTail = this._removalsHead = record; - record._prevRemoved = null; - } else { - record._prevRemoved = this._removalsTail; - this._removalsTail = this._removalsTail._nextRemoved = record; + if (this._removalsTail === null) { + this._removalsTail = this._removalsHead = record; + record._prevRemoved = null; + } else { + record._prevRemoved = this._removalsTail; + this._removalsTail = this._removalsTail._nextRemoved = record; + } + return record; } - return record; - } - /** @internal */ - _addIdentityChange(record: IterableChangeRecord_, item: V) { - record.item = item; - if (this._identityChangesTail === null) { - this._identityChangesTail = this._identityChangesHead = record; - } else { - this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record; + /** @internal */ + _addIdentityChange(record: IterableChangeRecord_, item: V) { + record.item = item; + if (this._identityChangesTail === null) { + this._identityChangesTail = this._identityChangesHead = record; + } else { + this._identityChangesTail = this._identityChangesTail._nextIdentityChange = record; + } + return record; } - return record; - } } export class IterableChangeRecord_ implements IterableChangeRecord { - currentIndex: number|null = null; - previousIndex: number|null = null; - - /** @internal */ - _nextPrevious: IterableChangeRecord_|null = null; - /** @internal */ - _prev: IterableChangeRecord_|null = null; - /** @internal */ - _next: IterableChangeRecord_|null = null; - /** @internal */ - _prevDup: IterableChangeRecord_|null = null; - /** @internal */ - _nextDup: IterableChangeRecord_|null = null; - /** @internal */ - _prevRemoved: IterableChangeRecord_|null = null; - /** @internal */ - _nextRemoved: IterableChangeRecord_|null = null; - /** @internal */ - _nextAdded: IterableChangeRecord_|null = null; - /** @internal */ - _nextMoved: IterableChangeRecord_|null = null; - /** @internal */ - _nextIdentityChange: IterableChangeRecord_|null = null; - - - constructor(public item: V, public trackById: any) {} + currentIndex: number | null = null; + previousIndex: number | null = null; + + /** @internal */ + _nextPrevious: IterableChangeRecord_ | null = null; + /** @internal */ + _prev: IterableChangeRecord_ | null = null; + /** @internal */ + _next: IterableChangeRecord_ | null = null; + /** @internal */ + _prevDup: IterableChangeRecord_ | null = null; + /** @internal */ + _nextDup: IterableChangeRecord_ | null = null; + /** @internal */ + _prevRemoved: IterableChangeRecord_ | null = null; + /** @internal */ + _nextRemoved: IterableChangeRecord_ | null = null; + /** @internal */ + _nextAdded: IterableChangeRecord_ | null = null; + /** @internal */ + _nextMoved: IterableChangeRecord_ | null = null; + /** @internal */ + _nextIdentityChange: IterableChangeRecord_ | null = null; + + constructor(public item: V, public trackById: any) {} } // A linked list of IterableChangeRecords with the same IterableChangeRecord_.item class _DuplicateItemRecordList { - /** @internal */ - _head: IterableChangeRecord_|null = null; - /** @internal */ - _tail: IterableChangeRecord_|null = null; - - /** - * Append the record to the list of duplicates. - * - * Note: by design all records in the list of duplicates hold the same value in record.item. - */ - add(record: IterableChangeRecord_): void { - if (this._head === null) { - this._head = this._tail = record; - record._nextDup = null; - record._prevDup = null; - } else { - this._tail!._nextDup = record; - record._prevDup = this._tail; - record._nextDup = null; - this._tail = record; - } - } - - // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and - // IterableChangeRecord_.currentIndex >= atOrAfterIndex - get(trackById: any, atOrAfterIndex: number|null): IterableChangeRecord_|null { - let record: IterableChangeRecord_|null; - for (record = this._head; record !== null; record = record._nextDup) { - if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex!) && - Object.is(record.trackById, trackById)) { - return record; - } - } - return null; - } - - /** - * Remove one {@link IterableChangeRecord_} from the list of duplicates. - * - * Returns whether the list of duplicates is empty. - */ - remove(record: IterableChangeRecord_): boolean { - - const prev: IterableChangeRecord_|null = record._prevDup; - const next: IterableChangeRecord_|null = record._nextDup; - if (prev === null) { - this._head = next; - } else { - prev._nextDup = next; - } - if (next === null) { - this._tail = prev; - } else { - next._prevDup = prev; - } - return this._head === null; - } + /** @internal */ + _head: IterableChangeRecord_ | null = null; + /** @internal */ + _tail: IterableChangeRecord_ | null = null; + + /** + * Append the record to the list of duplicates. + * + * Note: by design all records in the list of duplicates hold the same value in record.item. + */ + add(record: IterableChangeRecord_): void { + if (this._head === null) { + this._head = this._tail = record; + record._nextDup = null; + record._prevDup = null; + } else { + this._tail!._nextDup = record; + record._prevDup = this._tail; + record._nextDup = null; + this._tail = record; + } + } + + // Returns a IterableChangeRecord_ having IterableChangeRecord_.trackById == trackById and + // IterableChangeRecord_.currentIndex >= atOrAfterIndex + get(trackById: any, atOrAfterIndex: number | null): IterableChangeRecord_ | null { + let record: IterableChangeRecord_ | null; + for (record = this._head; record !== null; record = record._nextDup) { + if ((atOrAfterIndex === null || atOrAfterIndex <= record.currentIndex!) && Object.is(record.trackById, trackById)) { + return record; + } + } + return null; + } + + /** + * Remove one {@link IterableChangeRecord_} from the list of duplicates. + * + * Returns whether the list of duplicates is empty. + */ + remove(record: IterableChangeRecord_): boolean { + const prev: IterableChangeRecord_ | null = record._prevDup; + const next: IterableChangeRecord_ | null = record._nextDup; + if (prev === null) { + this._head = next; + } else { + prev._nextDup = next; + } + if (next === null) { + this._tail = prev; + } else { + next._prevDup = prev; + } + return this._head === null; + } } class _DuplicateMap { - map = new Map>(); - - put(record: IterableChangeRecord_) { - const key = record.trackById; - - let duplicates = this.map.get(key); - if (!duplicates) { - duplicates = new _DuplicateItemRecordList(); - this.map.set(key, duplicates); - } - duplicates.add(record); - } - - /** - * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we - * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there. - * - * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we - * have any more `a`s needs to return the second `a`. - */ - get(trackById: any, atOrAfterIndex: number|null): IterableChangeRecord_|null { - const key = trackById; - const recordList = this.map.get(key); - return recordList ? recordList.get(trackById, atOrAfterIndex) : null; - } - - /** - * Removes a {@link IterableChangeRecord_} from the list of duplicates. - * - * The list of duplicates also is removed from the map if it gets empty. - */ - remove(record: IterableChangeRecord_): IterableChangeRecord_ { - const key = record.trackById; - const recordList: _DuplicateItemRecordList = this.map.get(key)!; - // Remove the list of duplicates when it gets empty - if (recordList.remove(record)) { - this.map.delete(key); - } - return record; - } - - get isEmpty(): boolean { - return this.map.size === 0; - } - - clear() { - this.map.clear(); - } + map = new Map>(); + + put(record: IterableChangeRecord_) { + const key = record.trackById; + + let duplicates = this.map.get(key); + if (!duplicates) { + duplicates = new _DuplicateItemRecordList(); + this.map.set(key, duplicates); + } + duplicates.add(record); + } + + /** + * Retrieve the `value` using key. Because the IterableChangeRecord_ value may be one which we + * have already iterated over, we use the `atOrAfterIndex` to pretend it is not there. + * + * Use case: `[a, b, c, a, a]` if we are at index `3` which is the second `a` then asking if we + * have any more `a`s needs to return the second `a`. + */ + get(trackById: any, atOrAfterIndex: number | null): IterableChangeRecord_ | null { + const key = trackById; + const recordList = this.map.get(key); + return recordList ? recordList.get(trackById, atOrAfterIndex) : null; + } + + /** + * Removes a {@link IterableChangeRecord_} from the list of duplicates. + * + * The list of duplicates also is removed from the map if it gets empty. + */ + remove(record: IterableChangeRecord_): IterableChangeRecord_ { + const key = record.trackById; + const recordList: _DuplicateItemRecordList = this.map.get(key)!; + // Remove the list of duplicates when it gets empty + if (recordList.remove(record)) { + this.map.delete(key); + } + return record; + } + + get isEmpty(): boolean { + return this.map.size === 0; + } + + clear() { + this.map.clear(); + } } -function getPreviousIndex(item: any, addRemoveOffset: number, moveOffsets: number[]|null): number { - const previousIndex = item.previousIndex; - if (previousIndex === null) return previousIndex; - let moveOffset = 0; - if (moveOffsets && previousIndex < moveOffsets.length) { - moveOffset = moveOffsets[previousIndex]; - } - return previousIndex + addRemoveOffset + moveOffset; +function getPreviousIndex(item: any, addRemoveOffset: number, moveOffsets: number[] | null): number { + const previousIndex = item.previousIndex; + if (previousIndex === null) return previousIndex; + let moveOffset = 0; + if (moveOffsets && previousIndex < moveOffsets.length) { + moveOffset = moveOffsets[previousIndex]; + } + return previousIndex + addRemoveOffset + moveOffset; } diff --git a/packages/core/src/differs/iterable_differs.ts b/packages/core/src/differs/iterable_differs.ts index f5ad810b2..1bb4afb62 100644 --- a/packages/core/src/differs/iterable_differs.ts +++ b/packages/core/src/differs/iterable_differs.ts @@ -11,7 +11,7 @@ * * @publicApi */ -export type CustomIterable = Array|Iterable; +export type CustomIterable = Array | Iterable; /** * A strategy for tracking changes over time to an iterable. Used by {@link NgForOf} to @@ -20,14 +20,14 @@ export type CustomIterable = Array|Iterable; * @publicApi */ export interface IterableDiffer { - /** - * Compute a difference between the previous state and the new `object` state. - * - * @param object containing the new value. - * @returns an object describing the difference. The return value is only valid until the next - * `diff()` invocation. - */ - diff(object: CustomIterable|undefined|null): IterableChanges|null; + /** + * Compute a difference between the previous state and the new `object` state. + * + * @param object containing the new value. + * @returns an object describing the difference. The return value is only valid until the next + * `diff()` invocation. + */ + diff(object: CustomIterable | undefined | null): IterableChanges | null; } /** @@ -37,53 +37,50 @@ export interface IterableDiffer { * @publicApi */ export interface IterableChanges { - /** - * Iterate over all changes. `IterableChangeRecord` will contain information about changes - * to each item. - */ - forEachItem(fn: (record: IterableChangeRecord) => void): void; + /** + * Iterate over all changes. `IterableChangeRecord` will contain information about changes + * to each item. + */ + forEachItem(fn: (record: IterableChangeRecord) => void): void; - /** - * Iterate over a set of operations which when applied to the original `Iterable` will produce the - * new `Iterable`. - * - * NOTE: These are not necessarily the actual operations which were applied to the original - * `Iterable`, rather these are a set of computed operations which may not be the same as the - * ones applied. - * - * @param record A change which needs to be applied - * @param previousIndex The `IterableChangeRecord#previousIndex` of the `record` refers to the - * original `Iterable` location, where as `previousIndex` refers to the transient location - * of the item, after applying the operations up to this point. - * @param currentIndex The `IterableChangeRecord#currentIndex` of the `record` refers to the - * original `Iterable` location, where as `currentIndex` refers to the transient location - * of the item, after applying the operations up to this point. - */ - forEachOperation( - fn: - (record: IterableChangeRecord, previousIndex: number|null, - currentIndex: number|null) => void): void; + /** + * Iterate over a set of operations which when applied to the original `Iterable` will produce the + * new `Iterable`. + * + * NOTE: These are not necessarily the actual operations which were applied to the original + * `Iterable`, rather these are a set of computed operations which may not be the same as the + * ones applied. + * + * @param record A change which needs to be applied + * @param previousIndex The `IterableChangeRecord#previousIndex` of the `record` refers to the + * original `Iterable` location, where as `previousIndex` refers to the transient location + * of the item, after applying the operations up to this point. + * @param currentIndex The `IterableChangeRecord#currentIndex` of the `record` refers to the + * original `Iterable` location, where as `currentIndex` refers to the transient location + * of the item, after applying the operations up to this point. + */ + forEachOperation(fn: (record: IterableChangeRecord, previousIndex: number | null, currentIndex: number | null) => void): void; - /** - * Iterate over changes in the order of original `Iterable` showing where the original items - * have moved. - */ - forEachPreviousItem(fn: (record: IterableChangeRecord) => void): void; + /** + * Iterate over changes in the order of original `Iterable` showing where the original items + * have moved. + */ + forEachPreviousItem(fn: (record: IterableChangeRecord) => void): void; - /** Iterate over all added items. */ - forEachAddedItem(fn: (record: IterableChangeRecord) => void): void; + /** Iterate over all added items. */ + forEachAddedItem(fn: (record: IterableChangeRecord) => void): void; - /** Iterate over all moved items. */ - forEachMovedItem(fn: (record: IterableChangeRecord) => void): void; + /** Iterate over all moved items. */ + forEachMovedItem(fn: (record: IterableChangeRecord) => void): void; - /** Iterate over all removed items. */ - forEachRemovedItem(fn: (record: IterableChangeRecord) => void): void; + /** Iterate over all removed items. */ + forEachRemovedItem(fn: (record: IterableChangeRecord) => void): void; - /** - * Iterate over all items which had their identity (as computed by the `TrackByFunction`) - * changed. - */ - forEachIdentityChange(fn: (record: IterableChangeRecord) => void): void; + /** + * Iterate over all items which had their identity (as computed by the `TrackByFunction`) + * changed. + */ + forEachIdentityChange(fn: (record: IterableChangeRecord) => void): void; } /** @@ -92,17 +89,17 @@ export interface IterableChanges { * @publicApi */ export interface IterableChangeRecord { - /** Current index of the item in `Iterable` or null if removed. */ - readonly currentIndex: number|null; + /** Current index of the item in `Iterable` or null if removed. */ + readonly currentIndex: number | null; - /** Previous index of the item in `Iterable` or null if added. */ - readonly previousIndex: number|null; + /** Previous index of the item in `Iterable` or null if added. */ + readonly previousIndex: number | null; - /** The item. */ - readonly item: V; + /** The item. */ + readonly item: V; - /** Track by identity as computed by the `TrackByFunction`. */ - readonly trackById: any; + /** Track by identity as computed by the `TrackByFunction`. */ + readonly trackById: any; } /** @@ -150,15 +147,15 @@ export interface IterableChangeRecord { * @publicApi */ export interface TrackByFunction { - // Note: the type parameter `U` enables more accurate template type checking in case a trackBy - // function is declared using a base type of the iterated type. The `U` type gives TypeScript - // additional freedom to infer a narrower type for the `item` parameter type, instead of imposing - // the trackBy's declared item type as the inferred type for `T`. - // See https://github.com/angular/angular/issues/40125 + // Note: the type parameter `U` enables more accurate template type checking in case a trackBy + // function is declared using a base type of the iterated type. The `U` type gives TypeScript + // additional freedom to infer a narrower type for the `item` parameter type, instead of imposing + // the trackBy's declared item type as the inferred type for `T`. + // See https://github.com/angular/angular/issues/40125 - /** - * @param index The index of the item within the iterable. - * @param item The item in the iterable. - */ - (index: number, item: T&U): any; + /** + * @param index The index of the item within the iterable. + * @param item The item in the iterable. + */ + (index: number, item: T & U): any; } diff --git a/packages/core/src/interfaces/group.ts b/packages/core/src/interfaces/group.ts index f76221fb5..48db97bfd 100644 --- a/packages/core/src/interfaces/group.ts +++ b/packages/core/src/interfaces/group.ts @@ -1,4 +1,4 @@ -import { PlaitElement } from "./element"; +import { PlaitElement } from './element'; export interface PlaitGroup extends PlaitElement { type: 'group'; @@ -8,4 +8,4 @@ export const PlaitGroupElement = { isGroup: (value: any): value is PlaitGroup => { return value.type === 'group'; } -} \ No newline at end of file +}; diff --git a/packages/core/src/interfaces/point.ts b/packages/core/src/interfaces/point.ts index 75a6681c2..026123514 100644 --- a/packages/core/src/interfaces/point.ts +++ b/packages/core/src/interfaces/point.ts @@ -13,13 +13,13 @@ export const Point = { return point && otherPoint && Point.isOverHorizontal([point, otherPoint], tolerance); }, isOverHorizontal(points: Point[], tolerance: number = 0) { - return points.every(point => Math.abs(point[1] - points[0][1]) <= tolerance); + return points.every((point) => Math.abs(point[1] - points[0][1]) <= tolerance); }, isVertical(point?: Point, otherPoint?: Point, tolerance = 0) { return point && otherPoint && Point.isOverVertical([point, otherPoint], tolerance); }, isOverVertical(points: Point[], tolerance: number = 0) { - return points.every(point => Math.abs(point[0] - points[0][0]) <= tolerance); + return points.every((point) => Math.abs(point[0] - points[0][0]) <= tolerance); }, isAlign(points: Point[], tolerance: number = 0) { return Point.isOverHorizontal(points, tolerance) || Point.isOverVertical(points, tolerance); diff --git a/packages/core/src/interfaces/rectangle-client.ts b/packages/core/src/interfaces/rectangle-client.ts index 2ddf40ef9..a0abafd14 100644 --- a/packages/core/src/interfaces/rectangle-client.ts +++ b/packages/core/src/interfaces/rectangle-client.ts @@ -64,8 +64,8 @@ export const RectangleClient = { let xMax = -Infinity; let yMax = -Infinity; for (const point of points) { - const xArray = point.map(ele => ele[0]); - const yArray = point.map(ele => ele[1]); + const xArray = point.map((ele) => ele[0]); + const yArray = point.map((ele) => ele[1]); xMin = Math.min(xMin, ...xArray); yMin = Math.min(yMin, ...yArray); xMax = Math.max(xMax, ...xArray); @@ -76,8 +76,8 @@ export const RectangleClient = { return rect; }, getCornerPointsByPoints(points: Point[]) { - const xArray = points.map(ele => ele[0]); - const yArray = points.map(ele => ele[1]); + const xArray = points.map((ele) => ele[0]); + const yArray = points.map((ele) => ele[1]); const xMin = Math.min(...xArray); const xMax = Math.max(...xArray); const yMin = Math.min(...yArray); @@ -167,7 +167,7 @@ export const RectangleClient = { let minY = Number.MAX_VALUE; let maxX = Number.NEGATIVE_INFINITY; let maxY = Number.NEGATIVE_INFINITY; - rectangles.forEach(rect => { + rectangles.forEach((rect) => { minX = Math.min(minX, rect.x); minY = Math.min(minY, rect.y); maxX = Math.max(maxX, rect.x + rect.width); @@ -185,6 +185,6 @@ export const RectangleClient = { function isPointArray(data: Point[] | Point[][]): data is Point[] { return ( Array.isArray(data) && - data.every(item => Array.isArray(item) && item.length === 2 && typeof item[0] === 'number' && typeof item[1] === 'number') + data.every((item) => Array.isArray(item) && item.length === 2 && typeof item[0] === 'number' && typeof item[1] === 'number') ); } diff --git a/packages/core/src/plugins/index.ts b/packages/core/src/plugins/index.ts index 0680db099..79a355c9c 100644 --- a/packages/core/src/plugins/index.ts +++ b/packages/core/src/plugins/index.ts @@ -8,4 +8,4 @@ export * from './with-options'; export * from './with-related-fragment'; export * from './with-selection'; export * from './with-i18n'; -export * from './with-hand'; \ No newline at end of file +export * from './with-hand'; diff --git a/packages/core/src/plugins/with-board.ts b/packages/core/src/plugins/with-board.ts index 7405a1353..1ad5cda08 100644 --- a/packages/core/src/plugins/with-board.ts +++ b/packages/core/src/plugins/with-board.ts @@ -18,7 +18,7 @@ export function withBoard(board: PlaitBoard) { afterContextChange(); } afterChange(); - } + }; return board; } diff --git a/packages/core/src/plugins/with-hotkey.ts b/packages/core/src/plugins/with-hotkey.ts index 83321f485..11b6be6e0 100644 --- a/packages/core/src/plugins/with-hotkey.ts +++ b/packages/core/src/plugins/with-hotkey.ts @@ -14,13 +14,13 @@ export const withHotkey = (board: PlaitBoard) => { let elements: PlaitElement[] = []; depthFirstRecursion( board, - node => { + (node) => { if (PlaitBoard.isBoard(node)) { return; } elements.push(node as PlaitElement); }, - node => { + (node) => { if (PlaitBoard.isBoard(node) || board.isRecursion(node)) { return true; } else { diff --git a/packages/core/src/plugins/with-options.ts b/packages/core/src/plugins/with-options.ts index b17b974c1..72e226610 100644 --- a/packages/core/src/plugins/with-options.ts +++ b/packages/core/src/plugins/with-options.ts @@ -10,7 +10,7 @@ export const withOptions = (board: PlaitBoard) => { const pluginOptions = new Map(); const newBoard = board as PlaitOptionsBoard; - newBoard.getPluginOptions = key => { + newBoard.getPluginOptions = (key) => { return pluginOptions.get(key); }; diff --git a/packages/core/src/plugins/with-related-fragment.ts b/packages/core/src/plugins/with-related-fragment.ts index e3406d7ee..77caff8c6 100644 --- a/packages/core/src/plugins/with-related-fragment.ts +++ b/packages/core/src/plugins/with-related-fragment.ts @@ -13,7 +13,7 @@ export function withRelatedFragment(board: PlaitBoard) { let relatedFragment = board.getRelatedFragment(originData || []); if (relatedFragment) { if (originData?.length) { - relatedFragment = relatedFragment.filter(item => !originData.map(element => element.id).includes(item.id)); + relatedFragment = relatedFragment.filter((item) => !originData.map((element) => element.id).includes(item.id)); } if (relatedFragment.length) { const addition: WritableClipboardContext = { diff --git a/packages/core/src/testing/core/create-board.ts b/packages/core/src/testing/core/create-board.ts index 686719fd4..a512274fb 100644 --- a/packages/core/src/testing/core/create-board.ts +++ b/packages/core/src/testing/core/create-board.ts @@ -12,7 +12,7 @@ export const createTestingBoard = ( options: PlaitBoardOptions = { readonly: false, hideScrollbar: true, disabledScrollOnNonFocus: false } ) => { let board = createBoard(children, options); - plugins.forEach(plugin => { + plugins.forEach((plugin) => { board = plugin(board); }); KEY_TO_ELEMENT_MAP.set(board, new Map()); diff --git a/packages/core/src/testing/core/fake-weak-map.ts b/packages/core/src/testing/core/fake-weak-map.ts index 2ed01f2c9..9bc55049c 100644 --- a/packages/core/src/testing/core/fake-weak-map.ts +++ b/packages/core/src/testing/core/fake-weak-map.ts @@ -13,7 +13,7 @@ export const fakeNodeWeakMap = (object: PlaitNode | PlaitBoard) => { export const clearNodeWeakMap = (object: PlaitNode | PlaitBoard) => { const children = object.children || []; - children.forEach(value => { + children.forEach((value) => { NODE_TO_PARENT.delete(value); NODE_TO_INDEX.delete(value); clearNodeWeakMap(value); diff --git a/packages/core/src/transforms/board.ts b/packages/core/src/transforms/board.ts index 8de56c6ab..68427aa00 100644 --- a/packages/core/src/transforms/board.ts +++ b/packages/core/src/transforms/board.ts @@ -120,7 +120,7 @@ function updateThemeColor(board: PlaitBoard, mode: ThemeColorMode) { mode = mode ?? board.theme.themeColorMode; setTheme(board, { themeColorMode: mode }); - depthFirstRecursion((board as unknown) as PlaitElement, element => { + depthFirstRecursion(board as unknown as PlaitElement, (element) => { board.applyTheme(element); }); } diff --git a/packages/core/src/transforms/element.ts b/packages/core/src/transforms/element.ts index 903c3df18..529094dee 100644 --- a/packages/core/src/transforms/element.ts +++ b/packages/core/src/transforms/element.ts @@ -5,7 +5,7 @@ import { removeNode } from './node'; export const removeElements = (board: PlaitBoard, elements: PlaitElement[]) => { elements - .map(element => { + .map((element) => { const path = PlaitBoard.findPath(board, element); const ref = board.pathRef(path); return () => { @@ -14,7 +14,7 @@ export const removeElements = (board: PlaitBoard, elements: PlaitElement[]) => { removeSelectedElement(board, element, true); }; }) - .forEach(action => { + .forEach((action) => { action(); }); }; diff --git a/packages/core/src/transforms/group.spec.ts b/packages/core/src/transforms/group.spec.ts index 87cac8e91..b61cfd2d0 100644 --- a/packages/core/src/transforms/group.spec.ts +++ b/packages/core/src/transforms/group.spec.ts @@ -133,7 +133,7 @@ describe('group transform', () => { addSelectedElement(board, children); GroupTransforms.addGroup(board); expect(board.children.length).toBe(8); - const groups = board.children.filter(item => PlaitGroupElement.isGroup(item)); + const groups = board.children.filter((item) => PlaitGroupElement.isGroup(item)); expect(groups.length).toBe(3); const lastElement = board.children[board.children.length - 1]; expect(lastElement.groupId).toBe(undefined); @@ -153,7 +153,7 @@ describe('group transform', () => { addSelectedElement(board, children); GroupTransforms.removeGroup(board); expect(board.children.length).toBe(5); - const elementIngroup = board.children.filter(item => item.groupId); + const elementIngroup = board.children.filter((item) => item.groupId); expect(elementIngroup.length).toBe(0); }); diff --git a/packages/core/src/transforms/group.ts b/packages/core/src/transforms/group.ts index bd87cb048..db2437ea6 100644 --- a/packages/core/src/transforms/group.ts +++ b/packages/core/src/transforms/group.ts @@ -21,7 +21,7 @@ export const addGroup = (board: PlaitBoard, elements?: PlaitElement[]) => { const highestSelectedElements = [...selectedGroups, ...selectedIsolatedElements]; const group = createGroup(); if (canAddGroup(board)) { - highestSelectedElements.forEach(item => { + highestSelectedElements.forEach((item) => { const path = PlaitBoard.findPath(board, item); NodeTransforms.setNode(board, { groupId: group.id }, path); }); @@ -51,18 +51,18 @@ export const addGroup = (board: PlaitBoard, elements?: PlaitElement[]) => { export const removeGroup = (board: PlaitBoard, elements?: PlaitElement[]) => { const selectedGroups = getHighestSelectedGroups(board, elements); if (canRemoveGroup(board)) { - selectedGroups.forEach(group => { + selectedGroups.forEach((group) => { const elementsInGroup = findElements(board, { - match: item => item.groupId === group.id, + match: (item) => item.groupId === group.id, recursion: () => false }); - elementsInGroup.forEach(element => { + elementsInGroup.forEach((element) => { const path = PlaitBoard.findPath(board, element); NodeTransforms.setNode(board, { groupId: group.groupId || undefined }, path); }); }); selectedGroups - .map(group => { + .map((group) => { const groupPath = PlaitBoard.findPath(board, group); const groupRef = board.pathRef(groupPath); return () => { @@ -70,7 +70,7 @@ export const removeGroup = (board: PlaitBoard, elements?: PlaitElement[]) => { groupRef.unref(); }; }) - .forEach(action => { + .forEach((action) => { action(); }); } diff --git a/packages/core/src/transforms/selection.ts b/packages/core/src/transforms/selection.ts index 4194d77a6..0350f9f22 100644 --- a/packages/core/src/transforms/selection.ts +++ b/packages/core/src/transforms/selection.ts @@ -28,7 +28,7 @@ export function addSelectionWithTemporaryElements(board: PlaitBoard, elements: P if (ref) { clearTimeout(ref.timeoutId); const currentElements = ref.elements; - ref.elements.push(...elements.filter(element => !currentElements.includes(element))); + ref.elements.push(...elements.filter((element) => !currentElements.includes(element))); ref.timeoutId = timeoutId; } else { BOARD_TO_TEMPORARY_ELEMENTS.set(board, { timeoutId, elements }); diff --git a/packages/core/src/utils/clipboard/navigator-clipboard.ts b/packages/core/src/utils/clipboard/navigator-clipboard.ts index f61bdb8f2..37a0a3516 100644 --- a/packages/core/src/utils/clipboard/navigator-clipboard.ts +++ b/packages/core/src/utils/clipboard/navigator-clipboard.ts @@ -31,11 +31,11 @@ export const getNavigatorClipboard = async (): Promise => { if (Array.isArray(clipboardItems) && clipboardItems[0] instanceof ClipboardItem) { for (const item of clipboardItems) { if (isFile(item)) { - const clipboardFiles = item.types.filter(type => type.match(/^image\//)); - const fileBlobs = await Promise.all(clipboardFiles.map(type => item.getType(type)!)); - const urls = (fileBlobs.filter(Boolean) as (File | Blob)[]).map(blob => URL.createObjectURL(blob)); + const clipboardFiles = item.types.filter((type) => type.match(/^image\//)); + const fileBlobs = await Promise.all(clipboardFiles.map((type) => item.getType(type)!)); + const urls = (fileBlobs.filter(Boolean) as (File | Blob)[]).map((blob) => URL.createObjectURL(blob)); const files = await Promise.all( - urls.map(async url => { + urls.map(async (url) => { const blob = await (await fetch(url)).blob(); return new File([blob], 'plait-file', { type: blob.type }); }) @@ -66,7 +66,7 @@ export const getNavigatorClipboard = async (): Promise => { }; const isFile = (item: ClipboardItem) => { - return item.types.find(i => i.match(/^image\//)); + return item.types.find((i) => i.match(/^image\//)); }; const blobAsString = (blob: Blob) => { diff --git a/packages/core/src/utils/common.ts b/packages/core/src/utils/common.ts index 456f925e8..3c2555c9c 100644 --- a/packages/core/src/utils/common.ts +++ b/packages/core/src/utils/common.ts @@ -64,10 +64,10 @@ export const debounce = (func: (args?: T) => void, wait: number, options?: { export const getElementsIndices = (board: PlaitBoard, elements: PlaitElement[]): number[] => { sortElements(board, elements); return elements - .map(item => { - return board.children.map(item => item.id).indexOf(item.id); + .map((item) => { + return board.children.map((item) => item.id).indexOf(item.id); }) - .filter(item => item >= 0); + .filter((item) => item >= 0); }; export const getHighestIndexOfElement = (board: PlaitBoard, elements: PlaitElement[]) => { @@ -77,7 +77,7 @@ export const getHighestIndexOfElement = (board: PlaitBoard, elements: PlaitEleme export const moveElementsToNewPath = (board: PlaitBoard, moveOptions: MoveNodeOption[]) => { moveOptions - .map(item => { + .map((item) => { const path = PlaitBoard.findPath(board, item.element); const ref = board.pathRef(path); return () => { @@ -85,7 +85,7 @@ export const moveElementsToNewPath = (board: PlaitBoard, moveOptions: MoveNodeOp ref.unref(); }; }) - .forEach(action => { + .forEach((action) => { action(); }); }; diff --git a/packages/core/src/utils/dnd.ts b/packages/core/src/utils/dnd.ts index 14aba3724..825207bff 100644 --- a/packages/core/src/utils/dnd.ts +++ b/packages/core/src/utils/dnd.ts @@ -1,12 +1,11 @@ -import { PlaitBoard } from "../interfaces/board"; +import { PlaitBoard } from '../interfaces/board'; export const IS_DRAGGING = new WeakMap(); - export const isDragging = (board: PlaitBoard) => { return !!IS_DRAGGING.get(board); }; export const setDragging = (board: PlaitBoard, state: boolean) => { IS_DRAGGING.set(board, state); -} \ No newline at end of file +}; diff --git a/packages/core/src/utils/dom/common.ts b/packages/core/src/utils/dom/common.ts index e1d7df3b3..301aa891e 100644 --- a/packages/core/src/utils/dom/common.ts +++ b/packages/core/src/utils/dom/common.ts @@ -32,7 +32,7 @@ export const setStrokeLinecap = (g: SVGGElement, value: 'round' | 'square') => { }; export const setPathStrokeLinecap = (g: SVGGElement, value: 'round' | 'square') => { - g.querySelectorAll('path').forEach(path => { + g.querySelectorAll('path').forEach((path) => { path.setAttribute('stroke-linecap', value); }); }; diff --git a/packages/core/src/utils/element.ts b/packages/core/src/utils/element.ts index 1048c9321..be8fa7dad 100644 --- a/packages/core/src/utils/element.ts +++ b/packages/core/src/utils/element.ts @@ -15,12 +15,12 @@ export function getRectangleByElements(board: PlaitBoard, elements: PlaitElement console.error(`can not get rectangle of element:`, node); } }; - elements.forEach(element => { + elements.forEach((element) => { if (recursion) { depthFirstRecursion( element, - node => callback(node), - node => board.isRecursion(node) + (node) => callback(node), + (node) => board.isRecursion(node) ); } else { callback(element); @@ -66,9 +66,9 @@ export function getElementById( return cachedElement as T; } if (!dataSource) { - dataSource = findElements(board, { match: element => true, recursion: element => true }); + dataSource = findElements(board, { match: (element) => true, recursion: (element) => true }); } - let element = dataSource.find(element => element.id === id) as T; + let element = dataSource.find((element) => element.id === id) as T; return element; } @@ -92,7 +92,7 @@ export function findElements( const isReverse = options.isReverse ?? true; depthFirstRecursion( board, - node => { + (node) => { if (!PlaitBoard.isBoard(node) && options.match(node)) { elements.push(node as T); } diff --git a/packages/core/src/utils/environment.ts b/packages/core/src/utils/environment.ts index 79ef348df..817f2a251 100644 --- a/packages/core/src/utils/environment.ts +++ b/packages/core/src/utils/environment.ts @@ -18,4 +18,4 @@ export const IS_CHROME = typeof navigator !== 'undefined' && /Chrome/i.test(navi // Native beforeInput events don't work well with react on Chrome 75 and older, Chrome 76+ can use beforeInput export const IS_CHROME_LEGACY = typeof navigator !== 'undefined' && /Chrome?\/(?:[0-7][0-5]|[0-6][0-9])/i.test(navigator.userAgent); -export const IS_WINDOWS = typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent); \ No newline at end of file +export const IS_WINDOWS = typeof navigator !== 'undefined' && /Windows/.test(navigator.userAgent); diff --git a/packages/core/src/utils/helper.ts b/packages/core/src/utils/helper.ts index fd80cb743..5ef9c68ac 100644 --- a/packages/core/src/utils/helper.ts +++ b/packages/core/src/utils/helper.ts @@ -29,7 +29,7 @@ export function isContextmenu(event: MouseEvent) { export function uniqueById(elements: PlaitElement[]) { const uniqueMap = new Map(); - elements.forEach(item => { + elements.forEach((item) => { if (!uniqueMap.has(item.id)) { uniqueMap.set(item.id, item); } diff --git a/packages/core/src/utils/id-creator.ts b/packages/core/src/utils/id-creator.ts index 2e7b4db79..d7fa22258 100644 --- a/packages/core/src/utils/id-creator.ts +++ b/packages/core/src/utils/id-creator.ts @@ -1,6 +1,7 @@ export function idCreator(length = 5) { // remove numeral - const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'; /**** Easily confusing characters are removed by default oOLl,9gq,Vv,Uu,I1****/ + const $chars = + 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz'; /**** Easily confusing characters are removed by default oOLl,9gq,Vv,Uu,I1****/ const maxPosition = $chars.length; let key = ''; for (let i = 0; i < length; i++) { diff --git a/packages/core/src/utils/index.ts b/packages/core/src/utils/index.ts index 53fb8403d..48a518aa4 100644 --- a/packages/core/src/utils/index.ts +++ b/packages/core/src/utils/index.ts @@ -31,4 +31,4 @@ export * from './fragment'; export * from './snap/snap'; export * from './z-index'; export * from './position'; -export * from './pointer'; \ No newline at end of file +export * from './pointer'; diff --git a/packages/core/src/utils/math.spec.ts b/packages/core/src/utils/math.spec.ts index 6281618cf..af948726a 100644 --- a/packages/core/src/utils/math.spec.ts +++ b/packages/core/src/utils/math.spec.ts @@ -1,5 +1,5 @@ -import { Point } from "../interfaces"; -import { isLineHitLine } from "./math"; +import { Point } from '../interfaces'; +import { isLineHitLine } from './math'; describe('math', () => { describe('isLineHitLine', () => { @@ -8,7 +8,7 @@ describe('math', () => { const p2 = [0, 0] as Point; const p3 = [1, 2] as Point; const p4 = [1, 2] as Point; - const isHit = isLineHitLine(p1, p2, p3,p4); + const isHit = isLineHitLine(p1, p2, p3, p4); expect(isHit).toEqual(false); }); }); diff --git a/packages/core/src/utils/snap/snap-moving.ts b/packages/core/src/utils/snap/snap-moving.ts index 2c7be82f9..49c15a18a 100644 --- a/packages/core/src/utils/snap/snap-moving.ts +++ b/packages/core/src/utils/snap/snap-moving.ts @@ -107,7 +107,7 @@ function getGapLinesAndDelta(activeRectangle: RectangleClient, snapRectangles: R const side = isHorizontal ? 'width' : 'height'; const activeRectangleCenter = activeRectangle[axis] + activeRectangle[side] / 2; - snapRectangles.forEach(rec => { + snapRectangles.forEach((rec) => { const isCross = isHorizontal ? isHorizontalCross(rec, activeRectangle) : isVerticalCross(rec, activeRectangle); if (isCross && !RectangleClient.isHit(rec, activeRectangle)) { rectangles.push(rec); diff --git a/packages/core/src/utils/snap/snap.ts b/packages/core/src/utils/snap/snap.ts index 44f8da8bf..b1febbbaa 100644 --- a/packages/core/src/utils/snap/snap.ts +++ b/packages/core/src/utils/snap/snap.ts @@ -31,11 +31,11 @@ const SNAP_SPACING = 24; export function getSnapRectangles(board: PlaitBoard, activeElements: PlaitElement[]) { const elements = findElements(board, { - match: element => board.isAlign(element) && !activeElements.some(item => item.id === element.id), + match: (element) => board.isAlign(element) && !activeElements.some((item) => item.id === element.id), recursion: () => true, isReverse: false }); - return elements.map(item => { + return elements.map((item) => { const rectangle = board.getRectangle(item)!; return getRectangleByAngle(rectangle, item.angle || 0); }); @@ -55,7 +55,7 @@ export function getBarPoint(point: Point, isHorizontal: boolean) { export function getMinPointDelta(pointRectangles: RectangleClient[], axis: number, isHorizontal: boolean) { let delta = SNAP_TOLERANCE; - pointRectangles.forEach(item => { + pointRectangles.forEach((item) => { const distance = getNearestDelta(axis, item, isHorizontal); if (Math.abs(distance) < Math.abs(delta)) { delta = distance; @@ -66,8 +66,8 @@ export function getMinPointDelta(pointRectangles: RectangleClient[], axis: numbe export const getNearestDelta = (axis: number, rectangle: RectangleClient, isHorizontal: boolean) => { const pointAxis = getTripleAxis(rectangle, isHorizontal); - const deltas = pointAxis.map(item => item - axis); - const absDeltas = deltas.map(item => Math.abs(item)); + const deltas = pointAxis.map((item) => item - axis); + const absDeltas = deltas.map((item) => Math.abs(item)); const index = absDeltas.indexOf(Math.min(...absDeltas)); return deltas[index]; }; @@ -82,7 +82,7 @@ export function getNearestPointRectangle(snapRectangles: RectangleClient[], acti let minDistance = Infinity; let nearestRectangle = snapRectangles[0]; - snapRectangles.forEach(item => { + snapRectangles.forEach((item) => { const distance = Math.sqrt(Math.pow(activeRectangle.x - item.x, 2) + Math.pow(activeRectangle.y - item.y, 2)); if (distance < minDistance) { minDistance = distance; @@ -229,7 +229,7 @@ export function drawPointSnapLines( export function drawDashedLines(board: PlaitBoard, lines: [Point, Point][]) { const g = createG(); - lines.forEach(points => { + lines.forEach((points) => { if (!points.length) return; const line = PlaitBoard.getRoughSVG(board).line(points[0][0], points[0][1], points[1][0], points[1][1], { stroke: SELECTION_BORDER_COLOR, @@ -243,7 +243,7 @@ export function drawDashedLines(board: PlaitBoard, lines: [Point, Point][]) { export function drawSolidLines(board: PlaitBoard, lines: Point[][]) { const g = createG(); - lines.forEach(points => { + lines.forEach((points) => { if (!points.length) return; let isHorizontal = points[0][1] === points[1][1]; const line = PlaitBoard.getRoughSVG(board).line(points[0][0], points[0][1], points[1][0], points[1][1], { @@ -252,7 +252,7 @@ export function drawSolidLines(board: PlaitBoard, lines: Point[][]) { }); g.appendChild(line); - points.forEach(point => { + points.forEach((point) => { const barPoint = getBarPoint(point, isHorizontal); const bar = PlaitBoard.getRoughSVG(board).line(barPoint[0][0], barPoint[0][1], barPoint[1][0], barPoint[1][1], { stroke: SELECTION_BORDER_COLOR, diff --git a/packages/core/src/utils/tree.ts b/packages/core/src/utils/tree.ts index ce4952713..153380917 100644 --- a/packages/core/src/utils/tree.ts +++ b/packages/core/src/utils/tree.ts @@ -10,7 +10,7 @@ export function depthFirstRecursion( if (node.children && (!recursion || recursion(node))) { let children: TreeNode[] = [...node.children]; children = isReverse ? children.reverse() : children; - children.forEach(child => { + children.forEach((child) => { depthFirstRecursion(child as T, callback, recursion); }); } diff --git a/packages/core/src/utils/z-index.ts b/packages/core/src/utils/z-index.ts index 3c0ec3f30..57662d346 100644 --- a/packages/core/src/utils/z-index.ts +++ b/packages/core/src/utils/z-index.ts @@ -24,7 +24,7 @@ export const getOneMoveOptions = (board: PlaitBoard, direction: 'down' | 'up'): indices = indices.reverse(); } moveContents.push( - ...indices.map(path => { + ...indices.map((path) => { return { element: board.children[path], newPath: [targetIndex] @@ -43,7 +43,7 @@ export const getAllMoveOptions = (board: PlaitBoard, direction: 'down' | 'up'): if (direction === 'down') { groupedIndices = groupedIndices.reverse(); } - groupedIndices.forEach(indices => { + groupedIndices.forEach((indices) => { const leadingIndex = indices[0]; const trailingIndex = indices[indices.length - 1]; const boundaryIndex = direction === 'down' ? leadingIndex : trailingIndex; @@ -61,7 +61,7 @@ export const getAllMoveOptions = (board: PlaitBoard, direction: 'down' | 'up'): indices = indices.reverse(); } moveContents.push( - ...indices.map(path => { + ...indices.map((path) => { return { element: board.children[path], newPath: [targetIndex] @@ -74,7 +74,7 @@ export const getAllMoveOptions = (board: PlaitBoard, direction: 'down' | 'up'): }; export const canSetZIndex = (board: PlaitBoard) => { - const selectedElements = getSelectedElements(board).filter(item => board.canSetZIndex(item)); + const selectedElements = getSelectedElements(board).filter((item) => board.canSetZIndex(item)); return selectedElements.length > 0; }; @@ -132,8 +132,8 @@ const getTargetIndex = (board: PlaitBoard, boundaryIndex: number, direction: 'do }; const candidateIndex = direction === 'down' - ? findLastIndex(board.children, el => indexFilter(el), Math.max(0, boundaryIndex - 1)) - : findIndex(board.children, el => indexFilter(el), boundaryIndex + 1); + ? findLastIndex(board.children, (el) => indexFilter(el), Math.max(0, boundaryIndex - 1)) + : findIndex(board.children, (el) => indexFilter(el), boundaryIndex + 1); const nextElement = board.children[candidateIndex]; if (!nextElement) { @@ -147,7 +147,7 @@ const getTargetIndex = (board: PlaitBoard, boundaryIndex: number, direction: 'do // candidate element is a sibling in current editing group → return if (editingGroup && sourceElement?.groupId !== nextElement?.groupId) { // candidate element is outside current editing group → prevent - if (!(nextElementGroups as PlaitGroup[]).find(item => item.id === editingGroup.id)) { + if (!(nextElementGroups as PlaitGroup[]).find((item) => item.id === editingGroup.id)) { return -1; } } @@ -166,8 +166,8 @@ const getTargetIndex = (board: PlaitBoard, boundaryIndex: number, direction: 'do let elementsInSiblingGroup = getElementsInGroup(board, siblingGroup, true, false); if (elementsInSiblingGroup.length) { elementsInSiblingGroup.sort((a, b) => { - const indexA = board.children.findIndex(child => child.id === a.id); - const indexB = board.children.findIndex(child => child.id === b.id); + const indexA = board.children.findIndex((child) => child.id === a.id); + const indexB = board.children.findIndex((child) => child.id === b.id); return indexA - indexB; }); // assumes getElementsInGroup() returned elements are sorted diff --git a/packages/draw/src/constants/default.ts b/packages/draw/src/constants/default.ts index c50786628..c436a9102 100644 --- a/packages/draw/src/constants/default.ts +++ b/packages/draw/src/constants/default.ts @@ -3,4 +3,4 @@ export const WithDrawPluginKey = 'plait-draw-plugin-key'; export enum DrawI18nKey { lineText = 'line-text', geometryText = 'geometry-text' -} \ No newline at end of file +} diff --git a/packages/draw/src/constants/index.ts b/packages/draw/src/constants/index.ts index 6ce5f2f87..0532aee4b 100644 --- a/packages/draw/src/constants/index.ts +++ b/packages/draw/src/constants/index.ts @@ -5,4 +5,4 @@ export * from './image'; export * from './theme'; export * from './swimlane'; export * from './text'; -export * from './line'; \ No newline at end of file +export * from './line'; diff --git a/packages/draw/src/engines/basic-shapes/polygon.ts b/packages/draw/src/engines/basic-shapes/polygon.ts index 223928b47..c572689fe 100644 --- a/packages/draw/src/engines/basic-shapes/polygon.ts +++ b/packages/draw/src/engines/basic-shapes/polygon.ts @@ -45,7 +45,7 @@ export function createPolygonEngine(options: CreateOptions): ShapeEngine { let nearestDistance = distanceBetweenPointAndPoint(point[0], point[1], nearestPoint[0], nearestPoint[1]); crossingPoints .filter((v, index) => index > 0) - .forEach(crossingPoint => { + .forEach((crossingPoint) => { let distance = distanceBetweenPointAndPoint(point[0], point[1], crossingPoint[0], crossingPoint[1]); if (distance < nearestDistance) { nearestDistance = distance; diff --git a/packages/draw/src/engines/flowchart/delay.ts b/packages/draw/src/engines/flowchart/delay.ts index 633afaee5..b2abb3354 100644 --- a/packages/draw/src/engines/flowchart/delay.ts +++ b/packages/draw/src/engines/flowchart/delay.ts @@ -18,10 +18,11 @@ export const DelayEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( - `M${rectangle.x} ${rectangle.y} L${rectangle.x + (rectangle.width * 3) / 4} ${rectangle.y} A ${rectangle.width / - 4} ${rectangle.height / 2}, 0, 0, 1,${rectangle.x + (rectangle.width * 3) / 4} ${rectangle.y + rectangle.height} L${ - rectangle.x - } ${rectangle.y + rectangle.height} Z`, + `M${rectangle.x} ${rectangle.y} L${rectangle.x + (rectangle.width * 3) / 4} ${rectangle.y} A ${rectangle.width / 4} ${ + rectangle.height / 2 + }, 0, 0, 1,${rectangle.x + (rectangle.width * 3) / 4} ${rectangle.y + rectangle.height} L${rectangle.x} ${ + rectangle.y + rectangle.height + } Z`, { ...options, fillStyle: 'solid' } ); setStrokeLinecap(shape, 'round'); diff --git a/packages/draw/src/engines/flowchart/display.ts b/packages/draw/src/engines/flowchart/display.ts index 7bfc909b7..009f14ad2 100644 --- a/packages/draw/src/engines/flowchart/display.ts +++ b/packages/draw/src/engines/flowchart/display.ts @@ -32,9 +32,9 @@ export const DisplayEngine: ShapeEngine = { const shape = rs.path( `M${rectangle.x + rectangle.width * 0.15} ${rectangle.y} H${rectangle.x + rectangle.width - rectangle.width * 0.1} - A ${rectangle.width * 0.1} ${rectangle.height / 2}, 0, 0, 1,${rectangle.x + - rectangle.width - - rectangle.width * 0.1} ${rectangle.y + rectangle.height} + A ${rectangle.width * 0.1} ${rectangle.height / 2}, 0, 0, 1,${rectangle.x + rectangle.width - rectangle.width * 0.1} ${ + rectangle.y + rectangle.height + } H${rectangle.x + rectangle.width * 0.15} L${rectangle.x} ${rectangle.y + rectangle.height / 2} Z diff --git a/packages/draw/src/engines/flowchart/document.ts b/packages/draw/src/engines/flowchart/document.ts index bff6e0b1b..29e285c56 100644 --- a/packages/draw/src/engines/flowchart/document.ts +++ b/packages/draw/src/engines/flowchart/document.ts @@ -20,13 +20,14 @@ export const DocumentEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( - `M${rectangle.x} ${rectangle.y + rectangle.height - rectangle.height / 9} V${rectangle.y} H${rectangle.x + - rectangle.width} V${rectangle.y + rectangle.height - rectangle.height / 9} - Q${rectangle.x + rectangle.width - rectangle.width / 4} ${rectangle.y + - rectangle.height - - (rectangle.height / 9) * 3}, ${rectangle.x + rectangle.width / 2} ${rectangle.y + - rectangle.height - - rectangle.height / 9} T${rectangle.x} ${rectangle.y + rectangle.height - rectangle.height / 9} + `M${rectangle.x} ${rectangle.y + rectangle.height - rectangle.height / 9} V${rectangle.y} H${rectangle.x + rectangle.width} V${ + rectangle.y + rectangle.height - rectangle.height / 9 + } + Q${rectangle.x + rectangle.width - rectangle.width / 4} ${rectangle.y + rectangle.height - (rectangle.height / 9) * 3}, ${ + rectangle.x + rectangle.width / 2 + } ${rectangle.y + rectangle.height - rectangle.height / 9} T${rectangle.x} ${ + rectangle.y + rectangle.height - rectangle.height / 9 + } `, { ...options, fillStyle: 'solid' } ); diff --git a/packages/draw/src/engines/flowchart/hard-disk.ts b/packages/draw/src/engines/flowchart/hard-disk.ts index 2237e983b..246cc5123 100644 --- a/packages/draw/src/engines/flowchart/hard-disk.ts +++ b/packages/draw/src/engines/flowchart/hard-disk.ts @@ -22,15 +22,16 @@ export const HardDiskEngine: ShapeEngine = { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( `M${rectangle.x + rectangle.width - rectangle.width * 0.15} ${rectangle.y} - A${rectangle.width * 0.15} ${rectangle.height / 2}, 0, 0, 0,${rectangle.x + - rectangle.width - - rectangle.width * 0.15} ${rectangle.y + rectangle.height} + A${rectangle.width * 0.15} ${rectangle.height / 2}, 0, 0, 0,${rectangle.x + rectangle.width - rectangle.width * 0.15} ${ + rectangle.y + rectangle.height + } A${rectangle.width * 0.15} ${rectangle.height / 2}, 0, 0, 0,${rectangle.x + rectangle.width - rectangle.width * 0.15} ${ rectangle.y } H${rectangle.x + rectangle.width * 0.15} - A${rectangle.width * 0.15} ${rectangle.height / 2}, 0, 0, 0, ${rectangle.x + rectangle.width * 0.15} ${rectangle.y + - rectangle.height} + A${rectangle.width * 0.15} ${rectangle.height / 2}, 0, 0, 0, ${rectangle.x + rectangle.width * 0.15} ${ + rectangle.y + rectangle.height + } H${rectangle.x + rectangle.width - rectangle.width * 0.15}`, { ...options, fillStyle: 'solid' } ); diff --git a/packages/draw/src/engines/flowchart/internal-storage.ts b/packages/draw/src/engines/flowchart/internal-storage.ts index ec1fbd4a5..aa079bc2d 100644 --- a/packages/draw/src/engines/flowchart/internal-storage.ts +++ b/packages/draw/src/engines/flowchart/internal-storage.ts @@ -55,7 +55,10 @@ export const InternalStorageEngine: ShapeEngine = { height: textSize.height, width: width > 0 ? width : 0, x: elementRectangle.x + elementRectangle.width * 0.1 + ShapeDefaultSpace.rectangleAndText + strokeWidth, - y: elementRectangle.y + elementRectangle.height * 0.1 + (elementRectangle.height - elementRectangle.height * 0.1 - textSize.height) / 2 + y: + elementRectangle.y + + elementRectangle.height * 0.1 + + (elementRectangle.height - elementRectangle.height * 0.1 - textSize.height) / 2 }; } }; diff --git a/packages/draw/src/engines/flowchart/note-square.ts b/packages/draw/src/engines/flowchart/note-square.ts index e289dbca1..dfa168026 100644 --- a/packages/draw/src/engines/flowchart/note-square.ts +++ b/packages/draw/src/engines/flowchart/note-square.ts @@ -18,8 +18,9 @@ export const NoteSquareEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( - `M${rectangle.x + rectangle.width * 0.075} ${rectangle.y + rectangle.height} H${rectangle.x} V${rectangle.y} H${rectangle.x + - rectangle.width * 0.075} + `M${rectangle.x + rectangle.width * 0.075} ${rectangle.y + rectangle.height} H${rectangle.x} V${rectangle.y} H${ + rectangle.x + rectangle.width * 0.075 + } `, { ...options, fillStyle: 'solid', fill: 'transparent' } ); diff --git a/packages/draw/src/engines/flowchart/predefined-process.ts b/packages/draw/src/engines/flowchart/predefined-process.ts index d6bccf025..c1fdd75e9 100644 --- a/packages/draw/src/engines/flowchart/predefined-process.ts +++ b/packages/draw/src/engines/flowchart/predefined-process.ts @@ -18,12 +18,11 @@ export const PredefinedProcessEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( - `M${rectangle.x} ${rectangle.y} H${rectangle.x + rectangle.width} V${rectangle.y + rectangle.height} H${ - rectangle.x - } Z M${rectangle.x + rectangle.width * 0.06} ${rectangle.y} L${rectangle.x + rectangle.width * 0.06} ${rectangle.y + - rectangle.height} M${rectangle.x + rectangle.width - rectangle.width * 0.06} ${rectangle.y} L${rectangle.x + - rectangle.width - - rectangle.width * 0.06} ${rectangle.y + rectangle.height}`, + `M${rectangle.x} ${rectangle.y} H${rectangle.x + rectangle.width} V${rectangle.y + rectangle.height} H${rectangle.x} Z M${ + rectangle.x + rectangle.width * 0.06 + } ${rectangle.y} L${rectangle.x + rectangle.width * 0.06} ${rectangle.y + rectangle.height} M${ + rectangle.x + rectangle.width - rectangle.width * 0.06 + } ${rectangle.y} L${rectangle.x + rectangle.width - rectangle.width * 0.06} ${rectangle.y + rectangle.height}`, { ...options, fillStyle: 'solid' } ); setStrokeLinecap(shape, 'round'); diff --git a/packages/draw/src/engines/uml/activity-class.ts b/packages/draw/src/engines/uml/activity-class.ts index d595b5f36..cdb7c7ff4 100644 --- a/packages/draw/src/engines/uml/activity-class.ts +++ b/packages/draw/src/engines/uml/activity-class.ts @@ -18,12 +18,11 @@ export const ActiveClassEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( - `M${rectangle.x} ${rectangle.y} H${rectangle.x + rectangle.width} V${rectangle.y + rectangle.height} H${ - rectangle.x - } Z M${rectangle.x + rectangle.width * 0.125} ${rectangle.y} L${rectangle.x + rectangle.width * 0.125} ${rectangle.y + - rectangle.height} M${rectangle.x + rectangle.width - rectangle.width * 0.125} ${rectangle.y} L${rectangle.x + - rectangle.width - - rectangle.width * 0.125} ${rectangle.y + rectangle.height}`, + `M${rectangle.x} ${rectangle.y} H${rectangle.x + rectangle.width} V${rectangle.y + rectangle.height} H${rectangle.x} Z M${ + rectangle.x + rectangle.width * 0.125 + } ${rectangle.y} L${rectangle.x + rectangle.width * 0.125} ${rectangle.y + rectangle.height} M${ + rectangle.x + rectangle.width - rectangle.width * 0.125 + } ${rectangle.y} L${rectangle.x + rectangle.width - rectangle.width * 0.125} ${rectangle.y + rectangle.height}`, { ...options, fillStyle: 'solid' } ); setStrokeLinecap(shape, 'round'); diff --git a/packages/draw/src/engines/uml/assembly.ts b/packages/draw/src/engines/uml/assembly.ts index 0e583a9c5..d4ac55799 100644 --- a/packages/draw/src/engines/uml/assembly.ts +++ b/packages/draw/src/engines/uml/assembly.ts @@ -71,7 +71,9 @@ export const AssemblyEngine: ShapeEngine = { `M${startPoint[0]} ${startPoint[1]}`, `H${line1[1][0]}`, // 画完整的圆形:先画一个半圆,再画另一个半圆 - `A${circleArcCommand.rx} ${circleArcCommand.ry} ${circleArcCommand.xAxisRotation} ${circleArcCommand.largeArcFlag} ${circleArcCommand.sweepFlag} ${line1[1][0] + circleArcCommand.rx * 2} ${circleArcCommand.endY}`, + `A${circleArcCommand.rx} ${circleArcCommand.ry} ${circleArcCommand.xAxisRotation} ${circleArcCommand.largeArcFlag} ${ + circleArcCommand.sweepFlag + } ${line1[1][0] + circleArcCommand.rx * 2} ${circleArcCommand.endY}`, `A${circleArcCommand.rx} ${circleArcCommand.ry} ${circleArcCommand.xAxisRotation} ${circleArcCommand.largeArcFlag} ${circleArcCommand.sweepFlag} ${circleArcCommand.endX} ${circleArcCommand.endY}`, // 垂直椭圆 `M${verticalArcCommand.endX} ${rectangle.y}`, @@ -106,21 +108,12 @@ export const AssemblyEngine: ShapeEngine = { // 检查中间圆形 const circleCenter = [line1[1][0] + circleArcCommand.rx, line1[1][1]] as Point; - const nearestPointForCircle = getNearestPointBetweenPointAndEllipse( - point, - circleCenter, - circleArcCommand.rx, - circleArcCommand.ry - ); + const nearestPointForCircle = getNearestPointBetweenPointAndEllipse(point, circleCenter, circleArcCommand.rx, circleArcCommand.ry); const distanceForCircle = distanceBetweenPointAndPoint(...point, ...nearestPointForCircle); // 检查垂直椭圆(使用 getNearestPointBetweenPointAndArc 处理半圆弧) const arcStartPoint: Point = [verticalArcCommand.endX, rectangle.y]; - const nearestPointForEllipse = getNearestPointBetweenPointAndArc( - point, - arcStartPoint, - verticalArcCommand - ); + const nearestPointForEllipse = getNearestPointBetweenPointAndArc(point, arcStartPoint, verticalArcCommand); const distanceForEllipse = distanceBetweenPointAndPoint(...point, ...nearestPointForEllipse); // 返回最近的点 diff --git a/packages/draw/src/engines/uml/component.ts b/packages/draw/src/engines/uml/component.ts index 1504d434c..faca47118 100644 --- a/packages/draw/src/engines/uml/component.ts +++ b/packages/draw/src/engines/uml/component.ts @@ -36,7 +36,7 @@ function generateComponentPath(rectangle: RectangleClient): ComponentPathData { const boxHeight = rectangle.height - 28 - rectangle.height * 0.35 > 1 ? 14 : rectangle.height * 0.175; const topBoxY = rectangle.y + rectangle.height * 0.175; const bottomBoxY = rectangle.y + rectangle.height - rectangle.height * 0.175 - boxHeight; - + return { boxSize: { width: boxWidth, @@ -59,7 +59,7 @@ export const ComponentEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const { boxSize, points } = generateComponentPath(rectangle); - + const pathData = [ // 主矩形轮廓 `M${points.mainStart[0]} ${points.mainStart[1]}`, @@ -91,7 +91,7 @@ export const ComponentEngine: ShapeEngine = { getNearestPoint(rectangle: RectangleClient, point: Point) { const { boxSize, points } = generateComponentPath(rectangle); - + const segments: [Point, Point][] = [ // 主矩形轮廓 [points.mainStart, [points.rightTop[0], points.mainStart[1]]], @@ -100,18 +100,36 @@ export const ComponentEngine: ShapeEngine = { [[points.mainEnd[0], points.rightBottom[1]], points.mainStart], // 上方小矩形 - [points.topBoxStart, [points.topBoxStart[0] + boxSize.width/2, points.topBoxStart[1]]], - [[points.topBoxStart[0] + boxSize.width/2, points.topBoxStart[1]], [points.topBoxStart[0] + boxSize.width/2, points.topBoxEnd[1]]], - [[points.topBoxStart[0] + boxSize.width/2, points.topBoxEnd[1]], [points.topBoxStart[0] - boxSize.width/2, points.topBoxEnd[1]]], - [[points.topBoxStart[0] - boxSize.width/2, points.topBoxEnd[1]], [points.topBoxStart[0] - boxSize.width/2, points.topBoxStart[1]]], - [[points.topBoxStart[0] - boxSize.width/2, points.topBoxStart[1]], points.topBoxStart], + [points.topBoxStart, [points.topBoxStart[0] + boxSize.width / 2, points.topBoxStart[1]]], + [ + [points.topBoxStart[0] + boxSize.width / 2, points.topBoxStart[1]], + [points.topBoxStart[0] + boxSize.width / 2, points.topBoxEnd[1]] + ], + [ + [points.topBoxStart[0] + boxSize.width / 2, points.topBoxEnd[1]], + [points.topBoxStart[0] - boxSize.width / 2, points.topBoxEnd[1]] + ], + [ + [points.topBoxStart[0] - boxSize.width / 2, points.topBoxEnd[1]], + [points.topBoxStart[0] - boxSize.width / 2, points.topBoxStart[1]] + ], + [[points.topBoxStart[0] - boxSize.width / 2, points.topBoxStart[1]], points.topBoxStart], // 下方小矩形 - [points.bottomBoxStart, [points.bottomBoxStart[0] + boxSize.width/2, points.bottomBoxStart[1]]], - [[points.bottomBoxStart[0] + boxSize.width/2, points.bottomBoxStart[1]], [points.bottomBoxStart[0] + boxSize.width/2, points.bottomBoxEnd[1]]], - [[points.bottomBoxStart[0] + boxSize.width/2, points.bottomBoxEnd[1]], [points.bottomBoxStart[0] - boxSize.width/2, points.bottomBoxEnd[1]]], - [[points.bottomBoxStart[0] - boxSize.width/2, points.bottomBoxEnd[1]], [points.bottomBoxStart[0] - boxSize.width/2, points.bottomBoxStart[1]]], - [[points.bottomBoxStart[0] - boxSize.width/2, points.bottomBoxStart[1]], points.bottomBoxStart], + [points.bottomBoxStart, [points.bottomBoxStart[0] + boxSize.width / 2, points.bottomBoxStart[1]]], + [ + [points.bottomBoxStart[0] + boxSize.width / 2, points.bottomBoxStart[1]], + [points.bottomBoxStart[0] + boxSize.width / 2, points.bottomBoxEnd[1]] + ], + [ + [points.bottomBoxStart[0] + boxSize.width / 2, points.bottomBoxEnd[1]], + [points.bottomBoxStart[0] - boxSize.width / 2, points.bottomBoxEnd[1]] + ], + [ + [points.bottomBoxStart[0] - boxSize.width / 2, points.bottomBoxEnd[1]], + [points.bottomBoxStart[0] - boxSize.width / 2, points.bottomBoxStart[1]] + ], + [[points.bottomBoxStart[0] - boxSize.width / 2, points.bottomBoxStart[1]], points.bottomBoxStart], // 连接线 [points.mainStart, points.topBoxStart], diff --git a/packages/draw/src/engines/uml/container.ts b/packages/draw/src/engines/uml/container.ts index 6b8927687..8923d8f7e 100644 --- a/packages/draw/src/engines/uml/container.ts +++ b/packages/draw/src/engines/uml/container.ts @@ -18,9 +18,9 @@ export const ContainerEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const shape = rs.path( - `M${rectangle.x} ${rectangle.y} H${rectangle.x + rectangle.width} V${rectangle.y + rectangle.height} H${ - rectangle.x - } Z M${rectangle.x + 40} ${rectangle.y} L${rectangle.x + 40} ${rectangle.y + rectangle.height} `, + `M${rectangle.x} ${rectangle.y} H${rectangle.x + rectangle.width} V${rectangle.y + rectangle.height} H${rectangle.x} Z M${ + rectangle.x + 40 + } ${rectangle.y} L${rectangle.x + 40} ${rectangle.y + rectangle.height} `, { ...options, fillStyle: 'solid' } ); setStrokeLinecap(shape, 'round'); diff --git a/packages/draw/src/engines/uml/deletion.ts b/packages/draw/src/engines/uml/deletion.ts index 24112c6d1..5deed0732 100644 --- a/packages/draw/src/engines/uml/deletion.ts +++ b/packages/draw/src/engines/uml/deletion.ts @@ -30,10 +30,11 @@ export const DeletionEngine: ShapeEngine = { draw(board: PlaitBoard, rectangle: RectangleClient, options: Options) { const rs = PlaitBoard.getRoughSVG(board); const lines = getDeletionLines(rectangle); - const shape = rs.path( - lines.map(([from, to]) => `M${from[0]} ${from[1]} L${to[0]} ${to[1]}`).join(' '), - { ...options, fillStyle: 'solid', strokeWidth: 4 } - ); + const shape = rs.path(lines.map(([from, to]) => `M${from[0]} ${from[1]} L${to[0]} ${to[1]}`).join(' '), { + ...options, + fillStyle: 'solid', + strokeWidth: 4 + }); setStrokeLinecap(shape, 'round'); return shape; }, @@ -48,7 +49,7 @@ export const DeletionEngine: ShapeEngine = { const lines = getDeletionLines(rectangle); let minDistance = Infinity; let nearestPoint = point; - lines.forEach(line => { + lines.forEach((line) => { const currentPoint = getNearestPointBetweenPointAndSegment(point, line); const distance = distanceBetweenPointAndPoint(point[0], point[1], currentPoint[0], currentPoint[1]); if (distance < minDistance) { diff --git a/packages/draw/src/generators/single-text.generator.ts b/packages/draw/src/generators/single-text.generator.ts index f6dcf1f2e..89553ee55 100644 --- a/packages/draw/src/generators/single-text.generator.ts +++ b/packages/draw/src/generators/single-text.generator.ts @@ -21,7 +21,7 @@ export class SingleTextGenerator extends currentText: ParagraphElement | DrawTextInfo[], elementG: SVGElement ) { - if (!isMultipleTextGeometry((element as unknown) as PlaitCommonGeometry)) { + if (!isMultipleTextGeometry(element as unknown as PlaitCommonGeometry)) { super.update( element, [{ text: previousText as ParagraphElement, id: element.id }], diff --git a/packages/draw/src/generators/text.generator.ts b/packages/draw/src/generators/text.generator.ts index d2f8ae6d5..19617fe49 100644 --- a/packages/draw/src/generators/text.generator.ts +++ b/packages/draw/src/generators/text.generator.ts @@ -71,7 +71,7 @@ export class TextGenerator { initialize() { const textPlugins = ((this.board as PlaitOptionsBoard).getPluginOptions(WithTextPluginKey) || {}) .textPlugins; - this.textManages = this.texts.map(text => { + this.textManages = this.texts.map((text) => { const textManage = this.createTextManage(text, textPlugins); setTextManage(this.board, this.element, text, textManage); return textManage; @@ -82,7 +82,7 @@ export class TextGenerator { draw(elementG: SVGElement) { const centerPoint = RectangleClient.getCenterPoint(this.board.getRectangle(this.element)!); - this.texts.forEach(drawShapeText => { + this.texts.forEach((drawShapeText) => { const textManage = getTextManage(this.board, this.element, drawShapeText); if (drawShapeText.text && textManage) { textManage.draw(drawShapeText.text); @@ -98,13 +98,13 @@ export class TextGenerator { const centerPoint = RectangleClient.getCenterPoint(this.board.getRectangle(this.element)!); const textPlugins = ((this.board as PlaitOptionsBoard).getPluginOptions(WithTextPluginKey) || {}) .textPlugins; - const removedTexts = previousDrawShapeTexts.filter(value => { - return !currentDrawShapeTexts.find(item => item.id === value.id); + const removedTexts = previousDrawShapeTexts.filter((value) => { + return !currentDrawShapeTexts.find((item) => item.id === value.id); }); if (removedTexts.length) { - removedTexts.forEach(item => { + removedTexts.forEach((item) => { const textManage = getTextManage(this.board, element, item); - const index = this.textManages.findIndex(value => value === textManage); + const index = this.textManages.findIndex((value) => value === textManage); if (index > -1 && item.text) { this.textManages.splice(index, 1); } @@ -112,7 +112,7 @@ export class TextGenerator { deleteTextManage(this.board, item.id); }); } - currentDrawShapeTexts.forEach(drawShapeText => { + currentDrawShapeTexts.forEach((drawShapeText) => { if (drawShapeText.text) { let textManage = getTextManage(this.board, this.element, drawShapeText); if (!textManage) { @@ -165,7 +165,7 @@ export class TextGenerator { const ref = PlaitElement.getElementRef(this.element); ref.destroyTextManage(); this.textManages = []; - this.texts.forEach(item => { + this.texts.forEach((item) => { deleteTextManage(this.board, item.id); }); } diff --git a/packages/draw/src/interfaces/options.ts b/packages/draw/src/interfaces/options.ts index 37f26555d..f2c42d2fa 100644 --- a/packages/draw/src/interfaces/options.ts +++ b/packages/draw/src/interfaces/options.ts @@ -1,5 +1,5 @@ -import { WithPluginOptions } from "@plait/core"; +import { WithPluginOptions } from '@plait/core'; export interface WithDrawOptions extends WithPluginOptions { customGeometryTypes: string[]; -} \ No newline at end of file +} diff --git a/packages/draw/src/plugins/with-draw-fragment.ts b/packages/draw/src/plugins/with-draw-fragment.ts index 706a0f05b..e4a634182 100644 --- a/packages/draw/src/plugins/with-draw-fragment.ts +++ b/packages/draw/src/plugins/with-draw-fragment.ts @@ -27,19 +27,19 @@ export const withDrawFragment = (baseBoard: PlaitBoard) => { board.getDeletedFragment = (data: PlaitElement[]) => { const drawElements = getSelectedDrawElements(board); if (drawElements.length) { - const geometryElements = drawElements.filter(value => PlaitDrawElement.isGeometry(value)) as PlaitGeometry[]; - const arrowLineElements = drawElements.filter(value => PlaitDrawElement.isArrowLine(value)) as PlaitArrowLine[]; - const vectorLineElements = drawElements.filter(value => PlaitDrawElement.isVectorLine(value)) as PlaitVectorLine[]; - const imageElements = drawElements.filter(value => PlaitDrawElement.isImage(value)) as PlaitImage[]; - const tableElements = drawElements.filter(value => PlaitDrawElement.isTable(value)) as PlaitTable[]; - const swimlaneElements = drawElements.filter(value => PlaitDrawElement.isSwimlane(value)) as PlaitSwimlane[]; + const geometryElements = drawElements.filter((value) => PlaitDrawElement.isGeometry(value)) as PlaitGeometry[]; + const arrowLineElements = drawElements.filter((value) => PlaitDrawElement.isArrowLine(value)) as PlaitArrowLine[]; + const vectorLineElements = drawElements.filter((value) => PlaitDrawElement.isVectorLine(value)) as PlaitVectorLine[]; + const imageElements = drawElements.filter((value) => PlaitDrawElement.isImage(value)) as PlaitImage[]; + const tableElements = drawElements.filter((value) => PlaitDrawElement.isTable(value)) as PlaitTable[]; + const swimlaneElements = drawElements.filter((value) => PlaitDrawElement.isSwimlane(value)) as PlaitSwimlane[]; const boundLineElements = [ ...getBoundedArrowLineElements(board, geometryElements), ...getBoundedArrowLineElements(board, imageElements), ...getBoundedArrowLineElements(board, tableElements), ...getBoundedArrowLineElements(board, swimlaneElements) - ].filter(line => !arrowLineElements.includes(line)); + ].filter((line) => !arrowLineElements.includes(line)); data.push( ...[ ...geometryElements, @@ -48,7 +48,7 @@ export const withDrawFragment = (baseBoard: PlaitBoard) => { ...imageElements, ...tableElements, ...swimlaneElements, - ...boundLineElements.filter(line => !arrowLineElements.includes(line)) + ...boundLineElements.filter((line) => !arrowLineElements.includes(line)) ] ); } @@ -65,9 +65,9 @@ export const withDrawFragment = (baseBoard: PlaitBoard) => { let boundLineElements: PlaitArrowLine[] = []; if (targetDrawElements.length) { if (operationType === WritableClipboardOperationType.cut) { - const geometryElements = targetDrawElements.filter(value => PlaitDrawElement.isGeometry(value)) as PlaitGeometry[]; - const lineElements = targetDrawElements.filter(value => PlaitDrawElement.isArrowLine(value)) as PlaitArrowLine[]; - boundLineElements = getBoundedArrowLineElements(board, geometryElements).filter(line => !lineElements.includes(line)); + const geometryElements = targetDrawElements.filter((value) => PlaitDrawElement.isGeometry(value)) as PlaitGeometry[]; + const lineElements = targetDrawElements.filter((value) => PlaitDrawElement.isArrowLine(value)) as PlaitArrowLine[]; + boundLineElements = getBoundedArrowLineElements(board, geometryElements).filter((line) => !lineElements.includes(line)); } const selectedElements = [...targetDrawElements, ...boundLineElements]; const elements = buildClipboardData(board, selectedElements, rectangle ? [rectangle.x, rectangle.y] : [0, 0]); @@ -85,12 +85,12 @@ export const withDrawFragment = (baseBoard: PlaitBoard) => { board.insertFragment = (clipboardData: ClipboardData | null, targetPoint: Point, operationType?: WritableClipboardOperationType) => { const selectedElements = getSelectedElements(board); if (clipboardData?.files?.length) { - const acceptImageArray = acceptImageTypes.map(type => 'image/' + type); + const acceptImageArray = acceptImageTypes.map((type) => 'image/' + type); const canInsertionImage = !getElementOfFocusedImage(board) && !(selectedElements.length === 1 && board.isImageBindingAllowed(selectedElements[0])); if (acceptImageArray.includes(clipboardData.files[0].type) && canInsertionImage) { const imageFile = clipboardData.files[0]; - buildImage(board, imageFile, DEFAULT_IMAGE_WIDTH, imageItem => { + buildImage(board, imageFile, DEFAULT_IMAGE_WIDTH, (imageItem) => { DrawTransforms.insertImage(board, imageItem, targetPoint); }); return; @@ -98,7 +98,7 @@ export const withDrawFragment = (baseBoard: PlaitBoard) => { } if (clipboardData?.elements?.length) { - const drawElements = clipboardData.elements?.filter(value => PlaitDrawElement.isDrawElement(value)) as PlaitDrawElement[]; + const drawElements = clipboardData.elements?.filter((value) => PlaitDrawElement.isDrawElement(value)) as PlaitDrawElement[]; if (clipboardData.elements && clipboardData.elements.length > 0 && drawElements.length > 0) { insertClipboardData(board, drawElements, targetPoint); } @@ -124,7 +124,9 @@ export const withDrawFragment = (baseBoard: PlaitBoard) => { export const getBoundedArrowLineElements = (board: PlaitBoard, plaitShapes: PlaitShapeElement[]) => { const lines = getArrowLines(board); - return lines.filter(line => - plaitShapes.find(shape => PlaitArrowLine.isBoundElementOfSource(line, shape) || PlaitArrowLine.isBoundElementOfTarget(line, shape)) + return lines.filter((line) => + plaitShapes.find( + (shape) => PlaitArrowLine.isBoundElementOfSource(line, shape) || PlaitArrowLine.isBoundElementOfTarget(line, shape) + ) ); }; diff --git a/packages/draw/src/plugins/with-table-resize.ts b/packages/draw/src/plugins/with-table-resize.ts index 159acff85..fa012a072 100644 --- a/packages/draw/src/plugins/with-table-resize.ts +++ b/packages/draw/src/plugins/with-table-resize.ts @@ -1,12 +1,4 @@ -import { - PlaitBoard, - Point, - RectangleClient, - Transforms, - isSelectedElement, - getSelectedElements, - hasValidAngle, -} from '@plait/core'; +import { PlaitBoard, Point, RectangleClient, Transforms, isSelectedElement, getSelectedElements, hasValidAngle } from '@plait/core'; import { PlaitBaseTable, PlaitTableBoard, PlaitTableCellWithPoints } from '../interfaces/table'; import { getIndexByResizeHandle, @@ -21,11 +13,7 @@ import { } from '@plait/common'; import { getCellsWithPoints, updateColumns, updateRows } from '../utils/table'; import { getHitRectangleResizeHandleRef } from '../utils/position/geometry'; -import { - getResizeOriginPointAndHandlePoint, - getResizeZoom, - movePointByZoomAndOriginPoint -} from './with-draw-resize'; +import { getResizeOriginPointAndHandlePoint, getResizeZoom, movePointByZoomAndOriginPoint } from './with-draw-resize'; import { getSnapResizingRef, getSnapResizingRefOptions } from '../utils/snap-resizing'; import { PlaitDrawElement } from '../interfaces'; import { isSingleSelectTable } from '../utils'; diff --git a/packages/draw/src/plugins/with-vector-line-resize.ts b/packages/draw/src/plugins/with-vector-line-resize.ts index fed0829b6..b06b08eae 100644 --- a/packages/draw/src/plugins/with-vector-line-resize.ts +++ b/packages/draw/src/plugins/with-vector-line-resize.ts @@ -16,7 +16,7 @@ export const withVectorLineResize = (board: PlaitBoard) => { const selectedVectorLineElements = getSelectedVectorLineElements(board); if (selectedVectorLineElements.length > 0) { let result = null; - selectedVectorLineElements.forEach(value => { + selectedVectorLineElements.forEach((value) => { const handleRef = getHitLineResizeHandleRef(board, value, point); if (handleRef) { result = { diff --git a/packages/draw/src/transforms/arrow-line.ts b/packages/draw/src/transforms/arrow-line.ts index fea21c1e4..f8d934e5c 100644 --- a/packages/draw/src/transforms/arrow-line.ts +++ b/packages/draw/src/transforms/arrow-line.ts @@ -42,7 +42,7 @@ export const setArrowLineMark = (board: PlaitBoard, handleKey: ArrowLineHandleKe export const setArrowLineShape = (board: PlaitBoard, newProperties: Partial) => { const elements = getSelectedArrowLineElements(board); - elements.map(element => { + elements.map((element) => { const _properties = { ...newProperties }; if (element.shape === newProperties.shape) { return; diff --git a/packages/draw/src/transforms/multi-text-geometry-text.ts b/packages/draw/src/transforms/multi-text-geometry-text.ts index 84040a6b1..c41e2693e 100644 --- a/packages/draw/src/transforms/multi-text-geometry-text.ts +++ b/packages/draw/src/transforms/multi-text-geometry-text.ts @@ -3,7 +3,7 @@ import { PlaitMultipleTextGeometry } from '../interfaces'; import { DrawTextInfo } from '../generators/text.generator'; export const setDrawTexts = (board: PlaitBoard, element: PlaitMultipleTextGeometry, text: DrawTextInfo) => { - const newTexts = element.texts?.map(item => { + const newTexts = element.texts?.map((item) => { if (item.id === text.id) { return { ...item, ...text }; } @@ -12,6 +12,6 @@ export const setDrawTexts = (board: PlaitBoard, element: PlaitMultipleTextGeomet const newElement = { texts: newTexts }; - const path = board.children.findIndex(child => child === element); + const path = board.children.findIndex((child) => child === element); Transforms.setNode(board, newElement, [path]); }; diff --git a/packages/draw/src/transforms/swimlane.ts b/packages/draw/src/transforms/swimlane.ts index ab9a89869..1f8460410 100644 --- a/packages/draw/src/transforms/swimlane.ts +++ b/packages/draw/src/transforms/swimlane.ts @@ -36,7 +36,7 @@ export const addSwimlaneRow = (board: PlaitBoard, swimlane: PlaitSwimlane, index } newRows.splice(index, 0, ...addRows); const newCells = [...swimlane.cells]; - addRows.forEach(item => { + addRows.forEach((item) => { newCells.push(...createNewSwimlaneCells(swimlane, item.id, 'column')); }); const lastCellPoints = getCellWithPoints(board, swimlane, swimlane.cells[swimlane.cells.length - 1].id).points; @@ -55,7 +55,7 @@ export const addSwimlaneColumn = (board: PlaitBoard, swimlane: PlaitSwimlane, in } newColumns.splice(index, 0, ...addColumns); const newCells = [...swimlane.cells]; - addColumns.forEach(item => { + addColumns.forEach((item) => { newCells.push(...createNewSwimlaneCells(swimlane, item.id, 'row')); }); const lastCellPoints = getCellWithPoints(board, swimlane, swimlane.cells[swimlane.cells.length - 1].id).points; @@ -81,12 +81,12 @@ export const removeSwimlaneRow = (board: PlaitBoard, swimlane: PlaitSwimlane, in for (let i = index; i < count + index; i++) { const removeRow = swimlane.rows[i]; removeRows.push(removeRow); - newCells = newCells.filter(item => item.rowId !== removeRow.id); + newCells = newCells.filter((item) => item.rowId !== removeRow.id); } let removeRowHeight = 0; - removeRows.forEach(row => { + removeRows.forEach((row) => { if (!row.height) { - const rowCell = swimlane.cells.find(item => item.rowId === row.id)!; + const rowCell = swimlane.cells.find((item) => item.rowId === row.id)!; const cellPoints = getCellWithPoints(board, swimlane, rowCell.id).points; removeRowHeight += RectangleClient.getRectangleByPoints(cellPoints).height; } else { @@ -116,12 +116,12 @@ export const removeSwimlaneColumn = (board: PlaitBoard, swimlane: PlaitSwimlane, for (let i = index; i < count + index; i++) { const removeColumn = swimlane.columns[i]; removeColumns.push(removeColumn); - newCells = newCells.filter(item => item.columnId !== removeColumn.id); + newCells = newCells.filter((item) => item.columnId !== removeColumn.id); } let removeColumnWidth = 0; - removeColumns.forEach(column => { + removeColumns.forEach((column) => { if (!column.width) { - const rowCell = swimlane.cells.find(item => item.columnId === column.id)!; + const rowCell = swimlane.cells.find((item) => item.columnId === column.id)!; const cellPoints = getCellWithPoints(board, swimlane, rowCell.id).points; removeColumnWidth += RectangleClient.getRectangleByPoints(cellPoints).width; } else { @@ -135,7 +135,7 @@ export const removeSwimlaneColumn = (board: PlaitBoard, swimlane: PlaitSwimlane, }; const createNewSwimlaneCells = (swimlane: PlaitSwimlane, newId: string, type: 'row' | 'column'): PlaitTableCell[] => { - const cells: PlaitTableCell[] = swimlane[`${type}s`].map(item => ({ + const cells: PlaitTableCell[] = swimlane[`${type}s`].map((item) => ({ id: idCreator(), rowId: type === 'row' ? item.id : newId, columnId: type === 'row' ? newId : item.id diff --git a/packages/draw/src/transforms/table.ts b/packages/draw/src/transforms/table.ts index d86d5d222..aa1cd2d5a 100644 --- a/packages/draw/src/transforms/table.ts +++ b/packages/draw/src/transforms/table.ts @@ -6,14 +6,14 @@ export const setTableFill = (board: PlaitBoard, element: PlaitBaseTable, fill: s const selectedCells = getSelectedCells(element); let newCells = element.cells; if (selectedCells?.length) { - newCells = element.cells.map(cell => { - if (selectedCells.map(item => item.id).includes(cell.id)) { + newCells = element.cells.map((cell) => { + if (selectedCells.map((item) => item.id).includes(cell.id)) { return getNewCell(cell, fill); } return cell; }); } else { - newCells = element.cells.map(cell => { + newCells = element.cells.map((cell) => { if (cell.text) { return getNewCell(cell, fill); } diff --git a/packages/draw/src/transforms/vector-line.ts b/packages/draw/src/transforms/vector-line.ts index ae3ece8cf..031f4b48e 100644 --- a/packages/draw/src/transforms/vector-line.ts +++ b/packages/draw/src/transforms/vector-line.ts @@ -4,7 +4,7 @@ import { getSelectedVectorLineElements } from '../utils'; export const setVectorLineShape = (board: PlaitBoard, newProperties: Partial) => { const elements = getSelectedVectorLineElements(board); - elements.map(element => { + elements.map((element) => { if (element.shape === newProperties.shape) { return; } diff --git a/packages/draw/src/utils/arrow-line/arrow-line-common.ts b/packages/draw/src/utils/arrow-line/arrow-line-common.ts index e6b49b18c..f0accd37d 100644 --- a/packages/draw/src/utils/arrow-line/arrow-line-common.ts +++ b/packages/draw/src/utils/arrow-line/arrow-line-common.ts @@ -179,10 +179,10 @@ export const collectArrowLineUpdatedRefsByGeometry = ( } return false; }, - recursion: element => true + recursion: (element) => true }) as PlaitArrowLine[]; if (lines.length) { - lines.forEach(line => { + lines.forEach((line) => { const isSourceBound = line.source.boundId === element.id; const handle = isSourceBound ? 'source' : 'target'; const object = { ...line[handle] }; @@ -190,7 +190,7 @@ export const collectArrowLineUpdatedRefsByGeometry = ( const point = isSourceBound ? linePoints[0] : linePoints[linePoints.length - 1]; object.connection = getHitConnection(board, point, element); const path = PlaitBoard.findPath(board, line); - const index = refs.findIndex(obj => Path.equals(obj.path, path)); + const index = refs.findIndex((obj) => Path.equals(obj.path, path)); if (index === -1) { refs.push({ property: { diff --git a/packages/draw/src/utils/clipboard.ts b/packages/draw/src/utils/clipboard.ts index a3cd64aa5..715819ea0 100644 --- a/packages/draw/src/utils/clipboard.ts +++ b/packages/draw/src/utils/clipboard.ts @@ -28,7 +28,7 @@ export const buildClipboardData = (board: PlaitBoard, elements: PlaitDrawElement delete target.connection; } } - points = points.map(point => [point[0] - startPoint[0], point[1] - startPoint[1]]); + points = points.map((point) => [point[0] - startPoint[0], point[1] - startPoint[1]]); return { ...element, points, source, target } as PlaitArrowLine; } return undefined; @@ -39,13 +39,13 @@ export const insertClipboardData = (board: PlaitBoard, elements: PlaitDrawElemen basicInsertClipboard(board, elements, startPoint, (element: PlaitElement, idsMap: Record) => { if (PlaitDrawElement.isArrowLine(element)) { if (element.source.boundId) { - const boundElement = elements.find(item => [element.source.boundId, idsMap[element.source.boundId!]].includes(item.id)); + const boundElement = elements.find((item) => [element.source.boundId, idsMap[element.source.boundId!]].includes(item.id)); if (boundElement) { element.source.boundId = idsMap[element.source.boundId]; } } if (element.target.boundId) { - const boundElement = elements.find(item => [element.target.boundId, idsMap[element.target.boundId!]].includes(item.id)); + const boundElement = elements.find((item) => [element.target.boundId, idsMap[element.target.boundId!]].includes(item.id)); if (boundElement) { element.target.boundId = idsMap[element.target.boundId]; } diff --git a/packages/draw/src/utils/line.ts b/packages/draw/src/utils/line.ts index d5bf38ab6..a4c16a1b8 100644 --- a/packages/draw/src/utils/line.ts +++ b/packages/draw/src/utils/line.ts @@ -38,8 +38,8 @@ export function getMiddlePoints(board: PlaitBoard, element: PlaitLine) { result.push(pointsOnBezier[middleIndex]); } else { for (let i = 0; i < points.length - 1; i++) { - const startIndex = pointsOnBezier.findIndex(point => point[0] === points[i][0] && point[1] === points[i][1]); - const endIndex = pointsOnBezier.findIndex(point => point[0] === points[i + 1][0] && point[1] === points[i + 1][1]); + const startIndex = pointsOnBezier.findIndex((point) => point[0] === points[i][0] && point[1] === points[i][1]); + const endIndex = pointsOnBezier.findIndex((point) => point[0] === points[i + 1][0] && point[1] === points[i + 1][1]); const middleIndex = Math.round((startIndex + endIndex) / 2); const distance = distanceBetweenPointAndPoint(...points[i], ...points[i + 1]); if (distance < hideBuffer) continue; diff --git a/packages/draw/src/utils/position/line.ts b/packages/draw/src/utils/position/line.ts index c1e99781b..189a02d2b 100644 --- a/packages/draw/src/utils/position/line.ts +++ b/packages/draw/src/utils/position/line.ts @@ -38,7 +38,7 @@ export const getHitLineResizeHandleRef = (board: PlaitBoard, element: PlaitLine, }; export function getHitPointIndex(points: Point[], movingPoint: Point) { - const rectangles = points.map(point => { + const rectangles = points.map((point) => { return { x: point[0] - RESIZE_HANDLE_DIAMETER / 2, y: point[1] - RESIZE_HANDLE_DIAMETER / 2, @@ -46,7 +46,7 @@ export function getHitPointIndex(points: Point[], movingPoint: Point) { height: RESIZE_HANDLE_DIAMETER }; }); - const rectangle = rectangles.find(rectangle => { + const rectangle = rectangles.find((rectangle) => { return RectangleClient.isHit(RectangleClient.getRectangleByPoints([movingPoint, movingPoint]), rectangle); }); return rectangle ? rectangles.indexOf(rectangle) : -1; diff --git a/packages/draw/src/utils/selected.ts b/packages/draw/src/utils/selected.ts index ea3f45309..810d4b790 100644 --- a/packages/draw/src/utils/selected.ts +++ b/packages/draw/src/utils/selected.ts @@ -4,33 +4,33 @@ import { PlaitImage } from '../interfaces/image'; export const getSelectedDrawElements = (board: PlaitBoard, elements?: PlaitElement[]) => { const selectedElements = elements?.length ? elements : getSelectedElements(board); - return selectedElements.filter(value => PlaitDrawElement.isDrawElement(value)) as PlaitDrawElement[]; + return selectedElements.filter((value) => PlaitDrawElement.isDrawElement(value)) as PlaitDrawElement[]; }; export const getSelectedGeometryElements = (board: PlaitBoard) => { - const selectedElements = getSelectedElements(board).filter(value => PlaitDrawElement.isGeometry(value)) as PlaitGeometry[]; + const selectedElements = getSelectedElements(board).filter((value) => PlaitDrawElement.isGeometry(value)) as PlaitGeometry[]; return selectedElements; }; export const getSelectedCustomGeometryElements = (board: PlaitBoard) => { - const selectedElements = getSelectedElements(board).filter(value => + const selectedElements = getSelectedElements(board).filter((value) => PlaitDrawElement.isCustomGeometryElement(board, value) ) as PlaitCustomGeometry[]; return selectedElements; }; export const getSelectedArrowLineElements = (board: PlaitBoard) => { - const selectedElements = getSelectedElements(board).filter(value => PlaitDrawElement.isArrowLine(value)) as PlaitArrowLine[]; + const selectedElements = getSelectedElements(board).filter((value) => PlaitDrawElement.isArrowLine(value)) as PlaitArrowLine[]; return selectedElements; }; export const getSelectedVectorLineElements = (board: PlaitBoard) => { - const selectedElements = getSelectedElements(board).filter(value => PlaitDrawElement.isVectorLine(value)) as PlaitVectorLine[]; + const selectedElements = getSelectedElements(board).filter((value) => PlaitDrawElement.isVectorLine(value)) as PlaitVectorLine[]; return selectedElements; }; export const getSelectedImageElements = (board: PlaitBoard) => { - const selectedElements = getSelectedElements(board).filter(value => PlaitDrawElement.isImage(value)) as PlaitImage[]; + const selectedElements = getSelectedElements(board).filter((value) => PlaitDrawElement.isImage(value)) as PlaitImage[]; return selectedElements; }; @@ -46,5 +46,5 @@ export const isSingleSelectLine = (board: PlaitBoard) => { export const getSelectedSwimlane = (board: PlaitBoard): PlaitSwimlane => { const selectedElements = getSelectedElements(board); - return selectedElements.find(item => PlaitDrawElement.isSwimlane(item)) as PlaitSwimlane; + return selectedElements.find((item) => PlaitDrawElement.isSwimlane(item)) as PlaitSwimlane; }; diff --git a/packages/draw/src/utils/snap-resizing.ts b/packages/draw/src/utils/snap-resizing.ts index ba4c27d7f..20d474fd7 100644 --- a/packages/draw/src/utils/snap-resizing.ts +++ b/packages/draw/src/utils/snap-resizing.ts @@ -77,7 +77,7 @@ export function getSnapResizingRefOptions( resizeOriginPoint = resizeRef.element.points; } - const points = resizeOriginPoint.map(p => { + const points = resizeOriginPoint.map((p) => { return movePointByZoomAndOriginPoint(p, originPoint, xZoom, yZoom); }) as [Point, Point]; const rectangle = RectangleClient.getRectangleByPoints(points); @@ -161,7 +161,7 @@ function getActivePointAndZoom(resizeSnapDelta: SnapDelta, resizeSnapOptions: Re const resizeZoom = getResizeZoom(newResizePoints, originPoint!, handlePoint!, isFromCorner, isAspectRatio); xZoom = resizeZoom.xZoom; yZoom = resizeZoom.yZoom; - activePoints = resizeOriginPoint!.map(p => { + activePoints = resizeOriginPoint!.map((p) => { return movePointByZoomAndOriginPoint(p, originPoint!, xZoom, yZoom); }) as [Point, Point]; if (angle) { @@ -188,7 +188,7 @@ function getIsometricLineDelta(snapRectangles: RectangleClient[], resizeSnapOpti deltaY: 0 }; const { isAspectRatio, activeRectangle } = resizeSnapOptions; - const widthSnapRectangle = snapRectangles.find(item => Math.abs(item.width - activeRectangle.width) < SNAP_TOLERANCE); + const widthSnapRectangle = snapRectangles.find((item) => Math.abs(item.width - activeRectangle.width) < SNAP_TOLERANCE); if (widthSnapRectangle) { const deltaWidth = widthSnapRectangle.width - activeRectangle.width; isometricLineDelta.deltaX = deltaWidth * resizeSnapOptions.directionFactors[0]; @@ -198,7 +198,7 @@ function getIsometricLineDelta(snapRectangles: RectangleClient[], resizeSnapOpti return isometricLineDelta; } } - const heightSnapRectangle = snapRectangles.find(item => Math.abs(item.height - activeRectangle.height) < SNAP_TOLERANCE); + const heightSnapRectangle = snapRectangles.find((item) => Math.abs(item.height - activeRectangle.height) < SNAP_TOLERANCE); if (heightSnapRectangle) { const deltaHeight = heightSnapRectangle.height - activeRectangle.height; isometricLineDelta.deltaY = deltaHeight * resizeSnapOptions.directionFactors[1]; diff --git a/packages/draw/src/utils/table-selected.ts b/packages/draw/src/utils/table-selected.ts index 29da4a109..cae81e593 100644 --- a/packages/draw/src/utils/table-selected.ts +++ b/packages/draw/src/utils/table-selected.ts @@ -9,7 +9,7 @@ export const isSingleSelectTable = (board: PlaitBoard) => { export const getSelectedTableElements = (board: PlaitBoard, elements?: PlaitElement[]) => { const selectedElements = elements?.length ? elements : getSelectedElements(board); - return selectedElements.filter(value => PlaitDrawElement.isElementByTable(value)) as PlaitTable[]; + return selectedElements.filter((value) => PlaitDrawElement.isElementByTable(value)) as PlaitTable[]; }; export const SELECTED_CELLS = new WeakMap(); diff --git a/packages/draw/src/utils/table.ts b/packages/draw/src/utils/table.ts index 61719193c..ab1a84009 100644 --- a/packages/draw/src/utils/table.ts +++ b/packages/draw/src/utils/table.ts @@ -16,9 +16,9 @@ export function getCellsWithPoints(board: PlaitBoard, element: PlaitBaseTable): const rowsCount = table.rows.length; const cellWidths = calculateCellsSize(table.columns, rectangle.width, columnsCount, true); const cellHeights = calculateCellsSize(table.rows, rectangle.height, rowsCount, false); - const cells: PlaitTableCellWithPoints[] = table.cells.map(cell => { - const rowIdx = table.rows.findIndex(row => row.id === cell.rowId); - const columnIdx = table.columns.findIndex(column => column.id === cell.columnId); + const cells: PlaitTableCellWithPoints[] = table.cells.map((cell) => { + const rowIdx = table.rows.findIndex((row) => row.id === cell.rowId); + const columnIdx = table.columns.findIndex((column) => column.id === cell.columnId); let cellTopLeftX = rectangle.x; for (let i = 0; i < columnIdx; i++) { @@ -51,7 +51,7 @@ export function getCellsWithPoints(board: PlaitBoard, element: PlaitBaseTable): export function getCellWithPoints(board: PlaitBoard, table: PlaitBaseTable, cellId: string) { try { const cells = getCellsWithPoints(board as PlaitTableBoard, table); - const cellIndex = cells && table.cells.findIndex(item => item.id === cellId); + const cellIndex = cells && table.cells.findIndex((item) => item.id === cellId); return cells[cellIndex]; } catch (error) { throw new Error('can not get table cell points'); @@ -73,7 +73,7 @@ function calculateCellsSize(items: { id: string; [key: string]: any }[], tableSi }); // Divide the remaining size equally. - const remainingItemCount = count - cellSizes.filter(item => !!item).length; + const remainingItemCount = count - cellSizes.filter((item) => !!item).length; const remainingCellSize = remainingItemCount > 0 ? totalSizeRemaining / remainingItemCount : 0; for (let i = 0; i < count; i++) { if (!cellSizes[i]) { @@ -97,12 +97,12 @@ export function getHitCell(board: PlaitTableBoard, element: PlaitBaseTable, poin const table = board.buildTable(element); const cells = getCellsWithPoints(board, table); const rectangle = RectangleClient.getRectangleByPoints([point, point]); - const cell = cells.find(item => { + const cell = cells.find((item) => { const cellRectangle = RectangleClient.getRectangleByPoints(item.points); return RectangleClient.isHit(rectangle, cellRectangle); }); if (cell) { - return table.cells.find(item => item.id === cell.id); + return table.cells.find((item) => item.id === cell.id); } return null; } @@ -117,20 +117,20 @@ export function getTextManageByCell(board: PlaitBoard, cell: PlaitTableCell) { } export const updateColumns = (table: PlaitBaseTable, columnId: string, width: number, offset: number) => { - const columns = table.columns.map(item => (item.id === columnId ? { ...item, width } : item)); + const columns = table.columns.map((item) => (item.id === columnId ? { ...item, width } : item)); const points = [table.points[0], [table.points[1][0] + offset, table.points[1][1]]] as Point[]; return { columns, points }; }; export const updateRows = (table: PlaitBaseTable, rowId: string, height: number, offset: number) => { - const rows = table.rows.map(item => (item.id === rowId ? { ...item, height } : item)); + const rows = table.rows.map((item) => (item.id === rowId ? { ...item, height } : item)); const points = [table.points[0], [table.points[1][0], table.points[1][1] + offset]] as Point[]; return { rows, points }; }; export function updateCellIdsByRowOrColumn(cells: PlaitTableCell[], oldId: string, newId: string, type: 'row' | 'column') { const id: 'rowId' | 'columnId' = `${type}Id`; - cells.forEach(item => { + cells.forEach((item) => { if (item[id] === oldId) { item[id] = newId; } @@ -138,7 +138,7 @@ export function updateCellIdsByRowOrColumn(cells: PlaitTableCell[], oldId: strin } export function updateRowOrColumnIds(element: PlaitTable, type: 'row' | 'column') { - element[`${type}s`].forEach(item => { + element[`${type}s`].forEach((item) => { const newId = idCreator(); updateCellIdsByRowOrColumn(element.cells, item.id, newId, type); item.id = newId; @@ -146,7 +146,7 @@ export function updateRowOrColumnIds(element: PlaitTable, type: 'row' | 'column' } export function updateCellIds(cells: PlaitTableCell[]) { - cells.forEach(item => { + cells.forEach((item) => { const newId = idCreator(); item.id = newId; }); @@ -158,8 +158,8 @@ export function isCellIncludeText(cell: PlaitTableCell) { export function getCellsRectangle(board: PlaitTableBoard, element: PlaitTable, cells: PlaitTableCell[]) { const cellsWithPoints = getCellsWithPoints(board as PlaitTableBoard, element); - const points = cells.map(cell => { - const cellWithPoints = cellsWithPoints.find(item => item.id === cell.id); + const points = cells.map((cell) => { + const cellWithPoints = cellsWithPoints.find((item) => item.id === cell.id); return cellWithPoints!.points; }); return RectangleClient.getRectangleByPoints(points); @@ -184,7 +184,7 @@ export const getSelectedTableCellsEditor = (board: PlaitBoard): BaseEditor[] | u if (isSingleSelectTable(board)) { const elements = getSelectedTableElements(board); const selectedCells = getSelectedCells(elements[0]); - const selectedCellsEditor = selectedCells?.map(cell => { + const selectedCellsEditor = selectedCells?.map((cell) => { const textManage = getTextManageByCell(board, cell); return textManage?.editor; }); diff --git a/packages/flow/src/draw/edge.ts b/packages/flow/src/draw/edge.ts index 2ba216fb6..effe3b0d6 100644 --- a/packages/flow/src/draw/edge.ts +++ b/packages/flow/src/draw/edge.ts @@ -9,7 +9,7 @@ export const drawEdgeRoute = (board: PlaitBoard, edge: FlowEdge, state: EdgeStat const pathPoints = getEdgePoints(board, edge); const edgeStyles = getEdgeStyle(edge, state); return roughSVG.linearPath( - pathPoints.map(item => [item.x, item.y]), + pathPoints.map((item) => [item.x, item.y]), edgeStyles ); }; diff --git a/packages/flow/src/draw/handle.ts b/packages/flow/src/draw/handle.ts index 08416f762..dc2d6f132 100644 --- a/packages/flow/src/draw/handle.ts +++ b/packages/flow/src/draw/handle.ts @@ -11,7 +11,7 @@ export function drawNodeHandles(board: PlaitBoard, node: FlowNode) { const roughSVG = PlaitBoard.getRoughSVG(board); const handles = node.handles || getDefaultHandles(); const { x, y } = normalizePoint(node.points![0]); - return handles.map(handle => { + return handles.map((handle) => { const position = getHandleXYPosition( handle.position, { @@ -28,7 +28,7 @@ export function drawNodeHandles(board: PlaitBoard, node: FlowNode) { export function drawEdgeHandles(board: PlaitBoard, edge: FlowEdge) { const handles = getEdgeHandles(board, edge); - return handles.map(handle => { + return handles.map((handle) => { let { x, y } = normalizePoint(handle.node.points![0]); const position = getHandleXYPosition( handle.position, diff --git a/packages/flow/src/edge.component.ts b/packages/flow/src/edge.component.ts index 132784251..048589c1f 100644 --- a/packages/flow/src/edge.component.ts +++ b/packages/flow/src/edge.component.ts @@ -14,8 +14,10 @@ interface BoundedElements { target?: FlowNode; } -export class FlowEdgeComponent extends CommonElementFlavour, PlaitBoard, EdgeElementRef> - implements OnContextChanged { +export class FlowEdgeComponent + extends CommonElementFlavour, PlaitBoard, EdgeElementRef> + implements OnContextChanged +{ edgeGenerator!: EdgeGenerator; edgeLabelGenerator!: EdgeLabelGenerator; diff --git a/packages/flow/src/generators/edge-generator.ts b/packages/flow/src/generators/edge-generator.ts index ab795e8de..0cc9169a4 100644 --- a/packages/flow/src/generators/edge-generator.ts +++ b/packages/flow/src/generators/edge-generator.ts @@ -27,7 +27,7 @@ export class EdgeGenerator extends Generator { + handles.forEach((item) => { item.classList.add('flow-handle'); item.setAttribute('stroke-linecap', 'round'); }); diff --git a/packages/flow/src/generators/edge-label-generator.ts b/packages/flow/src/generators/edge-label-generator.ts index 1369063c4..11969668d 100644 --- a/packages/flow/src/generators/edge-label-generator.ts +++ b/packages/flow/src/generators/edge-label-generator.ts @@ -85,7 +85,7 @@ export class EdgeLabelGenerator extends Generator { if (hasHandle) { const handlesG = createG(); const handles = drawNodeHandles(this.board, element); - handles.forEach(item => { + handles.forEach((item) => { handlesG.append(item); item.classList.add('flow-handle'); }); diff --git a/packages/flow/src/plugins/with-edge-create.ts b/packages/flow/src/plugins/with-edge-create.ts index dc4998214..bb14ec361 100644 --- a/packages/flow/src/plugins/with-edge-create.ts +++ b/packages/flow/src/plugins/with-edge-create.ts @@ -21,7 +21,7 @@ export const withEdgeCreate: PlaitPlugin = (board: PlaitBoard) => { let drawNodeHandles = true; let hoveredNode: FlowNode | null; - board.pointerDown = event => { + board.pointerDown = (event) => { const point = toViewBoxPoint(board, toHostPoint(board, event.x, event.y)); if (hoveredNode) { sourceFlowNodeHandle = getHitHandleByNode(hoveredNode, point); diff --git a/packages/flow/src/plugins/with-flow.ts b/packages/flow/src/plugins/with-flow.ts index 45d993d8f..21de13ba4 100644 --- a/packages/flow/src/plugins/with-flow.ts +++ b/packages/flow/src/plugins/with-flow.ts @@ -63,14 +63,14 @@ export const withFlow: PlaitPlugin = (board: PlaitBoard) => { return isHit(element, point, isStrict); }; - board.isMovable = element => { + board.isMovable = (element) => { if (FlowNode.isFlowNodeElement(element as FlowElement)) { return true; } return isMovable(element); }; - board.getRectangle = element => { + board.getRectangle = (element) => { if (FlowNode.isFlowNodeElement(element as FlowElement)) { const { width, height, points } = element; return { diff --git a/packages/flow/src/plugins/with-label-icon.ts b/packages/flow/src/plugins/with-label-icon.ts index 0988af79f..1172adf09 100644 --- a/packages/flow/src/plugins/with-label-icon.ts +++ b/packages/flow/src/plugins/with-label-icon.ts @@ -1,7 +1,7 @@ -import { PlaitBoard } from "@plait/core"; -import { LabelIconItem } from "../interfaces/icon"; -import { FlowElement } from "../interfaces/element"; -import { RenderComponentRef } from "@plait/common"; +import { PlaitBoard } from '@plait/core'; +import { LabelIconItem } from '../interfaces/icon'; +import { FlowElement } from '../interfaces/element'; +import { RenderComponentRef } from '@plait/common'; export interface PlaitFlowLabelIconBoard { renderLabelIcon: (container: Element | DocumentFragment, props: LabelIconProps) => RenderComponentRef; @@ -21,4 +21,4 @@ export interface LabelIconProps { iconItem: LabelIconItem; element: FlowElement; fontSize: number; -} \ No newline at end of file +} diff --git a/packages/flow/src/utils/edge/dragging-edge.ts b/packages/flow/src/utils/edge/dragging-edge.ts index 418118f18..fe8d3466b 100644 --- a/packages/flow/src/utils/edge/dragging-edge.ts +++ b/packages/flow/src/utils/edge/dragging-edge.ts @@ -5,7 +5,7 @@ import { FlowEdge, FlowEdgeDragInfo } from '../../interfaces/edge'; export const isEdgeDragging = (board: PlaitBoard) => { const edges = getFlowElementsByType(board, FlowElementType.edge) as FlowElement[]; - return edges.some(item => FLOW_EDGE_DRAGGING_INFO.get(item)); + return edges.some((item) => FLOW_EDGE_DRAGGING_INFO.get(item)); }; export const addEdgeDraggingInfo = (edge: FlowEdge, data: FlowEdgeDragInfo) => { diff --git a/packages/flow/src/utils/edge/edge-render.ts b/packages/flow/src/utils/edge/edge-render.ts index f34667cf3..6948a6792 100644 --- a/packages/flow/src/utils/edge/edge-render.ts +++ b/packages/flow/src/utils/edge/edge-render.ts @@ -7,7 +7,7 @@ import { EdgeLabelGenerator } from '../../generators/edge-label-generator'; export const updateRelatedEdgeHighlight = (board: PlaitBoard, nodeId: string, highlight: boolean) => { const relationEdges = getEdgesByNodeId(board, nodeId); - (relationEdges || []).forEach(edge => { + (relationEdges || []).forEach((edge) => { const elementRef = PlaitElement.getElementRef(edge); const currentState = elementRef.getState(); const state = highlight @@ -44,7 +44,7 @@ export const renderEdge = (board: PlaitBoard, edge: FlowEdge, state?: EdgeState, export const renderRelatedEdges = (board: PlaitBoard, nodeId: string, state?: EdgeState) => { const relationEdges = getEdgesByNodeId(board, nodeId); - (relationEdges || []).forEach(edge => { + (relationEdges || []).forEach((edge) => { renderEdge(board, edge, state); }); }; diff --git a/packages/flow/src/utils/edge/edge.ts b/packages/flow/src/utils/edge/edge.ts index 68611612a..31272db12 100644 --- a/packages/flow/src/utils/edge/edge.ts +++ b/packages/flow/src/utils/edge/edge.ts @@ -106,10 +106,10 @@ export const buildEdgePathPoints = (board: PlaitBoard, edge: FlowEdge) => { }; let sourceHandle, targetHandle; if (edge.source?.handleId) { - sourceHandle = sourceNode.handles?.find(item => item.handleId === edge.source?.handleId); + sourceHandle = sourceNode.handles?.find((item) => item.handleId === edge.source?.handleId); } if (edge.target?.handleId) { - targetHandle = targetNode.handles?.find(item => item.handleId === edge.target?.handleId); + targetHandle = targetNode.handles?.find((item) => item.handleId === edge.target?.handleId); } const sourcePosition = getHandleXYPosition(sourceDirection, sourceRectangle, sourceHandle); const targetPosition = getHandleXYPosition(targetDirection, targetRectangle, targetHandle); @@ -125,7 +125,7 @@ export const buildEdgePathPoints = (board: PlaitBoard, edge: FlowEdge) => { targetPoint }; const points = getShapePoints(edge.shape, params); - return points.map(item => { + return points.map((item) => { return { x: item[0], y: item[1] diff --git a/packages/flow/src/utils/edge/get-edges-by-node.ts b/packages/flow/src/utils/edge/get-edges-by-node.ts index 5cb36091a..0577aaf0e 100644 --- a/packages/flow/src/utils/edge/get-edges-by-node.ts +++ b/packages/flow/src/utils/edge/get-edges-by-node.ts @@ -5,5 +5,5 @@ import { getFlowElementsByType } from '../node/get-node'; export const getEdgesByNodeId = (board: PlaitBoard, nodeId: string) => { const edges = getFlowElementsByType(board, FlowElementType.edge) as FlowEdge[]; - return edges.filter(item => item.target.nodeId === nodeId || item.source?.nodeId === nodeId); + return edges.filter((item) => item.target.nodeId === nodeId || item.source?.nodeId === nodeId); }; diff --git a/packages/flow/src/utils/edge/get-overlap-edges.ts b/packages/flow/src/utils/edge/get-overlap-edges.ts index 5987ed8e6..78aa37c87 100644 --- a/packages/flow/src/utils/edge/get-overlap-edges.ts +++ b/packages/flow/src/utils/edge/get-overlap-edges.ts @@ -7,7 +7,7 @@ export const getOverlapEdges = (board: PlaitBoard, edge: FlowEdge): FlowEdge[] = const edges = getFlowElementsByType(board, FlowElementType.edge) as FlowEdge[]; const sameEdges: FlowEdge[] = []; const overlapEdges: FlowEdge[] = []; - edges.forEach(item => { + edges.forEach((item) => { if ( item.source?.nodeId === edge.target?.nodeId && item.target.nodeId === edge.source?.nodeId && diff --git a/packages/flow/src/utils/edge/text.ts b/packages/flow/src/utils/edge/text.ts index 680108e08..3591bd89a 100644 --- a/packages/flow/src/utils/edge/text.ts +++ b/packages/flow/src/utils/edge/text.ts @@ -8,7 +8,7 @@ export function getEdgeTextXYPosition(board: PlaitBoard, edge: FlowEdge, width: const pathPoints = getEdgePoints(board, edge); const overlapEdges = getOverlapEdges(board, edge); const labelPoints = getLabelPoints(edge.shape, [...pathPoints].reverse(), overlapEdges?.length + 1); - const index = overlapEdges.findIndex(value => value.id === edge.id); + const index = overlapEdges.findIndex((value) => value.id === edge.id); const x = labelPoints[index]?.x - width / 2; const y = labelPoints[index]?.y - height / 2; return { diff --git a/packages/flow/src/utils/handle/edge.ts b/packages/flow/src/utils/handle/edge.ts index 1f2767270..17614abe9 100644 --- a/packages/flow/src/utils/handle/edge.ts +++ b/packages/flow/src/utils/handle/edge.ts @@ -18,7 +18,7 @@ export const getEdgeHandles = (board: PlaitBoard, edge: FlowEdge) => { } let sourceHandle: FlowNodeHandle; if (sourceNode.handles && edge.source.handleId) { - sourceHandle = sourceNode.handles.find(item => item.handleId === edge.source!.handleId) as FlowNodeHandle; + sourceHandle = sourceNode.handles.find((item) => item.handleId === edge.source!.handleId) as FlowNodeHandle; } else { sourceHandle = { position: edge.source.position @@ -38,7 +38,7 @@ export const getEdgeHandles = (board: PlaitBoard, edge: FlowEdge) => { } let targetHandle: FlowNodeHandle; if (targetNode.handles && edge.target?.handleId) { - targetHandle = targetNode.handles.find(item => item.handleId === edge.target?.handleId) as FlowNodeHandle; + targetHandle = targetNode.handles.find((item) => item.handleId === edge.target?.handleId) as FlowNodeHandle; } else { targetHandle = { position: edge.target.position @@ -56,7 +56,7 @@ export const getEdgeHandles = (board: PlaitBoard, edge: FlowEdge) => { export function isHitEdgeHandle(board: PlaitBoard, edge: FlowEdge, point: Point): boolean { let isHitHandle = false; const handles = getEdgeHandles(board, edge); - handles.find(handle => { + handles.find((handle) => { const { x, y } = normalizePoint(handle.node.points![0]); const position = getHandleXYPosition( handle.position, @@ -79,7 +79,7 @@ export function isHitEdgeHandle(board: PlaitBoard, edge: FlowEdge, point: Point) export function getHitHandleTypeByEdge(board: PlaitBoard, point: Point, edge: FlowEdge): FlowEdgeHandleType | null { let handleType = null; const handles = getEdgeHandles(board, edge); - handles.find(handle => { + handles.find((handle) => { const { x, y } = normalizePoint(handle.node.points![0]); const position = getHandleXYPosition( handle.position, diff --git a/packages/flow/src/utils/handle/get-default-handles.ts b/packages/flow/src/utils/handle/get-default-handles.ts index 576526f40..b1707a641 100644 --- a/packages/flow/src/utils/handle/get-default-handles.ts +++ b/packages/flow/src/utils/handle/get-default-handles.ts @@ -2,7 +2,7 @@ import { DEFAULT_POSITIONS } from '../../constants/handle'; import { FlowHandle } from '../../interfaces/element'; export const getDefaultHandles: () => FlowHandle[] = () => { - return DEFAULT_POSITIONS.map(item => { + return DEFAULT_POSITIONS.map((item) => { return { position: item }; diff --git a/packages/flow/src/utils/handle/node.ts b/packages/flow/src/utils/handle/node.ts index a8f92f296..b416a3105 100644 --- a/packages/flow/src/utils/handle/node.ts +++ b/packages/flow/src/utils/handle/node.ts @@ -20,9 +20,9 @@ export function getHitNodeHandle(board: PlaitBoard, point: Point): HitNodeHandle } if (!nodeHandle) { const flowNodeElements = getFlowElementsByType(board, FlowElementType.node) as FlowNode[]; - flowNodeElements.map(item => { + flowNodeElements.map((item) => { const handles = item.handles || getDefaultHandles(); - handles.filter(handle => { + handles.filter((handle) => { const { x, y } = normalizePoint(item.points![0]); let { x: handleX, y: handleY } = getHandleXYPosition( handle.position, @@ -52,7 +52,7 @@ export function getHitHandleByNode(node: FlowNode, point: Point): HitNodeHandle const handles = node.handles || getDefaultHandles(); let hitHandle: HitNodeHandle | null = null; const { x, y } = normalizePoint(node.points![0]); - handles.find(handle => { + handles.find((handle) => { const position = getHandleXYPosition( handle.position, { diff --git a/packages/flow/src/utils/node/get-node.ts b/packages/flow/src/utils/node/get-node.ts index ddaab9572..6450608bb 100644 --- a/packages/flow/src/utils/node/get-node.ts +++ b/packages/flow/src/utils/node/get-node.ts @@ -3,7 +3,7 @@ import { FlowNode } from '../../interfaces/node'; import { FlowElement, FlowElementType } from '../../interfaces/element'; export function getFlowNodeById(board: PlaitBoard, id: string): FlowNode { - let node = board.children.find(item => item.id === id) as FlowNode; + let node = board.children.find((item) => item.id === id) as FlowNode; return node; } @@ -17,5 +17,5 @@ export function getFakeFlowNodeById(board: PlaitBoard, id: string, offsetX = 0, } export function getFlowElementsByType(board: PlaitBoard, type: FlowElementType) { - return (board.children as FlowElement[]).filter(item => item.type === type); + return (board.children as FlowElement[]).filter((item) => item.type === type); } diff --git a/packages/graph-viz/src/force-atlas/edge.flavour.ts b/packages/graph-viz/src/force-atlas/edge.flavour.ts index 216236274..1e3be627b 100644 --- a/packages/graph-viz/src/force-atlas/edge.flavour.ts +++ b/packages/graph-viz/src/force-atlas/edge.flavour.ts @@ -5,8 +5,10 @@ import { ForceAtlasEdgeElement } from '../interfaces'; import { ForceAtlasEdgeGenerator } from './generators/edge.generator'; import { getEdgeGeneratorData } from './utils/edge'; -export class ForceAtlasEdgeFlavour extends CommonElementFlavour - implements OnContextChanged { +export class ForceAtlasEdgeFlavour + extends CommonElementFlavour + implements OnContextChanged +{ graph!: Graph; edgeGenerator!: ForceAtlasEdgeGenerator; diff --git a/packages/graph-viz/src/force-atlas/force-atlas.flavour.ts b/packages/graph-viz/src/force-atlas/force-atlas.flavour.ts index 5e579408b..737134659 100644 --- a/packages/graph-viz/src/force-atlas/force-atlas.flavour.ts +++ b/packages/graph-viz/src/force-atlas/force-atlas.flavour.ts @@ -6,8 +6,10 @@ import forceAtlas2 from 'graphology-layout-forceatlas2'; import { ForceAtlasElement, ForceAtlasNodeElement } from '../interfaces'; import { DEFAULT_NODE_SIZE } from './constants'; -export class ForceAtlasFlavour extends CommonElementFlavour - implements OnContextChanged { +export class ForceAtlasFlavour + extends CommonElementFlavour + implements OnContextChanged +{ graph!: Graph; constructor() { @@ -16,7 +18,7 @@ export class ForceAtlasFlavour extends CommonElementFlavour(); - this.element.children?.forEach(child => { + this.element.children?.forEach((child) => { if (ForceAtlasElement.isForceAtlasNodeElement(child)) { if (typeof child?.size === 'undefined') { child.size = DEFAULT_NODE_SIZE; @@ -41,7 +43,7 @@ export class ForceAtlasFlavour extends CommonElementFlavour { + this.element.children?.forEach((child) => { if (ForceAtlasElement.isForceAtlasNodeElement(child)) { const pos = positions[child.id]; child.points = [[pos.x, pos.y]]; diff --git a/packages/graph-viz/src/force-atlas/force-atlas.spec.ts b/packages/graph-viz/src/force-atlas/force-atlas.spec.ts index 6bf7da880..06e056b02 100644 --- a/packages/graph-viz/src/force-atlas/force-atlas.spec.ts +++ b/packages/graph-viz/src/force-atlas/force-atlas.spec.ts @@ -3,4 +3,4 @@ describe('mock test', () => { const a = '1'; expect(a).toEqual('1'); }); -}); \ No newline at end of file +}); diff --git a/packages/graph-viz/src/force-atlas/generators/node.generator.ts b/packages/graph-viz/src/force-atlas/generators/node.generator.ts index 64b76aefd..272e284bd 100644 --- a/packages/graph-viz/src/force-atlas/generators/node.generator.ts +++ b/packages/graph-viz/src/force-atlas/generators/node.generator.ts @@ -45,7 +45,7 @@ export class ForceAtlasNodeGenerator extends Generator - implements OnContextChanged { +export class ForceAtlasNodeFlavour + extends CommonElementFlavour + implements OnContextChanged +{ graph!: Graph; nodeGenerator!: ForceAtlasNodeGenerator; @@ -52,7 +54,7 @@ export class ForceAtlasNodeFlavour extends CommonElementFlavour { + nodes.forEach((node) => { const nodeGenerator = getNodeGenerator(node); nodeGenerator.destroy(); const isFirstDepth = selectElements.length > 0 && isFirstDepthNode(node.id, selectElements[0].id, parent); @@ -63,7 +65,7 @@ export class ForceAtlasNodeFlavour extends CommonElementFlavour { + associatedEdges.forEach((edge) => { const edgeGenerator = getEdgeGenerator(edge); edgeGenerator.destroy(); edgeGenerator.processDrawing(edge, PlaitBoard.getElementLowerHost(this.board), getEdgeGeneratorData(edge, this.board)); diff --git a/packages/graph-viz/src/force-atlas/utils/edge.ts b/packages/graph-viz/src/force-atlas/utils/edge.ts index e05991da4..2a719b4d8 100644 --- a/packages/graph-viz/src/force-atlas/utils/edge.ts +++ b/packages/graph-viz/src/force-atlas/utils/edge.ts @@ -7,12 +7,12 @@ import { getIsNodeActive, getNodeById } from './node'; export function getEdges(forceAtlasElement: ForceAtlasElement, andCallBack?: (edge: ForceAtlasEdgeElement) => boolean) { return forceAtlasElement.children?.filter( - f => ForceAtlasElement.isForceAtlasEdgeElement(f) && (andCallBack?.(f) ?? true) + (f) => ForceAtlasElement.isForceAtlasEdgeElement(f) && (andCallBack?.(f) ?? true) ) as ForceAtlasEdgeElement[]; } export function getEdgeById(id: string, forceAtlasElement: ForceAtlasElement) { - const edge = getEdges(forceAtlasElement, e => e.id === id)?.[0]; + const edge = getEdges(forceAtlasElement, (e) => e.id === id)?.[0]; if (!edge) { throw new Error('can not find edge.'); } @@ -20,7 +20,7 @@ export function getEdgeById(id: string, forceAtlasElement: ForceAtlasElement) { } export function getEdgesInSourceOrTarget(id: string, forceAtlasElement: ForceAtlasElement) { - const edges = getEdges(forceAtlasElement, edge => edge.source === id || edge.target === id); + const edges = getEdges(forceAtlasElement, (edge) => edge.source === id || edge.target === id); return edges; } diff --git a/packages/graph-viz/src/force-atlas/utils/node.ts b/packages/graph-viz/src/force-atlas/utils/node.ts index b16b18731..014ff731f 100644 --- a/packages/graph-viz/src/force-atlas/utils/node.ts +++ b/packages/graph-viz/src/force-atlas/utils/node.ts @@ -7,12 +7,12 @@ import { DEFAULT_NODE_ICON_COLOR, NODE_ICON_FONT_SIZE } from '../constants'; export function getNodes(forceAtlasElement: ForceAtlasElement, andBack?: (edge: ForceAtlasNodeElement) => boolean) { return forceAtlasElement.children?.filter( - f => ForceAtlasElement.isForceAtlasNodeElement(f) && (andBack?.(f) ?? true) + (f) => ForceAtlasElement.isForceAtlasNodeElement(f) && (andBack?.(f) ?? true) ) as ForceAtlasNodeElement[]; } export function getNodeById(id: string, forceAtlasElement: ForceAtlasElement) { - const node = getNodes(forceAtlasElement, node => node.id === id)?.[0]; + const node = getNodes(forceAtlasElement, (node) => node.id === id)?.[0]; if (!node) { throw new Error('can not find node.'); } @@ -20,7 +20,7 @@ export function getNodeById(id: string, forceAtlasElement: ForceAtlasElement) { } export function getIsNodeActive(id: string, selectElements: ForceAtlasNodeElement[]) { - return selectElements.some(node => node.id === id); + return selectElements.some((node) => node.id === id); } export function isHitNode(node: ForceAtlasNodeElement, point: [Point, Point]) { @@ -38,7 +38,7 @@ export function isHitNode(node: ForceAtlasNodeElement, point: [Point, Point]) { export function getAssociatedNodesById(id: string, forceAtlasElement: ForceAtlasElement) { const edges = getEdgesInSourceOrTarget(id, forceAtlasElement); const nodes: ForceAtlasNodeElement[] = []; - edges.forEach(edge => { + edges.forEach((edge) => { nodes.push(getNodeById(edge.source, forceAtlasElement)); nodes.push(getNodeById(edge.target, forceAtlasElement)); }); @@ -53,7 +53,7 @@ export function getNodeGenerator(node: ForceAtlasNodeElement) { export function isFirstDepthNode(currentNodeId: string, activeNodeId: string, forceAtlasElement: ForceAtlasElement) { const edges = getEdges(forceAtlasElement); return edges.some( - s => (s.source === activeNodeId && s.target === currentNodeId) || (s.target === activeNodeId && s.source === currentNodeId) + (s) => (s.source === activeNodeId && s.target === currentNodeId) || (s.target === activeNodeId && s.source === currentNodeId) ); } diff --git a/packages/layouts/src/algorithms/non-overlapping-tree-layout.ts b/packages/layouts/src/algorithms/non-overlapping-tree-layout.ts index b79f4eb7d..2ada1626f 100644 --- a/packages/layouts/src/algorithms/non-overlapping-tree-layout.ts +++ b/packages/layouts/src/algorithms/non-overlapping-tree-layout.ts @@ -125,7 +125,7 @@ function firstWalk(treeNode: LayoutTreeNode) { firstWalk(treeNode.children[0]); for (let i = 1; i < treeNode.childrenCount; i++) { // Handle abstract effects on layout at the next node next of abstract end node - const abstract = treeNode.children.find(abstract => { + const abstract = treeNode.children.find((abstract) => { let correctEnd = null; if (AbstractNode.isAbstract(abstract.origin.origin)) { let { end } = getCorrectStartEnd(abstract.origin.origin, treeNode.origin); diff --git a/packages/layouts/src/interfaces/layout-node.ts b/packages/layouts/src/interfaces/layout-node.ts index fd719f930..19d1a66c1 100644 --- a/packages/layouts/src/interfaces/layout-node.ts +++ b/packages/layouts/src/interfaces/layout-node.ts @@ -66,7 +66,7 @@ export class LayoutNode { width: 0, height: 0 }; - this.eachNode(node => { + this.eachNode((node) => { bb.left = Math.min(bb.left, node.x); bb.top = Math.min(bb.top, node.y); bb.right = Math.max(bb.right, node.x + node.width); @@ -78,7 +78,7 @@ export class LayoutNode { } translate(tx = 0, ty = 0) { - this.eachNode(node => { + this.eachNode((node) => { node.x += tx; node.y += ty; }); @@ -87,7 +87,7 @@ export class LayoutNode { right2left() { const me = this; const bb = me.getBoundingBox(); - me.eachNode(node => { + me.eachNode((node) => { node.x = node.x - (node.x - bb.left) * 2 - node.width; node.left = true; }); @@ -97,7 +97,7 @@ export class LayoutNode { down2up() { const me = this; const bb = me.getBoundingBox(); - me.eachNode(node => { + me.eachNode((node) => { node.y = node.y - (node.y - bb.top) * 2 - node.height; node.up = true; }); @@ -106,7 +106,7 @@ export class LayoutNode { } function depthFirstRecursion(node: LayoutNode, callback: (node: LayoutNode) => void) { - node.children?.forEach(child => { + node.children?.forEach((child) => { depthFirstRecursion(child, callback); }); callback(node); diff --git a/packages/layouts/src/layouts/base-layout.ts b/packages/layouts/src/layouts/base-layout.ts index dc74ee021..ed9600aa5 100644 --- a/packages/layouts/src/layouts/base-layout.ts +++ b/packages/layouts/src/layouts/base-layout.ts @@ -25,7 +25,7 @@ export class BaseLayout { // 2、handle sub node layout isolatedNodes - .filter(v => v.origin.children.length > 0) + .filter((v) => v.origin.children.length > 0) .forEach((isolatedNode: LayoutNode) => { const _mindLayoutType = isolatedNode.layout as MindLayoutType; const toTop = context.toTop || (isHorizontalLayout(context.rootLayoutType) && isTopLayout(_mindLayoutType)); @@ -85,7 +85,7 @@ export class BaseLayout { // 5、apply isolated nodes to root const attachedMetaOfIsolatedNodes: { parent: LayoutNode; offsetX: number; offsetY: number }[] = []; // store the offset caused by isolated nodes to avoid multiple offset accumulation isolatedNodes - .filter(v => v.origin.children.length > 0) + .filter((v) => v.origin.children.length > 0) .forEach((isolatedNode: LayoutNode, index) => { if (isolatedNode.parent) { const layoutRoot = isolatedLayoutRoots[index]; @@ -105,7 +105,7 @@ export class BaseLayout { const oldNode = isolatedNode.parent.children[_index]; isolatedNode.parent.children[_index] = Object.assign(oldNode, layoutRoot); const meta = attachedMetaOfIsolatedNodes.find( - m => m.parent === isolatedNode.parent && !AbstractNode.isAbstract(isolatedNode.origin) + (m) => m.parent === isolatedNode.parent && !AbstractNode.isAbstract(isolatedNode.origin) ); if (meta) { if (meta.offsetX < offsetX) { @@ -120,8 +120,8 @@ export class BaseLayout { } }); // 6、correct the offset of sibling nodes caused by sub-layout - attachedMetaOfIsolatedNodes.forEach(meta => { - meta.parent.children.forEach(child => child.translate(meta.offsetX, meta.offsetY)); + attachedMetaOfIsolatedNodes.forEach((meta) => { + meta.parent.children.forEach((child) => child.translate(meta.offsetX, meta.offsetY)); }); return root; diff --git a/packages/layouts/src/layouts/global-layout.ts b/packages/layouts/src/layouts/global-layout.ts index 3b648d15c..824f4d2f1 100644 --- a/packages/layouts/src/layouts/global-layout.ts +++ b/packages/layouts/src/layouts/global-layout.ts @@ -49,10 +49,10 @@ export class GlobalLayout { leftRoot.right2left(); rightRoot.translate(leftRoot.x - rightRoot.x, leftRoot.y - rightRoot.y); - const rightAbstractArray = rightRoot.children.filter(child => AbstractNode.isAbstract(child.origin)); - rightRoot.children = rightRoot.children.filter(child => !AbstractNode.isAbstract(child.origin)); + const rightAbstractArray = rightRoot.children.filter((child) => AbstractNode.isAbstract(child.origin)); + rightRoot.children = rightRoot.children.filter((child) => !AbstractNode.isAbstract(child.origin)); - leftRoot.children.forEach(leftPrimaryNode => { + leftRoot.children.forEach((leftPrimaryNode) => { rightRoot.children.push(leftPrimaryNode); leftPrimaryNode.parent = rightRoot; }); diff --git a/packages/layouts/src/layouts/indent.ts b/packages/layouts/src/layouts/indent.ts index debec4e0c..014f92a31 100644 --- a/packages/layouts/src/layouts/indent.ts +++ b/packages/layouts/src/layouts/indent.ts @@ -5,7 +5,7 @@ import { isHorizontalLogicLayout } from '../utils/layout'; export function separateXAxle(node: LayoutNode, d = 0) { node.x = d; - node.children.forEach(child => { + node.children.forEach((child) => { if (AbstractNode.isAbstract(child.origin)) { let width = 0; for (let i = child.origin.start!; i <= child.origin.end!; i++) { @@ -25,7 +25,7 @@ export function separateYAxle(root: LayoutNode, options: LayoutOptions) { updateY(root); function updateY(node: LayoutNode) { node.children.forEach((child, index) => { - const abstract = node.children.find(child => { + const abstract = node.children.find((child) => { return AbstractNode.isAbstract(child.origin) && child.origin.end === index - 1; }); if (abstract) { @@ -85,7 +85,7 @@ function abstractHandle(node: LayoutNode, abstract: LayoutNode) { if (abstractBranchHeight > abstractIncludedHeight) { const distance = (abstractBranchHeight - abstractIncludedHeight) / 2; for (let i = abstractNode.start; i <= abstractNode.end; i++) { - node.children[i].eachNode(child => { + node.children[i].eachNode((child) => { child.y += distance; }); } diff --git a/packages/layouts/src/layouts/logic.ts b/packages/layouts/src/layouts/logic.ts index d0da8b033..a039292f4 100644 --- a/packages/layouts/src/layouts/logic.ts +++ b/packages/layouts/src/layouts/logic.ts @@ -37,14 +37,14 @@ export function separateYAxle(node: LayoutNode, isHorizontal: boolean, d = 0) { node.y = d; d += node.height; } - node.children.forEach(child => { + node.children.forEach((child) => { separateYAxle(child, isHorizontal, d); }); } export const buildLayoutTree = (root: LayoutNode, isHorizontal: boolean) => { const children: LayoutTreeNode[] = []; - root.children.forEach(child => { + root.children.forEach((child) => { children.push(buildLayoutTree(child, isHorizontal)); }); if (isHorizontal) { diff --git a/packages/layouts/src/utils/abstract.ts b/packages/layouts/src/utils/abstract.ts index 461d9a1b7..9d3101744 100644 --- a/packages/layouts/src/utils/abstract.ts +++ b/packages/layouts/src/utils/abstract.ts @@ -5,7 +5,7 @@ import { isStandardLayout } from './layout'; export const getNonAbstractChildren = (parentNode: T) => { if (parentNode.children) { - return parentNode.children?.filter(child => { + return parentNode.children?.filter((child) => { if (child instanceof LayoutNode) { return !AbstractNode.isAbstract(child.origin); } @@ -21,7 +21,7 @@ export const getNonAbstractChildren = (parentNode: T, endNode: T) => { const index = parentNode.children.indexOf(endNode); - return parentNode.children.find(child => { + return parentNode.children.find((child) => { if (child instanceof LayoutNode) { return AbstractNode.isAbstract(child.origin) && child.origin.end === index; } @@ -38,7 +38,7 @@ export const findAbstractByEndNode = (parentNode: T, startNode: T) => { const index = parentNode.children.indexOf(startNode); - return parentNode.children.find(child => { + return parentNode.children.find((child) => { if (child instanceof LayoutNode) { return AbstractNode.isAbstract(child.origin) && child.origin.start === index; } diff --git a/packages/mind/src/constants/default.ts b/packages/mind/src/constants/default.ts index 3fef3f24a..a184383fb 100644 --- a/packages/mind/src/constants/default.ts +++ b/packages/mind/src/constants/default.ts @@ -1,4 +1,4 @@ -import { rgbaToHEX } from "@plait/core"; +import { rgbaToHEX } from '@plait/core'; export const WithMindPluginKey = 'plait-mind-plugin-key'; @@ -28,4 +28,4 @@ export const DEFAULT_MIND_IMAGE_WIDTH = 240; export enum MindI18nKey { mindCentralText = 'mind-center-text', abstractNodeText = 'abstract-node-text' -} \ No newline at end of file +} diff --git a/packages/mind/src/generators/node-emojis.generator.ts b/packages/mind/src/generators/node-emojis.generator.ts index 1327f944d..a87248f99 100644 --- a/packages/mind/src/generators/node-emojis.generator.ts +++ b/packages/mind/src/generators/node-emojis.generator.ts @@ -57,8 +57,8 @@ export class NodeEmojisGenerator { const container = document.createElement('div'); container.classList.add('node-emojis-container'); foreignObject.append(container); - this.emojiGenerators = element.data.emojis.map(emojiItem => { - const drawer = new EmojiGenerator((this.board as unknown) as PlaitBoard & PlaitMindEmojiBoard); + this.emojiGenerators = element.data.emojis.map((emojiItem) => { + const drawer = new EmojiGenerator(this.board as unknown as PlaitBoard & PlaitMindEmojiBoard); drawer.draw(container, emojiItem, element); return drawer; }); @@ -71,7 +71,7 @@ export class NodeEmojisGenerator { if (this.g) { this.g.remove(); } - this.emojiGenerators.forEach(drawer => drawer.destroy()); + this.emojiGenerators.forEach((drawer) => drawer.destroy()); this.emojiGenerators = []; } } diff --git a/packages/mind/src/plugins/with-mind-fragment.ts b/packages/mind/src/plugins/with-mind-fragment.ts index 7b19b437a..2bfab8c88 100644 --- a/packages/mind/src/plugins/with-mind-fragment.ts +++ b/packages/mind/src/plugins/with-mind-fragment.ts @@ -76,7 +76,7 @@ export const withMindFragment = (baseBoard: PlaitBoard) => { board.insertFragment = (clipboardData: ClipboardData | null, targetPoint: Point, operationType?: WritableClipboardOperationType) => { if (clipboardData?.elements?.length) { - const mindElements = clipboardData.elements?.filter(value => MindElement.isMindElement(board, value)); + const mindElements = clipboardData.elements?.filter((value) => MindElement.isMindElement(board, value)); if (mindElements && mindElements.length > 0) { insertClipboardData(board, mindElements, targetPoint, operationType); } @@ -120,7 +120,7 @@ export const getNextSelectedElement = (board: PlaitBoard, firstLevelElements: Mi const firstElement = firstLevelElements[0]; const firstElementParent = MindElement.findParent(firstElement); - const hasSameParent = firstLevelElements.every(element => { + const hasSameParent = firstLevelElements.every((element) => { return MindElement.findParent(element) === firstElementParent; }); if (firstElementParent && hasSameParent && !activeElement) { diff --git a/packages/mind/src/plugins/with-mind-hotkey.spec.ts b/packages/mind/src/plugins/with-mind-hotkey.spec.ts index 6ecbd8663..4b175c30c 100644 --- a/packages/mind/src/plugins/with-mind-hotkey.spec.ts +++ b/packages/mind/src/plugins/with-mind-hotkey.spec.ts @@ -22,7 +22,7 @@ describe('with mind hotkey plugin', () => { let board: PlaitBoard; const targetPath = [0, 0]; beforeEach(() => { - const child1 = createMindElement('sub child',{}); + const child1 = createMindElement('sub child', {}); const children = getTestingChildren(); board = createTestingBoard([withMindHotkey], children); fakeNodeWeakMap(board); diff --git a/packages/mind/src/plugins/with-mind-hotkey.ts b/packages/mind/src/plugins/with-mind-hotkey.ts index 23f475179..823f97ba9 100644 --- a/packages/mind/src/plugins/with-mind-hotkey.ts +++ b/packages/mind/src/plugins/with-mind-hotkey.ts @@ -66,8 +66,13 @@ export const withMindHotkey = (baseBoard: PlaitBoard) => { if (isHotkey('mod+z', event)) { const { history } = board; const { undos } = history; - const previousOp = undos.length > 0 ? undos[undos.length - 1][0] : undefined; - if (previousOp && previousOp.type === 'insert_node' && MindElement.isMindElement(board, previousOp.node) && getFirstTextManage(previousOp.node).isEditing) { + const previousOp = undos.length > 0 ? undos[undos.length - 1][0] : undefined; + if ( + previousOp && + previousOp.type === 'insert_node' && + MindElement.isMindElement(board, previousOp.node) && + getFirstTextManage(previousOp.node).isEditing + ) { board.undo(); } } diff --git a/packages/mind/src/queries/get-available-sublayouts-by-element.ts b/packages/mind/src/queries/get-available-sublayouts-by-element.ts index 766d6b826..19f3f465b 100644 --- a/packages/mind/src/queries/get-available-sublayouts-by-element.ts +++ b/packages/mind/src/queries/get-available-sublayouts-by-element.ts @@ -18,8 +18,8 @@ export const getAvailableSubLayoutsByElement = (board: PlaitBoard, element: Mind const parentDirections = getBranchDirectionsByLayouts(parentLayout); const parentAvailableSubLayouts = getAvailableSubLayoutsByLayoutDirections(parentDirections); - availableSubLayouts = availableSubLayouts.filter(layout => - parentAvailableSubLayouts.some(parentAvailableSubLayout => parentAvailableSubLayout === layout) + availableSubLayouts = availableSubLayouts.filter((layout) => + parentAvailableSubLayouts.some((parentAvailableSubLayout) => parentAvailableSubLayout === layout) ); return availableSubLayouts; } diff --git a/packages/mind/src/queries/get-correct-layout-by-element.ts b/packages/mind/src/queries/get-correct-layout-by-element.ts index ee07ddd4f..beb867ee6 100644 --- a/packages/mind/src/queries/get-correct-layout-by-element.ts +++ b/packages/mind/src/queries/get-correct-layout-by-element.ts @@ -26,7 +26,7 @@ export const getCorrectLayoutByElement = (board: PlaitBoard, element: MindElemen } let layout = null; - const elementWithLayout = ancestors.find(value => value.layout || AbstractNode.isAbstract(value)); + const elementWithLayout = ancestors.find((value) => value.layout || AbstractNode.isAbstract(value)); if (elementWithLayout) { if (AbstractNode.isAbstract(elementWithLayout)) { const parent = MindElement.getParent(elementWithLayout); diff --git a/packages/mind/src/testing/core/fake-layout-node.ts b/packages/mind/src/testing/core/fake-layout-node.ts index 291f82495..39f532da6 100644 --- a/packages/mind/src/testing/core/fake-layout-node.ts +++ b/packages/mind/src/testing/core/fake-layout-node.ts @@ -8,7 +8,7 @@ import { PlaitMindBoard } from '../../plugins/with-mind.board'; export const fakeMindLayout = (board: PlaitMindBoard, mind: PlaitMind) => { const mindLayoutType = mind.layout || getDefaultLayout(); - const root = (GlobalLayout.layout((mind as unknown) as OriginNode, getLayoutOptions(board), mindLayoutType) as unknown) as MindNode; + const root = GlobalLayout.layout(mind as unknown as OriginNode, getLayoutOptions(board), mindLayoutType) as unknown as MindNode; updateMindNodeLocation(mind, root); return root; }; @@ -17,7 +17,7 @@ export const updateMindNodeLocation = (mind: PlaitMind, root: MindNode) => { const { x, y, hGap, vGap } = root; const offsetX = x + hGap; const offsetY = y + vGap; - depthFirstRecursion(root, node => { + depthFirstRecursion(root, (node) => { node.x = node.x - offsetX + mind.points[0][0]; node.y = node.y - offsetY + mind.points[0][1]; MIND_ELEMENT_TO_NODE.set(node.origin, node); @@ -25,7 +25,7 @@ export const updateMindNodeLocation = (mind: PlaitMind, root: MindNode) => { }; export const clearLayoutNodeWeakMap = (root: MindNode) => { - depthFirstRecursion(root, node => { + depthFirstRecursion(root, (node) => { MIND_ELEMENT_TO_NODE.delete(node.origin); }); }; diff --git a/packages/mind/src/transforms/emoji.ts b/packages/mind/src/transforms/emoji.ts index 1fcdaed95..e85db7aff 100644 --- a/packages/mind/src/transforms/emoji.ts +++ b/packages/mind/src/transforms/emoji.ts @@ -14,7 +14,7 @@ export const addEmoji = (board: PlaitBoard, element: MindElement, emojiItem: Emo }; export const removeEmoji = (board: PlaitBoard, element: MindElement, emojiItem: EmojiItem) => { - const emojis = element.data.emojis.filter(value => value !== emojiItem); + const emojis = element.data.emojis.filter((value) => value !== emojiItem); const newElement = { data: { topic: element.data.topic } } as MindElement; @@ -34,7 +34,7 @@ export const replaceEmoji = (board: PlaitBoard, element: MindElement, const newElement = { data: { ...element.data } } as MindElement; - const newEmojis = element.data.emojis.map(value => { + const newEmojis = element.data.emojis.map((value) => { if (value === oldEmoji) { return newEmoji; } diff --git a/packages/mind/src/utils/abstract/common.ts b/packages/mind/src/utils/abstract/common.ts index 0a69df7f8..8792d412d 100644 --- a/packages/mind/src/utils/abstract/common.ts +++ b/packages/mind/src/utils/abstract/common.ts @@ -42,7 +42,7 @@ export const getCorrespondingAbstract = (element: MindElement) => { if (!parent) return undefined; const elementIndex = parent.children.indexOf(element); - return parent.children.find(child => { + return parent.children.find((child) => { return AbstractNode.isAbstract(child) && elementIndex >= child.start! && elementIndex <= child.end!; }); }; @@ -51,7 +51,7 @@ export const getBehindAbstracts = (element: MindElement) => { const parent = MindElement.findParent(element as MindElement); if (!parent) return []; const index = parent.children.indexOf(element); - return parent.children.filter(child => AbstractNode.isAbstract(child) && child.start! > index); + return parent.children.filter((child) => AbstractNode.isAbstract(child) && child.start! > index); }; /** @@ -60,13 +60,15 @@ export const getBehindAbstracts = (element: MindElement) => { export const getOverallAbstracts = (board: PlaitBoard, elements: MindElement[]) => { const overallAbstracts: MindElement[] = []; elements - .filter(value => !AbstractNode.isAbstract(value) && !PlaitMind.isMind(value)) - .forEach(value => { + .filter((value) => !AbstractNode.isAbstract(value) && !PlaitMind.isMind(value)) + .forEach((value) => { const abstract = getCorrespondingAbstract(value); if (abstract && elements.indexOf(abstract) === -1 && overallAbstracts.indexOf(abstract) === -1) { const { start, end } = abstract; const parent = MindElement.getParent(value); - const isOverall = parent.children.slice(start!, end! + 1).every(includedElement => elements.indexOf(includedElement) > -1); + const isOverall = parent.children + .slice(start!, end! + 1) + .every((includedElement) => elements.indexOf(includedElement) > -1); if (isOverall) { overallAbstracts.push(abstract); } @@ -86,11 +88,11 @@ export interface AbstractRef { export const getValidAbstractRefs = (board: PlaitBoard, elements: MindElement[]) => { const validAbstractRefs: AbstractRef[] = []; elements - .filter(value => !AbstractNode.isAbstract(value) && !PlaitMind.isMind(value)) - .forEach(value => { + .filter((value) => !AbstractNode.isAbstract(value) && !PlaitMind.isMind(value)) + .forEach((value) => { const abstract = getCorrespondingAbstract(value); if (abstract && elements.indexOf(abstract) > 0) { - const index = validAbstractRefs.findIndex(value => value.abstract === abstract); + const index = validAbstractRefs.findIndex((value) => value.abstract === abstract); if (index === -1) { validAbstractRefs.push({ abstract: abstract as MindElement & AbstractNode, @@ -123,14 +125,14 @@ export const insertElementHandleAbstract = ( let behindAbstracts: MindElement[]; if (!hasPreviousNode) { - behindAbstracts = parent.children.filter(child => AbstractNode.isAbstract(child)); + behindAbstracts = parent.children.filter((child) => AbstractNode.isAbstract(child)); } else { const selectedElement = PlaitNode.get(board, Path.previous(path)) as MindElement; behindAbstracts = getBehindAbstracts(selectedElement); } if (behindAbstracts.length) { - behindAbstracts.forEach(abstract => { + behindAbstracts.forEach((abstract) => { let newProperties = effectedAbstracts.get(abstract); if (!newProperties) { newProperties = { start: 0, end: 0 }; @@ -166,11 +168,11 @@ export const deleteElementHandleAbstract = ( deletableElements: MindElement[], effectedAbstracts = new Map>() ) => { - deletableElements.forEach(node => { + deletableElements.forEach((node) => { if (!PlaitMind.isMind(node)) { - const behindAbstracts = getBehindAbstracts(node).filter(abstract => !deletableElements.includes(abstract)); + const behindAbstracts = getBehindAbstracts(node).filter((abstract) => !deletableElements.includes(abstract)); if (behindAbstracts.length) { - behindAbstracts.forEach(abstract => { + behindAbstracts.forEach((abstract) => { let newProperties = effectedAbstracts.get(abstract); if (!newProperties) { newProperties = { start: 0, end: 0 }; @@ -198,5 +200,5 @@ export const deleteElementHandleAbstract = ( export const isChildOfAbstract = (board: PlaitBoard, element: MindElement) => { const ancestors = MindElement.getAncestors(board, element) as MindElement[]; - return !!ancestors.find(value => AbstractNode.isAbstract(value)); + return !!ancestors.find((value) => AbstractNode.isAbstract(value)); }; diff --git a/packages/mind/src/utils/abstract/resize.ts b/packages/mind/src/utils/abstract/resize.ts index b7fc4083b..bcb1236a7 100644 --- a/packages/mind/src/utils/abstract/resize.ts +++ b/packages/mind/src/utils/abstract/resize.ts @@ -52,19 +52,19 @@ export const getLocationScope = ( parent: LayoutNode, isHorizontal: boolean ) => { - const node = (MindElement.getNode(element) as unknown) as LayoutNode; + const node = MindElement.getNode(element) as unknown as LayoutNode; const { start, end } = getCorrectStartEnd(node.origin as AbstractNode, parent); const startNode = parentChildren[start]; const endNode = parentChildren[end]; if (handlePosition === AbstractHandlePosition.start) { - const abstractNode = parentChildren.filter(child => AbstractNode.isAbstract(child) && child.end < element.start!); + const abstractNode = parentChildren.filter((child) => AbstractNode.isAbstract(child) && child.end < element.start!); let minNode; if (abstractNode.length) { const index = abstractNode - .map(node => { + .map((node) => { const { end } = getCorrectStartEnd(node as AbstractNode, parent); return end; }) @@ -89,19 +89,19 @@ export const getLocationScope = ( }; } } else { - const abstractNode = parentChildren.filter(child => AbstractNode.isAbstract(child) && child.start > element.end!); + const abstractNode = parentChildren.filter((child) => AbstractNode.isAbstract(child) && child.start > element.end!); let maxNode; if (abstractNode.length) { const index = abstractNode - .map(node => { + .map((node) => { const { start } = getCorrectStartEnd(node as AbstractNode, parent); return start; }) .sort((a, b) => a - b)[0]; maxNode = parentChildren[index - 1]; } else { - const children = parentChildren.filter(child => !AbstractNode.isAbstract(child)); + const children = parentChildren.filter((child) => !AbstractNode.isAbstract(child)); maxNode = parentChildren[children.length - 1]; } @@ -167,10 +167,10 @@ export const getAbstractHandleRectangle = (rectangle: RectangleClient, isHorizon }; export function findLocationLeftIndex(board: PlaitBoard, parentChildren: MindElement[], location: number, isHorizontal: boolean) { - const children = parentChildren.filter(child => { + const children = parentChildren.filter((child) => { return !AbstractNode.isAbstract(child); }); - const recArray = children.map(child => { + const recArray = children.map((child) => { return getRectangleByElements(board, [child], false); }); @@ -208,7 +208,7 @@ export function findLocationLeftIndex(board: PlaitBoard, parentChildren: MindEle export function handleTouchedAbstract(board: PlaitBoard, touchedAbstract: MindElement | undefined, endPoint: Point) { let touchedHandle; - const abstract = (getSelectedElements(board).filter(element => AbstractNode.isAbstract(element)) as MindElement[]).find(element => { + const abstract = (getSelectedElements(board).filter((element) => AbstractNode.isAbstract(element)) as MindElement[]).find((element) => { touchedHandle = getHitAbstractHandle(board, element as MindElement, endPoint); return touchedHandle; }); diff --git a/packages/mind/src/utils/dnd/common.ts b/packages/mind/src/utils/dnd/common.ts index e73008af4..be2979095 100644 --- a/packages/mind/src/utils/dnd/common.ts +++ b/packages/mind/src/utils/dnd/common.ts @@ -8,7 +8,7 @@ export const addActiveOnDragOrigin = (activeElement: MindElement) => { PlaitElement.getElementG(activeElement).classList.add('dragging-node'); !activeElement.isCollapsed && - activeElement.children.forEach(child => { + activeElement.children.forEach((child) => { addActiveOnDragOrigin(child); }); }; @@ -16,7 +16,7 @@ export const addActiveOnDragOrigin = (activeElement: MindElement) => { export const removeActiveOnDragOrigin = (activeElement: MindElement) => { PlaitElement.getElementG(activeElement).classList.remove('dragging-node'); !activeElement.isCollapsed && - activeElement.children.forEach(child => { + activeElement.children.forEach((child) => { removeActiveOnDragOrigin(child); }); }; diff --git a/packages/mind/src/utils/draw/node-link/abstract-link.ts b/packages/mind/src/utils/draw/node-link/abstract-link.ts index 226f3d401..8869e82ca 100644 --- a/packages/mind/src/utils/draw/node-link/abstract-link.ts +++ b/packages/mind/src/utils/draw/node-link/abstract-link.ts @@ -16,7 +16,7 @@ export function drawAbstractLink(board: PlaitBoard, node: MindNode, isHorizontal const parent = node.parent; const branchShape = getBranchShapeByMindElement(board, node.origin); const abstractRectangle = getRectangleByNode(node); - let includedElements = parent.children.slice(node.origin.start, node.origin.end! + 1).map(node => { + let includedElements = parent.children.slice(node.origin.start, node.origin.end! + 1).map((node) => { return node.origin; }); const includedElementsRectangle = getRectangleByElements(board, includedElements, true); diff --git a/packages/mind/src/utils/layout.ts b/packages/mind/src/utils/layout.ts index aa0cd3ac6..e1bd455ab 100644 --- a/packages/mind/src/utils/layout.ts +++ b/packages/mind/src/utils/layout.ts @@ -3,9 +3,9 @@ import { isIndentedLayout, MindLayoutType } from '@plait/layouts'; export const getBranchDirectionsByLayouts = (branchLayouts: MindLayoutType[]) => { const branchDirections: LayoutDirection[] = []; - branchLayouts.forEach(l => { + branchLayouts.forEach((l) => { const directions = LayoutDirectionsMap[l]; - directions.forEach(d => { + directions.forEach((d) => { if (!branchDirections.includes(d) && !branchDirections.includes(getLayoutReverseDirection(d))) { branchDirections.push(d); } @@ -29,7 +29,7 @@ export const getInCorrectLayoutDirection = (rootLayout: MindLayoutType, layout: if (!subLayoutDirections) { throw new Error(`unexpected layout: ${layout} on correct layout`); } - return subLayoutDirections.find(d => directions.includes(getLayoutReverseDirection(d))); + return subLayoutDirections.find((d) => directions.includes(getLayoutReverseDirection(d))); }; export const correctLayoutByDirection = (layout: MindLayoutType, direction: LayoutDirection) => { @@ -80,8 +80,8 @@ export const getAvailableSubLayoutsByLayoutDirections = (directions: LayoutDirec const layout = MindLayoutType[key as keyof typeof MindLayoutType]; const layoutDirections = LayoutDirectionsMap[layout]; if (layoutDirections) { - const hasSameDirection = layoutDirections.some(d => directions.includes(d)); - const hasReverseDirection = layoutDirections.some(r => reverseDirections.includes(r)); + const hasSameDirection = layoutDirections.some((d) => directions.includes(d)); + const hasReverseDirection = layoutDirections.some((r) => reverseDirections.includes(r)); if (hasSameDirection && !hasReverseDirection) { result.push(layout); } diff --git a/packages/mind/src/utils/node-style/branch.ts b/packages/mind/src/utils/node-style/branch.ts index 512e09fb8..0790d1da0 100644 --- a/packages/mind/src/utils/node-style/branch.ts +++ b/packages/mind/src/utils/node-style/branch.ts @@ -62,7 +62,7 @@ export const getDefaultBranchColorByIndex = (board: PlaitBoard, index: number) = export const getMindThemeColor = (board: PlaitBoard) => { const themeColors = PlaitBoard.getThemeColors(board); - const themeColor = themeColors.find(val => val.mode === board.theme.themeColorMode); + const themeColor = themeColors.find((val) => val.mode === board.theme.themeColorMode); if (themeColor && MindThemeColor.isMindThemeColor(themeColor)) { return themeColor; } else { diff --git a/packages/mind/src/utils/node/common.ts b/packages/mind/src/utils/node/common.ts index 5858f72cf..9a803119c 100644 --- a/packages/mind/src/utils/node/common.ts +++ b/packages/mind/src/utils/node/common.ts @@ -6,7 +6,7 @@ export function editTopic(element: MindElement) { const textManage = getFirstTextManage(element); textManage?.edit( () => {}, - event => { + (event) => { const keyboardEvent = event as KeyboardEvent; return keyboardEvent.key === 'Enter' && !keyboardEvent.shiftKey; } @@ -15,5 +15,5 @@ export function editTopic(element: MindElement) { export const getSelectedMindElements = (board: PlaitBoard, elements?: PlaitElement[]) => { const selectedElements = elements?.length ? elements : getSelectedElements(board); - return selectedElements.filter(value => MindElement.isMindElement(board, value)) as MindElement[]; + return selectedElements.filter((value) => MindElement.isMindElement(board, value)) as MindElement[]; }; diff --git a/packages/mind/src/utils/position/image.ts b/packages/mind/src/utils/position/image.ts index 2a3eded65..8f426a1a1 100644 --- a/packages/mind/src/utils/position/image.ts +++ b/packages/mind/src/utils/position/image.ts @@ -33,7 +33,7 @@ export const isHitImage = (board: PlaitBoard, element: MindElement, p export const getHitImageResizeHandleDirection = (board: PlaitBoard, element: MindElement, point: Point) => { const imageRectangle = getImageForeignRectangle(board as PlaitMindBoard, element); const resizeHandleRefs = getRectangleResizeHandleRefs(imageRectangle, RESIZE_HANDLE_DIAMETER); - const result = resizeHandleRefs.find(resizeHandleRef => { + const result = resizeHandleRefs.find((resizeHandleRef) => { return RectangleClient.isHit(RectangleClient.getRectangleByPoints([point, point]), resizeHandleRef.rectangle); }); return result; diff --git a/packages/text-plugins/src/link/link-editor.ts b/packages/text-plugins/src/link/link-editor.ts index 44e3c4a86..1eb029bb6 100644 --- a/packages/text-plugins/src/link/link-editor.ts +++ b/packages/text-plugins/src/link/link-editor.ts @@ -30,14 +30,17 @@ export const LinkEditor = { at = { anchor: Editor.start(editor, [0]), focus: Editor.end(editor, [0]) }; } } - Transforms.unwrapNodes(editor, { at, match: n => Element.isElement(n) && (n as LinkElement).type === 'link' }); + Transforms.unwrapNodes(editor, { at, match: (n) => Element.isElement(n) && (n as LinkElement).type === 'link' }); }, isLinkActive(editor: Editor) { let at = editor.selection as BaseRange; if (!at && editor.children && editor.children.length > 0) { at = { anchor: Editor.start(editor, [0]), focus: Editor.end(editor, [0]) }; } - const [link] = Editor.nodes(editor, { match: n => Element.isElement(n) && (n as LinkElement).type === 'link', at }); + const [link] = Editor.nodes(editor, { + match: (n) => Element.isElement(n) && (n as LinkElement).type === 'link', + at + }); return !!link; }, getLinkElement(editor: Editor) { @@ -45,7 +48,10 @@ export const LinkEditor = { if (!at && editor.children && editor.children.length > 0) { at = { anchor: Editor.start(editor, [0]), focus: Editor.end(editor, [0]) }; } - const [link] = Editor.nodes(editor, { match: n => Element.isElement(n) && (n as LinkElement).type === 'link', at }); + const [link] = Editor.nodes(editor, { + match: (n) => Element.isElement(n) && (n as LinkElement).type === 'link', + at + }); return link; } }; diff --git a/packages/text-plugins/src/text-transforms.spec.ts b/packages/text-plugins/src/text-transforms.spec.ts index 6bf7da880..06e056b02 100644 --- a/packages/text-plugins/src/text-transforms.spec.ts +++ b/packages/text-plugins/src/text-transforms.spec.ts @@ -3,4 +3,4 @@ describe('mock test', () => { const a = '1'; expect(a).toEqual('1'); }); -}); \ No newline at end of file +}); diff --git a/packages/text-plugins/src/text-transforms.ts b/packages/text-plugins/src/text-transforms.ts index 6e53ea3d0..3f6685c25 100644 --- a/packages/text-plugins/src/text-transforms.ts +++ b/packages/text-plugins/src/text-transforms.ts @@ -17,9 +17,9 @@ const setTextMarks = (board: PlaitBoard, mark: MarkTypes, editors?: BaseEditor[] return; } const activeMarks = PlaitMarkEditor.getMarks(firstEditor); - const elements = selectedElements.filter(element => { + const elements = selectedElements.filter((element) => { const elementEditors = getTextEditorsByElement(element); - return elementEditors.some(editor => { + return elementEditors.some((editor) => { const elementMarks = PlaitMarkEditor.getMarks(editor); return elementMarks[mark] === activeMarks[mark]; }); @@ -28,7 +28,7 @@ const setTextMarks = (board: PlaitBoard, mark: MarkTypes, editors?: BaseEditor[] } } if (textEditors && textEditors.length) { - textEditors.forEach(editor => { + textEditors.forEach((editor) => { PlaitMarkEditor.toggleMark(editor, mark); }); } @@ -43,10 +43,10 @@ const setFontSize = ( const textEditors = getHandleTextEditors(board, editors); if (textEditors && textEditors.length) { const selectedElements = getSelectedElements(board); - textEditors.forEach(editor => { + textEditors.forEach((editor) => { let finalDefaultFontSize; if (typeof defaultFontSize === 'function') { - const element = selectedElements.find(element => { + const element = selectedElements.find((element) => { const textEditors = getTextEditorsByElement(element); return textEditors.includes(editor); }); @@ -63,7 +63,7 @@ const setFontSize = ( const setTextColor = (board: PlaitBoard, color: string | null, textSelection?: BaseRange, editors?: BaseEditor[]) => { const textEditors = getHandleTextEditors(board, editors); if (textEditors && textEditors.length) { - textEditors.forEach(editor => { + textEditors.forEach((editor) => { if (textSelection) { SlateTransforms.select(editor, textSelection); } @@ -79,7 +79,7 @@ const setTextColor = (board: PlaitBoard, color: string | null, textSelection?: B const setTextAlign = (board: PlaitBoard, align: Alignment, editors?: BaseEditor[]) => { const textEditors = getHandleTextEditors(board, editors); if (textEditors && textEditors.length) { - textEditors.forEach(editor => AlignEditor.setAlign(editor, align)); + textEditors.forEach((editor) => AlignEditor.setAlign(editor, align)); } }; diff --git a/packages/text-plugins/src/types.ts b/packages/text-plugins/src/types.ts index 3a79ec63c..1e6570d8b 100644 --- a/packages/text-plugins/src/types.ts +++ b/packages/text-plugins/src/types.ts @@ -28,4 +28,4 @@ export interface ParagraphElement extends BaseElement { export type CustomElement = ParagraphElement | LinkElement; -export type TextPlugin = (editor: Editor) => Editor; \ No newline at end of file +export type TextPlugin = (editor: Editor) => Editor; diff --git a/src/app/components/debug/point-display.component.ts b/src/app/components/debug/point-display.component.ts index 69c4334db..71a4def0d 100644 --- a/src/app/components/debug/point-display.component.ts +++ b/src/app/components/debug/point-display.component.ts @@ -1,15 +1,11 @@ import { Component, ElementRef, inject, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; -import { - PlaitBoard, - toViewBoxPoint, - toHostPoint -} from '@plait/core'; +import { PlaitBoard, toViewBoxPoint, toHostPoint } from '@plait/core'; @Component({ selector: 'debug-point-display', template: ``, imports: [], host: { - 'style': 'position: absolute;top:0;left:0;' + style: 'position: absolute;top:0;left:0;' } }) export class DebugPointDisplayComponent implements OnInit, OnChanges { @@ -26,11 +22,11 @@ export class DebugPointDisplayComponent implements OnInit, OnChanges { if (changes['board'] && this.board) { const board = this.board as PlaitBoard; const { pointerMove } = board; - board.pointerMove = e => { + board.pointerMove = (e) => { pointerMove(e); const point = toViewBoxPoint(board, toHostPoint(board, e.x, e.y)); this.elementRef.nativeElement.innerHTML = `${point[0]},${point[1]}`; - } + }; } } } diff --git a/src/app/editor/emoji/emoji.component.ts b/src/app/editor/emoji/emoji.component.ts index 6c411bb6a..c0fa6ac3a 100644 --- a/src/app/editor/emoji/emoji.component.ts +++ b/src/app/editor/emoji/emoji.component.ts @@ -8,7 +8,7 @@ import { MindEmojiBaseComponent } from '@plait/mind'; changeDetection: ChangeDetectionStrategy.OnPush }) export class MindEmojiComponent extends MindEmojiBaseComponent implements OnInit { - elementRef = inject(ElementRef) + elementRef = inject(ElementRef); nativeElement() { return this.elementRef.nativeElement; diff --git a/src/app/editor/image/image.component.ts b/src/app/editor/image/image.component.ts index ef1abee8a..6d89e4a4d 100644 --- a/src/app/editor/image/image.component.ts +++ b/src/app/editor/image/image.component.ts @@ -3,9 +3,7 @@ import { CommonImageItem, ImageBaseComponent } from '@plait/common'; @Component({ selector: 'app-plait-image', - template: ` - - `, + template: ` `, changeDetection: ChangeDetectionStrategy.OnPush, standalone: true }) @@ -29,6 +27,5 @@ export class PlaitImageComponent extends ImageBaseComponent implements OnInit { return this.elementRef.nativeElement; } - ngOnInit(): void { - } + ngOnInit(): void {} } diff --git a/src/app/flow/flow-node-data.ts b/src/app/flow/flow-node-data.ts index 33dc70d00..fe3bb4583 100644 --- a/src/app/flow/flow-node-data.ts +++ b/src/app/flow/flow-node-data.ts @@ -95,7 +95,7 @@ export const mockCustomNodes: FlowElement[] = [ target: { nodeId: 'custom_node_02', position: Direction.top, - marker: true + marker: true }, points: [] }, diff --git a/src/app/flow/icon.component.ts b/src/app/flow/icon.component.ts index 40931be9f..a4958024c 100644 --- a/src/app/flow/icon.component.ts +++ b/src/app/flow/icon.component.ts @@ -3,9 +3,7 @@ import { FlowEdgeLabelIconBaseComponent } from '@plait/flow'; @Component({ selector: 'flow-edge-label-icon', - template: ` - {{ iconItem.name }} - `, + template: ` {{ iconItem.name }} `, standalone: true, changeDetection: ChangeDetectionStrategy.OnPush }) diff --git a/src/app/flow/plugins/with-common.ts b/src/app/flow/plugins/with-common.ts index d1728a670..cfee79d60 100644 --- a/src/app/flow/plugins/with-common.ts +++ b/src/app/flow/plugins/with-common.ts @@ -6,7 +6,7 @@ import { CustomBoard } from '../interfaces/board'; export const withCommon: PlaitPlugin = (board: CustomBoard) => { const { pointerUp, keyDown } = board; - board.pointerUp = event => { + board.pointerUp = (event) => { const newEdge = getCreateEdgeInfo(board); if (newEdge) { const sourceNode = getFlowNodeById(board, newEdge?.source?.nodeId!); @@ -36,7 +36,7 @@ export const withCommon: PlaitPlugin = (board: CustomBoard) => { if (hotkeys.isDeleteBackward(event) || hotkeys.isDeleteForward(event)) { event.preventDefault(); const deleteElement = selectedElements[0] as FlowElement; - const path = board.children.findIndex(item => item.id === deleteElement.id); + const path = board.children.findIndex((item) => item.id === deleteElement.id); if (FlowEdge.isFlowEdgeElement(deleteElement)) { if (!deleteElement.undeletable) { // 删除 edge @@ -50,8 +50,8 @@ export const withCommon: PlaitPlugin = (board: CustomBoard) => { // 删除 node Transforms.removeNode(board, [path]); // 删除与 node 相关连的 edge - edges.map(edge => { - const edgePath = board.children.findIndex(item => item.id === edge.id); + edges.map((edge) => { + const edgePath = board.children.findIndex((item) => item.id === edge.id); !edge.undeletable && Transforms.removeNode(board, [edgePath]); }); return; diff --git a/src/app/graph-viz/icon.component.ts b/src/app/graph-viz/icon.component.ts index 3cbde8ba0..4e4f82912 100644 --- a/src/app/graph-viz/icon.component.ts +++ b/src/app/graph-viz/icon.component.ts @@ -4,7 +4,23 @@ import { ForceAtlasNodeIconBaseComponent } from '@plait/graph-viz'; @Component({ selector: 'force-atlas-node-icon', template: ` - + + + + + `, standalone: true, changeDetection: ChangeDetectionStrategy.OnPush diff --git a/src/app/graph-viz/mock-force-atlas-wiki.ts b/src/app/graph-viz/mock-force-atlas-wiki.ts index 3b9499030..59bed0e2e 100644 --- a/src/app/graph-viz/mock-force-atlas-wiki.ts +++ b/src/app/graph-viz/mock-force-atlas-wiki.ts @@ -2276,7 +2276,7 @@ export function getData(index: number = 0) { console.log('节点数:', res.pages.length); const activeId = res.pages[0]._id; const nodes = res.pages.map( - page => + (page) => ({ id: page._id, label: page.name, diff --git a/src/app/plugins/with-line-route.ts b/src/app/plugins/with-line-route.ts index 9933e7248..b707f5fd4 100644 --- a/src/app/plugins/with-line-route.ts +++ b/src/app/plugins/with-line-route.ts @@ -140,7 +140,7 @@ export const fakeLineRouteProcess = (board: PlaitBoard) => { }; // 2、Construct connected points const points = getGraphPoints(options); - points.forEach(p => { + points.forEach((p) => { const controlPointG = rough.circle(p[0], p[1], 4, { stroke: '#f08c02', fill: '#f08c02', @@ -164,13 +164,13 @@ export const fakeLineRouteProcess = (board: PlaitBoard) => { throw new Error(`can't find current`); } const currentPoint = current!.node.data; - current.node.adjacentNodes.forEach(next => { + current.node.adjacentNodes.forEach((next) => { if (!reached.has(next)) { reached.add(next); frontier.enqueue({ node: next, priority: 0 }); } if ( - !edges.find(line => { + !edges.find((line) => { return Point.isEquals(line[0], next.data) && Point.isEquals(line[1], currentPoint); }) ) { @@ -179,7 +179,7 @@ export const fakeLineRouteProcess = (board: PlaitBoard) => { }); } // Figure edges effect diagram - edges.forEach(edges => { + edges.forEach((edges) => { const connectionG = rough.line(edges[0][0], edges[0][1], edges[1][0], edges[1][1], { stroke: rgbaToHEX('#007500', 0.2), strokeWidth: 1.5 @@ -311,8 +311,7 @@ export const mockLineData = [ text: { children: [ { - text: - 'Green connection: the connection through the center line corrected based on the shortest path with the fewest turning points', + text: 'Green connection: the connection through the center line corrected based on the shortest path with the fewest turning points', color: '#2f9e44', 'font-size': 15 } diff --git a/src/app/utils/popover.ts b/src/app/utils/popover.ts index c8451e913..e0deffa19 100644 --- a/src/app/utils/popover.ts +++ b/src/app/utils/popover.ts @@ -4,7 +4,7 @@ export function closeAction(action: () => void) { setTimeout(() => { fromEvent(document, 'click') .pipe(take(1)) - .subscribe(event => { + .subscribe((event) => { action(); }); }, 201); diff --git a/src/main.ts b/src/main.ts index ac46408c0..5e7d531d8 100644 --- a/src/main.ts +++ b/src/main.ts @@ -12,4 +12,4 @@ if (environment.production) { bootstrapApplication(AppComponent, { providers: [importProvidersFrom(BrowserModule, FormsModule, AppRoutingModule, SlateModule)] -}).catch(err => console.error(err)); +}).catch((err) => console.error(err));