@univerjs/docs-drawing-ui 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/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,14 +1072,14 @@ 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;
1035
1079
  const bodyAnchor = findDrawingAnchorInPage(page, drawingId, page.marginTop, page.marginLeft);
1036
- 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.pageWidth);
1080
+ 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);
1037
1081
  const headerAnchor = header == null ? null : findDrawingAnchorInPage(header, drawingId, header.marginTop, page.marginLeft);
1038
- 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.pageWidth);
1082
+ 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);
1039
1083
  const footerTop = footer == null ? 0 : page.pageHeight - page.marginBottom + footer.marginTop;
1040
1084
  const footerAnchor = footer == null ? null : findDrawingAnchorInPage(footer, drawingId, footerTop, page.marginLeft);
1041
1085
  const anchor = bodyAnchor ?? headerAnchor ?? footerAnchor;
@@ -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.3";
1809
+ var version = "1.1.0";
1766
1810
 
1767
1811
  //#endregion
1768
1812
  //#region src/config/config.ts
@@ -1787,1346 +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;
1851
- this._initialize();
1852
- }
1853
- _initialize() {
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());
2047
+ this._initialize();
1854
2048
  this._commandExecutedListener();
2049
+ this.disposeWithMe((0, _univerjs_core.toDisposable)(() => this._clearPendingMultiDrawingSelection()));
1855
2050
  }
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
- }
2051
+ _initialize() {
2052
+ this._initialRenderRefresh();
2053
+ this._drawingInitializeListener();
2054
+ this._initTransformRefresh();
2055
+ }
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(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(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) renderedDrawings[drawingId] = { ...current };
2058
- else delete renderedDrawings[drawingId];
2059
- }
2060
- this._docDrawingService.setDrawingData(unitId, unitId, drawingData);
2061
- this._drawingManagerService.setDrawingData(unitId, unitId, renderedDrawings);
2062
- if (orderChanged) {
2063
- this._docDrawingService.setDrawingOrder(unitId, unitId, drawingsOrder);
2064
- this._drawingManagerService.setDrawingOrder(unitId, unitId, (0, _univerjs_docs_drawing.getDocDrawingRenderOrder)(drawingsOrder, drawings));
2065
- }
2066
- 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) => ({
2067
2215
  unitId,
2068
2216
  subUnitId: unitId,
2069
- 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
2070
2224
  }));
2071
- if (objects.length === 0) return;
2072
- if (hierarchyChanged) this._drawingManagerService.addNotification(Object.values(renderedDrawings));
2073
- this._docDrawingService.updateNotification(objects);
2074
- this._drawingManagerService.updateNotification(objects);
2075
- }
2076
- };
2077
- DocDrawingAddRemoveController = __decorate([
2078
- __decorateParam(0, _univerjs_core.IUniverInstanceService),
2079
- __decorateParam(1, _univerjs_core.ICommandService),
2080
- __decorateParam(2, _univerjs_drawing.IDrawingManagerService),
2081
- __decorateParam(3, _univerjs_docs_drawing.IDocDrawingService),
2082
- __decorateParam(4, _univerjs_engine_render.IRenderManagerService),
2083
- __decorateParam(5, (0, _univerjs_core.Inject)(DocRefreshDrawingsService))
2084
- ], DocDrawingAddRemoveController);
2085
-
2086
- //#endregion
2087
- //#region src/views/DocPrintingFloatDom.tsx
2088
- const DocPrintingFloatDom = (props) => {
2089
- const { floatDomInfos, scene, offset, bound } = props;
2090
- const width = bound.right - bound.left;
2091
- const height = bound.bottom - bound.top;
2092
- const floatDomParams = (0, react.useMemo)(() => floatDomInfos.map((info) => {
2093
- const { width = 0, height = 0, left = 0, top = 0 } = info.transform;
2094
- const domPos = calcDocFloatDomPositionByRect({
2095
- left,
2096
- right: left + width,
2097
- top,
2098
- bottom: top + height
2099
- }, scene);
2100
- const floatDom = {
2101
- position$: new rxjs.BehaviorSubject(domPos),
2102
- position: domPos,
2103
- id: info.drawingId,
2104
- componentKey: info.componentKey,
2105
- onPointerMove: () => {},
2106
- onPointerDown: () => {},
2107
- onPointerUp: () => {},
2108
- onWheel: () => {},
2109
- unitId: info.unitId,
2110
- data: info.data
2111
- };
2112
- return [info.drawingId, floatDom];
2113
- }).filter(([_, floatDom]) => !(floatDom.position.endX < 0 || floatDom.position.endY < 0 || floatDom.position.startX > width || floatDom.position.startY > height)), [
2114
- floatDomInfos,
2115
- scene,
2116
- offset,
2117
- width,
2118
- height
2119
- ]);
2120
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
2121
- className: "univer-absolute univer-left-0 univer-top-0",
2122
- children: floatDomParams.map(([id, floatDom]) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_univerjs_ui.PrintFloatDomSingle, {
2123
- layer: floatDom,
2124
- id,
2125
- position: floatDom.position
2126
- }, id))
2127
- });
2128
- };
2129
- function mountDocPrintingFloatDom(props, root, injector) {
2130
- const PrintingFloatDomInjector = (0, _univerjs_ui.connectInjector)(DocPrintingFloatDom, injector);
2131
- (0, _univerjs_design.render)(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(PrintingFloatDomInjector, { ...props }), root);
2132
- return () => (0, _univerjs_design.unmount)(root);
2133
- }
2134
-
2135
- //#endregion
2136
- //#region src/controllers/doc-drawing-printing.controller.ts
2137
- let DocDrawingPrintingController = class DocDrawingPrintingController extends _univerjs_core.Disposable {
2138
- constructor(_docPrintInterceptorService, _drawingRenderService, _drawingManagerService, _componetManager, _injector) {
2139
- super();
2140
- this._docPrintInterceptorService = _docPrintInterceptorService;
2141
- this._drawingRenderService = _drawingRenderService;
2142
- this._drawingManagerService = _drawingManagerService;
2143
- this._componetManager = _componetManager;
2144
- this._injector = _injector;
2145
- this._initPrinting();
2146
- this._initPrintingDom();
2147
- }
2148
- _initPrinting() {
2149
- this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_COMPONENT_COLLECT, { handler: (_param, pos, next) => {
2150
- const { unitId, scene, skeleton, pageIndex } = pos;
2151
- const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);
2152
- const subUnitData = unitData === null || unitData === void 0 ? void 0 : unitData[unitId];
2153
- const visibleDrawingIds = this._docPrintInterceptorService.getPageDrawingIds(skeleton, pageIndex);
2154
- if (subUnitData) subUnitData.order.forEach((id) => {
2155
- if (visibleDrawingIds && !visibleDrawingIds.has(id)) return;
2156
- const drawing = subUnitData.data[id];
2157
- if (drawing.drawingType !== _univerjs_core.DrawingTypeEnum.DRAWING_CHART && drawing.drawingType !== _univerjs_core.DrawingTypeEnum.DRAWING_DOM) this._drawingRenderService.renderDrawing(drawing, scene);
2158
- });
2159
- return next();
2160
- } }));
2161
2225
  }
2162
- _initPrintingDom() {
2163
- this.disposeWithMe(this._docPrintInterceptorService.interceptor.intercept(this._docPrintInterceptorService.interceptor.getInterceptPoints().PRINTING_DOM_COLLECT, { handler: (disposableCollection, pos, next) => {
2164
- const { unitId, skeleton, pageIndex } = pos;
2165
- const unitData = this._drawingManagerService.getDrawingDataForUnit(unitId);
2166
- const subUnitData = unitData === null || unitData === void 0 ? void 0 : unitData[unitId];
2167
- const visibleDrawingIds = this._docPrintInterceptorService.getPageDrawingIds(skeleton, pageIndex);
2168
- if (subUnitData) {
2169
- const floatDomInfos = subUnitData.order.filter((id) => !visibleDrawingIds || visibleDrawingIds.has(id)).map((id) => {
2170
- const drawing = subUnitData.data[id];
2171
- if (drawing.drawingType === _univerjs_core.DrawingTypeEnum.DRAWING_CHART) return {
2172
- ...drawing,
2173
- componentKey: this._componetManager.get(_univerjs_core.DOC_DRAWING_PRINTING_COMPONENT_KEY)
2174
- };
2175
- if (drawing.drawingType === _univerjs_core.DrawingTypeEnum.DRAWING_DOM) {
2176
- const printingComponentKey = this._docPrintInterceptorService.getPrintComponent(drawing.componentKey);
2177
- return {
2178
- ...drawing,
2179
- componentKey: this._componetManager.get(printingComponentKey || drawing.componentKey)
2180
- };
2181
- }
2182
- return null;
2183
- }).filter(Boolean);
2184
- const unmountPrintingFloatDom = mountDocPrintingFloatDom({
2185
- unitId,
2186
- floatDomInfos,
2187
- scene: pos.scene,
2188
- skeleton: pos.skeleton,
2189
- offset: pos.offset,
2190
- bound: pos.bound
2191
- }, pos.root, this._injector);
2192
- disposableCollection === null || disposableCollection === void 0 || disposableCollection.add(() => {
2193
- unmountPrintingFloatDom();
2194
- });
2195
- 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();
2196
2244
  }
2197
- } }));
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
+ }));
2198
2299
  }
