Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix: preserve embed hosts and align checkbox markers (#7488)

Univer151f8283a9f0
diff --git a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
index 91a9426e70..4eb947fd6f 100644
--- a/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
+++ b/packages/engine-render/src/components/docs/extensions/__tests__/font-and-base-line.spec.ts
@@ -311,13 +311,23 @@ describe('docs font and baseline extension', () => {
const checkedGlyph = createGlyph('\u2611', {
glyphType: GlyphType.LIST,
+ bBox: {
+ width: 18,
+ aba: 14,
+ abd: 4,
+ },
ts: {
fs: 10,
cl: { rgb: '#111111' },
},
});
extension.draw(TestContext, DEFAULT_SCALE, checkedGlyph);
- expect(checkSpy).toHaveBeenCalled();
+ expect(TestContext.translate).toHaveBeenCalledWith(29.5, 35.5);
+ expect(checkSpy).toHaveBeenCalledWith(TestContext, {
+ width: 18,
+ height: 18,
+ checked: true,
+ });
extension.clearCache();
extension.extensionOffset = {
diff --git a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
index f34c18314e..b6fc3381aa 100644
--- a/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
+++ b/packages/engine-render/src/components/docs/extensions/font-and-base-line.ts
@@ -25,7 +25,7 @@ import { cjk } from '../../../basics/cjk-regexp';
import { COLOR_BLACK_RGB } from '../../../basics/const';
import { resolveGlowEffect, resolveOuterShadowEffect } from '../../../basics/drawing-effect';
import { Vector2 } from '../../../basics/vector2';
-import { CheckboxShape } from '../../../shape';
+import { CheckboxShape, isCheckboxGlyph } from '../../../shape/checkbox';
import { DocumentsSpanAndLineExtensionRegistry } from '../../extension';
import { docExtension } from '../doc-extension';
@@ -428,23 +428,18 @@ export class FontAndBaseLine extends docExtension {
ctx.fillText(content, 0, 0);
ctx.restore();
} else {
- const CHECKED_GLYPH = '\u2611';
- const UNCHECKED_GLYPH = '\u2610';
- if ((content === UNCHECKED_GLYPH || content === CHECKED_GLYPH) && glyph.glyphType === GlyphType.LIST) {
- const size = Math.ceil((glyph.ts?.fs ?? 12) * 1.2);
+ if (isCheckboxGlyph(content) && glyph.glyphType === GlyphType.LIST) {
+ const size = glyph.bBox.width;
ctx.save();
- const fontHeight = glyph.bBox.aba - glyph.bBox.abd;
- const bottom = spanPointWithFont.y;
- const top = bottom - fontHeight;
const left = spanPointWithFont.x;
- const topOffset = top + (bottom - top - size) / 2;
- const leftOffset = left;
+ const top = spanPointWithFont.y - glyph.bBox.aba;
const BORDER_WIDTH = 1;
- ctx.translate(leftOffset - BORDER_WIDTH / 2, topOffset - BORDER_WIDTH / 2);
+ // The layout bbox already centers the custom shape on the marker's measured font metrics.
+ ctx.translate(left - BORDER_WIDTH / 2, top - BORDER_WIDTH / 2);
CheckboxShape.drawWith(ctx, {
width: size,
height: size,
- checked: content === CHECKED_GLYPH,
+ checked: content === '\u2611',
});
ctx.restore();
} else {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
index 5c9e0ac97f..dd071a8659 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/__tests__/layout-ruler.spec.ts
@@ -139,6 +139,36 @@ describe('layout-ruler', () => {
expect(result[0].sections[0].columns[0].lines[0].divides[0].glyphGroup[0].width).toBe(21);
});
+ it('does not compress a wide list marker into the hanging indent', () => {
+ const { ctx, paragraphNode, sectionBreakConfig, curPage } = createParagraphLayoutTestBed('Item');
+ const shapedTextList = shaping(ctx, paragraphNode.content!, ctx.viewModel, paragraphNode, sectionBreakConfig);
+ const paragraphConfig = {
+ paragraphIndex: paragraphNode.endIndex,
+ paragraphStyle: {},
+ bulletSkeleton: {
+ listId: 'wide-list',
+ symbol: '12345',
+ ts: { ff: 'Arial', fs: 9 },
+ startIndexItem: 1,
+ paragraphProperties: {
+ hanging: { v: 21 },
+ indentStart: { v: 0 },
+ },
+ },
+ } as unknown as IParagraphConfig;
+
+ const result = layoutParagraph(
+ ctx,
+ shapedTextList[0].glyphs,
+ [curPage],
+ sectionBreakConfig,
+ paragraphConfig,
+ true
+ );
+
+ expect(result[0].sections[0].columns[0].lines[0].divides[0].glyphGroup[0].width).toBe(42);
+ });
+
it('preserves bullet styles from a real PowerPoint import snapshot', () => {
const expectedCases = {
'case-A': {
diff --git a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
index acd52c3d48..cb05fa96fb 100644
--- a/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
+++ b/packages/engine-render/src/components/docs/layout/block/paragraph/layout-ruler.ts
@@ -130,6 +130,7 @@ export function layoutParagraph(
// elementIndex === 0 means the first character at the beginning of a paragraph, needs a new line to distinguish from the previous paragraph
if (renderBullet && paragraphConfig.bulletSkeleton) {
const { bulletSkeleton, paragraphStyle = {} } = paragraphConfig;
+ const directParagraphHanging = paragraphStyle.hanging;
// If it is the beginning of a paragraph, bullet needs to be added
const { gridType = GridType.LINES, charSpace = 0, defaultTabStop = 10.5 } = sectionBreakConfig;
@@ -150,7 +151,10 @@ export function layoutParagraph(
const hangingWidth = getNumberUnitValue(paragraphConfig.paragraphStyle.hanging, charSpaceApply);
if (hangingWidth > 0) {
- bulletGlyph.width = hangingWidth;
+ // Direct paragraph hanging is authored layout; the list default is only a minimum marker width.
+ bulletGlyph.width = directParagraphHanging == null
+ ? Math.max(bulletGlyph.width, hangingWidth)
+ : hangingWidth;
}
_lineOperator(ctx, [bulletGlyph, ...glyphGroup], pages, sectionBreakConfig, paragraphConfig, isParagraphFirstShapedText, breakPointType);
diff --git a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
index 47694917ec..b245afddf6 100644
--- a/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
+++ b/packages/engine-render/src/components/docs/layout/model/__tests__/glyph.spec.ts
@@ -224,6 +224,50 @@ describe('Glyph utils test cases', () => {
expect(measuredFont).toContain('24pt');
measureSpy.mockRestore();
});
+
+ it('centers the custom checkbox shape on the measured marker metrics', () => {
+ const measureSpy = vi.spyOn(FontCache, 'getTextSize').mockReturnValue({
+ width: 16,
+ ba: 18,
+ bd: 2,
+ aba: 18,
+ abd: 2,
+ sp: 0,
+ sbr: 0,
+ sbo: 0,
+ spr: 0,
+ spo: 0,
+ });
+
+ const bulletGlyph = createSkeletonBulletGlyph(
+ {
+ ts: { fs: 20 },
+ bBox: { ba: 18, bd: 2 },
+ } as IDocumentSkeletonGlyph,
+ {
+ listId: 'check-list',
+ symbol: '\u2610',
+ ts: { fs: 20 },
+ startIndexItem: 1,
+ },
+ 10
+ );
+
+ expect(bulletGlyph.width).toBe(30);
+ expect(bulletGlyph.bBox).toMatchObject({
+ width: 24,
+ ba: 20,
+ bd: 4,
+ aba: 20,
+ abd: 4,
+ });
+ expect(bulletGlyph.bBox.ba + bulletGlyph.bBox.bd).toBe(24);
+ expect(bulletGlyph.bBox.aba + bulletGlyph.bBox.abd).toBe(24);
+ expect((bulletGlyph.bBox.bd - bulletGlyph.bBox.ba) / 2).toBe(-8);
+ expect((bulletGlyph.bBox.abd - bulletGlyph.bBox.aba) / 2).toBe(-8);
+ expect(bulletGlyph.width).toBeGreaterThanOrEqual(bulletGlyph.bBox.width);
+ measureSpy.mockRestore();
+ });
});
describe('test font compatibility policy', () => {
diff --git a/packages/engine-render/src/components/docs/layout/model/glyph.ts b/packages/engine-render/src/components/docs/layout/model/glyph.ts
index 3fbb352d9a..58cb3ddd5e 100644
--- a/packages/engine-render/src/components/docs/layout/model/glyph.ts
+++ b/packages/engine-render/src/components/docs/layout/model/glyph.ts
@@ -31,6 +31,7 @@ import {
isCjkLeftAlignedPunctuation,
isCjkRightAlignedPunctuation,
} from '../../../../basics/tools';
+import { getCheckboxShapeSize, isCheckboxGlyph } from '../../../../shape/checkbox';
import {
applyFontMetricCompatibility,
getDocumentCompatibilityPolicy,
@@ -314,7 +315,11 @@ export function createSkeletonBulletGlyph(
},
};
const fontStyle = getFontStyleString(textStyle);
- const boundingBox = FontCache.getTextSize(content, fontStyle);
+ const measuredBoundingBox = FontCache.getTextSize(content, fontStyle);
+ const checkboxSize = isCheckboxGlyph(content) ? getCheckboxShapeSize(textStyle.fs) : null;
+ const boundingBox = checkboxSize == null
+ ? measuredBoundingBox
+ : _getCheckboxBoundingBox(measuredBoundingBox, checkboxSize);
const contentWidth = boundingBox.width;
// When text also needs to align to the grid, process it. LINES default reference is the global font size of the doc
@@ -334,7 +339,7 @@ export function createSkeletonBulletGlyph(
}
}
- const bBox = _getMaxBoundingBox(glyph, boundingBox);
+ const bBox = checkboxSize == null ? _getMaxBoundingBox(glyph, boundingBox) : boundingBox;
return {
content,
@@ -354,6 +359,24 @@ export function createSkeletonBulletGlyph(
};
}
+function _getCheckboxBoundingBox(
+ boundingBox: IDocumentSkeletonBoundingBox,
+ size: number
+): IDocumentSkeletonBoundingBox {
+ const fontExtra = size - Math.abs(boundingBox.ba) - Math.abs(boundingBox.bd);
+ const actualExtra = size - Math.abs(boundingBox.aba) - Math.abs(boundingBox.abd);
+
+ // Expand equally above and below the measured glyph so its font-relative center stays stable.
+ return {
+ ...boundingBox,
+ width: size,
+ ba: Math.abs(boundingBox.ba) + fontExtra / 2,
+ bd: Math.abs(boundingBox.bd) + fontExtra / 2,
+ aba: Math.abs(boundingBox.aba) + actualExtra / 2,
+ abd: Math.abs(boundingBox.abd) + actualExtra / 2,
+ };
+}
+
// Set the left value of the current glyph based on the width of pre glyph and the left value of the previous glyph.
export function setGlyphGroupLeft(glyphGroup: IDocumentSkeletonGlyph[], left: number = 0) {
const spanGroupLen = glyphGroup.length;
diff --git a/packages/engine-render/src/shape/checkbox.ts b/packages/engine-render/src/shape/checkbox.ts
index 6037053b9b..519184aab8 100644
--- a/packages/engine-render/src/shape/checkbox.ts
+++ b/packages/engine-render/src/shape/checkbox.ts
@@ -25,6 +25,14 @@ export interface ICheckboxShapeProps extends IShapeProps {
export const CHECK_OBJECT_ARRAY = ['checked'];
+export function isCheckboxGlyph(content: string): boolean {
+ return content === '\u2610' || content === '\u2611';
+}
+
+export function getCheckboxShapeSize(fontSize = 12): number {
+ return Math.ceil(fontSize * 1.2);
+}
+
export class CheckboxShape extends Shape<ICheckboxShapeProps> {
_checked = false;
diff --git a/packages/sheets-ui/src/index.ts b/packages/sheets-ui/src/index.ts
index 49cc64fc2b..677ecfa66a 100644
--- a/packages/sheets-ui/src/index.ts
+++ b/packages/sheets-ui/src/index.ts
@@ -251,6 +251,7 @@ export { SELECTION_SHAPE_DEPTH } from './services/selection/const';
export { SelectionControl, SelectionControl as SelectionShape } from './services/selection/selection-control';
export { SheetSelectionRenderService } from './services/selection/selection-render.service';
export { SelectionShapeExtension } from './services/selection/selection-shape-extension';
+export { ISheetBarService, SheetBarService } from './services/sheet-bar/sheet-bar.service';
export {
ISheetEmbedFloatingGeometryService,
ISheetEmbedInteractionBoundaryService,
diff --git a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
index c49a5d6a76..b8eee7b345 100644
--- a/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
+++ b/packages/sheets-ui/src/views/sheet-container/SheetContainer.tsx
@@ -27,11 +27,14 @@ import {
UniverInstanceType,
} from '@univerjs/core';
import { clsx } from '@univerjs/design';
+import { IRenderManagerService } from '@univerjs/engine-render';
import { LoadingMultiIcon } from '@univerjs/icons';
import { ComponentManager, ContextMenuPosition, IMenuManagerService, ToolbarItem, useConfigValue, useDependency, useObservable } from '@univerjs/ui';
import { useEffect, useMemo } from 'react';
+import { EMPTY, merge } from 'rxjs';
import { SHEETS_UI_PLUGIN_CONFIG_KEY } from '../../config/config';
import { getEmbedSheetsTabCustomData } from '../../embed-tab-anchor';
+import { ISheetEmbedRuntimeFocusCoordinator } from '../../services/sheet-embed-integration.service';
import { ISheetEmbedRuntimeService } from '../../services/sheet-embed-runtime.service';
import { AutoFillPopupMenu } from '../auto-fill-popup-menu/AutoFillPopupMenu';
import { EditorContainer } from '../editor-container/EditorContainer';
@@ -54,7 +57,7 @@ export function RenderSheetFooter() {
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
const menuManagerService = useDependency(IMenuManagerService);
const showFooter = config?.footer ?? true;
- const activeWorkbook = useActiveWorkbook();
+ const activeWorkbook = useRootWorkbenchWorkbook();
const loadingWorkbook = useSheetLoadingWorkbook();
const workbook = loadingWorkbook ?? activeWorkbook;
const isLoading = useSheetLoading();
@@ -113,7 +116,7 @@ export function RenderSheetFooter() {
export function RenderSheetHeader() {
const config = useConfigValue<IUniverSheetsUIConfig>(SHEETS_UI_PLUGIN_CONFIG_KEY);
- const activeWorkbook = useActiveWorkbook();
+ const activeWorkbook = useRootWorkbenchWorkbook();
const loadingWorkbook = useSheetLoadingWorkbook();
const workbook = loadingWorkbook ?? activeWorkbook;
const isLoading = useSheetLoading();
@@ -157,18 +160,21 @@ export function RenderSheetContent() {
const isLoading = useSheetLoading();
const isPreviewReady = useSheetLoadingPreviewReady();
const componentManager = useDependency(ComponentManager);
- const activeWorkbook = useActiveWorkbook();
+ const activeWorkbook = useRootWorkbenchWorkbook();
const loadingWorkbook = useSheetLoadingWorkbook();
const workbook = loadingWorkbook ?? activeWorkbook;
const activeEmbedTab = useActiveSheetEmbedTabData(workbook);
const injector = useDependency(Injector);
const activeWorkbookEmbeddedRender = useActiveWorkbookIsEmbeddedRender(workbook);
+ const focusedUnitType = useFocusedUnitType();
+ // An active embed tab remains the root Sheet surface; other product focus hides the Sheet workbench.
+ const rootWorkbenchOwnsSheet = activeEmbedTab != null || focusedUnitType == null || focusedUnitType === UniverInstanceType.UNIVER_SHEET;
// We use string keys to avoid a hard dependency on sheets-shape-ui.
const ShapeTextEditorContainer = componentManager.get('SheetShapeTextEditorContainer') ?? componentManager.get('ShapeTextEditorContainer');
useEffect(() => {
- if (!workbook || isLoading || activeEmbedTab || activeWorkbookEmbeddedRender) {
+ if (!workbook || isLoading || activeEmbedTab || activeWorkbookEmbeddedRender || !rootWorkbenchOwnsSheet) {
return;
}
@@ -176,9 +182,10 @@ export function RenderSheetContent() {
instanceService.setCurrentUnitForType(workbook.getUnitId());
instanceService.focusUnit(workbook.getUnitId());
tryGetSheetEmbedRuntimeService(injector)?.clearTab();
- }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, isLoading, workbook]);
+ }, [activeEmbedTab, activeWorkbookEmbeddedRender, injector, isLoading, rootWorkbenchOwnsSheet, workbook]);
if (!workbook) return null;
+ if (!rootWorkbenchOwnsSheet) return null;
if (isLoading) return isPreviewReady ? null : <SheetLoadingSkeleton />;
if (activeWorkbookEmbeddedRender) return null;
if (activeEmbedTab && workbook) {
@@ -289,13 +296,62 @@ function RenderSheetEmbedTabHost(props: { workbook: Workbook; worksheet: Workshe
function useActiveWorkbookIsEmbeddedRender(workbook: Workbook | null): boolean {
const univerInstanceService = useDependency(IUniverInstanceService);
+ const renderManagerService = useDependency(IRenderManagerService);
+ const injector = useDependency(Injector);
+ const runtimeFocusCoordinator = injector.has(ISheetEmbedRuntimeFocusCoordinator)
+ ? injector.get(ISheetEmbedRuntimeFocusCoordinator)
+ : undefined;
+ const renderLifecycle = useObservable(
+ () => merge(
+ renderManagerService.created$,
+ renderManagerService.disposed$,
+ runtimeFocusCoordinator?.runtimeSessionChanged$ ?? EMPTY
+ ),
+ null,
+ false,
+ [renderManagerService, runtimeFocusCoordinator]
+ );
return useMemo(() => {
+ void renderLifecycle;
if (!workbook) {
return false;
}
- return univerInstanceService.getUnitCreateOptions(workbook.getUnitId())?.embeddedRender === true;
- }, [univerInstanceService, workbook]);
+ // Imported Units may gain embedded ownership only after their non-main renderer is created.
+ return runtimeFocusCoordinator?.resolveRuntimeScopeByChildUnitId(workbook.getUnitId()) != null ||
+ renderManagerService.getRenderUnitById(workbook.getUnitId())?.isMainScene === false ||
+ univerInstanceService.getUnitCreateOptions(workbook.getUnitId())?.embeddedRender === true;
+ }, [renderLifecycle, renderManagerService, runtimeFocusCoordinator, univerInstanceService, workbook]);
+}
+
+function useRootWorkbenchWorkbook(): Workbook | null {
+ const activeWorkbook = useActiveWorkbook();
+ const injector = useDependency(Injector);
+ const instanceService = useDependency(IUniverInstanceService);
+ const runtimeFocusCoordinator = injector.has(ISheetEmbedRuntimeFocusCoordinator)
+ ? injector.get(ISheetEmbedRuntimeFocusCoordinator)
+ : undefined;
+ const runtimeSessionLifecycle = useObservable(
+ () => runtimeFocusCoordinator?.runtimeSessionChanged$ ?? EMPTY,
+ null,
+ false,
+ [runtimeFocusCoordinator]
+ );
+
+ return useMemo(() => {
+ void runtimeSessionLifecycle;
+ if (!activeWorkbook || !runtimeFocusCoordinator) {
+ return activeWorkbook;
+ }
+
+ const runtimeScope = runtimeFocusCoordinator.resolveRuntimeScopeByChildUnitId(activeWorkbook.getUnitId());
+ if (!runtimeScope?.hostUnitId) {
+ return activeWorkbook;
+ }
+
+ // Same-type embeds keep the host workbook in the root workbench while the child uses scoped services.
+ return instanceService.getUnit<Workbook>(runtimeScope.hostUnitId, UniverInstanceType.UNIVER_SHEET) ?? activeWorkbook;
+ }, [activeWorkbook, instanceService, runtimeFocusCoordinator, runtimeSessionLifecycle]);
}
function useFocusedUnitType(): UniverInstanceType | null {
diff --git a/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts b/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts
index 609a47d94d..22f5639742 100644
--- a/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts
+++ b/packages/ui/src/controllers/ui/__tests__/ui-shared.controller.spec.ts
@@ -48,17 +48,18 @@ class TestSingleUnitUIController extends SingleUnitUIController {
}
}
-function createRenderer(unitId: string) {
+function createRenderer(unitId: string, isMainScene = true) {
const canvas = document.createElement('canvas');
return {
unitId,
+ isMainScene,
activate: vi.fn(),
deactivate: vi.fn(),
engine: {
getCanvasElement: () => canvas,
- mount: vi.fn(),
- unmount: vi.fn(),
+ mount: vi.fn((element: HTMLElement) => element.appendChild(canvas)),
+ unmount: vi.fn(() => canvas.remove()),
},
};
}
@@ -144,6 +145,10 @@ describe('SingleUnitUIController', () => {
focused$.next('render-2');
expect(render2.engine.mount).toHaveBeenCalledTimes(1);
+ render2.engine.getCanvasElement().remove();
+ focused$.next('render-2');
+ expect(render2.engine.mount).toHaveBeenCalledTimes(2);
+
focused$.next('render-3');
expect(render2.deactivate).toHaveBeenCalledTimes(1);
expect(render2.engine.unmount).toHaveBeenCalledTimes(1);
@@ -154,7 +159,8 @@ describe('SingleUnitUIController', () => {
disposed$.next('render-3');
focused$.next('render-3');
- expect(render3.engine.mount).toHaveBeenCalledTimes(2);
+ expect(render3.engine.mount).toHaveBeenCalledTimes(1);
+ expect(render3.activate).toHaveBeenCalledTimes(2);
vi.advanceTimersByTime(3000);
expect(lifecycleService.stage).toBe(LifecycleStages.Steady);
@@ -208,7 +214,7 @@ describe('SingleUnitUIController', () => {
expect(renderer.activate).toHaveBeenCalledTimes(1);
});
- it('should not mount embedded renderers into the global workbench content', async () => {
+ it('should not switch the global workbench to a non-main renderer', async () => {
vi.useFakeTimers();
const layoutService = {
@@ -219,7 +225,9 @@ describe('SingleUnitUIController', () => {
const focused$ = new Subject<string>();
const created$ = new Subject<any>();
const normalRender = createRenderer('normal-render');
- const embeddedRender = createRenderer('embedded-render');
+ const embeddedRender = createRenderer('embedded-render', false);
+ const productCanvasHost = document.createElement('div');
+ productCanvasHost.appendChild(embeddedRender.engine.getCanvasElement());
const rendererMap = new Map<string, any>([
['normal-render', normalRender],
['embedded-render', embeddedRender],
@@ -235,7 +243,7 @@ describe('SingleUnitUIController', () => {
const instanceService = {
focused$,
getFocusedUnit: vi.fn(() => ({ getUnitId: () => 'embedded-render' })),
- getUnitCreateOptions: vi.fn((unitId: string) => unitId === 'embedded-render' ? { embeddedRender: true } : null),
+ getUnitCreateOptions: vi.fn(() => null),
};
const lifecycleService = {
@@ -262,8 +270,11 @@ describe('SingleUnitUIController', () => {
expect(embeddedRender.engine.mount).not.toHaveBeenCalled();
focused$.next('embedded-render');
+ expect(normalRender.deactivate).not.toHaveBeenCalled();
expect(normalRender.engine.unmount).not.toHaveBeenCalled();
expect(embeddedRender.engine.mount).not.toHaveBeenCalled();
+ expect(embeddedRender.engine.getCanvasElement().parentElement).toBe(productCanvasHost);
+ expect(embeddedRender.activate).not.toHaveBeenCalled();
created$.next({ unitId: 'embedded-render' });
expect(embeddedRender.engine.mount).not.toHaveBeenCalled();
diff --git a/packages/ui/src/controllers/ui/ui-shared.controller.ts b/packages/ui/src/controllers/ui/ui-shared.controller.ts
index f96e68003f..37da04e21a 100644
--- a/packages/ui/src/controllers/ui/ui-shared.controller.ts
+++ b/packages/ui/src/controllers/ui/ui-shared.controller.ts
@@ -109,18 +109,27 @@ export abstract class SingleUnitUIController extends Disposable {
private _currentRenderId: string | null = null;
private _changeRenderUnit(rendererId: string, contentElement: HTMLElement): boolean {
- if (this._currentRenderId === rendererId) return false;
- if (this._instanceService.getUnitCreateOptions(rendererId)?.embeddedRender) return false;
-
- const renderer = this._renderManagerService.getRenderUnitById(rendererId)!;
- if (!renderer || !renderer.unitId || isInternalEditorID(renderer.unitId)) return false;
+ const renderer = this._renderManagerService.getRenderUnitById(rendererId);
+ if (
+ !renderer ||
+ !renderer.unitId ||
+ renderer.isMainScene === false ||
+ isInternalEditorID(renderer.unitId)
+ ) {
+ return false;
+ }
- const currentRenderer = this._currentRenderId
- ? this._renderManagerService.getRenderUnitById(this._currentRenderId)
- : null;
- currentRenderer?.deactivate();
- currentRenderer?.engine.unmount();
const canvas = renderer.engine.getCanvasElement();
+ const isCurrentRenderer = this._currentRenderId === rendererId;
+ if (isCurrentRenderer && contentElement.contains(canvas)) return false;
+
+ if (!isCurrentRenderer) {
+ const currentRenderer = this._currentRenderId
+ ? this._renderManagerService.getRenderUnitById(this._currentRenderId)
+ : null;
+ currentRenderer?.deactivate();
+ currentRenderer?.engine.unmount();
+ }
if (!contentElement.contains(canvas)) {
renderer.engine.mount(contentElement);
}