@univerjs/docs-drawing-ui 1.0.4 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -1,12 +1,12 @@
1
- import { AlignTypeH, AlignTypeV, BooleanNumber, COLORS, CommandType, DOC_DRAWING_PRINTING_COMPONENT_KEY, DependentOn, Direction, Disposable, DisposableCollection, DocumentFlavor, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, ICommandService, IConfigService, IContextService, IImageIoService, IPermissionService, IUniverInstanceService, ImageSourceType, ImageUploadStatusType, Inject, Injector, JSON1, JSONX, LifecycleService, LifecycleStages, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, Plugin, PositionedObjectLayoutType, RedoCommand, RxDisposable, TextX, TextXActionType, Tools, UndoCommand, UniverInstanceType, WrapTextType, fromEventSubject, generateRandomId, getRichTextEditPath, isInternalEditorID, merge, throttle, toDisposable } from "@univerjs/core";
2
- import { IDocDrawingAdapterService, IDocDrawingService, InsertDocDrawingCommand, RemoveDocDrawingCommand, SetDocDrawingArrangeCommand, TextWrappingStyle, UniverDocsDrawingPlugin, UpdateDocDrawingWrappingStyleCommand, UpdateDrawingDocTransformCommand, collectDocDrawings, findDocDrawing, getDocDrawingRenderOrder } from "@univerjs/docs-drawing";
1
+ import { AlignTypeH, AlignTypeV, BooleanNumber, COLORS, CommandType, DOC_DRAWING_PRINTING_COMPONENT_KEY, DependentOn, Direction, Disposable, DisposableCollection, DocumentDataModel, DocumentFlavor, DrawingTypeEnum, FOCUSING_COMMON_DRAWINGS, FOCUSING_DOC, FOCUSING_UNIVER_EDITOR, ICommandService, IConfigService, IContextService, IImageIoService, IPermissionService, IUniverInstanceService, ImageSourceType, ImageUploadStatusType, Inject, Injector, JSON1, JSONX, LifecycleService, LifecycleStages, LocaleService, ObjectRelativeFromH, ObjectRelativeFromV, Plugin, PositionedObjectLayoutType, RedoCommand, RxDisposable, TextX, TextXActionType, ThemeService, Tools, UndoCommand, UniverInstanceType, WrapTextType, fromEventSubject, generateRandomId, getRichTextEditPath, isInternalEditorID, merge, toDisposable } from "@univerjs/core";
2
+ import { IDocDrawingAdapterService, IDocDrawingService, InsertDocDrawingCommand, RemoveDocDrawingCommand, SetDocDrawingArrangeCommand, TextWrappingStyle, UniverDocsDrawingPlugin, UpdateDocDrawingWrappingStyleCommand, UpdateDrawingDocTransformCommand, WRAPPING_STYLE_TO_LAYOUT_TYPE, collectDocDrawings, findDocDrawing, getDocDrawingRenderOrder } from "@univerjs/docs-drawing";
3
3
  import { DOC_CONTENT_INSERT_MENU_ID, DOC_PARAGRAPH_T_INSERT_BELOW_MENU_ID, DOC_PARAGRAPH_T_INSERT_MENU_ID, DocCanvasPopManagerService, DocPrintInterceptorService, DocSelectionRenderService, EMPTY_PARAGRAPH_MENU_ID, IEditorService, INSERT_BELLOW_MENU_ID, MOBILE_DOC_ELEMENT_MENU, NodePositionConvertToCursor, SetDocZoomRatioOperation, TEXT_RANGE_LAYER_INDEX, UniverDocsMobileUIPlugin, UniverDocsUIPlugin, VIEWPORT_KEY, getAnchorBounding, getOneTextSelectionRange, neoGetDocObject } from "@univerjs/docs-ui";
4
- import { CURSOR_TYPE, DocumentEditArea, DocumentSkeletonPageType, Documents, IRenderManagerService, Liquid, PageLayoutType, Rect, TRANSFORM_CHANGE_OBSERVABLE_TYPE, UniverRenderEnginePlugin, Vector2, getColor, getCurrentTypeOfRenderer, getDocsTableRenderViewport, getTableIdAndSliceIndex } from "@univerjs/engine-render";
4
+ import { CURSOR_TYPE, DocumentEditArea, DocumentSkeleton, DocumentSkeletonPageType, DocumentViewModel, Documents, IRenderManagerService, Liquid, PageLayoutType, Path, Rect, TRANSFORM_CHANGE_OBSERVABLE_TYPE, UniverRenderEnginePlugin, Vector2, getColor, getCurrentTypeOfRenderer, getDocsTableRenderViewport, getTableIdAndSliceIndex } from "@univerjs/engine-render";
5
5
  import { DocSelectionManagerService, DocSkeletonManagerService, RichTextEditingMutation, UniverDocsPlugin, buildDocTransform, canEditDocumentTargets, docDrawingPositionToTransform, getDocumentDrawingSegmentId, getDocumentEditTargetObjectIds, getDocumentEntityParentPermissionObjectIds, getDocumentEntityPermissionObjectId, isSheetLikeDocsCustomBlockChildType } from "@univerjs/docs";
6
6
  import { Checkbox, InputNumber, MessageType, MobileActionRow, Radio, RadioGroup, Select, clsx, render, unmount } from "@univerjs/design";
7
7
  import { DRAWING_IMAGE_ALLOW_IMAGE_LIST, DRAWING_IMAGE_COUNT_LIMIT, DRAWING_IMAGE_HEIGHT_LIMIT, DRAWING_IMAGE_WIDTH_LIMIT, IDrawingManagerService, UniverDrawingPlugin, getDrawingImageAllowSize, getDrawingShapeKeyByDrawingSearch, getImageSize } from "@univerjs/drawing";
8
8
  import { CanvasFloatDomService, ComponentManager, ContextMenuGroup, ContextMenuPosition, FloatingObjectToolbarPosition, IContextMenuService, ILocalFileService, IMenuManagerService, IMessageService, IShortcutService, ISidebarService, KeyCode, MenuItemType, PrintFloatDomSingle, RibbonInsertGroup, connectInjector, getMenuHiddenObservable, useDependency, useObservable } from "@univerjs/ui";
9
- import { BehaviorSubject, EMPTY, Observable, animationFrames, debounceTime, filter, map, merge as merge$1, of, startWith, switchMap, take, takeUntil } from "rxjs";
9
+ import { BehaviorSubject, EMPTY, Observable, Subscription, animationFrames, debounceTime, filter, map, merge as merge$1, of, startWith, switchMap, take, takeUntil, throttleTime } from "rxjs";
10
10
  import { COMPONENT_IMAGE_POPUP_MENU, COMPONENT_MOBILE_IMAGE_POPUP_MENU, DrawingCommonPanel, DrawingRenderService, ImageCropperObject, ImageResetSizeOperation, OpenImageCropOperation, UniverDrawingMobileUIPlugin, UniverDrawingUIPlugin } from "@univerjs/drawing-ui";
11
11
  import { useEffect, useMemo, useState } from "react";
12
12
  import { jsx, jsxs } from "react/jsx-runtime";
@@ -271,7 +271,7 @@ const UngroupDocDrawingCommand = {
271
271
  };
272
272
 
273
273
  //#endregion