2199
- };
2200
- DocDrawingPrintingController = __decorate([
2201
- __decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_docs_ui.DocPrintInterceptorService)),
2202
- __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_drawing_ui.DrawingRenderService)),
2203
- __decorateParam(2, _univerjs_drawing.IDrawingManagerService),
2204
- __decorateParam(3, (0, _univerjs_core.Inject)(_univerjs_ui.ComponentManager)),
2205
- __decorateParam(4, (0, _univerjs_core.Inject)(_univerjs_core.Injector))
2206
- ], DocDrawingPrintingController);
2207
-
2208
- //#endregion
2209
- //#region src/commands/commands/update-doc-drawing.command.ts
2210
- function getDeleteAndInsertCustomBlockActions(segmentId, oldSegmentId, segmentPage, offset, drawingId, documentDataModel, docSelectionRenderManager) {
2211
- var _documentDataModel$ge, _documentDataModel$ge2, _oldBody$customBlocks;
2212
- const textX = new _univerjs_core.TextX();
2213
- const jsonX = _univerjs_core.JSONX.getInstance();
2214
- const rawActions = [];
2215
- const oldBody = (_documentDataModel$ge = documentDataModel.getSelfOrHeaderFooterModel(oldSegmentId)) === null || _documentDataModel$ge === void 0 ? void 0 : _documentDataModel$ge.getBody();
2216
- const body = (_documentDataModel$ge2 = documentDataModel.getSelfOrHeaderFooterModel(segmentId)) === null || _documentDataModel$ge2 === void 0 ? void 0 : _documentDataModel$ge2.getBody();
2217
- if (oldBody == null || body == null) return;
2218
- 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;
2219
- if (oldOffset == null) return;
2220
- offset = Math.min(body.dataStream.length - 2, offset);
2221
- if (segmentId === oldSegmentId) {
2222
- if (offset < oldOffset) {
2223
- if (offset > 0) textX.push({
2224
- t: _univerjs_core.TextXActionType.RETAIN,
2225
- len: offset
2226
- });
2227
- textX.push({
2228
- t: _univerjs_core.TextXActionType.INSERT,
2229
- body: {
2230
- dataStream: "\b",
2231
- customBlocks: [{
2232
- startIndex: 0,
2233
- blockId: drawingId
2234
- }]
2235
- },
2236
- len: 1
2237
- });
2238
- textX.push({
2239
- t: _univerjs_core.TextXActionType.RETAIN,
2240
- len: oldOffset - offset
2241
- });
2242
- textX.push({
2243
- t: _univerjs_core.TextXActionType.DELETE,
2244
- len: 1
2245
- });
2246
- } else {
2247
- if (oldOffset > 0) textX.push({
2248
- t: _univerjs_core.TextXActionType.RETAIN,
2249
- len: oldOffset
2250
- });
2251
- textX.push({
2252
- t: _univerjs_core.TextXActionType.DELETE,
2253
- len: 1
2254
- });
2255
- if (offset - oldOffset - 1 > 0) textX.push({
2256
- t: _univerjs_core.TextXActionType.RETAIN,
2257
- len: offset - oldOffset - 1
2258
- });
2259
- textX.push({
2260
- t: _univerjs_core.TextXActionType.INSERT,
2261
- body: {
2262
- dataStream: "\b",
2263
- customBlocks: [{
2264
- startIndex: 0,
2265
- blockId: drawingId
2266
- }]
2267
- },
2268
- len: 1
2269
- });
2270
- }
2271
- if (offset !== oldOffset) {
2272
- const path = (0, _univerjs_core.getRichTextEditPath)(documentDataModel, oldSegmentId);
2273
- const action = jsonX.editOp(textX.serialize(), path);
2274
- rawActions.push(action);
2275
- }
2276
- } else {
2277
- if (oldOffset > 0) textX.push({
2278
- t: _univerjs_core.TextXActionType.RETAIN,
2279
- 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
2280
2307
  });
2281
- textX.push({
2282
- t: _univerjs_core.TextXActionType.DELETE,
2283
- 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
2284
2325
  });
2285
- let path = (0, _univerjs_core.getRichTextEditPath)(documentDataModel, oldSegmentId);
2286
- let action = jsonX.editOp(textX.serialize(), path);
2287
- rawActions.push(action);
2288
- textX.empty();
2289
- if (offset > 0) textX.push({
2290
- t: _univerjs_core.TextXActionType.RETAIN,
2291
- 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
2292
2341
  });
2293
- textX.push({
2294
- t: _univerjs_core.TextXActionType.INSERT,
2295
- body: {
2296
- dataStream: "\b",
2297
- customBlocks: [{
2298
- startIndex: 0,
2299
- blockId: drawingId
2300
- }]
2342
+ const { isMultiTransform = _univerjs_core.BooleanNumber.FALSE } = runtimeDrawing;
2343
+ const clipPage = getDocsDrawingClipPage({
2344
+ drawing: {
2345
+ behindText,
2346
+ transform: {
2347
+ width,
2348
+ height
2349
+ }
2301
2350
  },
2302
- len: 1
2351
+ hostPage: context.hostPage,
2352
+ page: context.page
2303
2353
  });
2304
- path = (0, _univerjs_core.getRichTextEditPath)(documentDataModel, segmentId);
2305
- action = jsonX.editOp(textX.serialize(), path);
2306
- rawActions.push(action);
2307
- docSelectionRenderManager.setSegment(segmentId);
2308
- docSelectionRenderManager.setSegmentPage(segmentPage);
2309
- }
2310
- return rawActions;
2311
- }
2312
- /**
2313
- * The command to update drawing wrap text.
2314
- */
2315
- const UpdateDocDrawingDistanceCommand = {
2316
- id: "doc.command.update-doc-drawing-distance",
2317
- type: _univerjs_core.CommandType.COMMAND,
2318
- handler: (accessor, params) => {
2319
- if (params == null) return false;
2320
- const commandService = accessor.get(_univerjs_core.ICommandService);
2321
- const univerInstanceService = accessor.get(_univerjs_core.IUniverInstanceService);
2322
- const { drawings, dist, unitId } = params;
2323
- const documentDataModel = univerInstanceService.getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
2324
- if (documentDataModel == null) return false;
2325
- const jsonX = _univerjs_core.JSONX.getInstance();
2326
- const rawActions = [];
2327
- const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
2328
- for (const drawing of drawings) {
2329
- const { drawingId } = drawing;
2330
- for (const [key, value] of Object.entries(dist)) {
2331
- const oldValue = oldDrawings[drawingId][key];
2332
- if (oldValue !== value) {
2333
- const action = jsonX.replaceOp([
2334
- "drawings",
2335
- drawingId,
2336
- key
2337
- ], oldValue, value);
2338
- rawActions.push(action);
2339
- }
2340
- }
2341
- }
2342
- const doMutation = {
2343
- id: _univerjs_docs.RichTextEditingMutation.id,
2344
- params: {
2345
- unitId,
2346
- actions: [],
2347
- textRanges: null
2348
- }
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
2349
2390
  };
2350
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2351
- return _univerjs_core.JSONX.compose(acc, cur);
2352
- }, null);
2353
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2354
- return Boolean(result);
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]));
2355
2403
  }
2356
- };
2357
- /**
2358
- * The command to update drawing wrap text.
2359
- */
2360
- const UpdateDocDrawingWrapTextCommand = {
2361
- id: "doc.command.update-doc-drawing-wrap-text",
2362
- type: _univerjs_core.CommandType.COMMAND,
2363
- handler: (accessor, params) => {
2364
- if (params == null) return false;
2365
- const commandService = accessor.get(_univerjs_core.ICommandService);
2366
- const univerInstanceService = accessor.get(_univerjs_core.IUniverInstanceService);
2367
- const { drawings, wrapText, unitId } = params;
2368
- const documentDataModel = univerInstanceService.getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
2369
- if (documentDataModel == null) return false;
2370
- const jsonX = _univerjs_core.JSONX.getInstance();
2371
- const rawActions = [];
2372
- const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
2373
- for (const drawing of drawings) {
2374
- const { drawingId } = drawing;
2375
- const oldWrapText = oldDrawings[drawingId].wrapText;
2376
- if (oldWrapText !== wrapText) {
2377
- const action = jsonX.replaceOp([
2378
- "drawings",
2379
- drawingId,
2380
- "wrapText"
2381
- ], oldWrapText, wrapText);
2382
- rawActions.push(action);
2383
- }
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);
2384
2430
  }
2385
- const doMutation = {
2386
- id: _univerjs_docs.RichTextEditingMutation.id,
2387
- params: {
2388
- unitId,
2389
- actions: [],
2390
- textRanges: null
2391
- }
2431
+ }
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);
2392
2475
  };
2393
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2394
- return _univerjs_core.JSONX.compose(acc, cur);
2395
- }, null);
2396
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2397
- 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));
2398
2480
  }
2399
2481
  };
2400
- /**
2401
- * The command to move inline drawing.
2402
- */
2403
- const IMoveInlineDrawingCommand = {
2404
- id: "doc.command.move-inline-drawing",
2405
- type: _univerjs_core.CommandType.COMMAND,
2406
- handler: (accessor, params) => {
2407
- var _renderManagerService;
2408
- if (params == null) return false;
2409
- const { drawing, unitId, offset, segmentId: newSegmentId, segmentPage, needRefreshDrawings } = params;
2410
- const renderManagerService = accessor.get(_univerjs_engine_render.IRenderManagerService);
2411
- const docSelectionRenderService = (_renderManagerService = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService === void 0 ? void 0 : _renderManagerService.with(_univerjs_docs_ui.DocSelectionRenderService);
2412
- const docRefreshDrawingsService = accessor.get(DocRefreshDrawingsService);
2413
- const renderObject = renderManagerService.getRenderUnitById(unitId);
2414
- const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
2415
- const skeleton = renderObject === null || renderObject === void 0 ? void 0 : renderObject.with(_univerjs_docs.DocSkeletonManagerService).getSkeleton();
2416
- if (scene == null || docSelectionRenderService == null) return false;
2417
- const transformer = scene.getTransformerByCreate();
2418
- const commandService = accessor.get(_univerjs_core.ICommandService);
2419
- const documentDataModel = accessor.get(_univerjs_core.IUniverInstanceService).getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
2420
- if (documentDataModel == null) return false;
2421
- if (needRefreshDrawings) {
2422
- docRefreshDrawingsService.refreshDrawings(skeleton);
2423
- transformer.refreshControls();
2424
- 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;
2425
2513
  }
2426
- const rawActions = [];
2427
- const { drawingId } = drawing;
2428
- const actions = getDeleteAndInsertCustomBlockActions(newSegmentId, docSelectionRenderService.getSegment() ?? "", segmentPage, offset, drawingId, documentDataModel, docSelectionRenderService);
2429
- if (actions == null || actions.length === 0) {
2430
- docRefreshDrawingsService.refreshDrawings(skeleton);
2431
- transformer.refreshControls();
2432
- 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;
2433
2517
  }
2434
- rawActions.push(...actions);
2435
- const doMutation = {
2436
- id: _univerjs_docs.RichTextEditingMutation.id,
2437
- params: {
2438
- unitId,
2439
- actions: [],
2440
- textRanges: null
2441
- }
2442
- };
2443
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2444
- return _univerjs_core.JSONX.compose(acc, cur);
2445
- }, null);
2446
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2447
- transformer.refreshControls();
2448
- return Boolean(result);
2518
+ return null;
2449
2519
  }
