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