274
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/typeof.js
274
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
275
275
  function _typeof(o) {
276
276
  "@babel/helpers - typeof";
277
277
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -282,7 +282,7 @@ function _typeof(o) {
282
282
  }
283
283
 
284
284
  //#endregion
285
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/toPrimitive.js
285
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
286
286
  function toPrimitive(t, r) {
287
287
  if ("object" != _typeof(t) || !t) return t;
288
288
  var e = t[Symbol.toPrimitive];
@@ -295,14 +295,14 @@ function toPrimitive(t, r) {
295
295
  }
296
296
 
297
297
  //#endregion
298
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/toPropertyKey.js
298
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
299
299
  function toPropertyKey(t) {
300
300
  var i = toPrimitive(t, "string");
301
301
  return "symbol" == _typeof(i) ? i : i + "";
302
302
  }
303
303
 
304
304
  //#endregion
305
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/defineProperty.js
305
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
306
306
  function _defineProperty(e, r, t) {
307
307
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
308
308
  value: t,
@@ -324,6 +324,60 @@ var DocRefreshDrawingsService = class {
324
324
  }
325
325
  };
326
326
 
327
+ //#endregion
328
+ //#region src/utils/drawing-text-anchor.ts
329
+ /** Locate the persisted object character without consulting the active text selection. */
330
+ function findDrawingTextAnchor(snapshot, drawingId) {
331
+ const segments = [
332
+ {
333
+ segmentId: "",
334
+ body: snapshot.body
335
+ },
336
+ ...Object.entries(snapshot.headers ?? {}).map(([segmentId, segment]) => ({
337
+ segmentId,
338
+ body: segment.body
339
+ })),
340
+ ...Object.entries(snapshot.footers ?? {}).map(([segmentId, segment]) => ({
341
+ segmentId,
342
+ body: segment.body
343
+ })),
344
+ ...Object.entries(snapshot.notes ?? {}).map(([segmentId, segment]) => ({
345
+ segmentId,
346
+ body: segment.body
347
+ }))
348
+ ];
349
+ for (const { segmentId, body } of segments) {
350
+ var _body$customBlocks;
351
+ const block = body === null || body === void 0 || (_body$customBlocks = body.customBlocks) === null || _body$customBlocks === void 0 ? void 0 : _body$customBlocks.find((item) => item.blockId === drawingId);
352
+ if (block) return {
353
+ offset: block.startIndex,
354
+ segmentId
355
+ };
356
+ }
357
+ return null;
358
+ }
359
+ /** Preserve keyboard/clipboard object ranges while replacing floating selection paint with an anchor icon. */
360
+ function getDrawingTextRanges(snapshot, drawingIds) {
361
+ return drawingIds.flatMap((drawingId) => {
362
+ var _findDocDrawing;
363
+ const anchor = findDrawingTextAnchor(snapshot, drawingId);
364
+ if (!anchor) return [];
365
+ const drawing = (_findDocDrawing = findDocDrawing(snapshot, drawingId)) === null || _findDocDrawing === void 0 ? void 0 : _findDocDrawing.drawing;
366
+ const floating = drawing && drawing.layoutType !== PositionedObjectLayoutType.INLINE;
367
+ return [{
368
+ startOffset: anchor.offset,
369
+ endOffset: anchor.offset + 1,
370
+ segmentId: anchor.segmentId,
371
+ ...floating ? { style: {
372
+ fill: "transparent",
373
+ stroke: "transparent",
374
+ strokeActive: "transparent",
375
+ strokeWidth: 1
376
+ } } : {}
377
+ }];
378
+ });
379
+ }
380
+
327
381
  //#endregion
328
382
  //#region src/controllers/render-controllers/doc-drawing-crop.ts
329
383
  function getDocImageCropUpdates(param, docDrawing, renderDrawing) {
@@ -406,7 +460,7 @@ function getDocMutationAffectedDrawingIds(actions) {
406
460
  }
407
461
 
408
462
  //#endregion
409
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/decorateParam.js
463
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/decorateParam.js
410
464
  function __decorateParam(paramIndex, decorator) {
411
465
  return function(target, key) {
412
466
  decorator(target, key, paramIndex);
@@ -414,7 +468,7 @@ function __decorateParam(paramIndex, decorator) {
414
468
  }
415
469
 
416
470
  //#endregion
417
- //#region \0@oxc-project+runtime@0.149.0/helpers/esm/decorate.js
471
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/decorate.js
418
472
  function __decorate(decorators, target, key, desc) {
419
473
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
420
474
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
@@ -718,7 +772,7 @@ let DocDrawingUpdateRenderController = class DocDrawingUpdateRenderController ex
718
772
  const fadeBody = isDocInteractionFocusing && drawing.isMultiTransform !== BooleanNumber.TRUE;
719
773
  shape.setOpacity(fadeBody ? .5 : 1);
720
774
  } catch {}
721
- if (!isDocInteractionFocusing) continue;
775
+ if (!isDocInteractionFocusing && !this._context.isMainScene) continue;
722
776
  if (isEditBody && drawing.isMultiTransform !== BooleanNumber.TRUE || !isEditBody && drawing.isMultiTransform === BooleanNumber.TRUE) {
723
777
  this._attachTransformerIfEditable(shape, editable, drawing.allowTransform);
724
778
  try {
@@ -843,17 +897,7 @@ let DocDrawingUpdateRenderController = class DocDrawingUpdateRenderController ex
843
897
  }
844
898
  _setDrawingSelections(params) {
845
899
  const { unit } = this._context;
846
- const ranges = params.flatMap((item) => {
847
- var _unit$getSelfOrHeader, _body$customBlocks;
848
- const segmentId = getDocumentDrawingSegmentId(unit, item.drawingId);
849
- const body = (_unit$getSelfOrHeader = unit.getSelfOrHeaderFooterModel(segmentId)) === null || _unit$getSelfOrHeader === void 0 ? void 0 : _unit$getSelfOrHeader.getBody();
850
- const block = body === null || body === void 0 || (_body$customBlocks = body.customBlocks) === null || _body$customBlocks === void 0 ? void 0 : _body$customBlocks.find((block) => block.blockId === item.drawingId);
851
- return block ? [{
852
- startOffset: block.startIndex,
853
- endOffset: block.startIndex + 1,
854
- segmentId
855
- }] : [];
856
- });
900
+ const ranges = getDrawingTextRanges(unit.getSnapshot(), params.map(({ drawingId }) => drawingId));
857
901
  this._docSelectionManagerService.replaceDocRanges(ranges);
858
902
  }
859
903
  };
@@ -992,7 +1036,7 @@ const MoveDocDrawingsCommand = {
992
1036
  const anchorLookup = skeletonData == null ? {
993
1037
  anchor: null,
994
1038
  previewOnly: false
995
- } : findDrawingAnchor(skeletonData, drawingId);
1039
+ } : findDrawingAnchor$1(skeletonData, drawingId);
996
1040
  if (anchorLookup.previewOnly) return null;
997
1041
  const { anchor } = anchorLookup;
998
1042
  const offsets = anchor == null ? {
@@ -1027,7 +1071,7 @@ const MoveDocDrawingsCommand = {
1027
1071
  return Boolean(result);
1028
1072
  }
1029
1073
  };
1030
- function findDrawingAnchor(skeletonData, drawingId) {
1074
+ function findDrawingAnchor$1(skeletonData, drawingId) {
1031
1075
  let foundInPreview = false;
1032
1076
  for (const page of skeletonData.pages) {
1033
1077
  var _skeletonData$skeHead, _skeletonData$skeFoot;
@@ -1761,7 +1805,7 @@ const menuSchema = {
1761
1805
  //#endregion
1762
1806
  //#region package.json
1763
1807
  var name = "@univerjs/docs-drawing-ui";
1764
- var version = "1.0.4";
1808
+ var version = "1.1.0";
1765
1809
 
1766
1810
  //#endregion
1767
1811
  //#region src/config/config.ts
@@ -1786,1351 +1830,1572 @@ const configSymbol = Symbol(DOCS_DRAWING_UI_PLUGIN_CONFIG_KEY);
1786
1830
  const defaultPluginConfig = {};
1787
1831
 
1788
1832
  //#endregion
1789
- //#region src/controllers/doc-drawing-notification.controller.ts
1790
- function getAddOrRemoveDrawings(actions) {
1791
- if (JSONX.isNoop(actions)) return null;
1792
- const drawings = [];
1793
- const cursor = JSON1.type.readCursor(actions);
1794
- cursor.traverse(null, () => {
1795
- const path = cursor.getPath();
1796
- if (path.length !== 2 || path[0] !== "drawings" || typeof path[1] !== "string") return;
1797
- const component = cursor.getComponent();
1798
- if ((component === null || component === void 0 ? void 0 : component.r) !== void 0) drawings.push({
1799
- type: "remove",
1800
- drawingId: path[1]
1833
+ //#region src/controllers/render-controllers/doc-drawing-transform-update.controller.ts
1834
+ function mergePublishedDrawing(drawings, next) {
1835
+ const current = drawings[next.drawingId];
1836
+ if (current == null) {
1837
+ drawings[next.drawingId] = next;
1838
+ return;
1839
+ }
1840
+ if (next.selectable && !current.selectable) {
1841
+ current.selectable = true;
1842
+ current.transform = next.transform;
1843
+ }
1844
+ if (next.isMultiTransform === BooleanNumber.TRUE) current.transforms.push(next.transform);
1845
+ }
1846
+ function isSameTransformValue(left, right) {
1847
+ return left === right || JSON.stringify(left) === JSON.stringify(right);
1848
+ }
1849
+ function shouldRefreshDocDrawingTransform(current, next) {
1850
+ if (!current || next.customBlockRenderViewport != null) return true;
1851
+ return !isSameTransformValue(current.transform, next.transform) || !isSameTransformValue(current.transforms, next.transforms) || current.isMultiTransform !== next.isMultiTransform || current.hidden !== next.hidden || current.behindText !== next.behindText || current.selectable !== next.selectable;
1852
+ }
1853
+ /**
1854
+ * Overlay drawings do not participate in text layout. While their skeleton
1855
+ * anchor remains valid, use the latest model transform so drag/resize/front-
1856
+ * behind changes can paint immediately without rebuilding document pages.
1857
+ */
1858
+ function getDocsOverlayRuntimeDrawing(skeletonDrawing, currentDrawing, measuredSize) {
1859
+ if (skeletonDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE && (currentDrawing === null || currentDrawing === void 0 ? void 0 : currentDrawing.layoutType) === PositionedObjectLayoutType.WRAP_NONE) return currentDrawing;
1860
+ return measuredSize ? {
1861
+ ...skeletonDrawing,
1862
+ docTransform: {
1863
+ ...skeletonDrawing.docTransform,
1864
+ size: measuredSize
1865
+ }
1866
+ } : skeletonDrawing;
1867
+ }
1868
+ var DocDrawingPublicationTracker = class {
1869
+ constructor() {
1870
+ _defineProperty(this, "_generation", -1);
1871
+ _defineProperty(this, "_publishedPageCount", 0);
1872
+ _defineProperty(this, "_drawingOccurrenceCount", 0);
1873
+ }
1874
+ reset() {
1875
+ this._generation = -1;
1876
+ this._publishedPageCount = 0;
1877
+ this._drawingOccurrenceCount = 0;
1878
+ }
1879
+ shouldRefresh(skeleton, progress) {
1880
+ if (!progress.didPublish && !progress.complete) return false;
1881
+ const isNewGeneration = progress.generation !== this._generation;
1882
+ if (isNewGeneration) {
1883
+ this._generation = progress.generation;
1884
+ this._publishedPageCount = 0;
1885
+ this._drawingOccurrenceCount = 0;
1886
+ }
1887
+ const skeletonData = skeleton.getSkeletonData();
1888
+ if (skeletonData == null) return false;
1889
+ const previousPublishedPageCount = this._publishedPageCount;
1890
+ const publishedPageCount = Math.min(progress.publishedPageCount, skeletonData.pages.length);
1891
+ this._publishedPageCount = Math.max(previousPublishedPageCount, publishedPageCount);
1892
+ const drawingOccurrenceCount = countPublishedDrawingOccurrences(skeletonData, publishedPageCount);
1893
+ const didDrawingOccurrencesChange = !(isNewGeneration && progress.reason === "edit") && drawingOccurrenceCount !== this._drawingOccurrenceCount;
1894
+ this._drawingOccurrenceCount = drawingOccurrenceCount;
1895
+ if (progress.complete || progress.didPublishAnchor || didDrawingOccurrencesChange) return true;
1896
+ if (isNewGeneration && progress.reason === "edit") return false;
1897
+ return hasNewPublishedPageDrawings(skeletonData, previousPublishedPageCount, publishedPageCount);
1898
+ }
1899
+ };
1900
+ function getDocsDrawingPageClipBounds(config) {
1901
+ const { docsLeft, docsTop, pageOffsetLeft, pageOffsetTop, clipOffsetLeft = 0, clipOffsetTop = 0, page } = config;
1902
+ if (page.type === DocumentSkeletonPageType.CELL && config.drawingLayoutType === PositionedObjectLayoutType.WRAP_NONE && config.overflowClipBounds != null) return config.overflowClipBounds;
1903
+ const { pageWidth, pageHeight } = page;
1904
+ if (!Number.isFinite(pageWidth) || !Number.isFinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) return;
1905
+ const cellInsetLeft = page.type === DocumentSkeletonPageType.CELL ? page.marginLeft ?? 0 : 0;
1906
+ const cellInsetTop = page.type === DocumentSkeletonPageType.CELL ? page.marginTop ?? 0 : 0;
1907
+ return {
1908
+ left: docsLeft + pageOffsetLeft + clipOffsetLeft - cellInsetLeft,
1909
+ top: docsTop + pageOffsetTop + clipOffsetTop - cellInsetTop,
1910
+ width: pageWidth,
1911
+ height: pageHeight
1912
+ };
1913
+ }
1914
+ function getDocsDrawingClipPage(config) {
1915
+ const { drawing, hostPage, page } = config;
1916
+ if (hostPage && (page.type === DocumentSkeletonPageType.HEADER || page.type === DocumentSkeletonPageType.FOOTER)) return hostPage;
1917
+ if (hostPage == null || drawing.behindText !== true || drawing.transform == null) return page;
1918
+ const { width, height } = drawing.transform;
1919
+ if (width == null || height == null) return page;
1920
+ if (width > page.pageWidth || height > page.pageHeight) return hostPage;
1921
+ const widthRatio = width / hostPage.pageWidth;
1922
+ const heightRatio = height / hostPage.pageHeight;
1923
+ if (widthRatio >= .8 && heightRatio >= .8) return hostPage;
1924
+ return page;
1925
+ }
1926
+ function getDocsPageRelativeDrawingLeft(config) {
1927
+ const { hostPage, positionH, width } = config;
1928
+ if (positionH.relativeFrom !== ObjectRelativeFromH.PAGE) return;
1929
+ if (positionH.align === AlignTypeH.RIGHT) return hostPage.pageWidth - width;
1930
+ if (positionH.align === AlignTypeH.CENTER) return hostPage.pageWidth / 2 - width / 2;
1931
+ if (positionH.align != null) return 0;
1932
+ if (positionH.posOffset != null) return positionH.posOffset;
1933
+ return positionH.percent ? positionH.percent * hostPage.pageWidth : 0;
1934
+ }
1935
+ function getDocsPageRelativeDrawingTop(config) {
1936
+ const { hostPage, positionV, height } = config;
1937
+ if (positionV.relativeFrom !== ObjectRelativeFromV.PAGE) return;
1938
+ if (positionV.align === AlignTypeV.BOTTOM) return hostPage.pageHeight - height;
1939
+ if (positionV.align === AlignTypeV.CENTER) return hostPage.pageHeight / 2 - height / 2;
1940
+ if (positionV.align != null) return 0;
1941
+ if (positionV.posOffset != null) return positionV.posOffset;
1942
+ return positionV.percent ? positionV.percent * hostPage.pageHeight : 0;
1943
+ }
1944
+ function getDocsPageRelativeDrawingAnchorPage(config) {
1945
+ const { page, clipPage, hostPage } = config;
1946
+ if (config.drawingLayoutType === PositionedObjectLayoutType.INLINE) return;
1947
+ if (hostPage != null && hostPage === clipPage) return hostPage;
1948
+ if (hostPage == null && page === clipPage && page.type !== DocumentSkeletonPageType.CELL) return page;
1949
+ }
1950
+ function getDocsDrawingBehindText(config) {
1951
+ const { drawingOrigin, hostPage } = config;
1952
+ if (hostPage != null) return true;
1953
+ return drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;
1954
+ }
1955
+ function getDocsTableCellDrawingOffset(unitId, table, row, cell) {
1956
+ const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;
1957
+ const viewport = getDocsTableRenderViewport(unitId, sourceTableId);
1958
+ const scrollLeft = hasHorizontalTableViewport(viewport) ? viewport.scrollLeft : 0;
1959
+ return {
1960
+ left: table.left + cell.left - scrollLeft + cell.marginLeft,
1961
+ top: table.top + row.top + cell.marginTop
1962
+ };
1963
+ }
1964
+ function hasHorizontalTableViewport(viewport) {
1965
+ return viewport != null && (viewport.leadingInsetLeft ?? 0) + viewport.contentWidth + (viewport.trailingInsetRight ?? 0) > viewport.viewportWidth;
1966
+ }
1967
+ function hasSkeletonPageDrawings(page) {
1968
+ var _page$notes, _page$skeTables, _page$skeColumnGroups;
1969
+ if (page.skeDrawings.size > 0 || ((_page$notes = page.notes) === null || _page$notes === void 0 ? void 0 : _page$notes.some((note) => hasSkeletonPageDrawings(note.page)))) return true;
1970
+ let hasDrawings = false;
1971
+ (_page$skeTables = page.skeTables) === null || _page$skeTables === void 0 || _page$skeTables.forEach((table) => {
1972
+ table.rows.forEach((row) => {
1973
+ row.cells.forEach((cell) => {
1974
+ if (hasSkeletonPageDrawings(cell)) hasDrawings = true;
1975
+ });
1801
1976
  });
1802
- if ((component === null || component === void 0 ? void 0 : component.i) !== void 0) drawings.push({
1803
- type: "add",
1804
- drawingId: path[1],
1805
- drawing: component.i
1977
+ });
1978
+ (_page$skeColumnGroups = page.skeColumnGroups) === null || _page$skeColumnGroups === void 0 || _page$skeColumnGroups.forEach((columnGroup) => {
1979
+ columnGroup.columns.forEach((column) => {
1980
+ if (hasSkeletonPageDrawings(column.page)) hasDrawings = true;
1806
1981
  });
1807
1982
  });
1808
- return drawings.length ? drawings : null;
1983
+ return hasDrawings;
1809
1984
  }
1810
- function getReOrderedDrawings(actions) {
1811
- if (!Array.isArray(actions) || actions.length < 3 || actions[0] !== "drawingsOrder") return [];
1812
- const drawingIndexes = [];
1813
- for (let i = 1; i < actions.length; i++) {
1814
- const action = actions[i];
1815
- if (Array.isArray(action) && typeof action[0] === "number" && typeof action[1] === "object") drawingIndexes.push(action[0]);
1816
- else {
1817
- drawingIndexes.length = 0;
1818
- break;
1819
- }
1985
+ function countSkeletonPageDrawings(page) {
1986
+ var _page$notes2, _page$skeTables2, _page$skeColumnGroups2;
1987
+ let count = page.skeDrawings.size;
1988
+ (_page$notes2 = page.notes) === null || _page$notes2 === void 0 || _page$notes2.forEach((note) => {
1989
+ count += countSkeletonPageDrawings(note.page);
1990
+ });
1991
+ (_page$skeTables2 = page.skeTables) === null || _page$skeTables2 === void 0 || _page$skeTables2.forEach((table) => {
1992
+ table.rows.forEach((row) => {
1993
+ row.cells.forEach((cell) => {
1994
+ count += countSkeletonPageDrawings(cell);
1995
+ });
1996
+ });
1997
+ });
1998
+ (_page$skeColumnGroups2 = page.skeColumnGroups) === null || _page$skeColumnGroups2 === void 0 || _page$skeColumnGroups2.forEach((columnGroup) => {
1999
+ columnGroup.columns.forEach((column) => {
2000
+ count += countSkeletonPageDrawings(column.page);
2001
+ });
2002
+ });
2003
+ return count;
2004
+ }
2005
+ function countPublishedDrawingOccurrences(skeletonData, publishedPageCount) {
2006
+ let count = 0;
2007
+ for (let index = 0; index < publishedPageCount; index++) {
2008
+ var _skeletonData$skeHead, _skeletonData$skeFoot;
2009
+ const page = skeletonData.pages[index];
2010
+ count += countSkeletonPageDrawings(page);
2011
+ const header = page.headerId == null ? void 0 : (_skeletonData$skeHead = skeletonData.skeHeaders.get(page.headerId)) === null || _skeletonData$skeHead === void 0 ? void 0 : _skeletonData$skeHead.get(page.headerLayoutKey ?? page.pageWidth);
2012
+ if (header != null) count += countSkeletonPageDrawings(header);
2013
+ const footer = page.footerId == null ? void 0 : (_skeletonData$skeFoot = skeletonData.skeFooters.get(page.footerId)) === null || _skeletonData$skeFoot === void 0 ? void 0 : _skeletonData$skeFoot.get(page.footerLayoutKey ?? page.pageWidth);
2014
+ if (footer != null) count += countSkeletonPageDrawings(footer);
1820
2015
  }
1821
- return drawingIndexes;
2016
+ return count;
1822
2017
  }
1823
- function collectUpdatedDrawingIds(actions, drawingIds = /* @__PURE__ */ new Set()) {
1824
- if (JSONX.isNoop(actions) || !Array.isArray(actions)) return drawingIds;
1825
- if (actions[0] === "drawings") {
1826
- const drawingKeyOrOps = actions[1];
1827
- if (typeof drawingKeyOrOps === "string") {
1828
- drawingIds.add(drawingKeyOrOps);
1829
- return drawingIds;
1830
- }
1831
- actions.slice(1).forEach((action) => {
1832
- if (Array.isArray(action) && typeof action[0] === "string") drawingIds.add(action[0]);
1833
- });
1834
- return drawingIds;
2018
+ function hasNewPublishedPageDrawings(skeletonData, startPageIndex, publishedPageCount) {
2019
+ for (let index = startPageIndex; index < publishedPageCount; index++) {
2020
+ var _skeletonData$skeHead2, _skeletonData$skeFoot2;
2021
+ const page = skeletonData.pages[index];
2022
+ if (hasSkeletonPageDrawings(page)) return true;
2023
+ const header = page.headerId == null ? void 0 : (_skeletonData$skeHead2 = skeletonData.skeHeaders.get(page.headerId)) === null || _skeletonData$skeHead2 === void 0 ? void 0 : _skeletonData$skeHead2.get(page.headerLayoutKey ?? page.pageWidth);
2024
+ if (header != null && hasSkeletonPageDrawings(header)) return true;
2025
+ const footer = page.footerId == null ? void 0 : (_skeletonData$skeFoot2 = skeletonData.skeFooters.get(page.footerId)) === null || _skeletonData$skeFoot2 === void 0 ? void 0 : _skeletonData$skeFoot2.get(page.footerLayoutKey ?? page.pageWidth);
2026
+ if (footer != null && hasSkeletonPageDrawings(footer)) return true;
1835
2027
  }
1836
- actions.forEach((action) => {
1837
- if (Array.isArray(action)) collectUpdatedDrawingIds(action, drawingIds);
1838
- });
1839
- return drawingIds;
2028
+ return false;
1840
2029
  }
1841
- let DocDrawingAddRemoveController = class DocDrawingAddRemoveController extends Disposable {
1842
- constructor(_univerInstanceService, _commandService, _drawingManagerService, _docDrawingService, _renderManagerService, _docRefreshDrawingsService) {
2030
+ let DocDrawingTransformUpdateController = class DocDrawingTransformUpdateController extends Disposable {
2031
+ constructor(_context, _docSkeletonManagerService, _commandService, _editorService, _drawingManagerService, _docRefreshDrawingsService, _univerInstanceService, _lifecycleService) {
1843
2032
  super();
1844
- this._univerInstanceService = _univerInstanceService;
2033
+ this._context = _context;
2034
+ this._docSkeletonManagerService = _docSkeletonManagerService;
1845
2035
  this._commandService = _commandService;
2036
+ this._editorService = _editorService;
1846
2037
  this._drawingManagerService = _drawingManagerService;
1847
- this._docDrawingService = _docDrawingService;
1848
- this._renderManagerService = _renderManagerService;
1849
2038
  this._docRefreshDrawingsService = _docRefreshDrawingsService;
2039
+ this._univerInstanceService = _univerInstanceService;
2040
+ this._lifecycleService = _lifecycleService;
2041
+ _defineProperty(this, "_liquid", new Liquid());
2042
+ _defineProperty(this, "_changesetDrawingRefreshScheduled", false);
2043
+ _defineProperty(this, "_pendingMultiDrawingSelection", /* @__PURE__ */ new Set());
2044
+ _defineProperty(this, "_pendingMultiDrawingSelectionSubscription", void 0);
2045
+ _defineProperty(this, "_publicationTracker", new DocDrawingPublicationTracker());
1850
2046
  this._initialize();
2047
+ this._commandExecutedListener();
2048
+ this.disposeWithMe(toDisposable(() => this._clearPendingMultiDrawingSelection()));
1851
2049
  }
1852
2050
  _initialize() {
1853
- this._commandExecutedListener();
2051
+ this._initialRenderRefresh();
2052
+ this._drawingInitializeListener();
2053
+ this._initTransformRefresh();
1854
2054
  }
1855
- _commandExecutedListener() {
1856
- this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
1857
- if (command.id !== RichTextEditingMutation.id) return;
1858
- const { unitId, actions, isSync, syncer } = command.params;
1859
- const addOrRemoveDrawings = getAddOrRemoveDrawings(actions);
1860
- if (addOrRemoveDrawings != null) for (const { type, drawingId, drawing } of addOrRemoveDrawings) {
1861
- if (isSync && (drawing === null || drawing === void 0 ? void 0 : drawing.unitId) === syncer) continue;
1862
- if (type === "add") this._addDrawings(unitId, [drawing]);
1863
- else this._removeDrawings(unitId, [drawingId]);
1864
- }
2055
+ _initialRenderRefresh() {
2056
+ this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.pipe(switchMap((documentSkeleton) => {
2057
+ this._publicationTracker.reset();
2058
+ if (documentSkeleton == null) return EMPTY;
2059
+ this._refreshDrawing(documentSkeleton);
2060
+ const positionRefresh$ = animationFrames().pipe(startWith(null), map(() => this._context.mainComponent), filter((documentComponent) => documentComponent instanceof Documents && documentComponent.left > -1e4 && documentComponent.top > -1e4), take(1), switchMap((documentComponent) => fromEventSubject(documentComponent.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.translate && "left" in evt.value && "left" in evt.preValue && (evt.value.left !== evt.preValue.left || evt.value.top !== evt.preValue.top)), map(() => ({
2061
+ documentSkeleton,
2062
+ progress: null
2063
+ })), startWith({
2064
+ documentSkeleton,
2065
+ progress: null
2066
+ }))));
2067
+ return merge$1(documentSkeleton.layoutProgress$.pipe(map((progress) => ({
2068
+ documentSkeleton,
2069
+ progress
2070
+ }))), documentSkeleton.layoutPageMaterialized$.pipe(map(() => ({
2071
+ documentSkeleton,
2072
+ progress: null
2073
+ }))), positionRefresh$);
2074
+ })).subscribe(({ documentSkeleton, progress }) => {
2075
+ if (progress == null || this._publicationTracker.shouldRefresh(documentSkeleton, progress)) this._refreshDrawing(documentSkeleton);
1865
2076
  }));
1866
- this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
1867
- if (command.id !== UpdateDocDrawingWrappingStyleCommand.id) return;
1868
- this._preserveWrappingStylePosition(command.params);
2077
+ this.disposeWithMe(this._docRefreshDrawingsService.refreshDrawings$.subscribe((skeleton) => {
2078
+ if (skeleton == null) return;
2079
+ this._refreshDrawing(skeleton);
1869
2080
  }));
1870
- this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
1871
- if (command.id !== RichTextEditingMutation.id) return;
1872
- const { unitId, actions } = command.params;
1873
- let changedNotes = false;
1874
- if (!JSONX.isNoop(actions)) {
1875
- const cursor = JSON1.type.readCursor(actions);
1876
- cursor.traverse(null, () => {
1877
- changedNotes ||= cursor.getPath()[0] === "notes";
1878
- });
2081
+ }
2082
+ _commandExecutedListener() {
2083
+ const updateCommandList = [RichTextEditingMutation.id, SetDocZoomRatioOperation.id];
2084
+ this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
2085
+ if (updateCommandList.includes(command.id)) {
2086
+ const params = command.params;
2087
+ const { unitId: commandUnitId } = params;
2088
+ const { unitId } = this._context;
2089
+ if (commandUnitId !== unitId) return;
2090
+ const drawingIds = command.id === RichTextEditingMutation.id ? getDocMutationAffectedDrawingIds(params.actions) : null;
2091
+ if ((drawingIds === null || drawingIds === void 0 ? void 0 : drawingIds.size) === 0) return;
2092
+ if (command.id === RichTextEditingMutation.id && (options === null || options === void 0 ? void 0 : options.fromChangeset)) {
2093
+ this._scheduleChangesetDrawingRefresh();
2094
+ return;
2095
+ }
2096
+ this._refreshCurrentDrawing(drawingIds ?? void 0, command.id === RichTextEditingMutation.id);
1879
2097
  }
1880
- if (changedNotes) this._syncNoteDrawings(unitId);
1881
- if (getReOrderedDrawings(actions).length > 0) this._updateDrawingsOrder(unitId);
1882
- const updatedDrawingIds = [...collectUpdatedDrawingIds(actions)];
1883
- if (updatedDrawingIds.length > 0) this._syncDrawingDataFromSnapshot(unitId, updatedDrawingIds);
1884
- }));
1885
- this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
1886
- if (command.id !== UpdateDrawingDocTransformCommand.id && command.id !== UpdateDocDrawingWrappingStyleCommand.id) return;
1887
- const { unitId } = command.params;
1888
- const renderObject = this._renderManagerService.getRenderUnitById(unitId);
1889
- const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
1890
- if (renderObject == null || scene == null) return;
1891
- if (command.id === UpdateDocDrawingWrappingStyleCommand.id) this._docRefreshDrawingsService.refreshDrawings(renderObject.with(DocSkeletonManagerService).getSkeleton());
1892
- scene.getTransformerByCreate().refreshControls();
1893
- }));
1894
- this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
1895
- var _this$_univerInstance;
1896
- if (command.id !== UndoCommand.id && command.id !== RedoCommand.id) return;
1897
- const unitId = (_this$_univerInstance = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getUnitId();
1898
- const focusedDrawings = this._drawingManagerService.getFocusDrawings();
1899
- if (unitId == null || focusedDrawings.length === 0) return;
1900
- const renderObject = this._renderManagerService.getRenderUnitById(unitId);
1901
- const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
1902
- if (renderObject == null || scene == null) return false;
1903
- this._docRefreshDrawingsService.refreshDrawings(renderObject.with(DocSkeletonManagerService).getSkeleton());
1904
- scene.getTransformerByCreate().refreshControls();
1905
2098
  }));
1906
2099
  }
1907
- _preserveWrappingStylePosition(params) {
1908
- if (params.wrappingStyle === TextWrappingStyle.INLINE) return;
1909
- const { unitId } = params;
1910
- const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
1911
- const renderObject = this._renderManagerService.getRenderUnitById(unitId);
1912
- const skeletonManager = renderObject === null || renderObject === void 0 ? void 0 : renderObject.with(DocSkeletonManagerService);
1913
- const skeletonData = skeletonManager === null || skeletonManager === void 0 ? void 0 : skeletonManager.getSkeleton().getSkeletonData();
1914
- const viewModel = skeletonManager === null || skeletonManager === void 0 ? void 0 : skeletonManager.getViewModel();
1915
- if (!documentDataModel || !skeletonData || !viewModel) return;
1916
- const editArea = viewModel.getEditArea();
1917
- const { pages, skeHeaders, skeFooters } = skeletonData;
1918
- const oldDrawings = documentDataModel.getDrawings() ?? {};
1919
- params.drawings = params.drawings.map((drawing) => {
1920
- const oldDrawing = oldDrawings[drawing.drawingId];
1921
- if (!oldDrawing) return drawing;
1922
- let drawingAnchor = null;
1923
- for (const page of pages) {
1924
- const { headerId, footerId, marginTop, marginLeft, marginBottom, pageWidth, pageHeight } = page;
1925
- if (editArea === DocumentEditArea.HEADER) {
1926
- var _skeHeaders$get;
1927
- const header = (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(page.headerLayoutKey ?? pageWidth);
1928
- if (header) drawingAnchor = findDrawingAnchorInPage(header, drawing.drawingId, header.marginTop, marginLeft);
1929
- } else if (editArea === DocumentEditArea.FOOTER) {
1930
- var _skeFooters$get;
1931
- const footer = (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(page.footerLayoutKey ?? pageWidth);
1932
- if (footer) drawingAnchor = findDrawingAnchorInPage(footer, drawing.drawingId, pageHeight - marginBottom + footer.marginTop, marginLeft);
1933
- } else drawingAnchor = findDrawingAnchorInPage(page, drawing.drawingId, marginTop, marginLeft);
1934
- if (drawingAnchor) break;
1935
- }
1936
- if (!drawingAnchor) return drawing;
1937
- const oldPositionH = oldDrawing.docTransform.positionH;
1938
- const oldPositionV = oldDrawing.docTransform.positionV;
1939
- const { horizontal: posOffsetH, vertical: posOffsetV } = resolveDrawingAnchorOffsets(drawingAnchor, oldPositionH, oldPositionV);
1940
- return {
1941
- ...oldDrawing,
1942
- ...drawing,
1943
- docTransform: {
1944
- ...oldDrawing.docTransform,
1945
- ...drawing.docTransform,
1946
- positionH: {
1947
- relativeFrom: oldPositionH.relativeFrom,
1948
- posOffset: posOffsetH
1949
- },
1950
- positionV: {
1951
- relativeFrom: oldPositionV.relativeFrom,
1952
- posOffset: posOffsetV
1953
- }
1954
- }
1955
- };
2100
+ _scheduleChangesetDrawingRefresh() {
2101
+ if (this._changesetDrawingRefreshScheduled) return;
2102
+ this._changesetDrawingRefreshScheduled = true;
2103
+ queueMicrotask(() => {
2104
+ queueMicrotask(() => {
2105
+ this._changesetDrawingRefreshScheduled = false;
2106
+ if (this._disposed) return;
2107
+ this._refreshCurrentDrawing(void 0, true);
2108
+ });
1956
2109
  });
1957
2110
  }
1958
- _addDrawings(unitId, drawings) {
1959
- const drawingManagerService = this._drawingManagerService;
1960
- const docDrawingService = this._docDrawingService;
1961
- const { subUnitId, redo: op, objects } = this._docDrawingService.getBatchAddOp(drawings.map((drawing) => ({
1962
- ...drawing,
1963
- unitId,
1964
- subUnitId: unitId
1965
- })));
1966
- drawingManagerService.applyJson1(unitId, subUnitId, op);
1967
- docDrawingService.applyJson1(unitId, subUnitId, op);
1968
- drawingManagerService.addNotification(objects);
1969
- docDrawingService.addNotification(objects);
2111
+ _refreshCurrentDrawing(drawingIds, forceRecreateMultiDrawings = false) {
2112
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
2113
+ if (skeleton == null) return;
2114
+ const { unitId, mainComponent } = this._context;
2115
+ if (this._editorService.isEditor(unitId)) {
2116
+ mainComponent === null || mainComponent === void 0 || mainComponent.makeDirty();
2117
+ return;
2118
+ }
2119
+ this._refreshDrawing(skeleton, drawingIds, forceRecreateMultiDrawings);
1970
2120
  }
1971
- _removeDrawings(unitId, drawingIds) {
1972
- const drawingManagerService = this._drawingManagerService;
1973
- const docDrawingService = this._docDrawingService;
1974
- const existingDrawingIds = drawingIds.filter((drawingId) => docDrawingService.getDrawingByParam({
2121
+ _initTransformRefresh() {
2122
+ this.disposeWithMe(merge$1(fromEventSubject(this._context.engine.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize)), fromEventSubject(this._context.scene.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale))).pipe(debounceTime(16)).subscribe(() => {
2123
+ var _scene$getTransformer;
2124
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
2125
+ const { scene } = this._context;
2126
+ (_scene$getTransformer = scene.getTransformer()) === null || _scene$getTransformer === void 0 || _scene$getTransformer.refreshControls();
2127
+ this._refreshDrawing(skeleton);
2128
+ }));
2129
+ }
2130
+ _refreshDrawing(skeleton, drawingIds, forceRecreateMultiDrawings = false) {
2131
+ const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
2132
+ const { mainComponent, unitId } = this._context;
2133
+ const documentComponent = mainComponent;
2134
+ if (!skeletonData) return;
2135
+ const { left: docsLeft, top: docsTop, pageLayoutType, pageMarginLeft, pageMarginTop } = documentComponent;
2136
+ if (docsLeft <= -1e4 || docsTop <= -1e4) return;
2137
+ const { pages, skeHeaders, skeFooters } = skeletonData;
2138
+ const updateDrawingMap = {};
2139
+ this._liquid.reset();
2140
+ /**
2141
+ * TODO: @DR-Univer We should not refresh all floating elements, but instead make a diff.
2142
+ */
2143
+ for (let i = 0, len = pages.length; i < len; i++) {
2144
+ const page = pages[i];
2145
+ this._collectPublishedPageDrawingPositions(unitId, page, skeHeaders, skeFooters, docsLeft, docsTop, updateDrawingMap);
2146
+ this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
2147
+ }
2148
+ const affectedDrawingIds = this._includeGroupChildren(drawingIds);
2149
+ const updateDrawings = Object.values(updateDrawingMap).filter((drawing) => affectedDrawingIds == null || affectedDrawingIds.has(drawing.drawingId));
2150
+ for (const drawing of updateDrawings) drawing.hidden = false;
2151
+ const staleNonMultiDrawings = this._getStaleNonMultiDrawings(unitId, updateDrawingMap, affectedDrawingIds);
2152
+ const nonMultiDrawings = updateDrawings.filter((drawing) => !drawing.isMultiTransform).concat(staleNonMultiDrawings).filter((drawing) => shouldRefreshDocDrawingTransform(this._drawingManagerService.getDrawingByParam({
1975
2153
  unitId,
1976
2154
  subUnitId: unitId,
1977
- drawingId
1978
- }));
1979
- if (existingDrawingIds.length === 0) return;
1980
- const { subUnitId, redo: op, objects } = this._docDrawingService.getBatchRemoveOp(existingDrawingIds.map((drawingId) => {
1981
- return {
2155
+ drawingId: drawing.drawingId
2156
+ }), drawing));
2157
+ if (nonMultiDrawings.length > 0) this._drawingManagerService.refreshTransform(nonMultiDrawings);
2158
+ const targetedMultiDrawing = affectedDrawingIds != null && [...affectedDrawingIds].some((drawingId) => {
2159
+ var _updateDrawingMap$dra, _this$_drawingManager;
2160
+ return ((_updateDrawingMap$dra = updateDrawingMap[drawingId]) === null || _updateDrawingMap$dra === void 0 ? void 0 : _updateDrawingMap$dra.isMultiTransform) === BooleanNumber.TRUE || ((_this$_drawingManager = this._drawingManagerService.getDrawingByParam({
1982
2161
  unitId,
1983
2162
  subUnitId: unitId,
1984
2163
  drawingId
1985
- };
1986
- }));
1987
- drawingManagerService.applyJson1(unitId, subUnitId, op);
1988
- docDrawingService.applyJson1(unitId, subUnitId, op);
1989
- drawingManagerService.removeNotification(objects);
1990
- docDrawingService.removeNotification(objects);
1991
- }
1992
- _updateDrawingsOrder(unitId) {
1993
- const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
1994
- if (documentDataModel == null) return;
1995
- const { drawings, drawingsOrder } = collectDocDrawings(documentDataModel.getSnapshot());
1996
- if (drawingsOrder == null) return;
1997
- const renderOrder = getDocDrawingRenderOrder(drawingsOrder, drawings);
1998
- const drawingManagerService = this._drawingManagerService;
1999
- const docDrawingService = this._docDrawingService;
2000
- drawingManagerService.setDrawingOrder(unitId, unitId, renderOrder);
2001
- docDrawingService.setDrawingOrder(unitId, unitId, drawingsOrder);
2002
- const objects = {
2003
- unitId,
2004
- subUnitId: unitId,
2005
- drawingIds: renderOrder
2006
- };
2007
- drawingManagerService.orderNotification(objects);
2008
- docDrawingService.orderNotification({
2009
- unitId,
2010
- subUnitId: unitId,
2011
- drawingIds: drawingsOrder
2164
+ })) === null || _this$_drawingManager === void 0 ? void 0 : _this$_drawingManager.isMultiTransform) === BooleanNumber.TRUE;
2012
2165
  });
2166
+ if (affectedDrawingIds == null || targetedMultiDrawing) {
2167
+ const allMultiDrawings = Object.values(updateDrawingMap).filter((drawing) => drawing.isMultiTransform);
2168
+ this._handleMultiDrawingsTransform(allMultiDrawings, forceRecreateMultiDrawings);
2169
+ }
2013
2170
  }
2014
- _syncNoteDrawings(unitId) {
2015
- const model = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2016
- if (!model) return;
2017
- const { drawings } = collectDocDrawings(model.getSnapshot());
2018
- const previous = this._docDrawingService.getDrawingData(unitId, unitId) ?? {};
2019
- const added = Object.keys(drawings).filter((id) => !previous[id]);
2020
- const removed = Object.keys(previous).filter((id) => !drawings[id]);
2021
- const changed = Object.keys(drawings).filter((id) => drawings[id] !== previous[id]);
2022
- if (added.length > 0) this._addDrawings(unitId, added.map((id) => ({
2023
- ...drawings[id],
2024
- unitId,
2025
- subUnitId: unitId
2026
- })));
2027
- if (removed.length > 0) this._removeDrawings(unitId, removed);
2028
- if (changed.length > 0) this._syncDrawingDataFromSnapshot(unitId, changed);
2171
+ _includeGroupChildren(drawingIds) {
2172
+ if (drawingIds == null) return;
2173
+ const affected = new Set(drawingIds);
2174
+ const { drawings } = collectDocDrawings(this._context.unit.getSnapshot());
2175
+ let previousSize = -1;
2176
+ while (previousSize !== affected.size) {
2177
+ previousSize = affected.size;
2178
+ for (const drawing of Object.values(drawings)) if (drawing.groupId && affected.has(drawing.groupId)) affected.add(drawing.drawingId);
2179
+ }
2180
+ return affected;
2029
2181
  }
2030
- _syncDrawingDataFromSnapshot(unitId, drawingIds) {
2031
- const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2032
- if (documentDataModel == null) return;
2033
- const { drawings, drawingsOrder } = collectDocDrawings(documentDataModel.getSnapshot());
2034
- const drawingData = Object.fromEntries(Object.entries(drawings).map(([id, drawing]) => [id, {
2035
- ...drawing,
2036
- unitId,
2037
- subUnitId: unitId
2038
- }]));
2039
- const previousDrawings = this._docDrawingService.getDrawingData(unitId, unitId);
2040
- const previousRendered = this._drawingManagerService.getDrawingData(unitId, unitId);
2041
- const missingIds = Object.keys(drawingData).filter((id) => !previousRendered[id]);
2042
- const synchronizedDrawingIds = [.../* @__PURE__ */ new Set([...drawingIds, ...missingIds])];
2043
- const orderChanged = drawingsOrder !== this._docDrawingService.getDrawingOrder(unitId, unitId) || synchronizedDrawingIds.some((drawingId) => {
2044
- const previous = previousDrawings[drawingId];
2045
- const current = drawingData[drawingId];
2046
- return ((previous === null || previous === void 0 ? void 0 : previous.layoutType) === PositionedObjectLayoutType.WRAP_NONE && previous.behindDoc === BooleanNumber.TRUE) !== ((current === null || current === void 0 ? void 0 : current.layoutType) === PositionedObjectLayoutType.WRAP_NONE && current.behindDoc === BooleanNumber.TRUE);
2182
+ _collectPublishedPageDrawingPositions(unitId, page, skeHeaders, skeFooters, docsLeft, docsTop, updateDrawingMap) {
2183
+ var _skeHeaders$get, _skeFooters$get;
2184
+ const selectable = !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder;
2185
+ const { headerId, footerId, pageWidth } = page;
2186
+ const headerPage = headerId ? (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(page.headerLayoutKey ?? pageWidth) : void 0;
2187
+ if (headerPage != null) this._collectSegmentDrawingPositions(unitId, headerPage, docsLeft, docsTop, updateDrawingMap, headerPage.marginTop, page.marginLeft, page, selectable);
2188
+ const footerPage = footerId ? (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(page.footerLayoutKey ?? pageWidth) : void 0;
2189
+ if (footerPage != null) {
2190
+ const footerTop = page.pageHeight - footerPage.height - footerPage.marginBottom;
2191
+ this._collectSegmentDrawingPositions(unitId, footerPage, docsLeft, docsTop, updateDrawingMap, footerTop, page.marginLeft, page, selectable);
2192
+ }
2193
+ this._collectSegmentDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft, void 0, selectable);
2194
+ for (const note of page.notes ?? []) this._collectSegmentDrawingPositions(unitId, note.page, docsLeft, docsTop, updateDrawingMap, note.top, note.left, void 0, selectable, {
2195
+ top: note.top,
2196
+ left: note.left
2047
2197
  });
2048
- const hierarchyChanged = synchronizedDrawingIds.some((id) => {
2049
- var _previousDrawings$id, _drawingData$id;
2050
- return ((_previousDrawings$id = previousDrawings[id]) === null || _previousDrawings$id === void 0 ? void 0 : _previousDrawings$id.groupId) !== ((_drawingData$id = drawingData[id]) === null || _drawingData$id === void 0 ? void 0 : _drawingData$id.groupId);
2198
+ }
2199
+ _collectSegmentDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable, clipOffset) {
2200
+ const overflowClipBounds = getDocsDrawingPageClipBounds({
2201
+ docsLeft,
2202
+ docsTop,
2203
+ pageOffsetLeft: this._liquid.x,
2204
+ pageOffsetTop: this._liquid.y,
2205
+ page: hostPage ?? page
2051
2206
  });
2052
- if (hierarchyChanged) this._drawingManagerService.removeNotification(Object.values(this._drawingManagerService.getDrawingData(unitId, unitId)));
2053
- const renderedDrawings = { ...this._drawingManagerService.getDrawingData(unitId, unitId) };
2054
- for (const drawingId of synchronizedDrawingIds) {
2055
- const current = drawingData[drawingId];
2056
- if (current) {
2057
- var _renderedDrawings$dra;
2058
- renderedDrawings[drawingId] = {
2059
- ...current,
2060
- transform: ((_renderedDrawings$dra = renderedDrawings[drawingId]) === null || _renderedDrawings$dra === void 0 ? void 0 : _renderedDrawings$dra.transform) ?? current.transform
2061
- };
2062
- } else delete renderedDrawings[drawingId];
2063
- }
2064
- this._docDrawingService.setDrawingData(unitId, unitId, drawingData);
2065
- this._drawingManagerService.setDrawingData(unitId, unitId, renderedDrawings);
2066
- if (orderChanged) {
2067
- this._docDrawingService.setDrawingOrder(unitId, unitId, drawingsOrder);
2068
- this._drawingManagerService.setDrawingOrder(unitId, unitId, getDocDrawingRenderOrder(drawingsOrder, drawings));
2069
- }
2070
- const objects = synchronizedDrawingIds.filter((drawingId) => drawingData[drawingId] != null).map((drawingId) => ({
2207
+ this._calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable, clipOffset, overflowClipBounds);
2208
+ this._calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2209
+ this._calculateColumnGroupDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2210
+ }
2211
+ _getStaleNonMultiDrawings(unitId, updateDrawingMap, drawingIds) {
2212
+ const drawingData = this._drawingManagerService.getDrawingData(unitId, unitId) ?? {};
2213
+ return Object.values(drawingData).filter((drawing) => drawing.isMultiTransform !== BooleanNumber.TRUE).filter((drawing) => drawingIds == null || drawingIds.has(drawing.drawingId)).filter((drawing) => updateDrawingMap[drawing.drawingId] == null).map((drawing) => ({
2071
2214
  unitId,
2072
2215
  subUnitId: unitId,
2073
- drawingId
2216
+ drawingId: drawing.drawingId,
2217
+ behindText: false,
2218
+ hidden: true,
2219
+ selectable: true,
2220
+ transform: drawing.transform,
2221
+ transforms: drawing.transforms ?? [],
2222
+ isMultiTransform: drawing.isMultiTransform ?? BooleanNumber.FALSE
2074
2223
  }));
2075
- if (objects.length === 0) return;
2076
- if (hierarchyChanged) this._drawingManagerService.addNotification(Object.values(renderedDrawings));
2077
- this._docDrawingService.updateNotification(objects);
2078
- this._drawingManagerService.updateNotification(objects);
2079
- }
2080
- };
2081
- DocDrawingAddRemoveController = __decorate([
2082
- __decorateParam(0, IUniverInstanceService),
2083
- __decorateParam(1, ICommandService),
2084
- __decorateParam(2, IDrawingManagerService),
2085
- __decorateParam(3, IDocDrawingService),
2086
- __decorateParam(4, IRenderManagerService),
2087
- __decorateParam(5, Inject(DocRefreshDrawingsService))
2088
- ], DocDrawingAddRemoveController);
2089
-
2090
- //#endregion
2091
- //#region src/views/DocPrintingFloatDom.tsx
2092
- const DocPrintingFloatDom = (props) => {
2093
- const { floatDomInfos, scene, offset, bound } = props;
2094
- const width = bound.right - bound.left;
2095
- const height = bound.bottom - bound.top;
2096
- const floatDomParams = useMemo(() => floatDomInfos.map((info) => {
2097
- const { width = 0, height = 0, left = 0, top = 0 } = info.transform;
2098
- const domPos = calcDocFloatDomPositionByRect({
2099
- left,
2100
- right: left + width,
2101
- top,
2102
- bottom: top + height
2103
- }, scene);
2104
- const floatDom = {
2105
- position$: new BehaviorSubject(domPos),
2106
- position: domPos,
2107
- id: info.drawingId,
2108
- componentKey: info.componentKey,
2109
- onPointerMove: () => {},
2110
- onPointerDown: () => {},
2111
- onPointerUp: () => {},
2112
- onWheel: () => {},
2113
- unitId: info.unitId,
2114
- data: info.data
2115
- };
2116
- return [info.drawingId, floatDom];
2117
- }).filter(([_, floatDom]) => !(floatDom.position.endX < 0 || floatDom.position.endY < 0 || floatDom.position.startX > width || floatDom.position.startY > height)), [
2118
- floatDomInfos,
2119
- scene,
2120
- offset,
2121
- width,
2122
- height
2123
- ]);
2124
- return /* @__PURE__ */ jsx("div", {
2125
- className: "univer-absolute univer-left-0 univer-top-0",
2126
- children: floatDomParams.map(([id, floatDom]) => /* @__PURE__ */ jsx(PrintFloatDomSingle, {
2127
- layer: floatDom,
2128
- id,
2129
- position: floatDom.position
2130
- }, id))
2131
- });
2132
- };
2133
- function mountDocPrintingFloatDom(props, root, injector) {
2134
- const PrintingFloatDomInjector = connectInjector(DocPrintingFloatDom, injector);
2135
- render(/* @__PURE__ */ jsx(PrintingFloatDomInjector, { ...props }), root);
2136
- return () => unmount(root);
2137
- }
2138
-
2139
- //#endregion
2140
- //#region src/controllers/doc-drawing-printing.controller.ts
2141
- let DocDrawingPrintingController = class DocDrawingPrintingController extends Disposable {
2142
- constructor(_docPrintInterceptorService, _drawingRenderService, _drawingManagerService, _componetManager, _injector) {
2143
- super();
2144
- this._docPrintInterceptorService = _docPrintInterceptorService;
2145
- this._drawingRenderService = _drawingRenderService;
2146
- this._drawingManagerService = _drawingManagerService;
2147
- this._componetManager = _componetManager;
2148
- this._injector = _injector;
2149
- this._initPrinting();
2150
- this._initPrintingDom();
2151
- }
2152
- _initPrinting() {
2153
- this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_COMPONENT_COLLECT, { handler: (_param, pos, next) => {
2154
- const { unitId, scene, skeleton, pageIndex } = pos;
2155
- const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);
2156
- const subUnitData = unitData === null || unitData === void 0 ? void 0 : unitData[unitId];
2157
- const visibleDrawingIds = this._docPrintInterceptorService.getPageDrawingIds(skeleton, pageIndex);
2158
- if (subUnitData) subUnitData.order.forEach((id) => {
2159
- if (visibleDrawingIds && !visibleDrawingIds.has(id)) return;
2160
- const drawing = subUnitData.data[id];
2161
- if (drawing.drawingType !== DrawingTypeEnum.DRAWING_CHART && drawing.drawingType !== DrawingTypeEnum.DRAWING_DOM) this._drawingRenderService.renderDrawing(drawing, scene);
2162
- });
2163
- return next();
2164
- } }));
2165
2224
  }
2166
- _initPrintingDom() {
2167
- this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_DOM_COLLECT, { handler: (disposableCollection, pos, next) => {
2168
- const { unitId, skeleton, pageIndex } = pos;
2169
- const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);
2170
- const subUnitData = unitData === null || unitData === void 0 ? void 0 : unitData[unitId];
2171
- const visibleDrawingIds = this._docPrintInterceptorService.getPageDrawingIds(skeleton, pageIndex);
2172
- if (subUnitData) {
2173
- const floatDomInfos = subUnitData.order.filter((id) => !visibleDrawingIds || visibleDrawingIds.has(id)).map((id) => {
2174
- const drawing = subUnitData.data[id];
2175
- if (drawing.drawingType === DrawingTypeEnum.DRAWING_CHART) return {
2176
- ...drawing,
2177
- componentKey: this._componetManager.get(DOC_DRAWING_PRINTING_COMPONENT_KEY)
2178
- };
2179
- if (drawing.drawingType === DrawingTypeEnum.DRAWING_DOM) {
2180
- const printingComponentKey = this._docPrintInterceptorService.getPrintComponent(drawing.componentKey);
2181
- return {
2182
- ...drawing,
2183
- componentKey: this._componetManager.get(printingComponentKey || drawing.componentKey)
2184
- };
2185
- }
2186
- return null;
2187
- }).filter(Boolean);
2188
- const unmountPrintingFloatDom = mountDocPrintingFloatDom({
2189
- unitId,
2190
- floatDomInfos,
2191
- scene: pos.scene,
2192
- skeleton: pos.skeleton,
2193
- offset: pos.offset,
2194
- bound: pos.bound
2195
- }, pos.root, this._injector);
2196
- disposableCollection === null || disposableCollection === void 0 || disposableCollection.add(() => {
2197
- unmountPrintingFloatDom();
2198
- });
2199
- return next(disposableCollection);
2225
+ _handleMultiDrawingsTransform(multiDrawings, forceRecreate = false) {
2226
+ const { scene, unitId } = this._context;
2227
+ const changedDrawings = multiDrawings.filter((drawing) => forceRecreate || shouldRefreshDocDrawingTransform(this._drawingManagerService.getDrawingByParam(drawing) ?? void 0, drawing));
2228
+ const publishedDrawingIds = new Set(multiDrawings.map((drawing) => drawing.drawingId));
2229
+ const removedDrawings = Object.values(this._drawingManagerService.getDrawingData(unitId, unitId)).filter((drawing) => drawing.isMultiTransform === BooleanNumber.TRUE && (forceRecreate || !publishedDrawingIds.has(drawing.drawingId) && drawing.hidden !== true));
2230
+ if (changedDrawings.length === 0 && removedDrawings.length === 0) return;
2231
+ const transformer = scene.getTransformer();
2232
+ const selectedObjectKeys = forceRecreate ? [.../* @__PURE__ */ new Set([...this._pendingMultiDrawingSelection, ...(transformer === null || transformer === void 0 ? void 0 : transformer.getSelectedObjectMap().keys()) ?? []])] : [];
2233
+ if (forceRecreate) this._clearPendingMultiDrawingSelection();
2234
+ changedDrawings.forEach((updateParam) => {
2235
+ var _updateParam$transfor, _param$transforms;
2236
+ const param = this._drawingManagerService.getDrawingByParam(updateParam);
2237
+ if (param == null) return;
2238
+ for (let index = ((_updateParam$transfor = updateParam.transforms) === null || _updateParam$transfor === void 0 ? void 0 : _updateParam$transfor.length) ?? 0; index < (((_param$transforms = param.transforms) === null || _param$transforms === void 0 ? void 0 : _param$transforms.length) ?? 0); index++) {
2239
+ var _scene$getObjectInclu;
2240
+ const key = getDrawingShapeKeyByDrawingSearch(param, index);
2241
+ transformer === null || transformer === void 0 || transformer.clearControlByIds([key]);
2242
+ (_scene$getObjectInclu = scene.getObjectIncludeInGroup(key)) === null || _scene$getObjectInclu === void 0 || _scene$getObjectInclu.dispose();
2200
2243
  }
2201
- } }));
2244
+ Object.assign(param, updateParam);
2245
+ });
2246
+ if (removedDrawings.length > 0) {
2247
+ this._drawingManagerService.removeNotification(removedDrawings);
2248
+ for (const drawing of removedDrawings) if (!publishedDrawingIds.has(drawing.drawingId)) drawing.hidden = true;
2249
+ }
2250
+ if (changedDrawings.length > 0) {
2251
+ if (forceRecreate) this._drawingManagerService.addNotification(changedDrawings);
2252
+ else this._drawingManagerService.refreshTransform(changedDrawings);
2253
+ }
2254
+ if (forceRecreate) this._restoreMultiDrawingSelection(selectedObjectKeys);
2255
+ else if (this._pendingMultiDrawingSelection.size > 0) this._restoreMultiDrawingSelection([...this._pendingMultiDrawingSelection]);
2256
+ else transformer === null || transformer === void 0 || transformer.refreshControls();
2257
+ }
2258
+ _clearPendingMultiDrawingSelection() {
2259
+ var _this$_pendingMultiDr;
2260
+ (_this$_pendingMultiDr = this._pendingMultiDrawingSelectionSubscription) === null || _this$_pendingMultiDr === void 0 || _this$_pendingMultiDr.dispose();
2261
+ this._pendingMultiDrawingSelectionSubscription = void 0;
2262
+ this._pendingMultiDrawingSelection.clear();
2263
+ }
2264
+ _restoreMultiDrawingSelection(selectedKeys) {
2265
+ this._clearPendingMultiDrawingSelection();
2266
+ const { scene, unitId } = this._context;
2267
+ const transformer = scene.getTransformer();
2268
+ if (!transformer || this._disposed) return;
2269
+ const publishedKeys = new Set(Object.values(this._drawingManagerService.getDrawingData(unitId, unitId)).filter((drawing) => drawing.isMultiTransform === BooleanNumber.TRUE && drawing.hidden !== true && drawing.selectable !== false).flatMap((drawing) => (drawing.transforms ?? []).map((_, index) => getDrawingShapeKeyByDrawingSearch(drawing, index))));
2270
+ for (const key of selectedKeys) {
2271
+ const drawingShape = scene.getObjectIncludeInGroup(key);
2272
+ if ((drawingShape === null || drawingShape === void 0 ? void 0 : drawingShape.visible) && drawingShape.evented) transformer.setSelectedControl(drawingShape);
2273
+ else if (!drawingShape && publishedKeys.has(key)) this._pendingMultiDrawingSelection.add(key);
2274
+ }
2275
+ transformer.refreshControls();
2276
+ if (this._pendingMultiDrawingSelection.size === 0) return;
2277
+ const subscriptions = new Subscription();
2278
+ this._pendingMultiDrawingSelectionSubscription = this.disposeWithMe(subscriptions);
2279
+ const allowedSelectionKeys = /* @__PURE__ */ new Set([...selectedKeys, ...transformer.getSelectedObjectMap().keys()]);
2280
+ const pendingDrawingIds = this._includeGroupChildren(new Set([...this._pendingMultiDrawingSelection].flatMap((key) => {
2281
+ const drawing = this._drawingManagerService.getDrawingOKey(key);
2282
+ return drawing ? [drawing.drawingId] : [];
2283
+ })));
2284
+ subscriptions.add(this._drawingManagerService.refreshTransform$.subscribe((drawings) => {
2285
+ if (drawings.some((drawing) => drawing.unitId === unitId && (pendingDrawingIds === null || pendingDrawingIds === void 0 ? void 0 : pendingDrawingIds.has(drawing.drawingId)))) this._restoreMultiDrawingSelection([...this._pendingMultiDrawingSelection]);
2286
+ }));
2287
+ subscriptions.add(this._drawingManagerService.remove$.subscribe((drawings) => {
2288
+ const removedKeys = drawings.map((drawing) => getDrawingShapeKeyByDrawingSearch(drawing));
2289
+ const remainingKeys = [...this._pendingMultiDrawingSelection].filter((key) => !removedKeys.some((removedKey) => key === removedKey || key.startsWith(`${removedKey}#-#`)));
2290
+ if (remainingKeys.length !== this._pendingMultiDrawingSelection.size) this._restoreMultiDrawingSelection(remainingKeys);
2291
+ }));
2292
+ subscriptions.add(merge$1(transformer.clearControl$, transformer.changeStart$).subscribe(() => {
2293
+ this._clearPendingMultiDrawingSelection();
2294
+ }));
2295
+ subscriptions.add(transformer.createControl$.subscribe(() => {
2296
+ if ([...transformer.getSelectedObjectMap().keys()].some((key) => !allowedSelectionKeys.has(key))) this._clearPendingMultiDrawingSelection();
2297
+ }));
2202
2298
  }
2203
- };
2204
- DocDrawingPrintingController = __decorate([
2205
- __decorateParam(0, Inject(DocPrintInterceptorService)),
2206
- __decorateParam(1, Inject(DrawingRenderService)),
2207
- __decorateParam(2, IDrawingManagerService),
2208
- __decorateParam(3, Inject(ComponentManager)),
2209
- __decorateParam(4, Inject(Injector))
2210
- ], DocDrawingPrintingController);
2211
-
2212
- //#endregion
2213
- //#region src/commands/commands/update-doc-drawing.command.ts
2214
- function getDeleteAndInsertCustomBlockActions(segmentId, oldSegmentId, segmentPage, offset, drawingId, documentDataModel, docSelectionRenderManager) {
2215
- var _documentDataModel$ge, _documentDataModel$ge2, _oldBody$customBlocks;
2216
- const textX = new TextX();
2217
- const jsonX = JSONX.getInstance();
2218
- const rawActions = [];
2219
- const oldBody = (_documentDataModel$ge = documentDataModel.getSelfOrHeaderFooterModel(oldSegmentId)) === null || _documentDataModel$ge === void 0 ? void 0 : _documentDataModel$ge.getBody();
2220
- const body = (_documentDataModel$ge2 = documentDataModel.getSelfOrHeaderFooterModel(segmentId)) === null || _documentDataModel$ge2 === void 0 ? void 0 : _documentDataModel$ge2.getBody();
2221
- if (oldBody == null || body == null) return;
2222
- const oldOffset = (_oldBody$customBlocks = oldBody.customBlocks) === null || _oldBody$customBlocks === void 0 || (_oldBody$customBlocks = _oldBody$customBlocks.find((block) => block.blockId === drawingId)) === null || _oldBody$customBlocks === void 0 ? void 0 : _oldBody$customBlocks.startIndex;
2223
- if (oldOffset == null) return;
2224
- offset = Math.min(body.dataStream.length - 2, offset);
2225
- if (segmentId === oldSegmentId) {
2226
- if (offset < oldOffset) {
2227
- if (offset > 0) textX.push({
2228
- t: TextXActionType.RETAIN,
2229
- len: offset
2230
- });
2231
- textX.push({
2232
- t: TextXActionType.INSERT,
2233
- body: {
2234
- dataStream: "\b",
2235
- customBlocks: [{
2236
- startIndex: 0,
2237
- blockId: drawingId
2238
- }]
2239
- },
2240
- len: 1
2241
- });
2242
- textX.push({
2243
- t: TextXActionType.RETAIN,
2244
- len: oldOffset - offset
2245
- });
2246
- textX.push({
2247
- t: TextXActionType.DELETE,
2248
- len: 1
2249
- });
2250
- } else {
2251
- if (oldOffset > 0) textX.push({
2252
- t: TextXActionType.RETAIN,
2253
- len: oldOffset
2254
- });
2255
- textX.push({
2256
- t: TextXActionType.DELETE,
2257
- len: 1
2258
- });
2259
- if (offset - oldOffset - 1 > 0) textX.push({
2260
- t: TextXActionType.RETAIN,
2261
- len: offset - oldOffset - 1
2262
- });
2263
- textX.push({
2264
- t: TextXActionType.INSERT,
2265
- body: {
2266
- dataStream: "\b",
2267
- customBlocks: [{
2268
- startIndex: 0,
2269
- blockId: drawingId
2270
- }]
2271
- },
2272
- len: 1
2273
- });
2274
- }
2275
- if (offset !== oldOffset) {
2276
- const path = getRichTextEditPath(documentDataModel, oldSegmentId);
2277
- const action = jsonX.editOp(textX.serialize(), path);
2278
- rawActions.push(action);
2279
- }
2280
- } else {
2281
- if (oldOffset > 0) textX.push({
2282
- t: TextXActionType.RETAIN,
2283
- len: oldOffset
2299
+ _calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable = true, clipOffset, overflowClipBounds) {
2300
+ const { skeDrawings } = page;
2301
+ const pageOffsetLeft = this._liquid.x;
2302
+ const pageOffsetTop = this._liquid.y;
2303
+ this._liquid.translatePagePadding({
2304
+ marginTop,
2305
+ marginLeft
2284
2306
  });
2285
- textX.push({
2286
- t: TextXActionType.DELETE,
2287
- len: 1
2307
+ const drawingPositionContext = {
2308
+ unitId,
2309
+ page,
2310
+ docsLeft,
2311
+ docsTop,
2312
+ pageOffsetLeft,
2313
+ pageOffsetTop,
2314
+ updateDrawingMap,
2315
+ hostPage,
2316
+ selectable,
2317
+ clipOffset,
2318
+ overflowClipBounds
2319
+ };
2320
+ skeDrawings.forEach((drawing) => this._collectDrawingPosition(drawing, drawingPositionContext));
2321
+ this._liquid.restorePagePadding({
2322
+ marginTop,
2323
+ marginLeft
2288
2324
  });
2289
- let path = getRichTextEditPath(documentDataModel, oldSegmentId);
2290
- let action = jsonX.editOp(textX.serialize(), path);
2291
- rawActions.push(action);
2292
- textX.empty();
2293
- if (offset > 0) textX.push({
2294
- t: TextXActionType.RETAIN,
2295
- len: offset
2325
+ }
2326
+ _collectDrawingPosition(drawing, context) {
2327
+ var _this$_context$unit, _this$_context$unit$g;
2328
+ const { aLeft, aTop, angle: skeletonAngle, drawingId, drawingOrigin, height: skeletonHeight, width: skeletonWidth } = drawing;
2329
+ const runtimeDrawing = getDocsOverlayRuntimeDrawing(drawingOrigin, (_this$_context$unit = this._context.unit) === null || _this$_context$unit === void 0 || (_this$_context$unit$g = _this$_context$unit.getSnapshot) === null || _this$_context$unit$g === void 0 || (_this$_context$unit$g = _this$_context$unit$g.call(_this$_context$unit).drawings) === null || _this$_context$unit$g === void 0 ? void 0 : _this$_context$unit$g[drawingId], drawing.customBlockRenderViewport ? {
2330
+ width: skeletonWidth,
2331
+ height: skeletonHeight
2332
+ } : void 0);
2333
+ const { angle = skeletonAngle, size } = runtimeDrawing.docTransform;
2334
+ const height = (size === null || size === void 0 ? void 0 : size.height) ?? skeletonHeight;
2335
+ const width = (size === null || size === void 0 ? void 0 : size.width) ?? skeletonWidth;
2336
+ const { left: clipOffsetLeft, top: clipOffsetTop } = context.clipOffset ?? {};
2337
+ const behindText = getDocsDrawingBehindText({
2338
+ drawingOrigin: runtimeDrawing,
2339
+ hostPage: context.hostPage
2296
2340
  });
2297
- textX.push({
2298
- t: TextXActionType.INSERT,
2299
- body: {
2300
- dataStream: "\b",
2301
- customBlocks: [{
2302
- startIndex: 0,
2303
- blockId: drawingId
2304
- }]
2341
+ const { isMultiTransform = BooleanNumber.FALSE } = runtimeDrawing;
2342
+ const clipPage = getDocsDrawingClipPage({
2343
+ drawing: {
2344
+ behindText,
2345
+ transform: {
2346
+ width,
2347
+ height
2348
+ }
2305
2349
  },
2306
- len: 1
2350
+ hostPage: context.hostPage,
2351
+ page: context.page
2307
2352
  });
2308
- path = getRichTextEditPath(documentDataModel, segmentId);
2309
- action = jsonX.editOp(textX.serialize(), path);
2310
- rawActions.push(action);
2311
- docSelectionRenderManager.setSegment(segmentId);
2312
- docSelectionRenderManager.setSegmentPage(segmentPage);
2353
+ const clipBounds = getDocsDrawingPageClipBounds({
2354
+ docsLeft: context.docsLeft,
2355
+ docsTop: context.docsTop,
2356
+ pageOffsetLeft: context.pageOffsetLeft,
2357
+ pageOffsetTop: context.pageOffsetTop,
2358
+ clipOffsetLeft,
2359
+ clipOffsetTop,
2360
+ page: clipPage,
2361
+ drawingLayoutType: runtimeDrawing.layoutType,
2362
+ overflowClipBounds: context.overflowClipBounds
2363
+ });
2364
+ const anchorPage = getDocsPageRelativeDrawingAnchorPage({
2365
+ page: context.page,
2366
+ clipPage,
2367
+ hostPage: context.hostPage,
2368
+ drawingLayoutType: runtimeDrawing.layoutType
2369
+ });
2370
+ const pageRelativeLeft = anchorPage == null ? void 0 : getDocsPageRelativeDrawingLeft({
2371
+ hostPage: anchorPage,
2372
+ positionH: runtimeDrawing.docTransform.positionH,
2373
+ width
2374
+ });
2375
+ const pageRelativeTop = anchorPage == null ? void 0 : getDocsPageRelativeDrawingTop({
2376
+ hostPage: anchorPage,
2377
+ positionV: runtimeDrawing.docTransform.positionV,
2378
+ height
2379
+ });
2380
+ const transform = {
2381
+ left: (pageRelativeLeft ?? aLeft) + context.docsLeft + (pageRelativeLeft == null ? this._liquid.x : context.pageOffsetLeft),
2382
+ top: (pageRelativeTop ?? aTop) + context.docsTop + (pageRelativeTop == null ? this._liquid.y : context.pageOffsetTop),
2383
+ width,
2384
+ height,
2385
+ angle,
2386
+ flipX: runtimeDrawing.docTransform.flipX,
2387
+ flipY: runtimeDrawing.docTransform.flipY,
2388
+ clipBounds
2389
+ };
2390
+ mergePublishedDrawing(context.updateDrawingMap, {
2391
+ unitId: context.unitId,
2392
+ subUnitId: context.unitId,
2393
+ drawingId,
2394
+ behindText,
2395
+ selectable: context.selectable,
2396
+ transform,
2397
+ transforms: [transform],
2398
+ customBlockRenderViewport: drawing.customBlockRenderViewport,
2399
+ isMultiTransform
2400
+ });
2401
+ if (runtimeDrawing.drawingType === DrawingTypeEnum.DRAWING_GROUP) this._collectGroupChildren(drawingId, context, behindText, isMultiTransform, /* @__PURE__ */ new Set([drawingId]));
2313
2402
  }
2314
- return rawActions;
2315
- }
2316
- /**
2317
- * The command to update drawing wrap text.
2318
- */
2319
- const UpdateDocDrawingDistanceCommand = {
2320
- id: "doc.command.update-doc-drawing-distance",
2321
- type: CommandType.COMMAND,
2322
- handler: (accessor, params) => {
2323
- if (params == null) return false;
2324
- const commandService = accessor.get(ICommandService);
2325
- const univerInstanceService = accessor.get(IUniverInstanceService);
2326
- const { drawings, dist, unitId } = params;
2327
- const documentDataModel = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2328
- if (documentDataModel == null) return false;
2329
- const jsonX = JSONX.getInstance();
2330
- const rawActions = [];
2331
- const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
2332
- for (const drawing of drawings) {
2333
- const { drawingId } = drawing;
2334
- for (const [key, value] of Object.entries(dist)) {
2335
- const oldValue = oldDrawings[drawingId][key];
2336
- if (oldValue !== value) {
2337
- const action = jsonX.replaceOp([
2338
- "drawings",
2339
- drawingId,
2340
- key
2341
- ], oldValue, value);
2342
- rawActions.push(action);
2343
- }
2344
- }
2403
+ _collectGroupChildren(groupId, context, behindText, isMultiTransform, visited) {
2404
+ const { drawings } = collectDocDrawings(this._context.unit.getSnapshot());
2405
+ for (const child of Object.values(drawings)) {
2406
+ if (child.groupId !== groupId || visited.has(child.drawingId)) continue;
2407
+ visited.add(child.drawingId);
2408
+ const { size, positionH, positionV, angle, flipX, flipY } = child.docTransform;
2409
+ const transform = {
2410
+ left: positionH.posOffset ?? 0,
2411
+ top: positionV.posOffset ?? 0,
2412
+ width: size.width,
2413
+ height: size.height,
2414
+ angle,
2415
+ flipX,
2416
+ flipY
2417
+ };
2418
+ mergePublishedDrawing(context.updateDrawingMap, {
2419
+ unitId: context.unitId,
2420
+ subUnitId: context.unitId,
2421
+ drawingId: child.drawingId,
2422
+ behindText,
2423
+ selectable: context.selectable,
2424
+ transform,
2425
+ transforms: [transform],
2426
+ isMultiTransform
2427
+ });
2428
+ this._collectGroupChildren(child.drawingId, context, behindText, isMultiTransform, visited);
2345
2429
  }
2346
- const doMutation = {
2347
- id: RichTextEditingMutation.id,
2348
- params: {
2349
- unitId,
2350
- actions: [],
2351
- textRanges: null
2352
- }
2353
- };
2354
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2355
- return JSONX.compose(acc, cur);
2356
- }, null);
2357
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2358
- return Boolean(result);
2359
2430
  }
2360
- };
2361
- /**
2362
- * The command to update drawing wrap text.
2363
- */
2364
- const UpdateDocDrawingWrapTextCommand = {
2365
- id: "doc.command.update-doc-drawing-wrap-text",
2366
- type: CommandType.COMMAND,
2367
- handler: (accessor, params) => {
2368
- if (params == null) return false;
2369
- const commandService = accessor.get(ICommandService);
2370
- const univerInstanceService = accessor.get(IUniverInstanceService);
2371
- const { drawings, wrapText, unitId } = params;
2372
- const documentDataModel = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2373
- if (documentDataModel == null) return false;
2374
- const jsonX = JSONX.getInstance();
2375
- const rawActions = [];
2376
- const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
2377
- for (const drawing of drawings) {
2378
- const { drawingId } = drawing;
2379
- const oldWrapText = oldDrawings[drawingId].wrapText;
2380
- if (oldWrapText !== wrapText) {
2381
- const action = jsonX.replaceOp([
2382
- "drawings",
2383
- drawingId,
2384
- "wrapText"
2385
- ], oldWrapText, wrapText);
2386
- rawActions.push(action);
2387
- }
2388
- }
2389
- const doMutation = {
2390
- id: RichTextEditingMutation.id,
2391
- params: {
2392
- unitId,
2393
- actions: [],
2394
- textRanges: null
2395
- }
2431
+ _calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, baseMarginTop, baseMarginLeft, selectable, overflowClipBounds) {
2432
+ var _page$skeTables3;
2433
+ (_page$skeTables3 = page.skeTables) === null || _page$skeTables3 === void 0 || _page$skeTables3.forEach((table) => {
2434
+ table.rows.forEach((row) => {
2435
+ row.cells.forEach((cell) => {
2436
+ var _cell$skeDrawings, _cell$skeTables, _cell$skeColumnGroups;
2437
+ if ((((_cell$skeDrawings = cell.skeDrawings) === null || _cell$skeDrawings === void 0 ? void 0 : _cell$skeDrawings.size) ?? 0) === 0 && (((_cell$skeTables = cell.skeTables) === null || _cell$skeTables === void 0 ? void 0 : _cell$skeTables.size) ?? 0) === 0 && (((_cell$skeColumnGroups = cell.skeColumnGroups) === null || _cell$skeColumnGroups === void 0 ? void 0 : _cell$skeColumnGroups.size) ?? 0) === 0) return;
2438
+ const cellOffset = getDocsTableCellDrawingOffset(unitId, table, row, cell);
2439
+ const marginTop = baseMarginTop + cellOffset.top;
2440
+ const marginLeft = baseMarginLeft + cellOffset.left;
2441
+ this._calculateDrawingPosition(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, void 0, selectable, {
2442
+ left: marginLeft,
2443
+ top: marginTop
2444
+ }, overflowClipBounds);
2445
+ this._calculateTableCellDrawingPositions(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2446
+ this._calculateColumnGroupDrawingPositions(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2447
+ });
2448
+ });
2449
+ });
2450
+ }
2451
+ _calculateColumnGroupDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, baseMarginTop, baseMarginLeft, selectable, overflowClipBounds) {
2452
+ var _page$skeColumnGroups3;
2453
+ (_page$skeColumnGroups3 = page.skeColumnGroups) === null || _page$skeColumnGroups3 === void 0 || _page$skeColumnGroups3.forEach((columnGroup) => {
2454
+ columnGroup.columns.forEach((column) => {
2455
+ const nestedPage = column.page;
2456
+ const marginTop = baseMarginTop + columnGroup.top + column.top + nestedPage.marginTop;
2457
+ const marginLeft = baseMarginLeft + columnGroup.left + column.left + nestedPage.marginLeft;
2458
+ const clipOffset = {
2459
+ left: marginLeft,
2460
+ top: marginTop
2461
+ };
2462
+ this._calculateDrawingPosition(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, void 0, selectable, clipOffset, overflowClipBounds);
2463
+ this._calculateTableCellDrawingPositions(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2464
+ this._calculateColumnGroupDrawingPositions(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2465
+ });
2466
+ });
2467
+ }
2468
+ _drawingInitializeListener() {
2469
+ const init = () => {
2470
+ const skeleton = this._docSkeletonManagerService.getSkeleton();
2471
+ if (skeleton == null) return;
2472
+ this._drawingManagerService.initializeNotification(this._context.unitId);
2473
+ this._refreshDrawing(skeleton);
2396
2474
  };
2397
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2398
- return JSONX.compose(acc, cur);
2399
- }, null);
2400
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2401
- return Boolean(result);
2475
+ if (this._lifecycleService.stage >= LifecycleStages.Rendered) {
2476
+ if (this._docSkeletonManagerService.getSkeleton()) init();
2477
+ else setTimeout(init, 500);
2478
+ } else this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(filter((stage) => stage === LifecycleStages.Rendered)).subscribe(init));
2402
2479
  }
2403
2480
  };
2404
- /**
2405
- * The command to move inline drawing.
2406
- */
2407
- const IMoveInlineDrawingCommand = {
2408
- id: "doc.command.move-inline-drawing",
2409
- type: CommandType.COMMAND,
2410
- handler: (accessor, params) => {
2411
- var _renderManagerService;
2412
- if (params == null) return false;
2413
- const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage, needRefreshDrawings } = params;
2414
- const renderManagerService = accessor.get(IRenderManagerService);
2415
- const docSelectionRenderService = (_renderManagerService = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService === void 0 ? void 0 : _renderManagerService.with(DocSelectionRenderService);
2416
- const docRefreshDrawingsService = accessor.get(DocRefreshDrawingsService);
2417
- const renderObject = renderManagerService.getRenderUnitById(unitId);
2418
- const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
2419
- const skeleton = renderObject === null || renderObject === void 0 ? void 0 : renderObject.with(DocSkeletonManagerService).getSkeleton();
2420
- if (scene == null || docSelectionRenderService == null) return false;
2421
- const transformer = scene.getTransformerByCreate();
2422
- const commandService = accessor.get(ICommandService);
2423
- const documentDataModel = accessor.get(IUniverInstanceService).getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2424
- if (documentDataModel == null) return false;
2425
- if (needRefreshDrawings) {
2426
- docRefreshDrawingsService.refreshDrawings(skeleton);
2427
- transformer.refreshControls();
2428
- return true;
2481
+ DocDrawingTransformUpdateController = __decorate([
2482
+ __decorateParam(1, Inject(DocSkeletonManagerService)),
2483
+ __decorateParam(2, ICommandService),
2484
+ __decorateParam(3, IEditorService),
2485
+ __decorateParam(4, IDrawingManagerService),
2486
+ __decorateParam(5, Inject(DocRefreshDrawingsService)),
2487
+ __decorateParam(6, IUniverInstanceService),
2488
+ __decorateParam(7, Inject(LifecycleService))
2489
+ ], DocDrawingTransformUpdateController);
2490
+
2491
+ //#endregion
2492
+ //#region src/utils/drawing-wrapping-position.ts
2493
+ function findDrawingAnchor(unitId, drawingId, skeleton, editArea, currentDrawing) {
2494
+ function findInPage(page, pageMarginLeft, pageMarginTop, hostPage) {
2495
+ var _page$skeColumnGroups;
2496
+ const cachedDrawing = page.skeDrawings.get(drawingId);
2497
+ const skeDrawing = cachedDrawing && currentDrawing ? {
2498
+ ...cachedDrawing,
2499
+ drawingOrigin: currentDrawing
2500
+ } : cachedDrawing;
2501
+ if (skeDrawing) return {
2502
+ skeDrawing,
2503
+ page,
2504
+ hostPage,
2505
+ pageMarginLeft,
2506
+ pageMarginTop
2507
+ };
2508
+ for (const table of page.skeTables.values()) for (const row of table.rows) for (const cell of row.cells) {
2509
+ const offset = getDocsTableCellDrawingOffset(unitId, table, row, cell);
2510
+ const found = findInPage(cell, pageMarginLeft + offset.left, pageMarginTop + offset.top);
2511
+ if (found) return found;
2429
2512
  }
2430
- const rawActions = [];
2431
- const { drawingId } = drawing;
2432
- const actions = getDeleteAndInsertCustomBlockActions(newSegmentId, docSelectionRenderService.getSegment() ?? "", segmentPage, offset, drawingId, documentDataModel, docSelectionRenderService);
2433
- if (actions == null || actions.length === 0) {
2434
- docRefreshDrawingsService.refreshDrawings(skeleton);
2435
- transformer.refreshControls();
2436
- return false;
2513
+ for (const group of ((_page$skeColumnGroups = page.skeColumnGroups) === null || _page$skeColumnGroups === void 0 ? void 0 : _page$skeColumnGroups.values()) ?? []) for (const column of group.columns) {
2514
+ const found = findInPage(column.page, pageMarginLeft + group.left + column.left + column.page.marginLeft, pageMarginTop + group.top + column.top + column.page.marginTop);
2515
+ if (found) return found;
2437
2516
  }
2438
- rawActions.push(...actions);
2439
- const doMutation = {
2440
- id: RichTextEditingMutation.id,
2441
- params: {
2442
- unitId,
2443
- actions: [],
2444
- textRanges: null
2445
- }
2446
- };
2447
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2448
- return JSONX.compose(acc, cur);
2449
- }, null);
2450
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2451
- transformer.refreshControls();
2452
- return Boolean(result);
2517
+ return null;
2453
2518
  }
2454
- };
2455
- /**
2456
- * The command to transform non-inline drawing.
2457
- */
2458
- const ITransformNonInlineDrawingCommand = {
2459
- id: "doc.command.transform-non-inline-drawing",
2460
- type: CommandType.COMMAND,
2461
- handler: (accessor, params) => {
2462
- var _renderManagerService2;
2463
- if (params == null) return false;
2464
- const { drawing, unitId, offset, docTransform, segmentId: newSegmentId, segmentPage } = params;
2465
- const renderManagerService = accessor.get(IRenderManagerService);
2466
- const docSelectionRenderService = (_renderManagerService2 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService2 === void 0 ? void 0 : _renderManagerService2.with(DocSelectionRenderService);
2467
- const renderObject = renderManagerService.getRenderUnitById(unitId);
2468
- const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
2469
- if (renderObject == null || scene == null || docSelectionRenderService == null) return false;
2470
- const transformer = scene.getTransformerByCreate();
2471
- const commandService = accessor.get(ICommandService);
2472
- const documentDataModel = accessor.get(IUniverInstanceService).getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2473
- if (documentDataModel == null) return false;
2474
- const rawActions = [];
2475
- const { drawingId } = drawing;
2476
- const actions = getDeleteAndInsertCustomBlockActions(newSegmentId, docSelectionRenderService.getSegment() ?? "", segmentPage, offset, drawingId, documentDataModel, docSelectionRenderService);
2477
- if (actions == null) return false;
2478
- if (actions.length > 0) rawActions.push(...actions);
2479
- const jsonX = JSONX.getInstance();
2480
- const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
2481
- const { positionH: oldPositionH, positionV: oldPositionV, size: oldSize, angle: oldAngle } = oldDrawings[drawingId].docTransform;
2482
- if (!Tools.diffValue(oldPositionH, docTransform.positionH)) {
2483
- const updateAction = jsonX.replaceOp([
2484
- "drawings",
2485
- drawingId,
2486
- "docTransform",
2487
- "positionH"
2488
- ], oldPositionH, docTransform.positionH);
2489
- rawActions.push(updateAction);
2490
- }
2491
- if (!Tools.diffValue(oldPositionV, docTransform.positionV)) {
2492
- const updateAction = jsonX.replaceOp([
2493
- "drawings",
2494
- drawingId,
2495
- "docTransform",
2496
- "positionV"
2497
- ], oldPositionV, docTransform.positionV);
2498
- rawActions.push(updateAction);
2519
+ for (const page of skeleton.pages) {
2520
+ const { headerId, footerId, marginLeft, marginTop, pageWidth, pageHeight } = page;
2521
+ let found = null;
2522
+ if (editArea === DocumentEditArea.HEADER) {
2523
+ var _skeleton$skeHeaders$;
2524
+ const header = (_skeleton$skeHeaders$ = skeleton.skeHeaders.get(headerId)) === null || _skeleton$skeHeaders$ === void 0 ? void 0 : _skeleton$skeHeaders$.get(page.headerLayoutKey ?? pageWidth);
2525
+ if (header) found = findInPage(header, marginLeft, header.marginTop, page);
2526
+ } else if (editArea === DocumentEditArea.FOOTER) {
2527
+ var _skeleton$skeFooters$;
2528
+ const footer = (_skeleton$skeFooters$ = skeleton.skeFooters.get(footerId)) === null || _skeleton$skeFooters$ === void 0 ? void 0 : _skeleton$skeFooters$.get(page.footerLayoutKey ?? pageWidth);
2529
+ if (footer) found = findInPage(footer, marginLeft, pageHeight - footer.height - footer.marginBottom, page);
2530
+ } else {
2531
+ found = findInPage(page, marginLeft, marginTop);
2532
+ if (!found) for (const note of page.notes ?? []) {
2533
+ found = findInPage(note.page, note.left, note.top);
2534
+ if (found) break;
2535
+ }
2499
2536
  }
2500
- if (!Tools.diffValue(oldSize, docTransform.size)) {
2501
- const updateAction = jsonX.replaceOp([
2502
- "drawings",
2503
- drawingId,
2504
- "docTransform",
2505
- "size"
2506
- ], oldSize, docTransform.size);
2507
- rawActions.push(updateAction);
2537
+ if (found) return found;
2538
+ }
2539
+ return null;
2540
+ }
2541
+ function getColumnOrigin(anchor, relativeFromV) {
2542
+ const { skeDrawing, page } = anchor;
2543
+ let origin = skeDrawing.isPageBreak ? 0 : skeDrawing.columnLeft;
2544
+ if ((skeDrawing.blockAnchorLeft ?? 0) > 0 && relativeFromV !== ObjectRelativeFromV.LINE) {
2545
+ origin += skeDrawing.blockAnchorLeft - (skeDrawing.isPageBreak ? 0 : skeDrawing.columnLeft || page.marginLeft);
2546
+ if (skeDrawing.normalizeTraditionalColumnAnchor && relativeFromV === ObjectRelativeFromV.PARAGRAPH) origin -= page.marginLeft;
2547
+ }
2548
+ return origin;
2549
+ }
2550
+ /** Resolve a text-relative origin before committing a wrapping reference change. */
2551
+ function resolveDrawingWrappingPosition(anchor, position, snapshot, localeService, editArea) {
2552
+ var _findDocDrawing;
2553
+ const drawing = anchor.skeDrawing.drawingOrigin;
2554
+ const relativeFrom = position.positionV.relativeFrom;
2555
+ if (drawing.layoutType !== PositionedObjectLayoutType.WRAP_TOP_AND_BOTTOM && drawing.layoutType !== PositionedObjectLayoutType.WRAP_SQUARE || relativeFrom !== ObjectRelativeFromV.PARAGRAPH && relativeFrom !== ObjectRelativeFromV.LINE || drawing.docTransform.positionV.relativeFrom === relativeFrom) return position;
2556
+ const model = new DocumentDataModel(Tools.deepClone(snapshot));
2557
+ const previewDrawing = (_findDocDrawing = findDocDrawing(model.getSnapshot(), drawing.drawingId)) === null || _findDocDrawing === void 0 ? void 0 : _findDocDrawing.drawing;
2558
+ if (!previewDrawing) {
2559
+ model.dispose();
2560
+ return null;
2561
+ }
2562
+ const viewModel = new DocumentViewModel(model);
2563
+ const skeleton = DocumentSkeleton.create(viewModel, localeService);
2564
+ let candidate = {
2565
+ ...position,
2566
+ positionV: {
2567
+ relativeFrom,
2568
+ posOffset: 0
2508
2569
  }
2509
- if (!Tools.diffValue(oldAngle, docTransform.angle)) {
2510
- const updateAction = jsonX.replaceOp([
2511
- "drawings",
2512
- drawingId,
2513
- "docTransform",
2514
- "angle"
2515
- ], oldAngle, docTransform.angle);
2516
- rawActions.push(updateAction);
2570
+ };
2571
+ const targetTop = anchor.skeDrawing.aTop + anchor.pageMarginTop;
2572
+ let previous;
2573
+ try {
2574
+ for (let attempt = 0; attempt < 8; attempt++) {
2575
+ previewDrawing.docTransform = candidate;
2576
+ skeleton.makeDirty(true);
2577
+ skeleton.calculate();
2578
+ const resolved = findDrawingAnchor(snapshot.id, drawing.drawingId, skeleton.getSkeletonData(), editArea, previewDrawing);
2579
+ if (!resolved) return null;
2580
+ const delta = targetTop - resolved.skeDrawing.aTop - resolved.pageMarginTop;
2581
+ if (Math.abs(delta) < .01) return candidate;
2582
+ const offset = candidate.positionV.posOffset ?? 0;
2583
+ const nextOffset = previous && Math.abs(previous.delta - delta) > .01 ? offset - delta * (offset - previous.offset) / (delta - previous.delta) : offset + delta;
2584
+ previous = {
2585
+ offset,
2586
+ delta
2587
+ };
2588
+ candidate = {
2589
+ ...candidate,
2590
+ positionV: {
2591
+ relativeFrom,
2592
+ posOffset: nextOffset
2593
+ }
2594
+ };
2517
2595
  }
2518
- const doMutation = {
2519
- id: RichTextEditingMutation.id,
2520
- params: {
2521
- unitId,
2522
- actions: [],
2523
- textRanges: null,
2524
- debounce: true
2596
+ return null;
2597
+ } finally {
2598
+ skeleton.dispose();
2599
+ viewModel.dispose();
2600
+ model.dispose();
2601
+ }
2602
+ }
2603
+ /** Preserve the rendered position when text wrapping or a positioning reference changes. */
2604
+ function getDrawingWrappingPosition(anchor, layoutType, relativeFromH = anchor.skeDrawing.drawingOrigin.docTransform.positionH.relativeFrom, relativeFromV = anchor.skeDrawing.drawingOrigin.docTransform.positionV.relativeFrom, offset) {
2605
+ const { skeDrawing, page, hostPage, pageMarginLeft, pageMarginTop } = anchor;
2606
+ const { drawingOrigin, width, height, aLeft, aTop } = skeDrawing;
2607
+ const { positionH, positionV } = drawingOrigin.docTransform;
2608
+ const clipPage = getDocsDrawingClipPage({
2609
+ drawing: {
2610
+ behindText: getDocsDrawingBehindText({
2611
+ drawingOrigin,
2612
+ hostPage
2613
+ }),
2614
+ transform: {
2615
+ width,
2616
+ height
2525
2617
  }
2618
+ },
2619
+ page,
2620
+ hostPage
2621
+ });
2622
+ const anchorPage = getDocsPageRelativeDrawingAnchorPage({
2623
+ page,
2624
+ clipPage,
2625
+ hostPage
2626
+ });
2627
+ const wasPageRelative = drawingOrigin.layoutType !== PositionedObjectLayoutType.INLINE && anchorPage != null;
2628
+ const isPageRelative = layoutType !== PositionedObjectLayoutType.INLINE && anchorPage != null;
2629
+ const wasInline = drawingOrigin.layoutType === PositionedObjectLayoutType.INLINE;
2630
+ const result = { ...drawingOrigin.docTransform };
2631
+ const columnOriginChanged = relativeFromH === ObjectRelativeFromH.COLUMN && (skeDrawing.blockAnchorLeft ?? 0) > 0 && relativeFromV !== positionV.relativeFrom;
2632
+ if ((offset === null || offset === void 0 ? void 0 : offset.left) || wasInline || columnOriginChanged || relativeFromH !== positionH.relativeFrom || positionH.relativeFrom === ObjectRelativeFromH.PAGE && wasPageRelative !== isPageRelative) {
2633
+ const left = (wasPageRelative ? getDocsPageRelativeDrawingLeft({
2634
+ hostPage: anchorPage,
2635
+ positionH,
2636
+ width
2637
+ }) : void 0) ?? aLeft + pageMarginLeft;
2638
+ const origins = {
2639
+ [ObjectRelativeFromH.PAGE]: isPageRelative ? 0 : pageMarginLeft - (skeDrawing.pageAnchorLeft ?? 0),
2640
+ [ObjectRelativeFromH.MARGIN]: pageMarginLeft + page.marginLeft - (skeDrawing.pageAnchorLeft ?? 0),
2641
+ [ObjectRelativeFromH.COLUMN]: pageMarginLeft + getColumnOrigin(anchor, relativeFromV)
2642
+ };
2643
+ result.positionH = {
2644
+ relativeFrom: relativeFromH,
2645
+ posOffset: left + ((offset === null || offset === void 0 ? void 0 : offset.left) ?? 0) - (origins[relativeFromH] ?? pageMarginLeft)
2526
2646
  };
2527
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2528
- return JSONX.compose(acc, cur);
2529
- }, null);
2530
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2531
- const skeleton = renderObject.with(DocSkeletonManagerService).getSkeleton();
2532
- accessor.get(DocRefreshDrawingsService).refreshDrawings(skeleton);
2533
- transformer.refreshControls();
2534
- return Boolean(result);
2535
- }
2536
- };
2537
-
2538
- //#endregion
2539
- //#region src/controllers/render-controllers/doc-drawing-transform-update.controller.ts
2540
- function mergePublishedDrawing(drawings, next) {
2541
- const current = drawings[next.drawingId];
2542
- if (current == null) {
2543
- drawings[next.drawingId] = next;
2544
- return;
2545
2647
  }
2546
- if (next.selectable && !current.selectable) {
2547
- current.selectable = true;
2548
- current.transform = next.transform;
2648
+ if ((offset === null || offset === void 0 ? void 0 : offset.top) || wasInline || relativeFromV !== positionV.relativeFrom || positionV.relativeFrom === ObjectRelativeFromV.PAGE && wasPageRelative !== isPageRelative) {
2649
+ const top = (wasPageRelative ? getDocsPageRelativeDrawingTop({
2650
+ hostPage: anchorPage,
2651
+ positionV,
2652
+ height
2653
+ }) : void 0) ?? aTop + pageMarginTop;
2654
+ const origins = {
2655
+ [ObjectRelativeFromV.PAGE]: isPageRelative ? 0 : pageMarginTop - page.marginTop,
2656
+ [ObjectRelativeFromV.LINE]: pageMarginTop + skeDrawing.lineTop,
2657
+ [ObjectRelativeFromV.PARAGRAPH]: pageMarginTop + (skeDrawing.isPageBreak ? 0 : skeDrawing.blockAnchorTop)
2658
+ };
2659
+ result.positionV = {
2660
+ relativeFrom: relativeFromV,
2661
+ posOffset: top + ((offset === null || offset === void 0 ? void 0 : offset.top) ?? 0) - (origins[relativeFromV] ?? pageMarginTop)
2662
+ };
2549
2663
  }
2550
- if (next.isMultiTransform === BooleanNumber.TRUE) current.transforms.push(next.transform);
2664
+ return result;
2551
2665
  }
2552
- function isSameTransformValue(left, right) {
2553
- return left === right || JSON.stringify(left) === JSON.stringify(right);
2554
- }
2555
- function shouldRefreshDocDrawingTransform(current, next) {
2556
- if (!current || next.customBlockRenderViewport != null) return true;
2557
- return !isSameTransformValue(current.transform, next.transform) || !isSameTransformValue(current.transforms, next.transforms) || current.isMultiTransform !== next.isMultiTransform || current.hidden !== next.hidden || current.behindText !== next.behindText || current.selectable !== next.selectable;
2558
- }
2559
- /**
2560
- * Overlay drawings do not participate in text layout. While their skeleton
2561
- * anchor remains valid, use the latest model transform so drag/resize/front-
2562
- * behind changes can paint immediately without rebuilding document pages.
2563
- */
2564
- function getDocsOverlayRuntimeDrawing(skeletonDrawing, currentDrawing, measuredSize) {
2565
- if (skeletonDrawing.layoutType === PositionedObjectLayoutType.WRAP_NONE && (currentDrawing === null || currentDrawing === void 0 ? void 0 : currentDrawing.layoutType) === PositionedObjectLayoutType.WRAP_NONE) return currentDrawing;
2566
- return measuredSize ? {
2567
- ...skeletonDrawing,
2568
- docTransform: {
2569
- ...skeletonDrawing.docTransform,
2570
- size: measuredSize
2571
- }
2572
- } : skeletonDrawing;
2573
- }
2574
- var DocDrawingPublicationTracker = class {
2575
- constructor() {
2576
- _defineProperty(this, "_generation", -1);
2577
- _defineProperty(this, "_publishedPageCount", 0);
2578
- _defineProperty(this, "_drawingOccurrenceCount", 0);
2579
- }
2580
- reset() {
2581
- this._generation = -1;
2582
- this._publishedPageCount = 0;
2583
- this._drawingOccurrenceCount = 0;
2584
- }
2585
- shouldRefresh(skeleton, progress) {
2586
- if (!progress.didPublish && !progress.complete) return false;
2587
- const isNewGeneration = progress.generation !== this._generation;
2588
- if (isNewGeneration) {
2589
- this._generation = progress.generation;
2590
- this._publishedPageCount = 0;
2591
- this._drawingOccurrenceCount = 0;
2592
- }
2593
- const skeletonData = skeleton.getSkeletonData();
2594
- if (skeletonData == null) return false;
2595
- const previousPublishedPageCount = this._publishedPageCount;
2596
- const publishedPageCount = Math.min(progress.publishedPageCount, skeletonData.pages.length);
2597
- this._publishedPageCount = Math.max(previousPublishedPageCount, publishedPageCount);
2598
- const drawingOccurrenceCount = countPublishedDrawingOccurrences(skeletonData, publishedPageCount);
2599
- const didDrawingOccurrencesChange = !(isNewGeneration && progress.reason === "edit") && drawingOccurrenceCount !== this._drawingOccurrenceCount;
2600
- this._drawingOccurrenceCount = drawingOccurrenceCount;
2601
- if (progress.complete || progress.didPublishAnchor || didDrawingOccurrencesChange) return true;
2602
- if (isNewGeneration && progress.reason === "edit") return false;
2603
- return hasNewPublishedPageDrawings(skeletonData, previousPublishedPageCount, publishedPageCount);
2604
- }
2605
- };
2606
- function getDocsDrawingPageClipBounds(config) {
2607
- const { docsLeft, docsTop, pageOffsetLeft, pageOffsetTop, clipOffsetLeft = 0, clipOffsetTop = 0, page } = config;
2608
- if (page.type === DocumentSkeletonPageType.CELL && config.drawingLayoutType === PositionedObjectLayoutType.WRAP_NONE && config.overflowClipBounds != null) return config.overflowClipBounds;
2609
- const { pageWidth, pageHeight } = page;
2610
- if (!Number.isFinite(pageWidth) || !Number.isFinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) return;
2611
- const cellInsetLeft = page.type === DocumentSkeletonPageType.CELL ? page.marginLeft ?? 0 : 0;
2612
- const cellInsetTop = page.type === DocumentSkeletonPageType.CELL ? page.marginTop ?? 0 : 0;
2613
- return {
2614
- left: docsLeft + pageOffsetLeft + clipOffsetLeft - cellInsetLeft,
2615
- top: docsTop + pageOffsetTop + clipOffsetTop - cellInsetTop,
2616
- width: pageWidth,
2617
- height: pageHeight
2618
- };
2619
- }
2620
- function getDocsDrawingClipPage(config) {
2621
- const { drawing, hostPage, page } = config;
2622
- if (hostPage && (page.type === DocumentSkeletonPageType.HEADER || page.type === DocumentSkeletonPageType.FOOTER)) return hostPage;
2623
- if (hostPage == null || drawing.behindText !== true || drawing.transform == null) return page;
2624
- const { width, height } = drawing.transform;
2625
- if (width == null || height == null) return page;
2626
- if (width > page.pageWidth || height > page.pageHeight) return hostPage;
2627
- const widthRatio = width / hostPage.pageWidth;
2628
- const heightRatio = height / hostPage.pageHeight;
2629
- if (widthRatio >= .8 && heightRatio >= .8) return hostPage;
2630
- return page;
2631
- }
2632
- function getDocsPageRelativeDrawingLeft(config) {
2633
- const { hostPage, positionH, width } = config;
2634
- if (positionH.relativeFrom !== ObjectRelativeFromH.PAGE) return;
2635
- if (positionH.align === AlignTypeH.RIGHT) return hostPage.pageWidth - width;
2636
- if (positionH.align === AlignTypeH.CENTER) return hostPage.pageWidth / 2 - width / 2;
2637
- if (positionH.posOffset != null) return positionH.posOffset;
2638
- return 0;
2639
- }
2640
- function getDocsPageRelativeDrawingTop(config) {
2641
- const { hostPage, positionV, height } = config;
2642
- if (positionV.relativeFrom !== ObjectRelativeFromV.PAGE) return;
2643
- if (positionV.align === AlignTypeV.BOTTOM) return hostPage.pageHeight - height;
2644
- if (positionV.align === AlignTypeV.CENTER) return hostPage.pageHeight / 2 - height / 2;
2645
- if (positionV.posOffset != null) return positionV.posOffset;
2646
- return 0;
2647
- }
2648
- function getDocsPageRelativeDrawingAnchorPage(config) {
2649
- const { page, clipPage, hostPage } = config;
2650
- if (config.drawingLayoutType === PositionedObjectLayoutType.INLINE) return;
2651
- if (hostPage != null && hostPage === clipPage) return hostPage;
2652
- if (hostPage == null && page === clipPage && page.type !== DocumentSkeletonPageType.CELL) return page;
2653
- }
2654
- function getDocsDrawingBehindText(config) {
2655
- const { drawingOrigin, hostPage } = config;
2656
- if (hostPage != null) return true;
2657
- return drawingOrigin.layoutType === PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === BooleanNumber.TRUE;
2658
- }
2659
- function getDocsTableCellDrawingOffset(unitId, table, row, cell) {
2660
- const sourceTableId = getTableIdAndSliceIndex(table.tableId).tableId;
2661
- const viewport = getDocsTableRenderViewport(unitId, sourceTableId);
2662
- const scrollLeft = hasHorizontalTableViewport(viewport) ? viewport.scrollLeft : 0;
2663
- return {
2664
- left: table.left + cell.left - scrollLeft + cell.marginLeft,
2665
- top: table.top + row.top + cell.marginTop
2666
- };
2667
- }
2668
- function hasHorizontalTableViewport(viewport) {
2669
- return viewport != null && (viewport.leadingInsetLeft ?? 0) + viewport.contentWidth + (viewport.trailingInsetRight ?? 0) > viewport.viewportWidth;
2670
- }
2671
- function hasSkeletonPageDrawings(page) {
2672
- var _page$notes, _page$skeTables, _page$skeColumnGroups;
2673
- if (page.skeDrawings.size > 0 || ((_page$notes = page.notes) === null || _page$notes === void 0 ? void 0 : _page$notes.some((note) => hasSkeletonPageDrawings(note.page)))) return true;
2674
- let hasDrawings = false;
2675
- (_page$skeTables = page.skeTables) === null || _page$skeTables === void 0 || _page$skeTables.forEach((table) => {
2676
- table.rows.forEach((row) => {
2677
- row.cells.forEach((cell) => {
2678
- if (hasSkeletonPageDrawings(cell)) hasDrawings = true;
2679
- });
2680
- });
2681
- });
2682
- (_page$skeColumnGroups = page.skeColumnGroups) === null || _page$skeColumnGroups === void 0 || _page$skeColumnGroups.forEach((columnGroup) => {
2683
- columnGroup.columns.forEach((column) => {
2684
- if (hasSkeletonPageDrawings(column.page)) hasDrawings = true;
2685
- });
2686
- });
2687
- return hasDrawings;
2688
- }
2689
- function countSkeletonPageDrawings(page) {
2690
- var _page$notes2, _page$skeTables2, _page$skeColumnGroups2;
2691
- let count = page.skeDrawings.size;
2692
- (_page$notes2 = page.notes) === null || _page$notes2 === void 0 || _page$notes2.forEach((note) => {
2693
- count += countSkeletonPageDrawings(note.page);
2694
- });
2695
- (_page$skeTables2 = page.skeTables) === null || _page$skeTables2 === void 0 || _page$skeTables2.forEach((table) => {
2696
- table.rows.forEach((row) => {
2697
- row.cells.forEach((cell) => {
2698
- count += countSkeletonPageDrawings(cell);
2699
- });
2666
+
2667
+ //#endregion
2668
+ //#region src/controllers/doc-drawing-notification.controller.ts
2669
+ function getAddOrRemoveDrawings(actions) {
2670
+ if (JSONX.isNoop(actions)) return null;
2671
+ const drawings = [];
2672
+ const cursor = JSON1.type.readCursor(actions);
2673
+ cursor.traverse(null, () => {
2674
+ const path = cursor.getPath();
2675
+ if (path.length !== 2 || path[0] !== "drawings" || typeof path[1] !== "string") return;
2676
+ const component = cursor.getComponent();
2677
+ if ((component === null || component === void 0 ? void 0 : component.r) !== void 0) drawings.push({
2678
+ type: "remove",
2679
+ drawingId: path[1]
2700
2680
  });
2701
- });
2702
- (_page$skeColumnGroups2 = page.skeColumnGroups) === null || _page$skeColumnGroups2 === void 0 || _page$skeColumnGroups2.forEach((columnGroup) => {
2703
- columnGroup.columns.forEach((column) => {
2704
- count += countSkeletonPageDrawings(column.page);
2681
+ if ((component === null || component === void 0 ? void 0 : component.i) !== void 0) drawings.push({
2682
+ type: "add",
2683
+ drawingId: path[1],
2684
+ drawing: component.i
2705
2685
  });
2706
2686
  });
2707
- return count;
2687
+ return drawings.length ? drawings : null;
2708
2688
  }
2709
- function countPublishedDrawingOccurrences(skeletonData, publishedPageCount) {
2710
- let count = 0;
2711
- for (let index = 0; index < publishedPageCount; index++) {
2712
- var _skeletonData$skeHead, _skeletonData$skeFoot;
2713
- const page = skeletonData.pages[index];
2714
- count += countSkeletonPageDrawings(page);
2715
- const header = page.headerId == null ? void 0 : (_skeletonData$skeHead = skeletonData.skeHeaders.get(page.headerId)) === null || _skeletonData$skeHead === void 0 ? void 0 : _skeletonData$skeHead.get(page.headerLayoutKey ?? page.pageWidth);
2716
- if (header != null) count += countSkeletonPageDrawings(header);
2717
- const footer = page.footerId == null ? void 0 : (_skeletonData$skeFoot = skeletonData.skeFooters.get(page.footerId)) === null || _skeletonData$skeFoot === void 0 ? void 0 : _skeletonData$skeFoot.get(page.footerLayoutKey ?? page.pageWidth);
2718
- if (footer != null) count += countSkeletonPageDrawings(footer);
2689
+ function getReOrderedDrawings(actions) {
2690
+ if (!Array.isArray(actions) || actions.length < 3 || actions[0] !== "drawingsOrder") return [];
2691
+ const drawingIndexes = [];
2692
+ for (let i = 1; i < actions.length; i++) {
2693
+ const action = actions[i];
2694
+ if (Array.isArray(action) && typeof action[0] === "number" && typeof action[1] === "object") drawingIndexes.push(action[0]);
2695
+ else {
2696
+ drawingIndexes.length = 0;
2697
+ break;
2698
+ }
2719
2699
  }
2720
- return count;
2700
+ return drawingIndexes;
2721
2701
  }
2722
- function hasNewPublishedPageDrawings(skeletonData, startPageIndex, publishedPageCount) {
2723
- for (let index = startPageIndex; index < publishedPageCount; index++) {
2724
- var _skeletonData$skeHead2, _skeletonData$skeFoot2;
2725
- const page = skeletonData.pages[index];
2726
- if (hasSkeletonPageDrawings(page)) return true;
2727
- const header = page.headerId == null ? void 0 : (_skeletonData$skeHead2 = skeletonData.skeHeaders.get(page.headerId)) === null || _skeletonData$skeHead2 === void 0 ? void 0 : _skeletonData$skeHead2.get(page.headerLayoutKey ?? page.pageWidth);
2728
- if (header != null && hasSkeletonPageDrawings(header)) return true;
2729
- const footer = page.footerId == null ? void 0 : (_skeletonData$skeFoot2 = skeletonData.skeFooters.get(page.footerId)) === null || _skeletonData$skeFoot2 === void 0 ? void 0 : _skeletonData$skeFoot2.get(page.footerLayoutKey ?? page.pageWidth);
2730
- if (footer != null && hasSkeletonPageDrawings(footer)) return true;
2702
+ function collectUpdatedDrawingIds(actions, drawingIds = /* @__PURE__ */ new Set()) {
2703
+ if (JSONX.isNoop(actions) || !Array.isArray(actions)) return drawingIds;
2704
+ if (actions[0] === "drawings") {
2705
+ const drawingKeyOrOps = actions[1];
2706
+ if (typeof drawingKeyOrOps === "string") {
2707
+ drawingIds.add(drawingKeyOrOps);
2708
+ return drawingIds;
2709
+ }
2710
+ actions.slice(1).forEach((action) => {
2711
+ if (Array.isArray(action) && typeof action[0] === "string") drawingIds.add(action[0]);
2712
+ });
2713
+ return drawingIds;
2731
2714
  }
2732
- return false;
2715
+ actions.forEach((action) => {
2716
+ if (Array.isArray(action)) collectUpdatedDrawingIds(action, drawingIds);
2717
+ });
2718
+ return drawingIds;
2733
2719
  }
2734
- let DocDrawingTransformUpdateController = class DocDrawingTransformUpdateController extends Disposable {
2735
- constructor(_context, _docSkeletonManagerService, _commandService, _editorService, _drawingManagerService, _docRefreshDrawingsService, _univerInstanceService, _lifecycleService) {
2720
+ let DocDrawingAddRemoveController = class DocDrawingAddRemoveController extends Disposable {
2721
+ constructor(_univerInstanceService, _commandService, _drawingManagerService, _docDrawingService, _renderManagerService, _docRefreshDrawingsService) {
2736
2722
  super();
2737
- this._context = _context;
2738
- this._docSkeletonManagerService = _docSkeletonManagerService;
2723
+ this._univerInstanceService = _univerInstanceService;
2739
2724
  this._commandService = _commandService;
2740
- this._editorService = _editorService;
2741
2725
  this._drawingManagerService = _drawingManagerService;
2726
+ this._docDrawingService = _docDrawingService;
2727
+ this._renderManagerService = _renderManagerService;
2742
2728
  this._docRefreshDrawingsService = _docRefreshDrawingsService;
2743
- this._univerInstanceService = _univerInstanceService;
2744
- this._lifecycleService = _lifecycleService;
2745
- _defineProperty(this, "_liquid", new Liquid());
2746
- _defineProperty(this, "_changesetDrawingRefreshScheduled", false);
2747
- _defineProperty(this, "_publicationTracker", new DocDrawingPublicationTracker());
2748
2729
  this._initialize();
2749
- this._commandExecutedListener();
2750
2730
  }
2751
2731
  _initialize() {
2752
- this._initialRenderRefresh();
2753
- this._drawingInitializeListener();
2754
- this._initTransformRefresh();
2732
+ this._commandExecutedListener();
2755
2733
  }
2756
- _initialRenderRefresh() {
2757
- this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.pipe(switchMap((documentSkeleton) => {
2758
- this._publicationTracker.reset();
2759
- if (documentSkeleton == null) return EMPTY;
2760
- this._refreshDrawing(documentSkeleton);
2761
- const positionRefresh$ = animationFrames().pipe(startWith(null), map(() => this._context.mainComponent), filter((documentComponent) => documentComponent instanceof Documents && documentComponent.left > -1e4 && documentComponent.top > -1e4), take(1), switchMap((documentComponent) => fromEventSubject(documentComponent.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.translate && "left" in evt.value && "left" in evt.preValue && (evt.value.left !== evt.preValue.left || evt.value.top !== evt.preValue.top)), map(() => ({
2762
- documentSkeleton,
2763
- progress: null
2764
- })), startWith({
2765
- documentSkeleton,
2766
- progress: null
2767
- }))));
2768
- return merge$1(documentSkeleton.layoutProgress$.pipe(map((progress) => ({
2769
- documentSkeleton,
2770
- progress
2771
- }))), documentSkeleton.layoutPageMaterialized$.pipe(map(() => ({
2772
- documentSkeleton,
2773
- progress: null
2774
- }))), positionRefresh$);
2775
- })).subscribe(({ documentSkeleton, progress }) => {
2776
- if (progress == null || this._publicationTracker.shouldRefresh(documentSkeleton, progress)) this._refreshDrawing(documentSkeleton);
2734
+ _commandExecutedListener() {
2735
+ this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
2736
+ if (command.id !== RichTextEditingMutation.id) return;
2737
+ const { unitId, actions, isSync, syncer } = command.params;
2738
+ const addOrRemoveDrawings = getAddOrRemoveDrawings(actions);
2739
+ if (addOrRemoveDrawings != null) for (const { type, drawingId, drawing } of addOrRemoveDrawings) {
2740
+ if (isSync && (drawing === null || drawing === void 0 ? void 0 : drawing.unitId) === syncer) continue;
2741
+ if (type === "add") this._addDrawings(unitId, [drawing]);
2742
+ else this._removeDrawings(unitId, [drawingId]);
2743
+ }
2777
2744
  }));
2778
- this.disposeWithMe(this._docRefreshDrawingsService.refreshDrawings$.subscribe((skeleton) => {
2779
- if (skeleton == null) return;
2780
- this._refreshDrawing(skeleton);
2745
+ this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
2746
+ if (command.id !== UpdateDocDrawingWrappingStyleCommand.id) return;
2747
+ this._preserveWrappingStylePosition(command.params);
2781
2748
  }));
2782
- }
2783
- _commandExecutedListener() {
2784
- const updateCommandList = [RichTextEditingMutation.id, SetDocZoomRatioOperation.id];
2785
- this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
2786
- if (updateCommandList.includes(command.id)) {
2787
- const params = command.params;
2788
- const { unitId: commandUnitId } = params;
2789
- const { unitId } = this._context;
2790
- if (commandUnitId !== unitId) return;
2791
- const drawingIds = command.id === RichTextEditingMutation.id ? getDocMutationAffectedDrawingIds(params.actions) : null;
2792
- if ((drawingIds === null || drawingIds === void 0 ? void 0 : drawingIds.size) === 0) return;
2793
- if (command.id === RichTextEditingMutation.id && (options === null || options === void 0 ? void 0 : options.fromChangeset)) {
2794
- this._scheduleChangesetDrawingRefresh();
2795
- return;
2796
- }
2797
- this._refreshCurrentDrawing(drawingIds ?? void 0);
2749
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
2750
+ if (command.id !== RichTextEditingMutation.id) return;
2751
+ const { unitId, actions } = command.params;
2752
+ let changedNotes = false;
2753
+ if (!JSONX.isNoop(actions)) {
2754
+ const cursor = JSON1.type.readCursor(actions);
2755
+ cursor.traverse(null, () => {
2756
+ changedNotes ||= cursor.getPath()[0] === "notes";
2757
+ });
2798
2758
  }
2759
+ if (changedNotes) this._syncNoteDrawings(unitId);
2760
+ if (getReOrderedDrawings(actions).length > 0) this._updateDrawingsOrder(unitId);
2761
+ const updatedDrawingIds = [...collectUpdatedDrawingIds(actions)];
2762
+ if (updatedDrawingIds.length > 0) this._syncDrawingDataFromSnapshot(unitId, updatedDrawingIds);
2763
+ }));
2764
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
2765
+ if (command.id !== UpdateDrawingDocTransformCommand.id && command.id !== UpdateDocDrawingWrappingStyleCommand.id) return;
2766
+ const { unitId } = command.params;
2767
+ const renderObject = this._renderManagerService.getRenderUnitById(unitId);
2768
+ const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
2769
+ if (renderObject == null || scene == null) return;
2770
+ if (command.id === UpdateDocDrawingWrappingStyleCommand.id) this._docRefreshDrawingsService.refreshDrawings(renderObject.with(DocSkeletonManagerService).getSkeleton());
2771
+ scene.getTransformerByCreate().refreshControls();
2772
+ }));
2773
+ this.disposeWithMe(this._commandService.onCommandExecuted((command) => {
2774
+ var _this$_univerInstance;
2775
+ if (command.id !== UndoCommand.id && command.id !== RedoCommand.id) return;
2776
+ const unitId = (_this$_univerInstance = this._univerInstanceService.getCurrentUnitOfType(UniverInstanceType.UNIVER_DOC)) === null || _this$_univerInstance === void 0 ? void 0 : _this$_univerInstance.getUnitId();
2777
+ const focusedDrawings = this._drawingManagerService.getFocusDrawings();
2778
+ if (unitId == null || focusedDrawings.length === 0) return;
2779
+ const renderObject = this._renderManagerService.getRenderUnitById(unitId);
2780
+ const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
2781
+ if (renderObject == null || scene == null) return false;
2782
+ this._docRefreshDrawingsService.refreshDrawings(renderObject.with(DocSkeletonManagerService).getSkeleton());
2783
+ scene.getTransformerByCreate().refreshControls();
2799
2784
  }));
2800
2785
  }
2801
- _scheduleChangesetDrawingRefresh() {
2802
- if (this._changesetDrawingRefreshScheduled) return;
2803
- this._changesetDrawingRefreshScheduled = true;
2804
- queueMicrotask(() => {
2805
- queueMicrotask(() => {
2806
- this._changesetDrawingRefreshScheduled = false;
2807
- if (this._disposed) return;
2808
- this._refreshCurrentDrawing();
2809
- });
2786
+ _preserveWrappingStylePosition(params) {
2787
+ if (params.wrappingStyle === TextWrappingStyle.INLINE) return;
2788
+ const { unitId } = params;
2789
+ const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2790
+ const renderObject = this._renderManagerService.getRenderUnitById(unitId);
2791
+ const skeletonManager = renderObject === null || renderObject === void 0 ? void 0 : renderObject.with(DocSkeletonManagerService);
2792
+ const skeletonData = skeletonManager === null || skeletonManager === void 0 ? void 0 : skeletonManager.getSkeleton().getSkeletonData();
2793
+ const viewModel = skeletonManager === null || skeletonManager === void 0 ? void 0 : skeletonManager.getViewModel();
2794
+ if (!documentDataModel || !skeletonData || !viewModel) return;
2795
+ const editArea = viewModel.getEditArea();
2796
+ const oldDrawings = collectDocDrawings(documentDataModel.getSnapshot()).drawings;
2797
+ params.drawings = params.drawings.map((drawing) => {
2798
+ const oldDrawing = oldDrawings[drawing.drawingId];
2799
+ if (!oldDrawing) return drawing;
2800
+ const drawingAnchor = findDrawingAnchor(unitId, drawing.drawingId, skeletonData, editArea, oldDrawing);
2801
+ if (!drawingAnchor) return drawing;
2802
+ const docTransform = getDrawingWrappingPosition(drawingAnchor, WRAPPING_STYLE_TO_LAYOUT_TYPE[params.wrappingStyle]);
2803
+ for (const key of ["positionH", "positionV"]) {
2804
+ var _drawing$docTransform;
2805
+ const requested = (_drawing$docTransform = drawing.docTransform) === null || _drawing$docTransform === void 0 ? void 0 : _drawing$docTransform[key];
2806
+ if (requested && !Tools.diffValue(requested, oldDrawing.docTransform[key])) Object.assign(docTransform, { [key]: requested });
2807
+ }
2808
+ return {
2809
+ ...oldDrawing,
2810
+ ...drawing,
2811
+ docTransform: {
2812
+ ...docTransform,
2813
+ ...drawing.docTransform,
2814
+ positionH: docTransform.positionH,
2815
+ positionV: docTransform.positionV
2816
+ }
2817
+ };
2810
2818
  });
2811
2819
  }
2812
- _refreshCurrentDrawing(drawingIds) {
2813
- const skeleton = this._docSkeletonManagerService.getSkeleton();
2814
- if (skeleton == null) return;
2815
- const { unitId, mainComponent } = this._context;
2816
- if (this._editorService.isEditor(unitId)) {
2817
- mainComponent === null || mainComponent === void 0 || mainComponent.makeDirty();
2818
- return;
2819
- }
2820
- this._refreshDrawing(skeleton, drawingIds);
2821
- }
2822
- _initTransformRefresh() {
2823
- this.disposeWithMe(merge$1(fromEventSubject(this._context.engine.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.resize)), fromEventSubject(this._context.scene.onTransformChange$).pipe(filter((evt) => evt.type === TRANSFORM_CHANGE_OBSERVABLE_TYPE.scale))).pipe(debounceTime(16)).subscribe(() => {
2824
- var _scene$getTransformer;
2825
- const skeleton = this._docSkeletonManagerService.getSkeleton();
2826
- const { scene } = this._context;
2827
- (_scene$getTransformer = scene.getTransformer()) === null || _scene$getTransformer === void 0 || _scene$getTransformer.refreshControls();
2828
- this._refreshDrawing(skeleton);
2829
- }));
2820
+ _addDrawings(unitId, drawings) {
2821
+ const drawingManagerService = this._drawingManagerService;
2822
+ const docDrawingService = this._docDrawingService;
2823
+ const { subUnitId, redo: op, objects } = this._docDrawingService.getBatchAddOp(drawings.map((drawing) => ({
2824
+ ...drawing,
2825
+ unitId,
2826
+ subUnitId: unitId
2827
+ })));
2828
+ drawingManagerService.applyJson1(unitId, subUnitId, op);
2829
+ docDrawingService.applyJson1(unitId, subUnitId, op);
2830
+ drawingManagerService.addNotification(objects);
2831
+ docDrawingService.addNotification(objects);
2830
2832
  }
2831
- _refreshDrawing(skeleton, drawingIds) {
2832
- const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
2833
- const { mainComponent, unitId } = this._context;
2834
- const documentComponent = mainComponent;
2835
- if (!skeletonData) return;
2836
- const { left: docsLeft, top: docsTop, pageLayoutType, pageMarginLeft, pageMarginTop } = documentComponent;
2837
- if (docsLeft <= -1e4 || docsTop <= -1e4) return;
2838
- const { pages, skeHeaders, skeFooters } = skeletonData;
2839
- const updateDrawingMap = {};
2840
- this._liquid.reset();
2841
- /**
2842
- * TODO: @DR-Univer We should not refresh all floating elements, but instead make a diff.
2843
- */
2844
- for (let i = 0, len = pages.length; i < len; i++) {
2845
- const page = pages[i];
2846
- this._collectPublishedPageDrawingPositions(unitId, page, skeHeaders, skeFooters, docsLeft, docsTop, updateDrawingMap);
2847
- this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
2848
- }
2849
- const affectedDrawingIds = this._includeGroupChildren(drawingIds);
2850
- const updateDrawings = Object.values(updateDrawingMap).filter((drawing) => affectedDrawingIds == null || affectedDrawingIds.has(drawing.drawingId));
2851
- for (const drawing of updateDrawings) drawing.hidden = false;
2852
- const staleNonMultiDrawings = this._getStaleNonMultiDrawings(unitId, updateDrawingMap, affectedDrawingIds);
2853
- const nonMultiDrawings = updateDrawings.filter((drawing) => !drawing.isMultiTransform).concat(staleNonMultiDrawings).filter((drawing) => shouldRefreshDocDrawingTransform(this._drawingManagerService.getDrawingByParam({
2833
+ _removeDrawings(unitId, drawingIds) {
2834
+ const drawingManagerService = this._drawingManagerService;
2835
+ const docDrawingService = this._docDrawingService;
2836
+ const existingDrawingIds = drawingIds.filter((drawingId) => docDrawingService.getDrawingByParam({
2854
2837
  unitId,
2855
2838
  subUnitId: unitId,
2856
- drawingId: drawing.drawingId
2857
- }), drawing));
2858
- if (nonMultiDrawings.length > 0) this._drawingManagerService.refreshTransform(nonMultiDrawings);
2859
- const targetedMultiDrawing = affectedDrawingIds != null && [...affectedDrawingIds].some((drawingId) => {
2860
- var _updateDrawingMap$dra, _this$_drawingManager;
2861
- return ((_updateDrawingMap$dra = updateDrawingMap[drawingId]) === null || _updateDrawingMap$dra === void 0 ? void 0 : _updateDrawingMap$dra.isMultiTransform) === BooleanNumber.TRUE || ((_this$_drawingManager = this._drawingManagerService.getDrawingByParam({
2839
+ drawingId
2840
+ }));
2841
+ if (existingDrawingIds.length === 0) return;
2842
+ const { subUnitId, redo: op, objects } = this._docDrawingService.getBatchRemoveOp(existingDrawingIds.map((drawingId) => {
2843
+ return {
2862
2844
  unitId,
2863
2845
  subUnitId: unitId,
2864
2846
  drawingId
2865
- })) === null || _this$_drawingManager === void 0 ? void 0 : _this$_drawingManager.isMultiTransform) === BooleanNumber.TRUE;
2866
- });
2867
- if (affectedDrawingIds == null || targetedMultiDrawing) {
2868
- const allMultiDrawings = Object.values(updateDrawingMap).filter((drawing) => drawing.isMultiTransform);
2869
- this._handleMultiDrawingsTransform(allMultiDrawings);
2870
- }
2871
- }
2872
- _includeGroupChildren(drawingIds) {
2873
- if (drawingIds == null) return;
2874
- const affected = new Set(drawingIds);
2875
- const { drawings } = collectDocDrawings(this._context.unit.getSnapshot());
2876
- let previousSize = -1;
2877
- while (previousSize !== affected.size) {
2878
- previousSize = affected.size;
2879
- for (const drawing of Object.values(drawings)) if (drawing.groupId && affected.has(drawing.groupId)) affected.add(drawing.drawingId);
2880
- }
2881
- return affected;
2882
- }
2883
- _collectPublishedPageDrawingPositions(unitId, page, skeHeaders, skeFooters, docsLeft, docsTop, updateDrawingMap) {
2884
- var _skeHeaders$get, _skeFooters$get;
2885
- const selectable = !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder;
2886
- const { headerId, footerId, pageWidth } = page;
2887
- const headerPage = headerId ? (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(page.headerLayoutKey ?? pageWidth) : void 0;
2888
- if (headerPage != null) this._collectSegmentDrawingPositions(unitId, headerPage, docsLeft, docsTop, updateDrawingMap, headerPage.marginTop, page.marginLeft, page, selectable);
2889
- const footerPage = footerId ? (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(page.footerLayoutKey ?? pageWidth) : void 0;
2890
- if (footerPage != null) {
2891
- const footerTop = page.pageHeight - footerPage.height - footerPage.marginBottom;
2892
- this._collectSegmentDrawingPositions(unitId, footerPage, docsLeft, docsTop, updateDrawingMap, footerTop, page.marginLeft, page, selectable);
2893
- }
2894
- this._collectSegmentDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft, void 0, selectable);
2895
- for (const note of page.notes ?? []) this._collectSegmentDrawingPositions(unitId, note.page, docsLeft, docsTop, updateDrawingMap, note.top, note.left, void 0, selectable, {
2896
- top: note.top,
2897
- left: note.left
2898
- });
2899
- }
2900
- _collectSegmentDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable, clipOffset) {
2901
- const overflowClipBounds = getDocsDrawingPageClipBounds({
2902
- docsLeft,
2903
- docsTop,
2904
- pageOffsetLeft: this._liquid.x,
2905
- pageOffsetTop: this._liquid.y,
2906
- page: hostPage ?? page
2907
- });
2908
- this._calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable, clipOffset, overflowClipBounds);
2909
- this._calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2910
- this._calculateColumnGroupDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2847
+ };
2848
+ }));
2849
+ drawingManagerService.applyJson1(unitId, subUnitId, op);
2850
+ docDrawingService.applyJson1(unitId, subUnitId, op);
2851
+ drawingManagerService.removeNotification(objects);
2852
+ docDrawingService.removeNotification(objects);
2911
2853
  }
2912
- _getStaleNonMultiDrawings(unitId, updateDrawingMap, drawingIds) {
2913
- const drawingData = this._drawingManagerService.getDrawingData(unitId, unitId) ?? {};
2914
- return Object.values(drawingData).filter((drawing) => drawing.isMultiTransform !== BooleanNumber.TRUE).filter((drawing) => drawingIds == null || drawingIds.has(drawing.drawingId)).filter((drawing) => updateDrawingMap[drawing.drawingId] == null).map((drawing) => ({
2854
+ _updateDrawingsOrder(unitId) {
2855
+ const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2856
+ if (documentDataModel == null) return;
2857
+ const { drawings, drawingsOrder } = collectDocDrawings(documentDataModel.getSnapshot());
2858
+ if (drawingsOrder == null) return;
2859
+ const renderOrder = getDocDrawingRenderOrder(drawingsOrder, drawings);
2860
+ const drawingManagerService = this._drawingManagerService;
2861
+ const docDrawingService = this._docDrawingService;
2862
+ drawingManagerService.setDrawingOrder(unitId, unitId, renderOrder);
2863
+ docDrawingService.setDrawingOrder(unitId, unitId, drawingsOrder);
2864
+ const objects = {
2915
2865
  unitId,
2916
2866
  subUnitId: unitId,
2917
- drawingId: drawing.drawingId,
2918
- behindText: false,
2919
- hidden: true,
2920
- selectable: true,
2921
- transform: drawing.transform,
2922
- transforms: drawing.transforms ?? [],
2923
- isMultiTransform: drawing.isMultiTransform ?? BooleanNumber.FALSE
2924
- }));
2925
- }
2926
- _handleMultiDrawingsTransform(multiDrawings) {
2927
- const { scene, unitId } = this._context;
2928
- const transformer = scene.getTransformerByCreate();
2929
- multiDrawings.forEach((updateParam) => {
2930
- const param = this._drawingManagerService.getDrawingByParam(updateParam);
2931
- if (param == null) return;
2932
- Object.assign(param, updateParam);
2867
+ drawingIds: renderOrder
2868
+ };
2869
+ drawingManagerService.orderNotification(objects);
2870
+ docDrawingService.orderNotification({
2871
+ unitId,
2872
+ subUnitId: unitId,
2873
+ drawingIds: drawingsOrder
2933
2874
  });
2934
- const selectedObjectKeys = [...transformer.getSelectedObjectMap().keys()];
2935
- const allMultiDrawings = Object.values(this._drawingManagerService.getDrawingData(unitId, unitId)).filter((drawing) => drawing.isMultiTransform === BooleanNumber.TRUE);
2936
- this._drawingManagerService.removeNotification(allMultiDrawings);
2937
- if (multiDrawings.length > 0) this._drawingManagerService.addNotification(multiDrawings);
2938
- for (const key of selectedObjectKeys) {
2939
- const drawingShape = scene.getObject(key);
2940
- if (drawingShape) transformer.setSelectedControl(drawingShape);
2941
- }
2942
2875
  }
2943
- _calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable = true, clipOffset, overflowClipBounds) {
2944
- const { skeDrawings } = page;
2945
- const pageOffsetLeft = this._liquid.x;
2946
- const pageOffsetTop = this._liquid.y;
2947
- this._liquid.translatePagePadding({
2948
- marginTop,
2949
- marginLeft
2950
- });
2951
- const drawingPositionContext = {
2876
+ _syncNoteDrawings(unitId) {
2877
+ const model = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2878
+ if (!model) return;
2879
+ const { drawings } = collectDocDrawings(model.getSnapshot());
2880
+ const previous = this._docDrawingService.getDrawingData(unitId, unitId) ?? {};
2881
+ const added = Object.keys(drawings).filter((id) => !previous[id]);
2882
+ const removed = Object.keys(previous).filter((id) => !drawings[id]);
2883
+ const changed = Object.keys(drawings).filter((id) => drawings[id] !== previous[id]);
2884
+ if (added.length > 0) this._addDrawings(unitId, added.map((id) => ({
2885
+ ...drawings[id],
2952
2886
  unitId,
2953
- page,
2954
- docsLeft,
2955
- docsTop,
2956
- pageOffsetLeft,
2957
- pageOffsetTop,
2958
- updateDrawingMap,
2959
- hostPage,
2960
- selectable,
2961
- clipOffset,
2962
- overflowClipBounds
2963
- };
2964
- skeDrawings.forEach((drawing) => this._collectDrawingPosition(drawing, drawingPositionContext));
2965
- this._liquid.restorePagePadding({
2966
- marginTop,
2967
- marginLeft
2968
- });
2887
+ subUnitId: unitId
2888
+ })));
2889
+ if (removed.length > 0) this._removeDrawings(unitId, removed);
2890
+ if (changed.length > 0) this._syncDrawingDataFromSnapshot(unitId, changed);
2969
2891
  }
2970
- _collectDrawingPosition(drawing, context) {
2971
- var _this$_context$unit, _this$_context$unit$g;
2972
- const { aLeft, aTop, angle: skeletonAngle, drawingId, drawingOrigin, height: skeletonHeight, width: skeletonWidth } = drawing;
2973
- const runtimeDrawing = getDocsOverlayRuntimeDrawing(drawingOrigin, (_this$_context$unit = this._context.unit) === null || _this$_context$unit === void 0 || (_this$_context$unit$g = _this$_context$unit.getSnapshot) === null || _this$_context$unit$g === void 0 || (_this$_context$unit$g = _this$_context$unit$g.call(_this$_context$unit).drawings) === null || _this$_context$unit$g === void 0 ? void 0 : _this$_context$unit$g[drawingId], drawing.customBlockRenderViewport ? {
2974
- width: skeletonWidth,
2975
- height: skeletonHeight
2976
- } : void 0);
2977
- const { angle = skeletonAngle, size } = runtimeDrawing.docTransform;
2978
- const height = (size === null || size === void 0 ? void 0 : size.height) ?? skeletonHeight;
2979
- const width = (size === null || size === void 0 ? void 0 : size.width) ?? skeletonWidth;
2980
- const { left: clipOffsetLeft, top: clipOffsetTop } = context.clipOffset ?? {};
2981
- const behindText = getDocsDrawingBehindText({
2982
- drawingOrigin: runtimeDrawing,
2983
- hostPage: context.hostPage
2892
+ _syncDrawingDataFromSnapshot(unitId, drawingIds) {
2893
+ const documentDataModel = this._univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
2894
+ if (documentDataModel == null) return;
2895
+ const { drawings, drawingsOrder } = collectDocDrawings(documentDataModel.getSnapshot());
2896
+ const drawingData = Object.fromEntries(Object.entries(drawings).map(([id, drawing]) => [id, {
2897
+ ...drawing,
2898
+ unitId,
2899
+ subUnitId: unitId
2900
+ }]));
2901
+ const previousDrawings = this._docDrawingService.getDrawingData(unitId, unitId);
2902
+ const previousRendered = this._drawingManagerService.getDrawingData(unitId, unitId);
2903
+ const missingIds = Object.keys(drawingData).filter((id) => !previousRendered[id]);
2904
+ const synchronizedDrawingIds = [.../* @__PURE__ */ new Set([...drawingIds, ...missingIds])];
2905
+ const orderChanged = drawingsOrder !== this._docDrawingService.getDrawingOrder(unitId, unitId) || synchronizedDrawingIds.some((drawingId) => {
2906
+ const previous = previousDrawings[drawingId];
2907
+ const current = drawingData[drawingId];
2908
+ return ((previous === null || previous === void 0 ? void 0 : previous.layoutType) === PositionedObjectLayoutType.WRAP_NONE && previous.behindDoc === BooleanNumber.TRUE) !== ((current === null || current === void 0 ? void 0 : current.layoutType) === PositionedObjectLayoutType.WRAP_NONE && current.behindDoc === BooleanNumber.TRUE);
2984
2909
  });
2985
- const { isMultiTransform = BooleanNumber.FALSE } = runtimeDrawing;
2986
- const clipPage = getDocsDrawingClipPage({
2987
- drawing: {
2988
- behindText,
2989
- transform: {
2990
- width,
2991
- height
2992
- }
2993
- },
2994
- hostPage: context.hostPage,
2995
- page: context.page
2910
+ const hierarchyChanged = synchronizedDrawingIds.some((id) => {
2911
+ var _previousDrawings$id, _drawingData$id;
2912
+ return ((_previousDrawings$id = previousDrawings[id]) === null || _previousDrawings$id === void 0 ? void 0 : _previousDrawings$id.groupId) !== ((_drawingData$id = drawingData[id]) === null || _drawingData$id === void 0 ? void 0 : _drawingData$id.groupId);
2996
2913
  });
2997
- const clipBounds = getDocsDrawingPageClipBounds({
2998
- docsLeft: context.docsLeft,
2999
- docsTop: context.docsTop,
3000
- pageOffsetLeft: context.pageOffsetLeft,
3001
- pageOffsetTop: context.pageOffsetTop,
3002
- clipOffsetLeft,
3003
- clipOffsetTop,
3004
- page: clipPage,
3005
- drawingLayoutType: runtimeDrawing.layoutType,
3006
- overflowClipBounds: context.overflowClipBounds
2914
+ if (hierarchyChanged) this._drawingManagerService.removeNotification(Object.values(this._drawingManagerService.getDrawingData(unitId, unitId)));
2915
+ const renderedDrawings = { ...this._drawingManagerService.getDrawingData(unitId, unitId) };
2916
+ for (const drawingId of synchronizedDrawingIds) {
2917
+ const current = drawingData[drawingId];
2918
+ if (current) {
2919
+ var _renderedDrawings$dra;
2920
+ renderedDrawings[drawingId] = {
2921
+ ...current,
2922
+ transform: ((_renderedDrawings$dra = renderedDrawings[drawingId]) === null || _renderedDrawings$dra === void 0 ? void 0 : _renderedDrawings$dra.transform) ?? current.transform
2923
+ };
2924
+ } else delete renderedDrawings[drawingId];
2925
+ }
2926
+ this._docDrawingService.setDrawingData(unitId, unitId, drawingData);
2927
+ this._drawingManagerService.setDrawingData(unitId, unitId, renderedDrawings);
2928
+ if (orderChanged) {
2929
+ this._docDrawingService.setDrawingOrder(unitId, unitId, drawingsOrder);
2930
+ this._drawingManagerService.setDrawingOrder(unitId, unitId, getDocDrawingRenderOrder(drawingsOrder, drawings));
2931
+ }
2932
+ const objects = synchronizedDrawingIds.filter((drawingId) => drawingData[drawingId] != null).map((drawingId) => ({
2933
+ unitId,
2934
+ subUnitId: unitId,
2935
+ drawingId
2936
+ }));
2937
+ if (objects.length === 0) return;
2938
+ if (hierarchyChanged) this._drawingManagerService.addNotification(Object.values(renderedDrawings));
2939
+ this._docDrawingService.updateNotification(objects);
2940
+ this._drawingManagerService.updateNotification(objects);
2941
+ }
2942
+ };
2943
+ DocDrawingAddRemoveController = __decorate([
2944
+ __decorateParam(0, IUniverInstanceService),
2945
+ __decorateParam(1, ICommandService),
2946
+ __decorateParam(2, IDrawingManagerService),
2947
+ __decorateParam(3, IDocDrawingService),
2948
+ __decorateParam(4, IRenderManagerService),
2949
+ __decorateParam(5, Inject(DocRefreshDrawingsService))
2950
+ ], DocDrawingAddRemoveController);
2951
+
2952
+ //#endregion
2953
+ //#region src/views/DocPrintingFloatDom.tsx
2954
+ const DocPrintingFloatDom = (props) => {
2955
+ const { floatDomInfos, scene, offset, bound } = props;
2956
+ const width = bound.right - bound.left;
2957
+ const height = bound.bottom - bound.top;
2958
+ const floatDomParams = useMemo(() => floatDomInfos.map((info) => {
2959
+ const { width = 0, height = 0, left = 0, top = 0 } = info.transform;
2960
+ const domPos = calcDocFloatDomPositionByRect({
2961
+ left,
2962
+ right: left + width,
2963
+ top,
2964
+ bottom: top + height
2965
+ }, scene);
2966
+ const floatDom = {
2967
+ position$: new BehaviorSubject(domPos),
2968
+ position: domPos,
2969
+ id: info.drawingId,
2970
+ componentKey: info.componentKey,
2971
+ onPointerMove: () => {},
2972
+ onPointerDown: () => {},
2973
+ onPointerUp: () => {},
2974
+ onWheel: () => {},
2975
+ unitId: info.unitId,
2976
+ data: info.data
2977
+ };
2978
+ return [info.drawingId, floatDom];
2979
+ }).filter(([_, floatDom]) => !(floatDom.position.endX < 0 || floatDom.position.endY < 0 || floatDom.position.startX > width || floatDom.position.startY > height)), [
2980
+ floatDomInfos,
2981
+ scene,
2982
+ offset,
2983
+ width,
2984
+ height
2985
+ ]);
2986
+ return /* @__PURE__ */ jsx("div", {
2987
+ className: "univer-absolute univer-left-0 univer-top-0",
2988
+ children: floatDomParams.map(([id, floatDom]) => /* @__PURE__ */ jsx(PrintFloatDomSingle, {
2989
+ layer: floatDom,
2990
+ id,
2991
+ position: floatDom.position
2992
+ }, id))
2993
+ });
2994
+ };
2995
+ function mountDocPrintingFloatDom(props, root, injector) {
2996
+ const PrintingFloatDomInjector = connectInjector(DocPrintingFloatDom, injector);
2997
+ render(/* @__PURE__ */ jsx(PrintingFloatDomInjector, { ...props }), root);
2998
+ return () => unmount(root);
2999
+ }
3000
+
3001
+ //#endregion
3002
+ //#region src/controllers/doc-drawing-printing.controller.ts
3003
+ let DocDrawingPrintingController = class DocDrawingPrintingController extends Disposable {
3004
+ constructor(_docPrintInterceptorService, _drawingRenderService, _drawingManagerService, _componetManager, _injector) {
3005
+ super();
3006
+ this._docPrintInterceptorService = _docPrintInterceptorService;
3007
+ this._drawingRenderService = _drawingRenderService;
3008
+ this._drawingManagerService = _drawingManagerService;
3009
+ this._componetManager = _componetManager;
3010
+ this._injector = _injector;
3011
+ this._initPrinting();
3012
+ this._initPrintingDom();
3013
+ }
3014
+ _initPrinting() {
3015
+ this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_COMPONENT_COLLECT, { handler: (_param, pos, next) => {
3016
+ const { unitId, scene, skeleton, pageIndex } = pos;
3017
+ const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);
3018
+ const subUnitData = unitData === null || unitData === void 0 ? void 0 : unitData[unitId];
3019
+ const visibleDrawingIds = this._docPrintInterceptorService.getPageDrawingIds(skeleton, pageIndex);
3020
+ if (subUnitData) subUnitData.order.forEach((id) => {
3021
+ if (visibleDrawingIds && !visibleDrawingIds.has(id)) return;
3022
+ const drawing = subUnitData.data[id];
3023
+ if (drawing.drawingType !== DrawingTypeEnum.DRAWING_CHART && drawing.drawingType !== DrawingTypeEnum.DRAWING_DOM) this._drawingRenderService.renderDrawing(drawing, scene);
3024
+ });
3025
+ return next();
3026
+ } }));
3027
+ }
3028
+ _initPrintingDom() {
3029
+ this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_DOM_COLLECT, { handler: (disposableCollection, pos, next) => {
3030
+ const { unitId, skeleton, pageIndex } = pos;
3031
+ const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);
3032
+ const subUnitData = unitData === null || unitData === void 0 ? void 0 : unitData[unitId];
3033
+ const visibleDrawingIds = this._docPrintInterceptorService.getPageDrawingIds(skeleton, pageIndex);
3034
+ if (subUnitData) {
3035
+ const floatDomInfos = subUnitData.order.filter((id) => !visibleDrawingIds || visibleDrawingIds.has(id)).map((id) => {
3036
+ const drawing = subUnitData.data[id];
3037
+ if (drawing.drawingType === DrawingTypeEnum.DRAWING_CHART) return {
3038
+ ...drawing,
3039
+ componentKey: this._componetManager.get(DOC_DRAWING_PRINTING_COMPONENT_KEY)
3040
+ };
3041
+ if (drawing.drawingType === DrawingTypeEnum.DRAWING_DOM) {
3042
+ const printingComponentKey = this._docPrintInterceptorService.getPrintComponent(drawing.componentKey);
3043
+ return {
3044
+ ...drawing,
3045
+ componentKey: this._componetManager.get(printingComponentKey || drawing.componentKey)
3046
+ };
3047
+ }
3048
+ return null;
3049
+ }).filter(Boolean);
3050
+ const unmountPrintingFloatDom = mountDocPrintingFloatDom({
3051
+ unitId,
3052
+ floatDomInfos,
3053
+ scene: pos.scene,
3054
+ skeleton: pos.skeleton,
3055
+ offset: pos.offset,
3056
+ bound: pos.bound
3057
+ }, pos.root, this._injector);
3058
+ disposableCollection === null || disposableCollection === void 0 || disposableCollection.add(() => {
3059
+ unmountPrintingFloatDom();
3060
+ });
3061
+ return next(disposableCollection);
3062
+ }
3063
+ } }));
3064
+ }
3065
+ };
3066
+ DocDrawingPrintingController = __decorate([
3067
+ __decorateParam(0, Inject(DocPrintInterceptorService)),
3068
+ __decorateParam(1, Inject(DrawingRenderService)),
3069
+ __decorateParam(2, IDrawingManagerService),
3070
+ __decorateParam(3, Inject(ComponentManager)),
3071
+ __decorateParam(4, Inject(Injector))
3072
+ ], DocDrawingPrintingController);
3073
+
3074
+ //#endregion
3075
+ //#region src/commands/commands/update-doc-drawing.command.ts
3076
+ function getDeleteAndInsertCustomBlockActions(segmentId, oldSegmentId, segmentPage, offset, drawingId, documentDataModel, docSelectionRenderManager) {
3077
+ var _documentDataModel$ge, _documentDataModel$ge2, _oldBody$customBlocks;
3078
+ const textX = new TextX();
3079
+ const jsonX = JSONX.getInstance();
3080
+ const rawActions = [];
3081
+ const oldBody = (_documentDataModel$ge = documentDataModel.getSelfOrHeaderFooterModel(oldSegmentId)) === null || _documentDataModel$ge === void 0 ? void 0 : _documentDataModel$ge.getBody();
3082
+ const body = (_documentDataModel$ge2 = documentDataModel.getSelfOrHeaderFooterModel(segmentId)) === null || _documentDataModel$ge2 === void 0 ? void 0 : _documentDataModel$ge2.getBody();
3083
+ if (oldBody == null || body == null) return;
3084
+ const oldOffset = (_oldBody$customBlocks = oldBody.customBlocks) === null || _oldBody$customBlocks === void 0 || (_oldBody$customBlocks = _oldBody$customBlocks.find((block) => block.blockId === drawingId)) === null || _oldBody$customBlocks === void 0 ? void 0 : _oldBody$customBlocks.startIndex;
3085
+ if (oldOffset == null) return;
3086
+ offset = Math.min(body.dataStream.length - 2, offset);
3087
+ if (segmentId === oldSegmentId) {
3088
+ if (offset < oldOffset) {
3089
+ if (offset > 0) textX.push({
3090
+ t: TextXActionType.RETAIN,
3091
+ len: offset
3092
+ });
3093
+ textX.push({
3094
+ t: TextXActionType.INSERT,
3095
+ body: {
3096
+ dataStream: "\b",
3097
+ customBlocks: [{
3098
+ startIndex: 0,
3099
+ blockId: drawingId
3100
+ }]
3101
+ },
3102
+ len: 1
3103
+ });
3104
+ textX.push({
3105
+ t: TextXActionType.RETAIN,
3106
+ len: oldOffset - offset
3107
+ });
3108
+ textX.push({
3109
+ t: TextXActionType.DELETE,
3110
+ len: 1
3111
+ });
3112
+ } else {
3113
+ if (oldOffset > 0) textX.push({
3114
+ t: TextXActionType.RETAIN,
3115
+ len: oldOffset
3116
+ });
3117
+ textX.push({
3118
+ t: TextXActionType.DELETE,
3119
+ len: 1
3120
+ });
3121
+ if (offset - oldOffset - 1 > 0) textX.push({
3122
+ t: TextXActionType.RETAIN,
3123
+ len: offset - oldOffset - 1
3124
+ });
3125
+ textX.push({
3126
+ t: TextXActionType.INSERT,
3127
+ body: {
3128
+ dataStream: "\b",
3129
+ customBlocks: [{
3130
+ startIndex: 0,
3131
+ blockId: drawingId
3132
+ }]
3133
+ },
3134
+ len: 1
3135
+ });
3136
+ }
3137
+ if (offset !== oldOffset) {
3138
+ const path = getRichTextEditPath(documentDataModel, oldSegmentId);
3139
+ const action = jsonX.editOp(textX.serialize(), path);
3140
+ rawActions.push(action);
3141
+ }
3142
+ } else {
3143
+ if (oldOffset > 0) textX.push({
3144
+ t: TextXActionType.RETAIN,
3145
+ len: oldOffset
3007
3146
  });
3008
- const anchorPage = getDocsPageRelativeDrawingAnchorPage({
3009
- page: context.page,
3010
- clipPage,
3011
- hostPage: context.hostPage,
3012
- drawingLayoutType: runtimeDrawing.layoutType
3147
+ textX.push({
3148
+ t: TextXActionType.DELETE,
3149
+ len: 1
3013
3150
  });
3014
- const pageRelativeLeft = anchorPage == null ? void 0 : getDocsPageRelativeDrawingLeft({
3015
- hostPage: anchorPage,
3016
- positionH: runtimeDrawing.docTransform.positionH,
3017
- width
3151
+ let path = getRichTextEditPath(documentDataModel, oldSegmentId);
3152
+ let action = jsonX.editOp(textX.serialize(), path);
3153
+ rawActions.push(action);
3154
+ textX.empty();
3155
+ if (offset > 0) textX.push({
3156
+ t: TextXActionType.RETAIN,
3157
+ len: offset
3018
3158
  });
3019
- const pageRelativeTop = anchorPage == null ? void 0 : getDocsPageRelativeDrawingTop({
3020
- hostPage: anchorPage,
3021
- positionV: runtimeDrawing.docTransform.positionV,
3022
- height
3159
+ textX.push({
3160
+ t: TextXActionType.INSERT,
3161
+ body: {
3162
+ dataStream: "\b",
3163
+ customBlocks: [{
3164
+ startIndex: 0,
3165
+ blockId: drawingId
3166
+ }]
3167
+ },
3168
+ len: 1
3023
3169
  });
3024
- const transform = {
3025
- left: (pageRelativeLeft ?? aLeft) + context.docsLeft + (pageRelativeLeft == null ? this._liquid.x : context.pageOffsetLeft),
3026
- top: (pageRelativeTop ?? aTop) + context.docsTop + (pageRelativeTop == null ? this._liquid.y : context.pageOffsetTop),
3027
- width,
3028
- height,
3029
- angle,
3030
- flipX: runtimeDrawing.docTransform.flipX,
3031
- flipY: runtimeDrawing.docTransform.flipY,
3032
- clipBounds
3170
+ path = getRichTextEditPath(documentDataModel, segmentId);
3171
+ action = jsonX.editOp(textX.serialize(), path);
3172
+ rawActions.push(action);
3173
+ docSelectionRenderManager.setSegment(segmentId);
3174
+ docSelectionRenderManager.setSegmentPage(segmentPage);
3175
+ }
3176
+ return rawActions;
3177
+ }
3178
+ /**
3179
+ * The command to update drawing wrap text.
3180
+ */
3181
+ const UpdateDocDrawingDistanceCommand = {
3182
+ id: "doc.command.update-doc-drawing-distance",
3183
+ type: CommandType.COMMAND,
3184
+ handler: (accessor, params) => {
3185
+ if (params == null) return false;
3186
+ const commandService = accessor.get(ICommandService);
3187
+ const univerInstanceService = accessor.get(IUniverInstanceService);
3188
+ const { drawings, dist, unitId } = params;
3189
+ const documentDataModel = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
3190
+ if (documentDataModel == null) return false;
3191
+ const jsonX = JSONX.getInstance();
3192
+ const rawActions = [];
3193
+ const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
3194
+ for (const drawing of drawings) {
3195
+ const { drawingId } = drawing;
3196
+ for (const [key, value] of Object.entries(dist)) {
3197
+ const oldValue = oldDrawings[drawingId][key];
3198
+ if (oldValue !== value) {
3199
+ const action = jsonX.replaceOp([
3200
+ "drawings",
3201
+ drawingId,
3202
+ key
3203
+ ], oldValue, value);
3204
+ rawActions.push(action);
3205
+ }
3206
+ }
3207
+ }
3208
+ const doMutation = {
3209
+ id: RichTextEditingMutation.id,
3210
+ params: {
3211
+ unitId,
3212
+ actions: [],
3213
+ textRanges: null
3214
+ }
3215
+ };
3216
+ doMutation.params.actions = rawActions.reduce((acc, cur) => {
3217
+ return JSONX.compose(acc, cur);
3218
+ }, null);
3219
+ const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
3220
+ return Boolean(result);
3221
+ }
3222
+ };
3223
+ /**
3224
+ * The command to update drawing wrap text.
3225
+ */
3226
+ const UpdateDocDrawingWrapTextCommand = {
3227
+ id: "doc.command.update-doc-drawing-wrap-text",
3228
+ type: CommandType.COMMAND,
3229
+ handler: (accessor, params) => {
3230
+ if (params == null) return false;
3231
+ const commandService = accessor.get(ICommandService);
3232
+ const univerInstanceService = accessor.get(IUniverInstanceService);
3233
+ const { drawings, wrapText, unitId } = params;
3234
+ const documentDataModel = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
3235
+ if (documentDataModel == null) return false;
3236
+ const jsonX = JSONX.getInstance();
3237
+ const rawActions = [];
3238
+ const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
3239
+ for (const drawing of drawings) {
3240
+ const { drawingId } = drawing;
3241
+ const oldWrapText = oldDrawings[drawingId].wrapText;
3242
+ if (oldWrapText !== wrapText) {
3243
+ const action = jsonX.replaceOp([
3244
+ "drawings",
3245
+ drawingId,
3246
+ "wrapText"
3247
+ ], oldWrapText, wrapText);
3248
+ rawActions.push(action);
3249
+ }
3250
+ }
3251
+ const doMutation = {
3252
+ id: RichTextEditingMutation.id,
3253
+ params: {
3254
+ unitId,
3255
+ actions: [],
3256
+ textRanges: null
3257
+ }
3258
+ };
3259
+ doMutation.params.actions = rawActions.reduce((acc, cur) => {
3260
+ return JSONX.compose(acc, cur);
3261
+ }, null);
3262
+ const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
3263
+ return Boolean(result);
3264
+ }
3265
+ };
3266
+ /**
3267
+ * The command to move inline drawing.
3268
+ */
3269
+ const IMoveInlineDrawingCommand = {
3270
+ id: "doc.command.move-inline-drawing",
3271
+ type: CommandType.COMMAND,
3272
+ handler: (accessor, params) => {
3273
+ var _renderManagerService;
3274
+ if (params == null) return false;
3275
+ const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage, needRefreshDrawings } = params;
3276
+ const renderManagerService = accessor.get(IRenderManagerService);
3277
+ const docSelectionRenderService = (_renderManagerService = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService === void 0 ? void 0 : _renderManagerService.with(DocSelectionRenderService);
3278
+ const docRefreshDrawingsService = accessor.get(DocRefreshDrawingsService);
3279
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
3280
+ const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
3281
+ const skeleton = renderObject === null || renderObject === void 0 ? void 0 : renderObject.with(DocSkeletonManagerService).getSkeleton();
3282
+ if (scene == null || docSelectionRenderService == null) return false;
3283
+ const transformer = scene.getTransformerByCreate();
3284
+ const commandService = accessor.get(ICommandService);
3285
+ const documentDataModel = accessor.get(IUniverInstanceService).getUnit(unitId, UniverInstanceType.UNIVER_DOC);
3286
+ if (documentDataModel == null) return false;
3287
+ if (needRefreshDrawings) {
3288
+ docRefreshDrawingsService.refreshDrawings(skeleton);
3289
+ transformer.refreshControls();
3290
+ return true;
3291
+ }
3292
+ const rawActions = [];
3293
+ const { drawingId } = drawing;
3294
+ const actions = getDeleteAndInsertCustomBlockActions(newSegmentId, docSelectionRenderService.getSegment() ?? "", segmentPage, offset, drawingId, documentDataModel, docSelectionRenderService);
3295
+ if (actions == null || actions.length === 0) {
3296
+ docRefreshDrawingsService.refreshDrawings(skeleton);
3297
+ transformer.refreshControls();
3298
+ return false;
3299
+ }
3300
+ rawActions.push(...actions);
3301
+ const doMutation = {
3302
+ id: RichTextEditingMutation.id,
3303
+ params: {
3304
+ unitId,
3305
+ actions: [],
3306
+ textRanges: null
3307
+ }
3033
3308
  };
3034
- mergePublishedDrawing(context.updateDrawingMap, {
3035
- unitId: context.unitId,
3036
- subUnitId: context.unitId,
3037
- drawingId,
3038
- behindText,
3039
- selectable: context.selectable,
3040
- transform,
3041
- transforms: [transform],
3042
- customBlockRenderViewport: drawing.customBlockRenderViewport,
3043
- isMultiTransform
3044
- });
3045
- if (runtimeDrawing.drawingType === DrawingTypeEnum.DRAWING_GROUP) this._collectGroupChildren(drawingId, context, behindText, isMultiTransform, /* @__PURE__ */ new Set([drawingId]));
3309
+ doMutation.params.actions = rawActions.reduce((acc, cur) => {
3310
+ return JSONX.compose(acc, cur);
3311
+ }, null);
3312
+ const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
3313
+ transformer.refreshControls();
3314
+ return Boolean(result);
3046
3315
  }
3047
- _collectGroupChildren(groupId, context, behindText, isMultiTransform, visited) {
3048
- const { drawings } = collectDocDrawings(this._context.unit.getSnapshot());
3049
- for (const child of Object.values(drawings)) {
3050
- if (child.groupId !== groupId || visited.has(child.drawingId)) continue;
3051
- visited.add(child.drawingId);
3052
- const { size, positionH, positionV, angle, flipX, flipY } = child.docTransform;
3053
- const transform = {
3054
- left: positionH.posOffset ?? 0,
3055
- top: positionV.posOffset ?? 0,
3056
- width: size.width,
3057
- height: size.height,
3058
- angle,
3059
- flipX,
3060
- flipY
3061
- };
3062
- mergePublishedDrawing(context.updateDrawingMap, {
3063
- unitId: context.unitId,
3064
- subUnitId: context.unitId,
3065
- drawingId: child.drawingId,
3066
- behindText,
3067
- selectable: context.selectable,
3068
- transform,
3069
- transforms: [transform],
3070
- isMultiTransform
3071
- });
3072
- this._collectGroupChildren(child.drawingId, context, behindText, isMultiTransform, visited);
3316
+ };
3317
+ /**
3318
+ * The command to transform non-inline drawing.
3319
+ */
3320
+ const ITransformNonInlineDrawingCommand = {
3321
+ id: "doc.command.transform-non-inline-drawing",
3322
+ type: CommandType.COMMAND,
3323
+ handler: (accessor, params) => {
3324
+ var _renderManagerService2;
3325
+ if (params == null) return false;
3326
+ const { drawing, unitId, offset, docTransform, segmentId: newSegmentId, segmentPage } = params;
3327
+ const renderManagerService = accessor.get(IRenderManagerService);
3328
+ const docSelectionRenderService = (_renderManagerService2 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService2 === void 0 ? void 0 : _renderManagerService2.with(DocSelectionRenderService);
3329
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
3330
+ const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
3331
+ if (renderObject == null || scene == null || docSelectionRenderService == null) return false;
3332
+ const transformer = scene.getTransformerByCreate();
3333
+ const commandService = accessor.get(ICommandService);
3334
+ const documentDataModel = accessor.get(IUniverInstanceService).getUnit(unitId, UniverInstanceType.UNIVER_DOC);
3335
+ if (documentDataModel == null) return false;
3336
+ const rawActions = [];
3337
+ const { drawingId } = drawing;
3338
+ const actions = getDeleteAndInsertCustomBlockActions(newSegmentId, docSelectionRenderService.getSegment() ?? "", segmentPage, offset, drawingId, documentDataModel, docSelectionRenderService);
3339
+ if (actions == null) return false;
3340
+ if (actions.length > 0) rawActions.push(...actions);
3341
+ const jsonX = JSONX.getInstance();
3342
+ const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
3343
+ const { positionH: oldPositionH, positionV: oldPositionV, size: oldSize, angle: oldAngle } = oldDrawings[drawingId].docTransform;
3344
+ if (!Tools.diffValue(oldPositionH, docTransform.positionH)) {
3345
+ const updateAction = jsonX.replaceOp([
3346
+ "drawings",
3347
+ drawingId,
3348
+ "docTransform",
3349
+ "positionH"
3350
+ ], oldPositionH, docTransform.positionH);
3351
+ rawActions.push(updateAction);
3073
3352
  }
3074
- }
3075
- _calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, baseMarginTop, baseMarginLeft, selectable, overflowClipBounds) {
3076
- var _page$skeTables3;
3077
- (_page$skeTables3 = page.skeTables) === null || _page$skeTables3 === void 0 || _page$skeTables3.forEach((table) => {
3078
- table.rows.forEach((row) => {
3079
- row.cells.forEach((cell) => {
3080
- var _cell$skeDrawings, _cell$skeTables, _cell$skeColumnGroups;
3081
- if ((((_cell$skeDrawings = cell.skeDrawings) === null || _cell$skeDrawings === void 0 ? void 0 : _cell$skeDrawings.size) ?? 0) === 0 && (((_cell$skeTables = cell.skeTables) === null || _cell$skeTables === void 0 ? void 0 : _cell$skeTables.size) ?? 0) === 0 && (((_cell$skeColumnGroups = cell.skeColumnGroups) === null || _cell$skeColumnGroups === void 0 ? void 0 : _cell$skeColumnGroups.size) ?? 0) === 0) return;
3082
- const cellOffset = getDocsTableCellDrawingOffset(unitId, table, row, cell);
3083
- const marginTop = baseMarginTop + cellOffset.top;
3084
- const marginLeft = baseMarginLeft + cellOffset.left;
3085
- this._calculateDrawingPosition(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, void 0, selectable, {
3086
- left: marginLeft,
3087
- top: marginTop
3088
- }, overflowClipBounds);
3089
- this._calculateTableCellDrawingPositions(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3090
- this._calculateColumnGroupDrawingPositions(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3091
- });
3092
- });
3093
- });
3094
- }
3095
- _calculateColumnGroupDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, baseMarginTop, baseMarginLeft, selectable, overflowClipBounds) {
3096
- var _page$skeColumnGroups3;
3097
- (_page$skeColumnGroups3 = page.skeColumnGroups) === null || _page$skeColumnGroups3 === void 0 || _page$skeColumnGroups3.forEach((columnGroup) => {
3098
- columnGroup.columns.forEach((column) => {
3099
- const nestedPage = column.page;
3100
- const marginTop = baseMarginTop + columnGroup.top + column.top + nestedPage.marginTop;
3101
- const marginLeft = baseMarginLeft + columnGroup.left + column.left + nestedPage.marginLeft;
3102
- const clipOffset = {
3103
- left: marginLeft,
3104
- top: marginTop
3105
- };
3106
- this._calculateDrawingPosition(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, void 0, selectable, clipOffset, overflowClipBounds);
3107
- this._calculateTableCellDrawingPositions(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3108
- this._calculateColumnGroupDrawingPositions(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3109
- });
3110
- });
3111
- }
3112
- _drawingInitializeListener() {
3113
- const init = () => {
3114
- const skeleton = this._docSkeletonManagerService.getSkeleton();
3115
- if (skeleton == null) return;
3116
- this._drawingManagerService.initializeNotification(this._context.unitId);
3117
- this._refreshDrawing(skeleton);
3353
+ if (!Tools.diffValue(oldPositionV, docTransform.positionV)) {
3354
+ const updateAction = jsonX.replaceOp([
3355
+ "drawings",
3356
+ drawingId,
3357
+ "docTransform",
3358
+ "positionV"
3359
+ ], oldPositionV, docTransform.positionV);
3360
+ rawActions.push(updateAction);
3361
+ }
3362
+ if (!Tools.diffValue(oldSize, docTransform.size)) {
3363
+ const updateAction = jsonX.replaceOp([
3364
+ "drawings",
3365
+ drawingId,
3366
+ "docTransform",
3367
+ "size"
3368
+ ], oldSize, docTransform.size);
3369
+ rawActions.push(updateAction);
3370
+ }
3371
+ if (!Tools.diffValue(oldAngle, docTransform.angle)) {
3372
+ const updateAction = jsonX.replaceOp([
3373
+ "drawings",
3374
+ drawingId,
3375
+ "docTransform",
3376
+ "angle"
3377
+ ], oldAngle, docTransform.angle);
3378
+ rawActions.push(updateAction);
3379
+ }
3380
+ const doMutation = {
3381
+ id: RichTextEditingMutation.id,
3382
+ params: {
3383
+ unitId,
3384
+ actions: [],
3385
+ textRanges: null,
3386
+ debounce: true
3387
+ }
3118
3388
  };
3119
- if (this._lifecycleService.stage >= LifecycleStages.Rendered) {
3120
- if (this._docSkeletonManagerService.getSkeleton()) init();
3121
- else setTimeout(init, 500);
3122
- } else this.disposeWithMe(this._lifecycleService.lifecycle$.pipe(filter((stage) => stage === LifecycleStages.Rendered)).subscribe(init));
3389
+ doMutation.params.actions = rawActions.reduce((acc, cur) => {
3390
+ return JSONX.compose(acc, cur);
3391
+ }, null);
3392
+ const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
3393
+ const skeleton = renderObject.with(DocSkeletonManagerService).getSkeleton();
3394
+ accessor.get(DocRefreshDrawingsService).refreshDrawings(skeleton);
3395
+ transformer.refreshControls();
3396
+ return Boolean(result);
3123
3397
  }
3124
3398
  };
3125
- DocDrawingTransformUpdateController = __decorate([
3126
- __decorateParam(1, Inject(DocSkeletonManagerService)),
3127
- __decorateParam(2, ICommandService),
3128
- __decorateParam(3, IEditorService),
3129
- __decorateParam(4, IDrawingManagerService),
3130
- __decorateParam(5, Inject(DocRefreshDrawingsService)),
3131
- __decorateParam(6, IUniverInstanceService),
3132
- __decorateParam(7, Inject(LifecycleService))
3133
- ], DocDrawingTransformUpdateController);
3134
3399
 
3135
3400
  //#endregion
3136
3401
  //#region src/controllers/doc-drawing-transformer-update.controller.ts
@@ -3181,12 +3446,26 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3181
3446
  this._drawingManagerService = _drawingManagerService;
3182
3447
  this._renderManagerService = _renderManagerService;
3183
3448
  _defineProperty(this, "_liquid", new Liquid());
3184
- _defineProperty(this, "_listenerOnImageMap", /* @__PURE__ */ new Set());
3449
+ _defineProperty(this, "_listenerOnImageMap", /* @__PURE__ */ new Map());
3185
3450
  _defineProperty(this, "_transformerCache", /* @__PURE__ */ new Map());
3186
3451
  _defineProperty(this, "_anchorShape", void 0);
3187
3452
  this._init();
3188
3453
  }
3454
+ dispose() {
3455
+ var _this$_anchorShape;
3456
+ for (const listener of this._listenerOnImageMap.values()) listener.dispose();
3457
+ this._listenerOnImageMap.clear();
3458
+ this._transformerCache.clear();
3459
+ (_this$_anchorShape = this._anchorShape) === null || _this$_anchorShape === void 0 || _this$_anchorShape.dispose();
3460
+ this._anchorShape = null;
3461
+ super.dispose();
3462
+ }
3189
3463
  _init() {
3464
+ this.disposeWithMe(this._renderManagerService.disposed$.subscribe((unitId) => {
3465
+ var _this$_listenerOnImag;
3466
+ (_this$_listenerOnImag = this._listenerOnImageMap.get(unitId)) === null || _this$_listenerOnImag === void 0 || _this$_listenerOnImag.dispose();
3467
+ this._listenerOnImageMap.delete(unitId);
3468
+ }));
3190
3469
  this._listenDrawingFocus();
3191
3470
  }
3192
3471
  _listenDrawingFocus() {
@@ -3195,17 +3474,25 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3195
3474
  for (const drawingParam of drawingParams) {
3196
3475
  const { unitId } = drawingParam;
3197
3476
  if (!this._listenerOnImageMap.has(unitId)) {
3198
- this._listenTransformerChange(unitId);
3199
- this._listenerOnImageMap.add(unitId);
3477
+ const listener = this._listenTransformerChange(unitId);
3478
+ if (listener) this._listenerOnImageMap.set(unitId, listener);
3200
3479
  }
3201
3480
  }
3202
3481
  }));
3203
3482
  }
3204
3483
  _listenTransformerChange(unitId) {
3205
- var _this$_getSceneAndTra;
3206
- const transformer = (_this$_getSceneAndTra = this._getSceneAndTransformerByDrawingSearch(unitId)) === null || _this$_getSceneAndTra === void 0 ? void 0 : _this$_getSceneAndTra.transformer;
3484
+ const context = this._getSceneAndTransformerByDrawingSearch(unitId);
3485
+ const transformer = context === null || context === void 0 ? void 0 : context.transformer;
3207
3486
  if (transformer == null) return;
3208
- this.disposeWithMe(toDisposable(transformer.changeStart$.subscribe((state) => {
3487
+ const listeners = new DisposableCollection();
3488
+ listeners.add(toDisposable(() => {
3489
+ for (const [id, cached] of this._transformerCache) if (cached.drawing.unitId === unitId) this._transformerCache.delete(id);
3490
+ if (this._anchorShape && this._anchorShape.getScene() === (context === null || context === void 0 ? void 0 : context.scene)) {
3491
+ this._anchorShape.dispose();
3492
+ this._anchorShape = null;
3493
+ }
3494
+ }));
3495
+ listeners.add(toDisposable(transformer.changeStart$.subscribe((state) => {
3209
3496
  this._transformerCache.clear();
3210
3497
  const { objects } = state;
3211
3498
  for (const object of objects.values()) {
@@ -3217,7 +3504,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3217
3504
  const drawingData = documentDataModel ? (_findDocDrawing = findDocDrawing(documentDataModel.getSnapshot(), drawing.drawingId)) === null || _findDocDrawing === void 0 ? void 0 : _findDocDrawing.drawing : void 0;
3218
3505
  if ((drawingData === null || drawingData === void 0 ? void 0 : drawingData.layoutType) === PositionedObjectLayoutType.INLINE) try {
3219
3506
  object.setOpacity(.2);
3220
- } catch (e) {}
3507
+ } catch {}
3221
3508
  if (drawingData != null) this._transformerCache.set(drawing.drawingId, {
3222
3509
  drawing: drawingData,
3223
3510
  top,
@@ -3228,18 +3515,20 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3228
3515
  });
3229
3516
  }
3230
3517
  })));
3231
- const throttleMultipleDrawingUpdate = throttle(this._updateMultipleDrawingDocTransform.bind(this), 50);
3232
- this.disposeWithMe(toDisposable(transformer.changing$.subscribe((state) => {
3518
+ listeners.add(toDisposable(transformer.changeStart$.pipe(switchMap(() => transformer.changing$.pipe(filter(({ objects }) => objects.size > 1), throttleTime(50, void 0, {
3519
+ leading: true,
3520
+ trailing: true
3521
+ }), takeUntil(transformer.changeEnd$)))).subscribe(({ objects }) => this._updateMultipleDrawingDocTransform(objects))));
3522
+ listeners.add(toDisposable(transformer.changing$.subscribe((state) => {
3233
3523
  const { objects, offsetX, offsetY } = state;
3234
- if (objects.size > 1) throttleMultipleDrawingUpdate(objects);
3235
- else if (objects.size === 1) {
3524
+ if (objects.size === 1) {
3236
3525
  const drawingCache = this._transformerCache.values().next().value;
3237
3526
  const { width, height, top, left, angle } = objects.values().next().value;
3238
3527
  if (drawingCache && width === drawingCache.width && height === drawingCache.height && top === drawingCache.top && left === drawingCache.left && angle === drawingCache.angle) return;
3239
3528
  if (drawingCache && drawingCache.drawing.layoutType === PositionedObjectLayoutType.INLINE && offsetX != null && offsetY != null) this._updateInlineDrawingAnchor(drawingCache.drawing, offsetX, offsetY);
3240
3529
  }
3241
3530
  })));
3242
- this.disposeWithMe(toDisposable(transformer.changeEnd$.subscribe((state) => {
3531
+ listeners.add(toDisposable(transformer.changeEnd$.subscribe((state) => {
3243
3532
  const { objects, offsetX, offsetY } = state;
3244
3533
  for (const object of objects.values()) {
3245
3534
  const drawing = this._drawingManagerService.getDrawingOKey(object.oKey);
@@ -3247,7 +3536,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3247
3536
  const drawingCache = this._transformerCache.get(drawing === null || drawing === void 0 ? void 0 : drawing.drawingId);
3248
3537
  if ((drawingCache === null || drawingCache === void 0 ? void 0 : drawingCache.drawing.layoutType) === PositionedObjectLayoutType.INLINE) try {
3249
3538
  object.setOpacity(1);
3250
- } catch (e) {}
3539
+ } catch {}
3251
3540
  }
3252
3541
  if (this._anchorShape) this._anchorShape.hide();
3253
3542
  if (objects.size > 1) this._updateMultipleDrawingDocTransform(objects);
@@ -3263,6 +3552,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3263
3552
  }
3264
3553
  this._transformerCache.clear();
3265
3554
  })));
3555
+ return listeners;
3266
3556
  }
3267
3557
  _updateMultipleDrawingDocTransform(objects) {
3268
3558
  if (objects.size < 1) return;
@@ -3298,20 +3588,37 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3298
3588
  if (oldTop !== top || oldLeft !== left) {
3299
3589
  const verticalDelta = top - oldTop;
3300
3590
  const horizontalDelta = left - oldLeft;
3301
- if (verticalDelta !== 0) drawings.push({
3591
+ const { positionH, positionV } = drawingData.docTransform;
3592
+ let resolvedPosition;
3593
+ const hasHorizontalOffset = positionH.posOffset != null && positionH.align == null;
3594
+ const hasVerticalOffset = positionV.posOffset != null && positionV.align == null;
3595
+ if (!hasHorizontalOffset || !hasVerticalOffset) {
3596
+ var _this$_renderManagerS;
3597
+ const manager = (_this$_renderManagerS = this._renderManagerService.getRenderUnitById(unitId)) === null || _this$_renderManagerS === void 0 ? void 0 : _this$_renderManagerS.with(DocSkeletonManagerService);
3598
+ const skeleton = manager === null || manager === void 0 ? void 0 : manager.getSkeleton().getSkeletonData();
3599
+ const viewModel = manager === null || manager === void 0 ? void 0 : manager.getViewModel();
3600
+ const anchor = skeleton && viewModel ? findDrawingAnchor(unitId, drawing.drawingId, skeleton, viewModel.getEditArea(), drawingData) : null;
3601
+ if (anchor) resolvedPosition = getDrawingWrappingPosition(anchor, drawingData.layoutType, void 0, void 0, {
3602
+ left: horizontalDelta,
3603
+ top: verticalDelta
3604
+ });
3605
+ }
3606
+ const posOffsetV = hasVerticalOffset ? positionV.posOffset + verticalDelta : resolvedPosition === null || resolvedPosition === void 0 ? void 0 : resolvedPosition.positionV.posOffset;
3607
+ const posOffsetH = hasHorizontalOffset ? positionH.posOffset + horizontalDelta : resolvedPosition === null || resolvedPosition === void 0 ? void 0 : resolvedPosition.positionH.posOffset;
3608
+ if (verticalDelta !== 0 && posOffsetV != null) drawings.push({
3302
3609
  drawingId: drawing.drawingId,
3303
3610
  key: "positionV",
3304
3611
  value: {
3305
- relativeFrom: drawingData.docTransform.positionV.relativeFrom,
3306
- posOffset: drawingData.docTransform.positionV.posOffset + verticalDelta
3612
+ relativeFrom: positionV.relativeFrom,
3613
+ posOffset: posOffsetV
3307
3614
  }
3308
3615
  });
3309
- if (horizontalDelta !== 0) drawings.push({
3616
+ if (horizontalDelta !== 0 && posOffsetH != null) drawings.push({
3310
3617
  drawingId: drawing.drawingId,
3311
3618
  key: "positionH",
3312
3619
  value: {
3313
- relativeFrom: drawingData.docTransform.positionH.relativeFrom,
3314
- posOffset: drawingData.docTransform.positionH.posOffset + horizontalDelta
3620
+ relativeFrom: positionH.relativeFrom,
3621
+ posOffset: posOffsetH
3315
3622
  }
3316
3623
  });
3317
3624
  }
@@ -3322,12 +3629,6 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3322
3629
  drawings
3323
3630
  });
3324
3631
  }
3325
- _updateDrawingAnchor(objects) {
3326
- if (this._transformerCache.size !== 1) return;
3327
- const drawingCache = this._transformerCache.values().next().value;
3328
- const object = objects.values().next().value;
3329
- this._getDrawingAnchor(drawingCache.drawing, object);
3330
- }
3331
3632
  _updateInlineDrawingAnchor(drawing, offsetX, offsetY) {
3332
3633
  if (this._transformerCache.size !== 1) return;
3333
3634
  const { contentBoxPointGroup } = this._getInlineDrawingAnchor(drawing, offsetX, offsetY) ?? {};
@@ -3335,7 +3636,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3335
3636
  this._createOrUpdateInlineAnchor(drawing.unitId, contentBoxPointGroup);
3336
3637
  }
3337
3638
  _getInlineDrawingAnchor(drawing, offsetX, offsetY) {
3338
- var _this$_renderManagerS;
3639
+ var _this$_renderManagerS2;
3339
3640
  const currentRender = this._renderManagerService.getRenderUnitById(drawing.unitId);
3340
3641
  const skeleton = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(DocSkeletonManagerService).getSkeleton();
3341
3642
  if (currentRender == null) return;
@@ -3350,7 +3651,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3350
3651
  const HALF = .5;
3351
3652
  const coord = this._getTransformCoordForDocumentOffset(documentComponent, activeViewport, offsetX, offsetY);
3352
3653
  if (coord == null) return;
3353
- const docSelectionRenderService = (_this$_renderManagerS = this._renderManagerService.getRenderUnitById(drawing.unitId)) === null || _this$_renderManagerS === void 0 ? void 0 : _this$_renderManagerS.with(DocSelectionRenderService);
3654
+ const docSelectionRenderService = (_this$_renderManagerS2 = this._renderManagerService.getRenderUnitById(drawing.unitId)) === null || _this$_renderManagerS2 === void 0 ? void 0 : _this$_renderManagerS2.with(DocSelectionRenderService);
3354
3655
  if (docSelectionRenderService == null) return;
3355
3656
  const nodeInfo = skeleton === null || skeleton === void 0 ? void 0 : skeleton.findNodeByCoord(coord, pageLayoutType, pageMarginLeft, pageMarginTop, {
3356
3657
  strict: false,
@@ -3384,7 +3685,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3384
3685
  };
3385
3686
  }
3386
3687
  _getDrawingAnchor(drawing, object) {
3387
- var _this$_renderManagerS2, _glyphAnchor$parent, _column$parent, _column$parent2;
3688
+ var _this$_renderManagerS3, _glyphAnchor$parent, _column$parent, _column$parent2;
3388
3689
  const currentRender = this._renderManagerService.getRenderUnitById(drawing.unitId);
3389
3690
  const skeleton = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(DocSkeletonManagerService).getSkeleton();
3390
3691
  const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
@@ -3415,7 +3716,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3415
3716
  const { x, y } = scene.getViewportScrollXY(activeViewport);
3416
3717
  const coord = this._getTransformCoordForDocumentOffset(documentComponent, activeViewport, left - x, top - y);
3417
3718
  if (coord == null) return;
3418
- const docSelectionRenderService = (_this$_renderManagerS2 = this._renderManagerService.getRenderUnitById(drawing.unitId)) === null || _this$_renderManagerS2 === void 0 ? void 0 : _this$_renderManagerS2.with(DocSelectionRenderService);
3719
+ const docSelectionRenderService = (_this$_renderManagerS3 = this._renderManagerService.getRenderUnitById(drawing.unitId)) === null || _this$_renderManagerS3 === void 0 ? void 0 : _this$_renderManagerS3.with(DocSelectionRenderService);
3419
3720
  if (docSelectionRenderService == null) return;
3420
3721
  const nodeInfo = skeleton === null || skeleton === void 0 ? void 0 : skeleton.findNodeByCoord(coord, pageLayoutType, pageMarginLeft, pageMarginTop, {
3421
3722
  strict: false,
@@ -3726,7 +4027,8 @@ function useDocDrawingPosition(props) {
3726
4027
  const { unitId } = drawings[0];
3727
4028
  const documentDataModel = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
3728
4029
  const documentFlavor = documentDataModel === null || documentDataModel === void 0 ? void 0 : documentDataModel.getSnapshot().documentStyle.documentFlavor;
3729
- const transformer = renderManagerService.getRenderUnitById(unitId).scene.getTransformerByCreate();
4030
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
4031
+ const transformer = renderObject.scene.getTransformerByCreate();
3730
4032
  const HORIZONTAL_RELATIVE_FROM = [
3731
4033
  {
3732
4034
  label: localeService.t("docs-drawing-ui.image-position.column"),
@@ -3773,7 +4075,7 @@ function useDocDrawingPosition(props) {
3773
4075
  });
3774
4076
  const [followTextMove, setFollowTextMove] = useState(true);
3775
4077
  const [showPanel, setShowPanel] = useState(true);
3776
- function handlePositionChange(direction, value) {
4078
+ function handlePositionChange(direction, value, positionH) {
3777
4079
  var _renderManagerService;
3778
4080
  const focusDrawings = drawingManagerService.getFocusDrawings();
3779
4081
  if (focusDrawings.length === 0) return;
@@ -3787,74 +4089,43 @@ function useDocDrawingPosition(props) {
3787
4089
  commandService.executeCommand(UpdateDrawingDocTransformCommand.id, {
3788
4090
  unitId: focusDrawings[0].unitId,
3789
4091
  subUnitId: focusDrawings[0].subUnitId,
3790
- drawings: drawings.map((drawing) => ({
4092
+ drawings: drawings.flatMap((drawing) => [{
3791
4093
  drawingId: drawing.drawingId,
3792
4094
  key: direction,
3793
4095
  value
3794
- }))
4096
+ }, ...positionH ? [{
4097
+ drawingId: drawing.drawingId,
4098
+ key: "positionH",
4099
+ value: positionH
4100
+ }] : []])
3795
4101
  });
3796
4102
  const docSelectionRenderService = (_renderManagerService = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService === void 0 ? void 0 : _renderManagerService.with(DocSelectionRenderService);
3797
4103
  if (docSelectionRenderService) docSelectionRenderService.blur();
3798
4104
  transformer.refreshControls();
3799
4105
  }
4106
+ function getFocusedDrawingAnchor() {
4107
+ var _renderManagerService2, _findDocDrawing;
4108
+ const drawing = drawingManagerService.getFocusDrawings()[0];
4109
+ if (!drawing) return null;
4110
+ const manager = (_renderManagerService2 = renderManagerService.getRenderUnitById(drawing.unitId)) === null || _renderManagerService2 === void 0 ? void 0 : _renderManagerService2.with(DocSkeletonManagerService);
4111
+ const skeleton = manager === null || manager === void 0 ? void 0 : manager.getSkeleton().getSkeletonData();
4112
+ const viewModel = manager === null || manager === void 0 ? void 0 : manager.getViewModel();
4113
+ const snapshot = documentDataModel === null || documentDataModel === void 0 ? void 0 : documentDataModel.getSnapshot();
4114
+ return skeleton && viewModel ? findDrawingAnchor(drawing.unitId, drawing.drawingId, skeleton, viewModel.getEditArea(), snapshot && ((_findDocDrawing = findDocDrawing(snapshot, drawing.drawingId)) === null || _findDocDrawing === void 0 ? void 0 : _findDocDrawing.drawing)) : null;
4115
+ }
3800
4116
  function handleHorizontalRelativeFromChange(value) {
3801
- var _renderManagerService2;
3802
- const prevRelativeFrom = hPosition.relativeFrom;
3803
- const prevPosOffset = hPosition.posOffset;
3804
4117
  const relativeFrom = [
3805
4118
  ObjectRelativeFromH.COLUMN,
3806
4119
  ObjectRelativeFromH.PAGE,
3807
4120
  ObjectRelativeFromH.MARGIN
3808
4121
  ].find((reference) => String(reference) === value);
3809
4122
  if (relativeFrom == null) return;
3810
- if (prevRelativeFrom === relativeFrom) return;
3811
- const focusDrawings = drawingManagerService.getFocusDrawings();
3812
- if (focusDrawings.length === 0) return;
3813
- const drawingId = focusDrawings[0].drawingId;
3814
- const unitId = focusDrawings[0].unitId;
3815
- let drawing = null;
3816
- let pageMarginLeft = 0;
3817
- const skeleton = (_renderManagerService2 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService2 === void 0 ? void 0 : _renderManagerService2.with(DocSkeletonManagerService).getSkeleton();
3818
- const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
3819
- if (skeletonData == null) return;
3820
- const { pages, skeHeaders, skeFooters } = skeletonData;
3821
- for (const page of pages) {
3822
- var _skeHeaders$get, _skeFooters$get;
3823
- const { marginLeft, skeDrawings, headerId, footerId, pageWidth } = page;
3824
- if (skeDrawings.has(drawingId)) {
3825
- drawing = skeDrawings.get(drawingId);
3826
- pageMarginLeft = marginLeft;
3827
- break;
3828
- }
3829
- const headerPage = (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(page.headerLayoutKey ?? pageWidth);
3830
- if (headerPage === null || headerPage === void 0 ? void 0 : headerPage.skeDrawings.has(drawingId)) {
3831
- drawing = headerPage === null || headerPage === void 0 ? void 0 : headerPage.skeDrawings.get(drawingId);
3832
- pageMarginLeft = marginLeft;
3833
- break;
3834
- }
3835
- const footerPage = (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(page.footerLayoutKey ?? pageWidth);
3836
- if (footerPage === null || footerPage === void 0 ? void 0 : footerPage.skeDrawings.has(drawingId)) {
3837
- drawing = footerPage === null || footerPage === void 0 ? void 0 : footerPage.skeDrawings.get(drawingId);
3838
- pageMarginLeft = marginLeft;
3839
- break;
3840
- }
3841
- }
3842
- if (drawing == null) return;
3843
- let delta = 0;
3844
- if (prevRelativeFrom === ObjectRelativeFromH.COLUMN) delta -= drawing.columnLeft;
3845
- else if (prevRelativeFrom === ObjectRelativeFromH.MARGIN) delta -= pageMarginLeft;
3846
- if (relativeFrom === ObjectRelativeFromH.COLUMN) delta += drawing.columnLeft;
3847
- else if (relativeFrom === ObjectRelativeFromH.MARGIN) delta += pageMarginLeft;
3848
- else if (relativeFrom === ObjectRelativeFromH.PAGE) {}
3849
- handlePositionChange("positionH", {
3850
- relativeFrom,
3851
- posOffset: (prevPosOffset ?? 0) - delta
3852
- });
4123
+ if (hPosition.relativeFrom === relativeFrom) return;
4124
+ const anchor = getFocusedDrawingAnchor();
4125
+ if (!anchor) return;
4126
+ handlePositionChange("positionH", getDrawingWrappingPosition(anchor, anchor.skeDrawing.drawingOrigin.layoutType, relativeFrom).positionH);
3853
4127
  }
3854
4128
  function handleVerticalRelativeFromChange(value) {
3855
- var _renderManagerService3, _renderManagerService4, _documentDataModel$ge, _glyph$parent, _column$parent;
3856
- const prevRelativeFrom = vPosition.relativeFrom;
3857
- const prevPosOffset = vPosition.posOffset;
3858
4129
  const relativeFrom = [
3859
4130
  ObjectRelativeFromV.LINE,
3860
4131
  ObjectRelativeFromV.PAGE,
@@ -3862,44 +4133,22 @@ function useDocDrawingPosition(props) {
3862
4133
  ObjectRelativeFromV.PARAGRAPH
3863
4134
  ].find((reference) => String(reference) === value);
3864
4135
  if (relativeFrom == null) return;
3865
- if (prevRelativeFrom === relativeFrom) return;
3866
- const focusDrawings = drawingManagerService.getFocusDrawings();
3867
- if (focusDrawings.length === 0) return;
3868
- const { drawingId, unitId } = focusDrawings[0];
3869
- const documentDataModel = univerInstanceService.getUnit(unitId, UniverInstanceType.UNIVER_DOC);
3870
- const skeleton = (_renderManagerService3 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService3 === void 0 ? void 0 : _renderManagerService3.with(DocSkeletonManagerService).getSkeleton();
3871
- const docSelectionRenderService = (_renderManagerService4 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService4 === void 0 ? void 0 : _renderManagerService4.with(DocSelectionRenderService);
3872
- const segmentId = docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.getSegment();
3873
- const segmentPage = docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.getSegmentPage();
3874
- const drawing = documentDataModel === null || documentDataModel === void 0 || (_documentDataModel$ge = documentDataModel.getSelfOrHeaderFooterModel(segmentId)) === null || _documentDataModel$ge === void 0 || (_documentDataModel$ge = _documentDataModel$ge.getBody()) === null || _documentDataModel$ge === void 0 || (_documentDataModel$ge = _documentDataModel$ge.customBlocks) === null || _documentDataModel$ge === void 0 ? void 0 : _documentDataModel$ge.find((c) => c.blockId === drawingId);
3875
- if (drawing == null || skeleton == null || docSelectionRenderService == null) return;
3876
- const { startIndex } = drawing;
3877
- const glyph = skeleton.findNodeByCharIndex(startIndex, segmentId, segmentPage);
3878
- const line = glyph === null || glyph === void 0 || (_glyph$parent = glyph.parent) === null || _glyph$parent === void 0 ? void 0 : _glyph$parent.parent;
3879
- const column = line === null || line === void 0 ? void 0 : line.parent;
3880
- const paragraphStartLine = column === null || column === void 0 ? void 0 : column.lines.find((l) => l.paragraphIndex === (line === null || line === void 0 ? void 0 : line.paragraphIndex) && l.paragraphStart);
3881
- const page = column === null || column === void 0 || (_column$parent = column.parent) === null || _column$parent === void 0 ? void 0 : _column$parent.parent;
3882
- if (glyph == null || line == null || paragraphStartLine == null || column == null || page == null) return;
3883
- let delta = 0;
3884
- if (prevRelativeFrom === ObjectRelativeFromV.PARAGRAPH) delta -= paragraphStartLine.top;
3885
- else if (prevRelativeFrom === ObjectRelativeFromV.LINE) delta -= line.top;
3886
- else if (prevRelativeFrom === ObjectRelativeFromV.PAGE) delta += page.marginTop;
3887
- if (relativeFrom === ObjectRelativeFromV.PARAGRAPH) delta += paragraphStartLine.top;
3888
- else if (relativeFrom === ObjectRelativeFromV.LINE) delta += line.top;
3889
- else if (relativeFrom === ObjectRelativeFromV.PAGE) delta -= page.marginTop;
3890
- handlePositionChange("positionV", {
3891
- relativeFrom,
3892
- posOffset: (prevPosOffset ?? 0) - delta
3893
- });
4136
+ if (vPosition.relativeFrom === relativeFrom) return;
4137
+ const anchor = getFocusedDrawingAnchor();
4138
+ if (!anchor) return;
4139
+ const initialPosition = getDrawingWrappingPosition(anchor, anchor.skeDrawing.drawingOrigin.layoutType, void 0, relativeFrom);
4140
+ const position = documentDataModel ? resolveDrawingWrappingPosition(anchor, initialPosition, documentDataModel.getSnapshot(), localeService, renderObject.with(DocSkeletonManagerService).getViewModel().getEditArea()) : initialPosition;
4141
+ if (!position) return;
4142
+ handlePositionChange("positionV", position.positionV, position.positionH);
3894
4143
  }
3895
4144
  function handleFollowTextMoveCheck(val) {
3896
4145
  handleVerticalRelativeFromChange(val ? String(ObjectRelativeFromV.PARAGRAPH) : String(ObjectRelativeFromV.PAGE));
3897
4146
  }
3898
4147
  useEffect(() => {
3899
4148
  function updateState(drawingParam) {
3900
- var _snapshot$drawings;
4149
+ var _findDocDrawing2;
3901
4150
  const snapshot = documentDataModel === null || documentDataModel === void 0 ? void 0 : documentDataModel.getSnapshot();
3902
- const drawing = snapshot === null || snapshot === void 0 || (_snapshot$drawings = snapshot.drawings) === null || _snapshot$drawings === void 0 ? void 0 : _snapshot$drawings[drawingParam.drawingId];
4151
+ const drawing = snapshot && ((_findDocDrawing2 = findDocDrawing(snapshot, drawingParam.drawingId)) === null || _findDocDrawing2 === void 0 ? void 0 : _findDocDrawing2.drawing);
3903
4152
  if (drawing == null) return;
3904
4153
  const { layoutType } = drawing;
3905
4154
  const { positionH, positionV } = drawing.docTransform;
@@ -5222,6 +5471,105 @@ let ComponentsController = class ComponentsController extends Disposable {
5222
5471
  };
5223
5472
  ComponentsController = __decorate([__decorateParam(0, Inject(ComponentManager))], ComponentsController);
5224
5473
 
5474
+ //#endregion
5475
+ //#region src/controllers/render-controllers/doc-drawing-anchor.render-controller.ts
5476
+ const ANCHOR_PATH = "M 8 4 C 9.104 4 10 3.104 10 2 C 10 0.896 9.104 0 8 0 C 6.896 0 6 0.896 6 2 C 6 3.104 6.896 4 8 4 Z M 8 4 L 8 16 M 5 7.2 L 11 7.2 M 1 9.5 L 1 10.5 C 1 13.5 4.25 16 8 16 C 11.75 16 15 13.5 15 10.5 L 15 9.5 M 1 9.5 L 3.25 11 M 15 9.5 L 12.75 11";
5477
+ let DocDrawingAnchorRenderController = class DocDrawingAnchorRenderController extends Disposable {
5478
+ constructor(_context, drawingManager, _skeletonManager, _selectionRender, _themeService) {
5479
+ super();
5480
+ this._context = _context;
5481
+ this._skeletonManager = _skeletonManager;
5482
+ this._selectionRender = _selectionRender;
5483
+ this._themeService = _themeService;
5484
+ _defineProperty(this, "_stroke", "");
5485
+ _defineProperty(this, "_focused", []);
5486
+ _defineProperty(this, "_markers", /* @__PURE__ */ new Map());
5487
+ this.disposeWithMe(drawingManager.focus$.subscribe((drawings) => {
5488
+ this._focused = (drawings ?? []).filter((drawing) => drawing.unitId === this._context.unitId);
5489
+ this._updateMarkers();
5490
+ }));
5491
+ this.disposeWithMe(this._context.scene.beforeRender$.subscribe(() => this._updateMarkers()));
5492
+ this.disposeWithMe(this._themeService.currentTheme$.subscribe(() => {
5493
+ this._stroke = this._themeService.getColorFromTheme("gray.500");
5494
+ this._updateMarkers();
5495
+ }));
5496
+ this.disposeWithMe({ dispose: () => {
5497
+ this._markers.forEach((marker) => marker.dispose());
5498
+ this._markers.clear();
5499
+ } });
5500
+ }
5501
+ _updateMarkers() {
5502
+ const { scene, unit, mainComponent } = this._context;
5503
+ const snapshot = unit.getSnapshot();
5504
+ const skeleton = this._skeletonManager.getSkeleton();
5505
+ const active = /* @__PURE__ */ new Set();
5506
+ const document = mainComponent;
5507
+ if (skeleton && document) {
5508
+ const config = document.getOffsetConfig();
5509
+ const converter = new NodePositionConvertToCursor(config, skeleton);
5510
+ const scale = scene.getAncestorScale();
5511
+ for (const { drawingId } of this._focused) {
5512
+ var _findDocDrawing, _glyph$parent, _line$parent, _startLine$divides$;
5513
+ const drawing = (_findDocDrawing = findDocDrawing(snapshot, drawingId)) === null || _findDocDrawing === void 0 ? void 0 : _findDocDrawing.drawing;
5514
+ const anchor = findDrawingTextAnchor(snapshot, drawingId);
5515
+ if (!drawing || drawing.layoutType === PositionedObjectLayoutType.INLINE || !anchor) continue;
5516
+ if (anchor.segmentId !== this._selectionRender.getSegment()) continue;
5517
+ const position = skeleton.findNodePositionByCharIndex(anchor.offset, true, anchor.segmentId, this._selectionRender.getSegmentPage());
5518
+ const glyph = skeleton.findGlyphByPosition(position);
5519
+ const line = glyph === null || glyph === void 0 || (_glyph$parent = glyph.parent) === null || _glyph$parent === void 0 ? void 0 : _glyph$parent.parent;
5520
+ const startLine = (line === null || line === void 0 || (_line$parent = line.parent) === null || _line$parent === void 0 ? void 0 : _line$parent.lines.find((item) => item.paragraphIndex === line.paragraphIndex && item.paragraphStart)) ?? line;
5521
+ const startGlyph = startLine === null || startLine === void 0 || (_startLine$divides$ = startLine.divides[0]) === null || _startLine$divides$ === void 0 ? void 0 : _startLine$divides$.glyphGroup[0];
5522
+ const paragraphPosition = startGlyph && skeleton.findPositionByGlyph(startGlyph, this._selectionRender.getSegmentPage());
5523
+ if (!paragraphPosition) continue;
5524
+ const caret = {
5525
+ ...paragraphPosition,
5526
+ isBack: true
5527
+ };
5528
+ const { contentBoxPointGroup } = converter.getRangePointData(caret, caret);
5529
+ if (!contentBoxPointGroup.length) continue;
5530
+ const bounds = getAnchorBounding(contentBoxPointGroup);
5531
+ const left = config.docsLeft + bounds.left - 22 / scale.scaleX;
5532
+ const top = config.docsTop + bounds.top;
5533
+ let marker = this._markers.get(drawingId);
5534
+ const stroke = this._stroke;
5535
+ if (!marker) {
5536
+ marker = new Path(`__DocDrawingAnchor__${drawingId}`, {
5537
+ data: ANCHOR_PATH,
5538
+ width: 14,
5539
+ height: 16,
5540
+ stroke,
5541
+ strokeWidth: 1.25,
5542
+ strokeLineCap: "round",
5543
+ strokeLineJoin: "round",
5544
+ evented: false,
5545
+ debounceParentDirty: false
5546
+ });
5547
+ this._markers.set(drawingId, marker);
5548
+ scene.addObject(marker, TEXT_RANGE_LAYER_INDEX);
5549
+ }
5550
+ if (marker.left !== left || marker.top !== top || marker.scaleX !== 1 / scale.scaleX || marker.scaleY !== 1 / scale.scaleY) marker.transformByState({
5551
+ left,
5552
+ top,
5553
+ scaleX: 1 / scale.scaleX,
5554
+ scaleY: 1 / scale.scaleY
5555
+ });
5556
+ if (marker.stroke !== stroke) marker.setProps({ stroke });
5557
+ active.add(drawingId);
5558
+ }
5559
+ }
5560
+ for (const [id, marker] of this._markers) if (!active.has(id)) {
5561
+ marker.dispose();
5562
+ this._markers.delete(id);
5563
+ }
5564
+ }
5565
+ };
5566
+ DocDrawingAnchorRenderController = __decorate([
5567
+ __decorateParam(1, IDrawingManagerService),
5568
+ __decorateParam(2, Inject(DocSkeletonManagerService)),
5569
+ __decorateParam(3, Inject(DocSelectionRenderService)),
5570
+ __decorateParam(4, Inject(ThemeService))
5571
+ ], DocDrawingAnchorRenderController);
5572
+
5225
5573
  //#endregion
5226
5574
  //#region src/controllers/shortcuts/drawing.shortcut.ts
5227
5575
  function whenDocDrawingFocused(contextService) {
@@ -5701,7 +6049,11 @@ let UniverDocsDrawingUIPlugin = class UniverDocsDrawingUIPlugin extends Plugin {
5701
6049
  this._injector.get(ComponentsController);
5702
6050
  }
5703
6051
  onReady() {
5704
- [[DocDrawingUpdateRenderController], [DocDrawingTransformUpdateController]].forEach((m) => this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m));
6052
+ [
6053
+ [DocDrawingUpdateRenderController],
6054
+ [DocDrawingTransformUpdateController],
6055
+ [DocDrawingAnchorRenderController]
6056
+ ].forEach((m) => this._renderManagerSrv.registerRenderModule(UniverInstanceType.UNIVER_DOC, m));
5705
6057
  this._injector.get(DocDrawingAddRemoveController);
5706
6058
  this._injector.get(DocDrawingUIController);
5707
6059
  this._injector.get(DocDrawingTransformerController);