2450
- };
2451
- /**
2452
- * The command to transform non-inline drawing.
2453
- */
2454
- const ITransformNonInlineDrawingCommand = {
2455
- id: "doc.command.transform-non-inline-drawing",
2456
- type: _univerjs_core.CommandType.COMMAND,
2457
- handler: (accessor, params) => {
2458
- var _renderManagerService2;
2459
- if (params == null) return false;
2460
- const { drawing, unitId, offset, docTransform, segmentId: newSegmentId, segmentPage } = params;
2461
- const renderManagerService = accessor.get(_univerjs_engine_render.IRenderManagerService);
2462
- const docSelectionRenderService = (_renderManagerService2 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService2 === void 0 ? void 0 : _renderManagerService2.with(_univerjs_docs_ui.DocSelectionRenderService);
2463
- const renderObject = renderManagerService.getRenderUnitById(unitId);
2464
- const scene = renderObject === null || renderObject === void 0 ? void 0 : renderObject.scene;
2465
- if (renderObject == null || scene == null || docSelectionRenderService == null) return false;
2466
- const transformer = scene.getTransformerByCreate();
2467
- const commandService = accessor.get(_univerjs_core.ICommandService);
2468
- const documentDataModel = accessor.get(_univerjs_core.IUniverInstanceService).getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
2469
- if (documentDataModel == null) return false;
2470
- const rawActions = [];
2471
- const { drawingId } = drawing;
2472
- const actions = getDeleteAndInsertCustomBlockActions(newSegmentId, docSelectionRenderService.getSegment() ?? "", segmentPage, offset, drawingId, documentDataModel, docSelectionRenderService);
2473
- if (actions == null) return false;
2474
- if (actions.length > 0) rawActions.push(...actions);
2475
- const jsonX = _univerjs_core.JSONX.getInstance();
2476
- const { drawings: oldDrawings = {} } = documentDataModel.getSnapshot();
2477
- const { positionH: oldPositionH, positionV: oldPositionV, size: oldSize, angle: oldAngle } = oldDrawings[drawingId].docTransform;
2478
- if (!_univerjs_core.Tools.diffValue(oldPositionH, docTransform.positionH)) {
2479
- const updateAction = jsonX.replaceOp([
2480
- "drawings",
2481
- drawingId,
2482
- "docTransform",
2483
- "positionH"
2484
- ], oldPositionH, docTransform.positionH);
2485
- rawActions.push(updateAction);
2486
- }
2487
- if (!_univerjs_core.Tools.diffValue(oldPositionV, docTransform.positionV)) {
2488
- const updateAction = jsonX.replaceOp([
2489
- "drawings",
2490
- drawingId,
2491
- "docTransform",
2492
- "positionV"
2493
- ], oldPositionV, docTransform.positionV);
2494
- 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
+ }
2495
2537
  }
2496
- if (!_univerjs_core.Tools.diffValue(oldSize, docTransform.size)) {
2497
- const updateAction = jsonX.replaceOp([
2498
- "drawings",
2499
- drawingId,
2500
- "docTransform",
2501
- "size"
2502
- ], oldSize, docTransform.size);
2503
- 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
2504
2570
  }
2505
- if (!_univerjs_core.Tools.diffValue(oldAngle, docTransform.angle)) {
2506
- const updateAction = jsonX.replaceOp([
2507
- "drawings",
2508
- drawingId,
2509
- "docTransform",
2510
- "angle"
2511
- ], oldAngle, docTransform.angle);
2512
- 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
+ };
2513
2596
  }
2514
- const doMutation = {
2515
- id: _univerjs_docs.RichTextEditingMutation.id,
2516
- params: {
2517
- unitId,
2518
- actions: [],
2519
- textRanges: null,
2520
- 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
2521
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)
2522
2647
  };
2523
- doMutation.params.actions = rawActions.reduce((acc, cur) => {
2524
- return _univerjs_core.JSONX.compose(acc, cur);
2525
- }, null);
2526
- const result = commandService.syncExecuteCommand(doMutation.id, doMutation.params);
2527
- const skeleton = renderObject.with(_univerjs_docs.DocSkeletonManagerService).getSkeleton();
2528
- accessor.get(DocRefreshDrawingsService).refreshDrawings(skeleton);
2529
- transformer.refreshControls();
2530
- return Boolean(result);
2531
- }
2532
- };
2533
-
2534
- //#endregion
2535
- //#region src/controllers/render-controllers/doc-drawing-transform-update.controller.ts
2536
- function mergePublishedDrawing(drawings, next) {
2537
- const current = drawings[next.drawingId];
2538
- if (current == null) {
2539
- drawings[next.drawingId] = next;
2540
- return;
2541
2648
  }
2542
- if (next.selectable && !current.selectable) {
2543
- current.selectable = true;
2544
- 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
+ };
2545
2664
  }
2546
- if (next.isMultiTransform === _univerjs_core.BooleanNumber.TRUE) current.transforms.push(next.transform);
2547
- }
2548
- function isSameTransformValue(left, right) {
2549
- return left === right || JSON.stringify(left) === JSON.stringify(right);
2665
+ return result;
2550
2666
  }
2551
- function shouldRefreshDocDrawingTransform(current, next) {
2552
- if (!current || next.customBlockRenderViewport != null) return true;
2553
- 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;
2554
- }
2555
- /**
2556
- * Overlay drawings do not participate in text layout. While their skeleton
2557
- * anchor remains valid, use the latest model transform so drag/resize/front-
2558
- * behind changes can paint immediately without rebuilding document pages.
2559
- */
2560
- function getDocsOverlayRuntimeDrawing(skeletonDrawing, currentDrawing, measuredSize) {
2561
- if (skeletonDrawing.layoutType === _univerjs_core.PositionedObjectLayoutType.WRAP_NONE && (currentDrawing === null || currentDrawing === void 0 ? void 0 : currentDrawing.layoutType) === _univerjs_core.PositionedObjectLayoutType.WRAP_NONE) return currentDrawing;
2562
- return measuredSize ? {
2563
- ...skeletonDrawing,
2564
- docTransform: {
2565
- ...skeletonDrawing.docTransform,
2566
- size: measuredSize
2567
- }
2568
- } : skeletonDrawing;
2569
- }
2570
- var DocDrawingPublicationTracker = class {
2571
- constructor() {
2572
- _defineProperty(this, "_generation", -1);
2573
- _defineProperty(this, "_publishedPageCount", 0);
2574
- _defineProperty(this, "_drawingOccurrenceCount", 0);
2575
- }
2576
- reset() {
2577
- this._generation = -1;
2578
- this._publishedPageCount = 0;
2579
- this._drawingOccurrenceCount = 0;
2580
- }
2581
- shouldRefresh(skeleton, progress) {
2582
- if (!progress.didPublish && !progress.complete) return false;
2583
- const isNewGeneration = progress.generation !== this._generation;
2584
- if (isNewGeneration) {
2585
- this._generation = progress.generation;
2586
- this._publishedPageCount = 0;
2587
- this._drawingOccurrenceCount = 0;
2588
- }
2589
- const skeletonData = skeleton.getSkeletonData();
2590
- if (skeletonData == null) return false;
2591
- const previousPublishedPageCount = this._publishedPageCount;
2592
- const publishedPageCount = Math.min(progress.publishedPageCount, skeletonData.pages.length);
2593
- this._publishedPageCount = Math.max(previousPublishedPageCount, publishedPageCount);
2594
- const drawingOccurrenceCount = countPublishedDrawingOccurrences(skeletonData, publishedPageCount);
2595
- const didDrawingOccurrencesChange = !(isNewGeneration && progress.reason === "edit") && drawingOccurrenceCount !== this._drawingOccurrenceCount;
2596
- this._drawingOccurrenceCount = drawingOccurrenceCount;
2597
- if (progress.complete || progress.didPublishAnchor || didDrawingOccurrencesChange) return true;
2598
- if (isNewGeneration && progress.reason === "edit") return false;
2599
- return hasNewPublishedPageDrawings(skeletonData, previousPublishedPageCount, publishedPageCount);
2600
- }
2601
- };
2602
- function getDocsDrawingPageClipBounds(config) {
2603
- const { docsLeft, docsTop, pageOffsetLeft, pageOffsetTop, clipOffsetLeft = 0, clipOffsetTop = 0, page } = config;
2604
- if (page.type === _univerjs_engine_render.DocumentSkeletonPageType.CELL && config.drawingLayoutType === _univerjs_core.PositionedObjectLayoutType.WRAP_NONE && config.overflowClipBounds != null) return config.overflowClipBounds;
2605
- const { pageWidth, pageHeight } = page;
2606
- if (!Number.isFinite(pageWidth) || !Number.isFinite(pageHeight) || pageWidth <= 0 || pageHeight <= 0) return;
2607
- const cellInsetLeft = page.type === _univerjs_engine_render.DocumentSkeletonPageType.CELL ? page.marginLeft ?? 0 : 0;
2608
- const cellInsetTop = page.type === _univerjs_engine_render.DocumentSkeletonPageType.CELL ? page.marginTop ?? 0 : 0;
2609
- return {
2610
- left: docsLeft + pageOffsetLeft + clipOffsetLeft - cellInsetLeft,
2611
- top: docsTop + pageOffsetTop + clipOffsetTop - cellInsetTop,
2612
- width: pageWidth,
2613
- height: pageHeight
2614
- };
2615
- }
2616
- function getDocsDrawingClipPage(config) {
2617
- const { drawing, hostPage, page } = config;
2618
- if (hostPage && (page.type === _univerjs_engine_render.DocumentSkeletonPageType.HEADER || page.type === _univerjs_engine_render.DocumentSkeletonPageType.FOOTER)) return hostPage;
2619
- if (hostPage == null || drawing.behindText !== true || drawing.transform == null) return page;
2620
- const { width, height } = drawing.transform;
2621
- if (width == null || height == null) return page;
2622
- if (width > page.pageWidth || height > page.pageHeight) return hostPage;
2623
- const widthRatio = width / hostPage.pageWidth;
2624
- const heightRatio = height / hostPage.pageHeight;
2625
- if (widthRatio >= .8 && heightRatio >= .8) return hostPage;
2626
- return page;
2627
- }
2628
- function getDocsPageRelativeDrawingLeft(config) {
2629
- const { hostPage, positionH, width } = config;
2630
- if (positionH.relativeFrom !== _univerjs_core.ObjectRelativeFromH.PAGE) return;
2631
- if (positionH.align === _univerjs_core.AlignTypeH.RIGHT) return hostPage.pageWidth - width;
2632
- if (positionH.align === _univerjs_core.AlignTypeH.CENTER) return hostPage.pageWidth / 2 - width / 2;
2633
- if (positionH.posOffset != null) return positionH.posOffset;
2634
- return 0;
2635
- }
2636
- function getDocsPageRelativeDrawingTop(config) {
2637
- const { hostPage, positionV, height } = config;
2638
- if (positionV.relativeFrom !== _univerjs_core.ObjectRelativeFromV.PAGE) return;
2639
- if (positionV.align === _univerjs_core.AlignTypeV.BOTTOM) return hostPage.pageHeight - height;
2640
- if (positionV.align === _univerjs_core.AlignTypeV.CENTER) return hostPage.pageHeight / 2 - height / 2;
2641
- if (positionV.posOffset != null) return positionV.posOffset;
2642
- return 0;
2643
- }
2644
- function getDocsPageRelativeDrawingAnchorPage(config) {
2645
- const { page, clipPage, hostPage } = config;
2646
- if (config.drawingLayoutType === _univerjs_core.PositionedObjectLayoutType.INLINE) return;
2647
- if (hostPage != null && hostPage === clipPage) return hostPage;
2648
- if (hostPage == null && page === clipPage && page.type !== _univerjs_engine_render.DocumentSkeletonPageType.CELL) return page;
2649
- }
2650
- function getDocsDrawingBehindText(config) {
2651
- const { drawingOrigin, hostPage } = config;
2652
- if (hostPage != null) return true;
2653
- return drawingOrigin.layoutType === _univerjs_core.PositionedObjectLayoutType.WRAP_NONE && drawingOrigin.behindDoc === _univerjs_core.BooleanNumber.TRUE;
2654
- }
2655
- function getDocsTableCellDrawingOffset(unitId, table, row, cell) {
2656
- const sourceTableId = (0, _univerjs_engine_render.getTableIdAndSliceIndex)(table.tableId).tableId;
2657
- const viewport = (0, _univerjs_engine_render.getDocsTableRenderViewport)(unitId, sourceTableId);
2658
- const scrollLeft = hasHorizontalTableViewport(viewport) ? viewport.scrollLeft : 0;
2659
- return {
2660
- left: table.left + cell.left - scrollLeft + cell.marginLeft,
2661
- top: table.top + row.top + cell.marginTop
2662
- };
2663
- }
2664
- function hasHorizontalTableViewport(viewport) {
2665
- return viewport != null && (viewport.leadingInsetLeft ?? 0) + viewport.contentWidth + (viewport.trailingInsetRight ?? 0) > viewport.viewportWidth;
2666
- }
2667
- function hasSkeletonPageDrawings(page) {
2668
- var _page$notes, _page$skeTables, _page$skeColumnGroups;
2669
- 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;
2670
- let hasDrawings = false;
2671
- (_page$skeTables = page.skeTables) === null || _page$skeTables === void 0 || _page$skeTables.forEach((table) => {
2672
- table.rows.forEach((row) => {
2673
- row.cells.forEach((cell) => {
2674
- if (hasSkeletonPageDrawings(cell)) hasDrawings = true;
2675
- });
2676
- });
2677
- });
2678
- (_page$skeColumnGroups = page.skeColumnGroups) === null || _page$skeColumnGroups === void 0 || _page$skeColumnGroups.forEach((columnGroup) => {
2679
- columnGroup.columns.forEach((column) => {
2680
- if (hasSkeletonPageDrawings(column.page)) hasDrawings = true;
2681
- });
2682
- });
2683
- return hasDrawings;
2684
- }
2685
- function countSkeletonPageDrawings(page) {
2686
- var _page$notes2, _page$skeTables2, _page$skeColumnGroups2;
2687
- let count = page.skeDrawings.size;
2688
- (_page$notes2 = page.notes) === null || _page$notes2 === void 0 || _page$notes2.forEach((note) => {
2689
- count += countSkeletonPageDrawings(note.page);
2690
- });
2691
- (_page$skeTables2 = page.skeTables) === null || _page$skeTables2 === void 0 || _page$skeTables2.forEach((table) => {
2692
- table.rows.forEach((row) => {
2693
- row.cells.forEach((cell) => {
2694
- count += countSkeletonPageDrawings(cell);
2695
- });
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]
2696
2681
  });
2697
- });
2698
- (_page$skeColumnGroups2 = page.skeColumnGroups) === null || _page$skeColumnGroups2 === void 0 || _page$skeColumnGroups2.forEach((columnGroup) => {
2699
- columnGroup.columns.forEach((column) => {
2700
- 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
2701
2686
  });
2702
2687
  });
2703
- return count;
2688
+ return drawings.length ? drawings : null;
2704
2689
  }
2705
- function countPublishedDrawingOccurrences(skeletonData, publishedPageCount) {
2706
- let count = 0;
2707
- for (let index = 0; index < publishedPageCount; index++) {
2708
- var _skeletonData$skeHead, _skeletonData$skeFoot;
2709
- const page = skeletonData.pages[index];
2710
- count += countSkeletonPageDrawings(page);
2711
- 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.pageWidth);
2712
- if (header != null) count += countSkeletonPageDrawings(header);
2713
- 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.pageWidth);
2714
- 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
+ }
2715
2700
  }
2716
- return count;
2701
+ return drawingIndexes;
2717
2702
  }
2718
- function hasNewPublishedPageDrawings(skeletonData, startPageIndex, publishedPageCount) {
2719
- for (let index = startPageIndex; index < publishedPageCount; index++) {
2720
- var _skeletonData$skeHead2, _skeletonData$skeFoot2;
2721
- const page = skeletonData.pages[index];
2722
- if (hasSkeletonPageDrawings(page)) return true;
2723
- 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.pageWidth);
2724
- if (header != null && hasSkeletonPageDrawings(header)) return true;
2725
- 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.pageWidth);
2726
- 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;
2727
2715
  }
2728
- return false;
2716
+ actions.forEach((action) => {
2717
+ if (Array.isArray(action)) collectUpdatedDrawingIds(action, drawingIds);
2718
+ });
2719
+ return drawingIds;
2729
2720
  }
2730
- let DocDrawingTransformUpdateController = class DocDrawingTransformUpdateController extends _univerjs_core.Disposable {
2731
- 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) {
2732
2723
  super();
2733
- this._context = _context;
2734
- this._docSkeletonManagerService = _docSkeletonManagerService;
2724
+ this._univerInstanceService = _univerInstanceService;
2735
2725
  this._commandService = _commandService;
2736
- this._editorService = _editorService;
2737
2726
  this._drawingManagerService = _drawingManagerService;
2727
+ this._docDrawingService = _docDrawingService;
2728
+ this._renderManagerService = _renderManagerService;
2738
2729
  this._docRefreshDrawingsService = _docRefreshDrawingsService;
2739
- this._univerInstanceService = _univerInstanceService;
2740
- this._lifecycleService = _lifecycleService;
2741
- _defineProperty(this, "_liquid", new _univerjs_engine_render.Liquid());
2742
- _defineProperty(this, "_changesetDrawingRefreshScheduled", false);
2743
- _defineProperty(this, "_publicationTracker", new DocDrawingPublicationTracker());
2744
2730
  this._initialize();
2745
- this._commandExecutedListener();
2746
2731
  }
2747
2732
  _initialize() {
2748
- this._initialRenderRefresh();
2749
- this._drawingInitializeListener();
2750
- this._initTransformRefresh();
2751
- }
2752
- _initialRenderRefresh() {
2753
- this.disposeWithMe(this._docSkeletonManagerService.currentSkeleton$.pipe((0, rxjs.switchMap)((documentSkeleton) => {
2754
- this._publicationTracker.reset();
2755
- if (documentSkeleton == null) return rxjs.EMPTY;
2756
- this._refreshDrawing(documentSkeleton);
2757
- 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)(() => ({
2758
- documentSkeleton,
2759
- progress: null
2760
- })), (0, rxjs.startWith)({
2761
- documentSkeleton,
2762
- progress: null
2763
- }))));
2764
- return (0, rxjs.merge)(documentSkeleton.layoutProgress$.pipe((0, rxjs.map)((progress) => ({
2765
- documentSkeleton,
2766
- progress
2767
- }))), documentSkeleton.layoutPageMaterialized$.pipe((0, rxjs.map)(() => ({
2768
- documentSkeleton,
2769
- progress: null
2770
- }))), positionRefresh$);
2771
- })).subscribe(({ documentSkeleton, progress }) => {
2772
- if (progress == null || this._publicationTracker.shouldRefresh(documentSkeleton, progress)) this._refreshDrawing(documentSkeleton);
2773
- }));
2774
- this.disposeWithMe(this._docRefreshDrawingsService.refreshDrawings$.subscribe((skeleton) => {
2775
- if (skeleton == null) return;
2776
- this._refreshDrawing(skeleton);
2777
- }));
2733
+ this._commandExecutedListener();
2778
2734
  }
2779
2735
  _commandExecutedListener() {
2780
- const updateCommandList = [_univerjs_docs.RichTextEditingMutation.id, _univerjs_docs_ui.SetDocZoomRatioOperation.id];
2781
- this.disposeWithMe(this._commandService.onCommandExecuted((command, options) => {
2782
- if (updateCommandList.includes(command.id)) {
2783
- const params = command.params;
2784
- const { unitId: commandUnitId } = params;
2785
- const { unitId } = this._context;
2786
- if (commandUnitId !== unitId) return;
2787
- const drawingIds = command.id === _univerjs_docs.RichTextEditingMutation.id ? getDocMutationAffectedDrawingIds(params.actions) : null;
2788
- if ((drawingIds === null || drawingIds === void 0 ? void 0 : drawingIds.size) === 0) return;
2789
- if (command.id === _univerjs_docs.RichTextEditingMutation.id && (options === null || options === void 0 ? void 0 : options.fromChangeset)) {
2790
- this._scheduleChangesetDrawingRefresh();
2791
- return;
2792
- }
2793
- this._refreshCurrentDrawing(drawingIds ?? void 0);
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
+ }
2745
+ }));
2746
+ this.disposeWithMe(this._commandService.beforeCommandExecuted((command) => {
2747
+ if (command.id !== _univerjs_docs_drawing.UpdateDocDrawingWrappingStyleCommand.id) return;
2748
+ this._preserveWrappingStylePosition(command.params);
2749
+ }));
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
+ });
2794
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();
2795
2785
  }));
2796
2786
  }
2797
- _scheduleChangesetDrawingRefresh() {
2798
- if (this._changesetDrawingRefreshScheduled) return;
2799
- this._changesetDrawingRefreshScheduled = true;
2800
- queueMicrotask(() => {
2801
- queueMicrotask(() => {
2802
- this._changesetDrawingRefreshScheduled = false;
2803
- if (this._disposed) return;
2804
- this._refreshCurrentDrawing();
2805
- });
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
+ };
2806
2819
  });
2807
2820
  }
2808
- _refreshCurrentDrawing(drawingIds) {
2809
- const skeleton = this._docSkeletonManagerService.getSkeleton();
2810
- if (skeleton == null) return;
2811
- const { unitId, mainComponent } = this._context;
2812
- if (this._editorService.isEditor(unitId)) {
2813
- mainComponent === null || mainComponent === void 0 || mainComponent.makeDirty();
2814
- return;
2815
- }
2816
- this._refreshDrawing(skeleton, drawingIds);
2817
- }
2818
- _initTransformRefresh() {
2819
- 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(() => {
2820
- var _scene$getTransformer;
2821
- const skeleton = this._docSkeletonManagerService.getSkeleton();
2822
- const { scene } = this._context;
2823
- (_scene$getTransformer = scene.getTransformer()) === null || _scene$getTransformer === void 0 || _scene$getTransformer.refreshControls();
2824
- this._refreshDrawing(skeleton);
2825
- }));
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);
2826
2833
  }
2827
- _refreshDrawing(skeleton, drawingIds) {
2828
- const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
2829
- const { mainComponent, unitId } = this._context;
2830
- const documentComponent = mainComponent;
2831
- if (!skeletonData) return;
2832
- const { left: docsLeft, top: docsTop, pageLayoutType, pageMarginLeft, pageMarginTop } = documentComponent;
2833
- if (docsLeft <= -1e4 || docsTop <= -1e4) return;
2834
- const { pages, skeHeaders, skeFooters } = skeletonData;
2835
- const updateDrawingMap = {};
2836
- this._liquid.reset();
2837
- /**
2838
- * TODO: @DR-Univer We should not refresh all floating elements, but instead make a diff.
2839
- */
2840
- for (let i = 0, len = pages.length; i < len; i++) {
2841
- const page = pages[i];
2842
- this._collectPublishedPageDrawingPositions(unitId, page, skeHeaders, skeFooters, docsLeft, docsTop, updateDrawingMap);
2843
- this._liquid.translatePage(page, pageLayoutType, pageMarginLeft, pageMarginTop);
2844
- }
2845
- const affectedDrawingIds = this._includeGroupChildren(drawingIds);
2846
- const updateDrawings = Object.values(updateDrawingMap).filter((drawing) => affectedDrawingIds == null || affectedDrawingIds.has(drawing.drawingId));
2847
- for (const drawing of updateDrawings) drawing.hidden = false;
2848
- const staleNonMultiDrawings = this._getStaleNonMultiDrawings(unitId, updateDrawingMap, affectedDrawingIds);
2849
- 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({
2850
2838
  unitId,
2851
2839
  subUnitId: unitId,
2852
- drawingId: drawing.drawingId
2853
- }), drawing));
2854
- if (nonMultiDrawings.length > 0) this._drawingManagerService.refreshTransform(nonMultiDrawings);
2855
- const targetedMultiDrawing = affectedDrawingIds != null && [...affectedDrawingIds].some((drawingId) => {
2856
- var _updateDrawingMap$dra, _this$_drawingManager;
2857
- 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 {
2858
2845
  unitId,
2859
2846
  subUnitId: unitId,
2860
2847
  drawingId
2861
- })) === null || _this$_drawingManager === void 0 ? void 0 : _this$_drawingManager.isMultiTransform) === _univerjs_core.BooleanNumber.TRUE;
2862
- });
2863
- if (affectedDrawingIds == null || targetedMultiDrawing) {
2864
- const allMultiDrawings = Object.values(updateDrawingMap).filter((drawing) => drawing.isMultiTransform);
2865
- this._handleMultiDrawingsTransform(allMultiDrawings);
2866
- }
2867
- }
2868
- _includeGroupChildren(drawingIds) {
2869
- if (drawingIds == null) return;
2870
- const affected = new Set(drawingIds);
2871
- const { drawings } = (0, _univerjs_docs_drawing.collectDocDrawings)(this._context.unit.getSnapshot());
2872
- let previousSize = -1;
2873
- while (previousSize !== affected.size) {
2874
- previousSize = affected.size;
2875
- for (const drawing of Object.values(drawings)) if (drawing.groupId && affected.has(drawing.groupId)) affected.add(drawing.drawingId);
2876
- }
2877
- return affected;
2878
- }
2879
- _collectPublishedPageDrawingPositions(unitId, page, skeHeaders, skeFooters, docsLeft, docsTop, updateDrawingMap) {
2880
- var _skeHeaders$get, _skeFooters$get;
2881
- const selectable = !page.isLayoutPlaceholder && !page.isMaterializationPlaceholder;
2882
- const { headerId, footerId, pageWidth } = page;
2883
- const headerPage = headerId ? (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(pageWidth) : void 0;
2884
- if (headerPage != null) this._collectSegmentDrawingPositions(unitId, headerPage, docsLeft, docsTop, updateDrawingMap, headerPage.marginTop, page.marginLeft, page, selectable);
2885
- const footerPage = footerId ? (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(pageWidth) : void 0;
2886
- if (footerPage != null) {
2887
- const footerTop = page.pageHeight - footerPage.height - footerPage.marginBottom;
2888
- this._collectSegmentDrawingPositions(unitId, footerPage, docsLeft, docsTop, updateDrawingMap, footerTop, page.marginLeft, page, selectable);
2889
- }
2890
- this._collectSegmentDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, page.marginTop, page.marginLeft, void 0, selectable);
2891
- for (const note of page.notes ?? []) this._collectSegmentDrawingPositions(unitId, note.page, docsLeft, docsTop, updateDrawingMap, note.top, note.left, void 0, selectable, {
2892
- top: note.top,
2893
- left: note.left
2894
- });
2895
- }
2896
- _collectSegmentDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable, clipOffset) {
2897
- const overflowClipBounds = getDocsDrawingPageClipBounds({
2898
- docsLeft,
2899
- docsTop,
2900
- pageOffsetLeft: this._liquid.x,
2901
- pageOffsetTop: this._liquid.y,
2902
- page: hostPage ?? page
2903
- });
2904
- this._calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable, clipOffset, overflowClipBounds);
2905
- this._calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
2906
- 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);
2907
2854
  }
2908
- _getStaleNonMultiDrawings(unitId, updateDrawingMap, drawingIds) {
2909
- const drawingData = this._drawingManagerService.getDrawingData(unitId, unitId) ?? {};
2910
- 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 = {
2911
2866
  unitId,
2912
2867
  subUnitId: unitId,
2913
- drawingId: drawing.drawingId,
2914
- behindText: false,
2915
- hidden: true,
2916
- selectable: true,
2917
- transform: drawing.transform,
2918
- transforms: drawing.transforms ?? [],
2919
- isMultiTransform: drawing.isMultiTransform ?? _univerjs_core.BooleanNumber.FALSE
2920
- }));
2921
- }
2922
- _handleMultiDrawingsTransform(multiDrawings) {
2923
- const { scene, unitId } = this._context;
2924
- const transformer = scene.getTransformerByCreate();
2925
- multiDrawings.forEach((updateParam) => {
2926
- const param = this._drawingManagerService.getDrawingByParam(updateParam);
2927
- if (param == null) return;
2928
- Object.assign(param, updateParam);
2868
+ drawingIds: renderOrder
2869
+ };
2870
+ drawingManagerService.orderNotification(objects);
2871
+ docDrawingService.orderNotification({
2872
+ unitId,
2873
+ subUnitId: unitId,
2874
+ drawingIds: drawingsOrder
2929
2875
  });
2930
- const selectedObjectKeys = [...transformer.getSelectedObjectMap().keys()];
2931
- const allMultiDrawings = Object.values(this._drawingManagerService.getDrawingData(unitId, unitId)).filter((drawing) => drawing.isMultiTransform === _univerjs_core.BooleanNumber.TRUE);
2932
- this._drawingManagerService.removeNotification(allMultiDrawings);
2933
- if (multiDrawings.length > 0) this._drawingManagerService.addNotification(multiDrawings);
2934
- for (const key of selectedObjectKeys) {
2935
- const drawingShape = scene.getObject(key);
2936
- if (drawingShape) transformer.setSelectedControl(drawingShape);
2937
- }
2938
2876
  }
2939
- _calculateDrawingPosition(unitId, page, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, hostPage, selectable = true, clipOffset, overflowClipBounds) {
2940
- const { skeDrawings } = page;
2941
- const pageOffsetLeft = this._liquid.x;
2942
- const pageOffsetTop = this._liquid.y;
2943
- this._liquid.translatePagePadding({
2944
- marginTop,
2945
- marginLeft
2946
- });
2947
- 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],
2948
2887
  unitId,
2949
- page,
2950
- docsLeft,
2951
- docsTop,
2952
- pageOffsetLeft,
2953
- pageOffsetTop,
2954
- updateDrawingMap,
2955
- hostPage,
2956
- selectable,
2957
- clipOffset,
2958
- overflowClipBounds
2959
- };
2960
- skeDrawings.forEach((drawing) => this._collectDrawingPosition(drawing, drawingPositionContext));
2961
- this._liquid.restorePagePadding({
2962
- marginTop,
2963
- marginLeft
2964
- });
2888
+ subUnitId: unitId
2889
+ })));
2890
+ if (removed.length > 0) this._removeDrawings(unitId, removed);
2891
+ if (changed.length > 0) this._syncDrawingDataFromSnapshot(unitId, changed);
2965
2892
  }
2966
- _collectDrawingPosition(drawing, context) {
2967
- var _this$_context$unit, _this$_context$unit$g;
2968
- const { aLeft, aTop, angle: skeletonAngle, drawingId, drawingOrigin, height: skeletonHeight, width: skeletonWidth } = drawing;
2969
- 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 ? {
2970
- width: skeletonWidth,
2971
- height: skeletonHeight
2972
- } : void 0);
2973
- const { angle = skeletonAngle, size } = runtimeDrawing.docTransform;
2974
- const height = (size === null || size === void 0 ? void 0 : size.height) ?? skeletonHeight;
2975
- const width = (size === null || size === void 0 ? void 0 : size.width) ?? skeletonWidth;
2976
- const { left: clipOffsetLeft, top: clipOffsetTop } = context.clipOffset ?? {};
2977
- const behindText = getDocsDrawingBehindText({
2978
- drawingOrigin: runtimeDrawing,
2979
- 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);
2980
2910
  });
2981
- const { isMultiTransform = _univerjs_core.BooleanNumber.FALSE } = runtimeDrawing;
2982
- const clipPage = getDocsDrawingClipPage({
2983
- drawing: {
2984
- behindText,
2985
- transform: {
2986
- width,
2987
- height
2988
- }
2989
- },
2990
- hostPage: context.hostPage,
2991
- 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);
2992
2914
  });
2993
- const clipBounds = getDocsDrawingPageClipBounds({
2994
- docsLeft: context.docsLeft,
2995
- docsTop: context.docsTop,
2996
- pageOffsetLeft: context.pageOffsetLeft,
2997
- pageOffsetTop: context.pageOffsetTop,
2998
- clipOffsetLeft,
2999
- clipOffsetTop,
3000
- page: clipPage,
3001
- drawingLayoutType: runtimeDrawing.layoutType,
3002
- 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
3003
3147
  });
3004
- const anchorPage = getDocsPageRelativeDrawingAnchorPage({
3005
- page: context.page,
3006
- clipPage,
3007
- hostPage: context.hostPage,
3008
- drawingLayoutType: runtimeDrawing.layoutType
3148
+ textX.push({
3149
+ t: _univerjs_core.TextXActionType.DELETE,
3150
+ len: 1
3009
3151
  });
3010
- const pageRelativeLeft = anchorPage == null ? void 0 : getDocsPageRelativeDrawingLeft({
3011
- hostPage: anchorPage,
3012
- positionH: runtimeDrawing.docTransform.positionH,
3013
- 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
3014
3159
  });
3015
- const pageRelativeTop = anchorPage == null ? void 0 : getDocsPageRelativeDrawingTop({
3016
- hostPage: anchorPage,
3017
- positionV: runtimeDrawing.docTransform.positionV,
3018
- 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
3019
3170
  });
3020
- const transform = {
3021
- left: (pageRelativeLeft ?? aLeft) + context.docsLeft + (pageRelativeLeft == null ? this._liquid.x : context.pageOffsetLeft),
3022
- top: (pageRelativeTop ?? aTop) + context.docsTop + (pageRelativeTop == null ? this._liquid.y : context.pageOffsetTop),
3023
- width,
3024
- height,
3025
- angle,
3026
- flipX: runtimeDrawing.docTransform.flipX,
3027
- flipY: runtimeDrawing.docTransform.flipY,
3028
- 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
+ }
3029
3309
  };
3030
- mergePublishedDrawing(context.updateDrawingMap, {
3031
- unitId: context.unitId,
3032
- subUnitId: context.unitId,
3033
- drawingId,
3034
- behindText,
3035
- selectable: context.selectable,
3036
- transform,
3037
- transforms: [transform],
3038
- customBlockRenderViewport: drawing.customBlockRenderViewport,
3039
- isMultiTransform
3040
- });
3041
- 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);
3042
3316
  }
3043
- _collectGroupChildren(groupId, context, behindText, isMultiTransform, visited) {
3044
- const { drawings } = (0, _univerjs_docs_drawing.collectDocDrawings)(this._context.unit.getSnapshot());
3045
- for (const child of Object.values(drawings)) {
3046
- if (child.groupId !== groupId || visited.has(child.drawingId)) continue;
3047
- visited.add(child.drawingId);
3048
- const { size, positionH, positionV, angle, flipX, flipY } = child.docTransform;
3049
- const transform = {
3050
- left: positionH.posOffset ?? 0,
3051
- top: positionV.posOffset ?? 0,
3052
- width: size.width,
3053
- height: size.height,
3054
- angle,
3055
- flipX,
3056
- flipY
3057
- };
3058
- mergePublishedDrawing(context.updateDrawingMap, {
3059
- unitId: context.unitId,
3060
- subUnitId: context.unitId,
3061
- drawingId: child.drawingId,
3062
- behindText,
3063
- selectable: context.selectable,
3064
- transform,
3065
- transforms: [transform],
3066
- isMultiTransform
3067
- });
3068
- 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);
3069
3353
  }
3070
- }
3071
- _calculateTableCellDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, baseMarginTop, baseMarginLeft, selectable, overflowClipBounds) {
3072
- var _page$skeTables3;
3073
- (_page$skeTables3 = page.skeTables) === null || _page$skeTables3 === void 0 || _page$skeTables3.forEach((table) => {
3074
- table.rows.forEach((row) => {
3075
- row.cells.forEach((cell) => {
3076
- var _cell$skeDrawings, _cell$skeTables, _cell$skeColumnGroups;
3077
- 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;
3078
- const cellOffset = getDocsTableCellDrawingOffset(unitId, table, row, cell);
3079
- const marginTop = baseMarginTop + cellOffset.top;
3080
- const marginLeft = baseMarginLeft + cellOffset.left;
3081
- this._calculateDrawingPosition(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, void 0, selectable, {
3082
- left: marginLeft,
3083
- top: marginTop
3084
- }, overflowClipBounds);
3085
- this._calculateTableCellDrawingPositions(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3086
- this._calculateColumnGroupDrawingPositions(unitId, cell, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3087
- });
3088
- });
3089
- });
3090
- }
3091
- _calculateColumnGroupDrawingPositions(unitId, page, docsLeft, docsTop, updateDrawingMap, baseMarginTop, baseMarginLeft, selectable, overflowClipBounds) {
3092
- var _page$skeColumnGroups3;
3093
- (_page$skeColumnGroups3 = page.skeColumnGroups) === null || _page$skeColumnGroups3 === void 0 || _page$skeColumnGroups3.forEach((columnGroup) => {
3094
- columnGroup.columns.forEach((column) => {
3095
- const nestedPage = column.page;
3096
- const marginTop = baseMarginTop + columnGroup.top + column.top + nestedPage.marginTop;
3097
- const marginLeft = baseMarginLeft + columnGroup.left + column.left + nestedPage.marginLeft;
3098
- const clipOffset = {
3099
- left: marginLeft,
3100
- top: marginTop
3101
- };
3102
- this._calculateDrawingPosition(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, void 0, selectable, clipOffset, overflowClipBounds);
3103
- this._calculateTableCellDrawingPositions(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3104
- this._calculateColumnGroupDrawingPositions(unitId, nestedPage, docsLeft, docsTop, updateDrawingMap, marginTop, marginLeft, selectable, overflowClipBounds);
3105
- });
3106
- });
3107
- }
3108
- _drawingInitializeListener() {
3109
- const init = () => {
3110
- const skeleton = this._docSkeletonManagerService.getSkeleton();
3111
- if (skeleton == null) return;
3112
- this._drawingManagerService.initializeNotification(this._context.unitId);
3113
- 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
+ }
3114
3389
  };
3115
- if (this._lifecycleService.stage >= _univerjs_core.LifecycleStages.Rendered) {
3116
- if (this._docSkeletonManagerService.getSkeleton()) init();
3117
- else setTimeout(init, 500);
3118
- } 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);
3119
3398
  }
3120
3399
  };
3121
- DocDrawingTransformUpdateController = __decorate([
3122
- __decorateParam(1, (0, _univerjs_core.Inject)(_univerjs_docs.DocSkeletonManagerService)),
3123
- __decorateParam(2, _univerjs_core.ICommandService),
3124
- __decorateParam(3, _univerjs_docs_ui.IEditorService),
3125
- __decorateParam(4, _univerjs_drawing.IDrawingManagerService),
3126
- __decorateParam(5, (0, _univerjs_core.Inject)(DocRefreshDrawingsService)),
3127
- __decorateParam(6, _univerjs_core.IUniverInstanceService),
3128
- __decorateParam(7, (0, _univerjs_core.Inject)(_univerjs_core.LifecycleService))
3129
- ], DocDrawingTransformUpdateController);
3130
3400
 
3131
3401
  //#endregion
3132
3402
  //#region src/controllers/doc-drawing-transformer-update.controller.ts
@@ -3177,12 +3447,26 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3177
3447
  this._drawingManagerService = _drawingManagerService;
3178
3448
  this._renderManagerService = _renderManagerService;
3179
3449
  _defineProperty(this, "_liquid", new _univerjs_engine_render.Liquid());
3180
- _defineProperty(this, "_listenerOnImageMap", /* @__PURE__ */ new Set());
3450
+ _defineProperty(this, "_listenerOnImageMap", /* @__PURE__ */ new Map());
3181
3451
  _defineProperty(this, "_transformerCache", /* @__PURE__ */ new Map());
3182
3452
  _defineProperty(this, "_anchorShape", void 0);
3183
3453
  this._init();
3184
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
+ }
3185
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
+ }));
3186
3470
  this._listenDrawingFocus();
3187
3471
  }
3188
3472
  _listenDrawingFocus() {
@@ -3191,17 +3475,25 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3191
3475
  for (const drawingParam of drawingParams) {
3192
3476
  const { unitId } = drawingParam;
3193
3477
  if (!this._listenerOnImageMap.has(unitId)) {
3194
- this._listenTransformerChange(unitId);
3195
- this._listenerOnImageMap.add(unitId);
3478
+ const listener = this._listenTransformerChange(unitId);
3479
+ if (listener) this._listenerOnImageMap.set(unitId, listener);
3196
3480
  }
3197
3481
  }
3198
3482
  }));
3199
3483
  }
3200
3484
  _listenTransformerChange(unitId) {
3201
- var _this$_getSceneAndTra;
3202
- 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;
3203
3487
  if (transformer == null) return;
3204
- 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) => {
3205
3497
  this._transformerCache.clear();
3206
3498
  const { objects } = state;
3207
3499
  for (const object of objects.values()) {
@@ -3213,7 +3505,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3213
3505
  const drawingData = documentDataModel ? (_findDocDrawing = (0, _univerjs_docs_drawing.findDocDrawing)(documentDataModel.getSnapshot(), drawing.drawingId)) === null || _findDocDrawing === void 0 ? void 0 : _findDocDrawing.drawing : void 0;
3214
3506
  if ((drawingData === null || drawingData === void 0 ? void 0 : drawingData.layoutType) === _univerjs_core.PositionedObjectLayoutType.INLINE) try {
3215
3507
  object.setOpacity(.2);
3216
- } catch (e) {}
3508
+ } catch {}
3217
3509
  if (drawingData != null) this._transformerCache.set(drawing.drawingId, {
3218
3510
  drawing: drawingData,
3219
3511
  top,
@@ -3224,18 +3516,20 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3224
3516
  });
3225
3517
  }
3226
3518
  })));
3227
- const throttleMultipleDrawingUpdate = (0, _univerjs_core.throttle)(this._updateMultipleDrawingDocTransform.bind(this), 50);
3228
- 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) => {
3229
3524
  const { objects, offsetX, offsetY } = state;
3230
- if (objects.size > 1) throttleMultipleDrawingUpdate(objects);
3231
- else if (objects.size === 1) {
3525
+ if (objects.size === 1) {
3232
3526
  const drawingCache = this._transformerCache.values().next().value;
3233
3527
  const { width, height, top, left, angle } = objects.values().next().value;
3234
3528
  if (drawingCache && width === drawingCache.width && height === drawingCache.height && top === drawingCache.top && left === drawingCache.left && angle === drawingCache.angle) return;
3235
3529
  if (drawingCache && drawingCache.drawing.layoutType === _univerjs_core.PositionedObjectLayoutType.INLINE && offsetX != null && offsetY != null) this._updateInlineDrawingAnchor(drawingCache.drawing, offsetX, offsetY);
3236
3530
  }
3237
3531
  })));
3238
- this.disposeWithMe((0, _univerjs_core.toDisposable)(transformer.changeEnd$.subscribe((state) => {
3532
+ listeners.add((0, _univerjs_core.toDisposable)(transformer.changeEnd$.subscribe((state) => {
3239
3533
  const { objects, offsetX, offsetY } = state;
3240
3534
  for (const object of objects.values()) {
3241
3535
  const drawing = this._drawingManagerService.getDrawingOKey(object.oKey);
@@ -3243,7 +3537,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3243
3537
  const drawingCache = this._transformerCache.get(drawing === null || drawing === void 0 ? void 0 : drawing.drawingId);
3244
3538
  if ((drawingCache === null || drawingCache === void 0 ? void 0 : drawingCache.drawing.layoutType) === _univerjs_core.PositionedObjectLayoutType.INLINE) try {
3245
3539
  object.setOpacity(1);
3246
- } catch (e) {}
3540
+ } catch {}
3247
3541
  }
3248
3542
  if (this._anchorShape) this._anchorShape.hide();
3249
3543
  if (objects.size > 1) this._updateMultipleDrawingDocTransform(objects);
@@ -3259,6 +3553,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3259
3553
  }
3260
3554
  this._transformerCache.clear();
3261
3555
  })));
3556
+ return listeners;
3262
3557
  }
3263
3558
  _updateMultipleDrawingDocTransform(objects) {
3264
3559
  if (objects.size < 1) return;
@@ -3294,20 +3589,37 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3294
3589
  if (oldTop !== top || oldLeft !== left) {
3295
3590
  const verticalDelta = top - oldTop;
3296
3591
  const horizontalDelta = left - oldLeft;
3297
- 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({
3298
3610
  drawingId: drawing.drawingId,
3299
3611
  key: "positionV",
3300
3612
  value: {
3301
- relativeFrom: drawingData.docTransform.positionV.relativeFrom,
3302
- posOffset: drawingData.docTransform.positionV.posOffset + verticalDelta
3613
+ relativeFrom: positionV.relativeFrom,
3614
+ posOffset: posOffsetV
3303
3615
  }
3304
3616
  });
3305
- if (horizontalDelta !== 0) drawings.push({
3617
+ if (horizontalDelta !== 0 && posOffsetH != null) drawings.push({
3306
3618
  drawingId: drawing.drawingId,
3307
3619
  key: "positionH",
3308
3620
  value: {
3309
- relativeFrom: drawingData.docTransform.positionH.relativeFrom,
3310
- posOffset: drawingData.docTransform.positionH.posOffset + horizontalDelta
3621
+ relativeFrom: positionH.relativeFrom,
3622
+ posOffset: posOffsetH
3311
3623
  }
3312
3624
  });
3313
3625
  }
@@ -3318,12 +3630,6 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3318
3630
  drawings
3319
3631
  });
3320
3632
  }
3321
- _updateDrawingAnchor(objects) {
3322
- if (this._transformerCache.size !== 1) return;
3323
- const drawingCache = this._transformerCache.values().next().value;
3324
- const object = objects.values().next().value;
3325
- this._getDrawingAnchor(drawingCache.drawing, object);
3326
- }
3327
3633
  _updateInlineDrawingAnchor(drawing, offsetX, offsetY) {
3328
3634
  if (this._transformerCache.size !== 1) return;
3329
3635
  const { contentBoxPointGroup } = this._getInlineDrawingAnchor(drawing, offsetX, offsetY) ?? {};
@@ -3331,7 +3637,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3331
3637
  this._createOrUpdateInlineAnchor(drawing.unitId, contentBoxPointGroup);
3332
3638
  }
3333
3639
  _getInlineDrawingAnchor(drawing, offsetX, offsetY) {
3334
- var _this$_renderManagerS;
3640
+ var _this$_renderManagerS2;
3335
3641
  const currentRender = this._renderManagerService.getRenderUnitById(drawing.unitId);
3336
3642
  const skeleton = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(_univerjs_docs.DocSkeletonManagerService).getSkeleton();
3337
3643
  if (currentRender == null) return;
@@ -3346,7 +3652,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3346
3652
  const HALF = .5;
3347
3653
  const coord = this._getTransformCoordForDocumentOffset(documentComponent, activeViewport, offsetX, offsetY);
3348
3654
  if (coord == null) return;
3349
- 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);
3350
3656
  if (docSelectionRenderService == null) return;
3351
3657
  const nodeInfo = skeleton === null || skeleton === void 0 ? void 0 : skeleton.findNodeByCoord(coord, pageLayoutType, pageMarginLeft, pageMarginTop, {
3352
3658
  strict: false,
@@ -3380,7 +3686,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3380
3686
  };
3381
3687
  }
3382
3688
  _getDrawingAnchor(drawing, object) {
3383
- var _this$_renderManagerS2, _glyphAnchor$parent, _column$parent, _column$parent2;
3689
+ var _this$_renderManagerS3, _glyphAnchor$parent, _column$parent, _column$parent2;
3384
3690
  const currentRender = this._renderManagerService.getRenderUnitById(drawing.unitId);
3385
3691
  const skeleton = currentRender === null || currentRender === void 0 ? void 0 : currentRender.with(_univerjs_docs.DocSkeletonManagerService).getSkeleton();
3386
3692
  const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
@@ -3411,7 +3717,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3411
3717
  const { x, y } = scene.getViewportScrollXY(activeViewport);
3412
3718
  const coord = this._getTransformCoordForDocumentOffset(documentComponent, activeViewport, left - x, top - y);
3413
3719
  if (coord == null) return;
3414
- 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);
3415
3721
  if (docSelectionRenderService == null) return;
3416
3722
  const nodeInfo = skeleton === null || skeleton === void 0 ? void 0 : skeleton.findNodeByCoord(coord, pageLayoutType, pageMarginLeft, pageMarginTop, {
3417
3723
  strict: false,
@@ -3454,7 +3760,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3454
3760
  switch (pageType) {
3455
3761
  case _univerjs_engine_render.DocumentSkeletonPageType.HEADER: {
3456
3762
  var _skeHeaders$get;
3457
- const headerSke = (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(pageWidth);
3763
+ const headerSke = (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(p.headerLayoutKey ?? pageWidth);
3458
3764
  if (headerSke) this._liquid.translatePagePadding({
3459
3765
  marginTop: headerSke.marginTop,
3460
3766
  marginLeft
@@ -3464,7 +3770,7 @@ let DocDrawingTransformerController = class DocDrawingTransformerController exte
3464
3770
  }
3465
3771
  case _univerjs_engine_render.DocumentSkeletonPageType.FOOTER: {
3466
3772
  var _skeFooters$get;
3467
- const footerSke = (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(pageWidth);
3773
+ const footerSke = (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(p.footerLayoutKey ?? pageWidth);
3468
3774
  if (footerSke) this._liquid.translatePagePadding({
3469
3775
  marginTop: pageHeight - marginBottom + footerSke.marginTop,
3470
3776
  marginLeft
@@ -3722,7 +4028,8 @@ function useDocDrawingPosition(props) {
3722
4028
  const { unitId } = drawings[0];
3723
4029
  const documentDataModel = univerInstanceService.getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
3724
4030
  const documentFlavor = documentDataModel === null || documentDataModel === void 0 ? void 0 : documentDataModel.getSnapshot().documentStyle.documentFlavor;
3725
- const transformer = renderManagerService.getRenderUnitById(unitId).scene.getTransformerByCreate();
4031
+ const renderObject = renderManagerService.getRenderUnitById(unitId);
4032
+ const transformer = renderObject.scene.getTransformerByCreate();
3726
4033
  const HORIZONTAL_RELATIVE_FROM = [
3727
4034
  {
3728
4035
  label: localeService.t("docs-drawing-ui.image-position.column"),
@@ -3769,7 +4076,7 @@ function useDocDrawingPosition(props) {
3769
4076
  });
3770
4077
  const [followTextMove, setFollowTextMove] = (0, react.useState)(true);
3771
4078
  const [showPanel, setShowPanel] = (0, react.useState)(true);
3772
- function handlePositionChange(direction, value) {
4079
+ function handlePositionChange(direction, value, positionH) {
3773
4080
  var _renderManagerService;
3774
4081
  const focusDrawings = drawingManagerService.getFocusDrawings();
3775
4082
  if (focusDrawings.length === 0) return;
@@ -3783,74 +4090,43 @@ function useDocDrawingPosition(props) {
3783
4090
  commandService.executeCommand(_univerjs_docs_drawing.UpdateDrawingDocTransformCommand.id, {
3784
4091
  unitId: focusDrawings[0].unitId,
3785
4092
  subUnitId: focusDrawings[0].subUnitId,
3786
- drawings: drawings.map((drawing) => ({
4093
+ drawings: drawings.flatMap((drawing) => [{
3787
4094
  drawingId: drawing.drawingId,
3788
4095
  key: direction,
3789
4096
  value
3790
- }))
4097
+ }, ...positionH ? [{
4098
+ drawingId: drawing.drawingId,
4099
+ key: "positionH",
4100
+ value: positionH
4101
+ }] : []])
3791
4102
  });
3792
4103
  const docSelectionRenderService = (_renderManagerService = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService === void 0 ? void 0 : _renderManagerService.with(_univerjs_docs_ui.DocSelectionRenderService);
3793
4104
  if (docSelectionRenderService) docSelectionRenderService.blur();
3794
4105
  transformer.refreshControls();
3795
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
+ }
3796
4117
  function handleHorizontalRelativeFromChange(value) {
3797
- var _renderManagerService2;
3798
- const prevRelativeFrom = hPosition.relativeFrom;
3799
- const prevPosOffset = hPosition.posOffset;
3800
4118
  const relativeFrom = [
3801
4119
  _univerjs_core.ObjectRelativeFromH.COLUMN,
3802
4120
  _univerjs_core.ObjectRelativeFromH.PAGE,
3803
4121
  _univerjs_core.ObjectRelativeFromH.MARGIN
3804
4122
  ].find((reference) => String(reference) === value);
3805
4123
  if (relativeFrom == null) return;
3806
- if (prevRelativeFrom === relativeFrom) return;
3807
- const focusDrawings = drawingManagerService.getFocusDrawings();
3808
- if (focusDrawings.length === 0) return;
3809
- const drawingId = focusDrawings[0].drawingId;
3810
- const unitId = focusDrawings[0].unitId;
3811
- let drawing = null;
3812
- let pageMarginLeft = 0;
3813
- const skeleton = (_renderManagerService2 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService2 === void 0 ? void 0 : _renderManagerService2.with(_univerjs_docs.DocSkeletonManagerService).getSkeleton();
3814
- const skeletonData = skeleton === null || skeleton === void 0 ? void 0 : skeleton.getSkeletonData();
3815
- if (skeletonData == null) return;
3816
- const { pages, skeHeaders, skeFooters } = skeletonData;
3817
- for (const page of pages) {
3818
- var _skeHeaders$get, _skeFooters$get;
3819
- const { marginLeft, skeDrawings, headerId, footerId, pageWidth } = page;
3820
- if (skeDrawings.has(drawingId)) {
3821
- drawing = skeDrawings.get(drawingId);
3822
- pageMarginLeft = marginLeft;
3823
- break;
3824
- }
3825
- const headerPage = (_skeHeaders$get = skeHeaders.get(headerId)) === null || _skeHeaders$get === void 0 ? void 0 : _skeHeaders$get.get(pageWidth);
3826
- if (headerPage === null || headerPage === void 0 ? void 0 : headerPage.skeDrawings.has(drawingId)) {
3827
- drawing = headerPage === null || headerPage === void 0 ? void 0 : headerPage.skeDrawings.get(drawingId);
3828
- pageMarginLeft = marginLeft;
3829
- break;
3830
- }
3831
- const footerPage = (_skeFooters$get = skeFooters.get(footerId)) === null || _skeFooters$get === void 0 ? void 0 : _skeFooters$get.get(pageWidth);
3832
- if (footerPage === null || footerPage === void 0 ? void 0 : footerPage.skeDrawings.has(drawingId)) {
3833
- drawing = footerPage === null || footerPage === void 0 ? void 0 : footerPage.skeDrawings.get(drawingId);
3834
- pageMarginLeft = marginLeft;
3835
- break;
3836
- }
3837
- }
3838
- if (drawing == null) return;
3839
- let delta = 0;
3840
- if (prevRelativeFrom === _univerjs_core.ObjectRelativeFromH.COLUMN) delta -= drawing.columnLeft;
3841
- else if (prevRelativeFrom === _univerjs_core.ObjectRelativeFromH.MARGIN) delta -= pageMarginLeft;
3842
- if (relativeFrom === _univerjs_core.ObjectRelativeFromH.COLUMN) delta += drawing.columnLeft;
3843
- else if (relativeFrom === _univerjs_core.ObjectRelativeFromH.MARGIN) delta += pageMarginLeft;
3844
- else if (relativeFrom === _univerjs_core.ObjectRelativeFromH.PAGE) {}
3845
- handlePositionChange("positionH", {
3846
- relativeFrom,
3847
- posOffset: (prevPosOffset ?? 0) - delta
3848
- });
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);
3849
4128
  }
3850
4129
  function handleVerticalRelativeFromChange(value) {
3851
- var _renderManagerService3, _renderManagerService4, _documentDataModel$ge, _glyph$parent, _column$parent;
3852
- const prevRelativeFrom = vPosition.relativeFrom;
3853
- const prevPosOffset = vPosition.posOffset;
3854
4130
  const relativeFrom = [
3855
4131
  _univerjs_core.ObjectRelativeFromV.LINE,
3856
4132
  _univerjs_core.ObjectRelativeFromV.PAGE,
@@ -3858,44 +4134,22 @@ function useDocDrawingPosition(props) {
3858
4134
  _univerjs_core.ObjectRelativeFromV.PARAGRAPH
3859
4135
  ].find((reference) => String(reference) === value);
3860
4136
  if (relativeFrom == null) return;
3861
- if (prevRelativeFrom === relativeFrom) return;
3862
- const focusDrawings = drawingManagerService.getFocusDrawings();
3863
- if (focusDrawings.length === 0) return;
3864
- const { drawingId, unitId } = focusDrawings[0];
3865
- const documentDataModel = univerInstanceService.getUnit(unitId, _univerjs_core.UniverInstanceType.UNIVER_DOC);
3866
- const skeleton = (_renderManagerService3 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService3 === void 0 ? void 0 : _renderManagerService3.with(_univerjs_docs.DocSkeletonManagerService).getSkeleton();
3867
- const docSelectionRenderService = (_renderManagerService4 = renderManagerService.getRenderUnitById(unitId)) === null || _renderManagerService4 === void 0 ? void 0 : _renderManagerService4.with(_univerjs_docs_ui.DocSelectionRenderService);
3868
- const segmentId = docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.getSegment();
3869
- const segmentPage = docSelectionRenderService === null || docSelectionRenderService === void 0 ? void 0 : docSelectionRenderService.getSegmentPage();
3870
- 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);
3871
- if (drawing == null || skeleton == null || docSelectionRenderService == null) return;
3872
- const { startIndex } = drawing;
3873
- const glyph = skeleton.findNodeByCharIndex(startIndex, segmentId, segmentPage);
3874
- const line = glyph === null || glyph === void 0 || (_glyph$parent = glyph.parent) === null || _glyph$parent === void 0 ? void 0 : _glyph$parent.parent;
3875
- const column = line === null || line === void 0 ? void 0 : line.parent;
3876
- 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);
3877
- const page = column === null || column === void 0 || (_column$parent = column.parent) === null || _column$parent === void 0 ? void 0 : _column$parent.parent;
3878
- if (glyph == null || line == null || paragraphStartLine == null || column == null || page == null) return;
3879
- let delta = 0;
3880
- if (prevRelativeFrom === _univerjs_core.ObjectRelativeFromV.PARAGRAPH) delta -= paragraphStartLine.top;
3881
- else if (prevRelativeFrom === _univerjs_core.ObjectRelativeFromV.LINE) delta -= line.top;
3882
- else if (prevRelativeFrom === _univerjs_core.ObjectRelativeFromV.PAGE) delta += page.marginTop;
3883
- if (relativeFrom === _univerjs_core.ObjectRelativeFromV.PARAGRAPH) delta += paragraphStartLine.top;
3884
- else if (relativeFrom === _univerjs_core.ObjectRelativeFromV.LINE) delta += line.top;
3885
- else if (relativeFrom === _univerjs_core.ObjectRelativeFromV.PAGE) delta -= page.marginTop;
3886
- handlePositionChange("positionV", {
3887
- relativeFrom,
3888
- posOffset: (prevPosOffset ?? 0) - delta
3889
- });
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);
3890
4144
  }
3891
4145
  function handleFollowTextMoveCheck(val) {
3892
4146
  handleVerticalRelativeFromChange(val ? String(_univerjs_core.ObjectRelativeFromV.PARAGRAPH) : String(_univerjs_core.ObjectRelativeFromV.PAGE));
3893
4147
  }
3894
4148
  (0, react.useEffect)(() => {
3895
4149
  function updateState(drawingParam) {
3896
- var _snapshot$drawings;
4150
+ var _findDocDrawing2;
3897
4151
  const snapshot = documentDataModel === null || documentDataModel === void 0 ? void 0 : documentDataModel.getSnapshot();
3898
- 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);
3899
4153
  if (drawing == null) return;
3900
4154
  const { layoutType } = drawing;
3901
4155
  const { positionH, positionV } = drawing.docTransform;
@@ -4507,10 +4761,7 @@ let MobileDocDrawingPopupMenuController = class MobileDocDrawingPopupMenuControl
4507
4761
  });
4508
4762
  return (edit === null || edit === void 0 ? void 0 : edit.commandId) === command.id;
4509
4763
  });
4510
- if (command.id === EditDocDrawingOperation.id || opensDrawingEditor) {
4511
- this._isDrawingPanelOpen = true;
4512
- this._clearPopups(void 0, true);
4513
- }
4764
+ if (command.id === EditDocDrawingOperation.id || opensDrawingEditor) this._clearPopups(void 0, true);
4514
4765
  if (command.id === SidebarDocDrawingMobileOperation.id) {
4515
4766
  const params = command.params;
4516
4767
  this._isDrawingPanelOpen = (params === null || params === void 0 ? void 0 : params.value) === "open";
@@ -5221,6 +5472,105 @@ let ComponentsController = class ComponentsController extends _univerjs_core.Dis
5221
5472
  };
5222
5473
  ComponentsController = __decorate([__decorateParam(0, (0, _univerjs_core.Inject)(_univerjs_ui.ComponentManager))], ComponentsController);
5223
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
+
5224
5574
  //#endregion
5225
5575
  //#region src/controllers/shortcuts/drawing.shortcut.ts
5226
5576
  function whenDocDrawingFocused(contextService) {
@@ -5382,10 +5732,7 @@ let DocDrawingPopupMenuController = class DocDrawingPopupMenuController extends
5382
5732
  });
5383
5733
  return (edit === null || edit === void 0 ? void 0 : edit.commandId) === command.id;
5384
5734
  });
5385
- if (command.id === EditDocDrawingOperation.id || opensDrawingEditor) {
5386
- this._isDrawingPanelOpen = true;
5387
- this._clearPopups(void 0, true);
5388
- }
5735
+ if (command.id === EditDocDrawingOperation.id || opensDrawingEditor) this._clearPopups(void 0, true);
5389
5736
  if (command.id === SidebarDocDrawingOperation.id) {
5390
5737
  const params = command.params;
5391
5738
  this._isDrawingPanelOpen = (params === null || params === void 0 ? void 0 : params.value) === "open";
@@ -5703,7 +6050,11 @@ let UniverDocsDrawingUIPlugin = class UniverDocsDrawingUIPlugin extends _univerj
5703
6050
  this._injector.get(ComponentsController);
5704
6051
  }
5705
6052
  onReady() {
5706
- [[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));
5707
6058
  this._injector.get(DocDrawingAddRemoveController);
5708
6059
  this._injector.get(DocDrawingUIController);
5709
6060
  this._injector.get(DocDrawingTransformerController);
@@ -5734,7 +6085,7 @@ exports.DeleteDocDrawingsCommand = DeleteDocDrawingsCommand;
5734
6085
  exports.DocDrawingFloatingToolbarAdapterService = DocDrawingFloatingToolbarAdapterService;
5735
6086
  exports.DocDrawingPosition = DocDrawingPosition;
5736
6087
  exports.DocDrawingTextWrap = DocDrawingTextWrap;
5737
- Object.defineProperty(exports, 'DocFloatDomController', {
6088
+ Object.defineProperty(exports, "DocFloatDomController", {
5738
6089
  enumerable: true,
5739
6090
  get: function () {
5740
6091
  return DocFloatDomController;
@@ -5751,13 +6102,13 @@ exports.MobileDocDrawingTextWrap = MobileDocDrawingTextWrap;
5751
6102
  exports.MoveDocDrawingsCommand = MoveDocDrawingsCommand;
5752
6103
  exports.SidebarDocDrawingOperation = SidebarDocDrawingOperation;
5753
6104
  exports.UngroupDocDrawingCommand = UngroupDocDrawingCommand;
5754
- Object.defineProperty(exports, 'UniverDocsDrawingMobileUIPlugin', {
6105
+ Object.defineProperty(exports, "UniverDocsDrawingMobileUIPlugin", {
5755
6106
  enumerable: true,
5756
6107
  get: function () {
5757
6108
  return UniverDocsDrawingMobileUIPlugin;
5758
6109
  }
5759
6110
  });
5760
- Object.defineProperty(exports, 'UniverDocsDrawingUIPlugin', {
6111
+ Object.defineProperty(exports, "UniverDocsDrawingUIPlugin", {
5761
6112
  enumerable: true,
5762
6113
  get: function () {
5763
6114
  return UniverDocsDrawingUIPlugin;