From c3c3272b9ad2e1a3e243f2ebbe98cbeafc7c7d6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Rio?= Date: Wed, 4 Nov 2026 18:57:56 +0000 Subject: [PATCH 1/7] fix(toolbar): keep the centered title in place while measuring the slots In the ionic theme with title-placement center, measure the slotted content with a ResizeObserver instead of a setTimeout with retries, so the slot sizes are set before the first paint and updated whenever the content changes size or a hidden toolbar becomes visible. Measure the slotted elements instead of the slot so the slots shrink when their content does, and call updateSlotClasses from the onSlotchange handlers. --- .../test/title-placement/toolbar.e2e.ts | 113 +++++++++++++++ core/src/components/toolbar/toolbar.tsx | 131 +++++++++++++++--- 2 files changed, 225 insertions(+), 19 deletions(-) diff --git a/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts b/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts index 3336337ec0f..14ca1987100 100644 --- a/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts +++ b/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts @@ -1,4 +1,5 @@ import { expect } from '@playwright/test'; +import type { E2EPage } from '@utils/test/playwright'; import { configs, test } from '@utils/test/playwright'; /** @@ -43,3 +44,115 @@ configs({ modes: ['ionic-md'] }).forEach(({ title, screenshot, config }) => { }); }); }); + +/** + * Title placement is only supported by the `ionic` theme. + * This behavior does not vary across directions. + */ +configs({ modes: ['ionic-md'], directions: ['ltr'] }).forEach(({ title, config }) => { + test.describe(title('toolbar: title-placement center sizing'), () => { + /** + * Returns how far the title is from the center of the toolbar, in pixels. + */ + const getTitleOffset = async (page: E2EPage) => { + const toolbarBox = (await page.locator('ion-toolbar').boundingBox())!; + const titleBox = (await page.locator('ion-title .toolbar-title').boundingBox())!; + + const toolbarCenter = toolbarBox.x + toolbarBox.width / 2; + const titleCenter = titleBox.x + titleBox.width / 2; + + return Math.abs(titleCenter - toolbarCenter); + }; + + test('should keep the title centered when buttons are added to a slot', async ({ page }) => { + await page.setContent( + ` + + + + Back + + Center Placement + + Edit + + + + `, + config + ); + + await page.locator('ion-buttons[slot="end"]').evaluate((el) => { + el.insertAdjacentHTML('beforeend', 'Share'); + }); + + await expect.poll(() => getTitleOffset(page)).toBeLessThanOrEqual(1); + }); + + test('should give the title the space freed when buttons are removed from a slot', async ({ page }) => { + /** + * Each toolbar is in its own header so both get the same styles. + * The reference toolbar renders the final content from the start. + */ + const getHeader = (id: string, endButtons: string) => ` + + + + Back + + Center Placement + ${endButtons} + + + `; + await page.setContent( + getHeader('changed', 'EditShare') + + getHeader('reference', 'Edit'), + config + ); + + const getTitleWidth = async (headerId: string) => + (await page.locator(`#${headerId} ion-title .toolbar-title`).boundingBox())!.width; + + await page.locator('#share').evaluate((el) => el.remove()); + + // Once the Share button is gone, both toolbars have the same content. + await expect + .poll(async () => { + const changedWidth = await getTitleWidth('changed'); + const referenceWidth = await getTitleWidth('reference'); + return changedWidth - referenceWidth; + }) + .toBe(0); + }); + + test('should center the title when a hidden toolbar becomes visible', async ({ page }) => { + await page.setContent( + ` + + + + Back + + Center Placement + + Edit + Share + + + + `, + config + ); + + /** + * Pages stay hidden while they are being navigated to. Wait longer + * than the toolbar would take to give up measuring a hidden slot. + */ + await page.waitForTimeout(1000); + await page.locator('ion-header').evaluate((el: HTMLElement) => (el.style.display = '')); + + await expect.poll(() => getTitleOffset(page)).toBeLessThanOrEqual(1); + }); + }); +}); diff --git a/core/src/components/toolbar/toolbar.tsx b/core/src/components/toolbar/toolbar.tsx index 09ab315e35f..401ce12462d 100644 --- a/core/src/components/toolbar/toolbar.tsx +++ b/core/src/components/toolbar/toolbar.tsx @@ -38,6 +38,12 @@ export class Toolbar implements ComponentInterface { ]; private readonly showClasses = ['show-start', 'show-end', 'show-primary', 'show-secondary']; private readonly slotSizeVars = ['--start-end-size', '--primary-secondary-size']; + /** + * Watches the slotted content so the slot widths are measured + * again whenever that content changes size. + */ + private slotResizeObserver?: ResizeObserver; + private hasLoaded = false; @Element() el!: HTMLIonToolbarElement; @@ -80,9 +86,25 @@ export class Toolbar implements ComponentInterface { this.updateSlotClasses(); } + connectedCallback() { + /** + * The resize observer is stopped when the toolbar is removed from the DOM. + * If the toolbar is added back (for example, when it is moved), start it again. + * On the first connection the toolbar has not rendered yet, so this is left + * to componentDidLoad. + */ + if (this.hasLoaded) { + this.updateSlotClasses(); + } + } + componentDidLoad() { + this.hasLoaded = true; this.updateSlotClasses(); - this.updateSlotWidths(); + } + + disconnectedCallback() { + this.stopObservingSlotSizes(); } @Watch('titlePlacement') @@ -107,28 +129,86 @@ export class Toolbar implements ComponentInterface { * Updates the CSS custom properties for slot widths * This ensures that slots shown by their met conditions * have a minimum width matching their required slot + * + * The slotted content is watched with a ResizeObserver instead of being + * measured after a timeout: + * - The observer callback runs after layout and before paint, so the slot + * widths are set in the same frame the content is first laid out. The + * title is already centered when it is first painted and does not move. + * - The callback runs again whenever the slotted content changes size, + * for example when a button is added or removed, or when a hidden + * toolbar becomes visible. */ - private updateSlotWidths(tries: number = 0) { - // Set timeout to try to execute after everything is rendered - setTimeout(() => { - // Attempt to measure and update - const success = this.measureAndUpdateSlots(); - - // If not all measurements were successful, try again in 100 ms - // cap recursion at 5 tries for safety - if (!success && tries < 5) { - setTimeout(() => { - this.updateSlotWidths(tries + 1); - }, 100); + private updateSlotWidths() { + // Stop watching the previous content before watching the current one. + this.stopObservingSlotSizes(); + + // Browsers without ResizeObserver can only measure once. + if (typeof ResizeObserver === 'undefined') { + this.measureAndUpdateSlots(); + return; + } + + const elementsToObserve: Element[] = []; + const slots = ['start', 'end', 'primary', 'secondary']; + slots.forEach((slot) => { + if (this.el.classList.contains(`has-${slot}-content`)) { + elementsToObserve.push(...this.getSlottedElements(slot)); } }); + + if (elementsToObserve.length === 0) { + return; + } + + /** + * The observer also calls the callback once right after observing + * an element, which takes care of the first measurement. + */ + const observer = new ResizeObserver(() => this.measureAndUpdateSlots()); + elementsToObserve.forEach((element) => observer.observe(element)); + this.slotResizeObserver = observer; + } + + /** + * Stops watching the slotted content for size changes. + */ + private stopObservingSlotSizes() { + if (this.slotResizeObserver) { + this.slotResizeObserver.disconnect(); + this.slotResizeObserver = undefined; + } + } + + /** + * Returns the elements assigned to the given slot of the toolbar. + */ + private getSlottedElements(slotName: string): Element[] { + const slotElement = this.el.shadowRoot?.querySelector(`slot[name="${slotName}"]`) as HTMLSlotElement | null; + if (!slotElement) { + return []; + } + + return slotElement.assignedElements({ flatten: true }); + } + + /** + * Returns the width an element takes up in the toolbar, + * including its horizontal margins. + */ + private getOuterWidth(element: Element): number { + const { width } = element.getBoundingClientRect(); + const { marginLeft, marginRight } = getComputedStyle(element); + + return width + parseFloat(marginLeft) + parseFloat(marginRight); } /** * Measure the widths of the slots and update the CSS custom properties * for the minimum width of each pair of slots based on the largest width in each pair. * Returns whether we successfully measured all of the slots we expect to have content. - * If not, the content probably hasn't rendered yet and we need to try again. + * If not, the content probably hasn't rendered yet, and the ResizeObserver + * measures again once it does. */ private measureAndUpdateSlots(): boolean { // Define the relationship between slots based on the conditions array @@ -166,7 +246,18 @@ export class Toolbar implements ComponentInterface { this.el.style.setProperty(`--${name}-size`, 'auto'); } - const width = slotElement.offsetWidth; + /** + * Measure the slotted content rather than the slot itself. Once the + * size property is set, the slot cannot be narrower than it, so + * measuring the slot would never let it shrink when the content does. + */ + let contentWidth = 0; + assignedElements.forEach((element) => { + contentWidth += this.getOuterWidth(element); + }); + + // Round up so the content is never cut off by a fraction of a pixel. + const width = Math.ceil(contentWidth); if (width > 0) { slotWidths.set(slot, width); @@ -204,6 +295,8 @@ export class Toolbar implements ComponentInterface { * Removes all slot visibility classes and slot width CSS variables. */ private removeSlotClasses() { + // The slot widths are no longer used, so there is nothing to watch. + this.stopObservingSlotSizes(); this.el.classList.remove(...this.slotClasses, ...this.showClasses); this.slotSizeVars.forEach((cssVar) => this.el.style.removeProperty(cssVar)); } @@ -315,13 +408,13 @@ export class Toolbar implements ComponentInterface { >
- this.updateSlotClasses}> - this.updateSlotClasses}> + this.updateSlotClasses()}> + this.updateSlotClasses()}>
- this.updateSlotClasses}> - this.updateSlotClasses}> + this.updateSlotClasses()}> + this.updateSlotClasses()}>
); From c88a1d09f7a9cb4a26b3a7d74fc4128a4f15a212 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Rio?= Date: Wed, 4 Nov 2026 19:49:22 +0000 Subject: [PATCH 2/7] fix(toolbar): measure the slots instead of their content Summing the slotted elements' widths missed the space between them and did not match the slot when it shrinks, which changed the slot sizes (e.g. by 1px in WebKit). Measure the slot again, removing the size properties right before measuring so the slots can still shrink when their content does. --- core/src/components/toolbar/toolbar.tsx | 32 +++++++------------------ 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/core/src/components/toolbar/toolbar.tsx b/core/src/components/toolbar/toolbar.tsx index 401ce12462d..b289fd2dcfe 100644 --- a/core/src/components/toolbar/toolbar.tsx +++ b/core/src/components/toolbar/toolbar.tsx @@ -192,17 +192,6 @@ export class Toolbar implements ComponentInterface { return slotElement.assignedElements({ flatten: true }); } - /** - * Returns the width an element takes up in the toolbar, - * including its horizontal margins. - */ - private getOuterWidth(element: Element): number { - const { width } = element.getBoundingClientRect(); - const { marginLeft, marginRight } = getComputedStyle(element); - - return width + parseFloat(marginLeft) + parseFloat(marginRight); - } - /** * Measure the widths of the slots and update the CSS custom properties * for the minimum width of each pair of slots based on the largest width in each pair. @@ -218,6 +207,14 @@ export class Toolbar implements ComponentInterface { { name: 'primary-secondary', slots: ['primary', 'secondary'] }, ]; + /** + * Once a size property is set, the slots cannot be narrower than it. + * Remove the properties first so each slot is measured at the width of + * its content, which lets the slots shrink when their content does. + * This runs before paint, so the slots are never painted without a size. + */ + this.slotSizeVars.forEach((cssVar) => this.el.style.removeProperty(cssVar)); + // First, measure all slot widths const slotWidths = new Map(); let allMeasurementsSuccessful = true; @@ -246,18 +243,7 @@ export class Toolbar implements ComponentInterface { this.el.style.setProperty(`--${name}-size`, 'auto'); } - /** - * Measure the slotted content rather than the slot itself. Once the - * size property is set, the slot cannot be narrower than it, so - * measuring the slot would never let it shrink when the content does. - */ - let contentWidth = 0; - assignedElements.forEach((element) => { - contentWidth += this.getOuterWidth(element); - }); - - // Round up so the content is never cut off by a fraction of a pixel. - const width = Math.ceil(contentWidth); + const width = slotElement.offsetWidth; if (width > 0) { slotWidths.set(slot, width); From 41637318b940a07a1835edd90a62e01cd26b5c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Rio?= Date: Fri, 6 Nov 2026 10:25:45 +0000 Subject: [PATCH 3/7] Update core/src/components/toolbar/test/title-placement/toolbar.e2e.ts Co-authored-by: Shane --- .../components/toolbar/test/title-placement/toolbar.e2e.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts b/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts index 14ca1987100..6cdde1b034d 100644 --- a/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts +++ b/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts @@ -146,8 +146,9 @@ configs({ modes: ['ionic-md'], directions: ['ltr'] }).forEach(({ title, config } ); /** - * Pages stay hidden while they are being navigated to. Wait longer - * than the toolbar would take to give up measuring a hidden slot. + * Pages stay hidden while they are being navigated to. Keep the toolbar + * hidden long enough that it can only be centered by measuring the + * slots again once it is shown. */ await page.waitForTimeout(1000); await page.locator('ion-header').evaluate((el: HTMLElement) => (el.style.display = '')); From 72a4274658cbbb57c4c84f6cc148314d1353df9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Rio?= Date: Fri, 6 Nov 2026 10:27:46 +0000 Subject: [PATCH 4/7] Update core/src/components/toolbar/toolbar.tsx Co-authored-by: Shane --- core/src/components/toolbar/toolbar.tsx | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/core/src/components/toolbar/toolbar.tsx b/core/src/components/toolbar/toolbar.tsx index b289fd2dcfe..7256db1431f 100644 --- a/core/src/components/toolbar/toolbar.tsx +++ b/core/src/components/toolbar/toolbar.tsx @@ -130,14 +130,9 @@ export class Toolbar implements ComponentInterface { * This ensures that slots shown by their met conditions * have a minimum width matching their required slot * - * The slotted content is watched with a ResizeObserver instead of being - * measured after a timeout: - * - The observer callback runs after layout and before paint, so the slot - * widths are set in the same frame the content is first laid out. The - * title is already centered when it is first painted and does not move. - * - The callback runs again whenever the slotted content changes size, - * for example when a button is added or removed, or when a hidden - * toolbar becomes visible. + * The slotted content is watched with a ResizeObserver, which runs + * before paint and again whenever the content changes size, so the + * title is centered on first paint and stays centered. */ private updateSlotWidths() { // Stop watching the previous content before watching the current one. From 17fa7a9abac185c25a54c38f21f19c5615158139 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Rio?= Date: Fri, 6 Nov 2026 10:41:14 +0000 Subject: [PATCH 5/7] Update core/src/components/toolbar/test/title-placement/toolbar.e2e.ts Co-authored-by: Shane --- .../test/title-placement/toolbar.e2e.ts | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts b/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts index 6cdde1b034d..cd151444902 100644 --- a/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts +++ b/core/src/components/toolbar/test/title-placement/toolbar.e2e.ts @@ -155,5 +155,58 @@ configs({ modes: ['ionic-md'], directions: ['ltr'] }).forEach(({ title, config } await expect.poll(() => getTitleOffset(page)).toBeLessThanOrEqual(1); }); + + test('should keep the title centered when buttons are added to an empty slot', async ({ page }) => { + await page.setContent( + ` + + + + Back + + Center Placement + + + `, + config + ); + + await page.locator('ion-toolbar').evaluate((el) => { + el.insertAdjacentHTML( + 'beforeend', + 'EditShare' + ); + }); + + await expect.poll(() => getTitleOffset(page)).toBeLessThanOrEqual(1); + }); + + test('should keep the title centered when buttons are added after the toolbar is moved', async ({ page }) => { + await page.setContent( + ` + + + + Back + + Center Placement + + Edit + + + + `, + config + ); + + // Moving the header disconnects and reconnects the toolbar. + await page.locator('ion-header').evaluate((el) => el.parentElement!.appendChild(el)); + + await page.locator('ion-buttons[slot="end"]').evaluate((el) => { + el.insertAdjacentHTML('beforeend', 'Share'); + }); + + await expect.poll(() => getTitleOffset(page)).toBeLessThanOrEqual(1); + }); }); }); From 8c70fdf829f61465d1ee4ae8e2f0f5373c5e8282 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Rio?= Date: Fri, 6 Nov 2026 10:43:06 +0000 Subject: [PATCH 6/7] refactor(toolbar): remove the unused return value of measureAndUpdateSlots --- core/src/components/toolbar/toolbar.tsx | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/core/src/components/toolbar/toolbar.tsx b/core/src/components/toolbar/toolbar.tsx index 7256db1431f..c498a446284 100644 --- a/core/src/components/toolbar/toolbar.tsx +++ b/core/src/components/toolbar/toolbar.tsx @@ -190,11 +190,10 @@ export class Toolbar implements ComponentInterface { /** * Measure the widths of the slots and update the CSS custom properties * for the minimum width of each pair of slots based on the largest width in each pair. - * Returns whether we successfully measured all of the slots we expect to have content. - * If not, the content probably hasn't rendered yet, and the ResizeObserver - * measures again once it does. + * Slots that measure 0 (for example, in a hidden toolbar) are skipped. The + * ResizeObserver measures them again when their content changes size. */ - private measureAndUpdateSlots(): boolean { + private measureAndUpdateSlots() { // Define the relationship between slots based on the conditions array // Group slots that should have the same width const slotPairs = [ @@ -212,7 +211,6 @@ export class Toolbar implements ComponentInterface { // First, measure all slot widths const slotWidths = new Map(); - let allMeasurementsSuccessful = true; // Measure all slots with content const slots = ['start', 'end', 'primary', 'secondary']; @@ -242,8 +240,6 @@ export class Toolbar implements ComponentInterface { if (width > 0) { slotWidths.set(slot, width); - } else { - allMeasurementsSuccessful = false; } } } @@ -268,8 +264,6 @@ export class Toolbar implements ComponentInterface { this.el.style.setProperty(`--${name}-size`, `${maxWidth}px`); } }); - - return allMeasurementsSuccessful; } /** From bf8963ff898247a4c9c2f5a55d5b774a0f907ff8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=CC=81=20Rio?= Date: Tue, 10 Nov 2026 10:28:29 +0000 Subject: [PATCH 7/7] refactor(toolbar): share the slot names and slot lookup; rename hasLoaded to didLoad --- core/src/components/toolbar/toolbar.tsx | 27 +++++++++++++------------ 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/core/src/components/toolbar/toolbar.tsx b/core/src/components/toolbar/toolbar.tsx index c498a446284..1e33af3877a 100644 --- a/core/src/components/toolbar/toolbar.tsx +++ b/core/src/components/toolbar/toolbar.tsx @@ -30,6 +30,7 @@ import type { Color, CssClassMap, StyleEventDetail } from '../../interface'; }) export class Toolbar implements ComponentInterface { private childrenStyles = new Map(); + private readonly slotNames = ['start', 'end', 'primary', 'secondary']; private readonly slotClasses = [ 'has-start-content', 'has-end-content', @@ -43,7 +44,7 @@ export class Toolbar implements ComponentInterface { * again whenever that content changes size. */ private slotResizeObserver?: ResizeObserver; - private hasLoaded = false; + private didLoad = false; @Element() el!: HTMLIonToolbarElement; @@ -93,13 +94,13 @@ export class Toolbar implements ComponentInterface { * On the first connection the toolbar has not rendered yet, so this is left * to componentDidLoad. */ - if (this.hasLoaded) { + if (this.didLoad) { this.updateSlotClasses(); } } componentDidLoad() { - this.hasLoaded = true; + this.didLoad = true; this.updateSlotClasses(); } @@ -145,8 +146,7 @@ export class Toolbar implements ComponentInterface { } const elementsToObserve: Element[] = []; - const slots = ['start', 'end', 'primary', 'secondary']; - slots.forEach((slot) => { + this.slotNames.forEach((slot) => { if (this.el.classList.contains(`has-${slot}-content`)) { elementsToObserve.push(...this.getSlottedElements(slot)); } @@ -179,7 +179,7 @@ export class Toolbar implements ComponentInterface { * Returns the elements assigned to the given slot of the toolbar. */ private getSlottedElements(slotName: string): Element[] { - const slotElement = this.el.shadowRoot?.querySelector(`slot[name="${slotName}"]`) as HTMLSlotElement | null; + const slotElement = this.getSlotElement(slotName); if (!slotElement) { return []; } @@ -213,10 +213,9 @@ export class Toolbar implements ComponentInterface { const slotWidths = new Map(); // Measure all slots with content - const slots = ['start', 'end', 'primary', 'secondary']; - slots.forEach((slot) => { + this.slotNames.forEach((slot) => { if (this.el.classList.contains(`has-${slot}-content`)) { - const slotElement = this.el.shadowRoot?.querySelector(`slot[name="${slot}"]`) as HTMLSlotElement | null; + const slotElement = this.getSlotElement(slot); if (slotElement) { // Check if the slot contains an img or ion-img const assignedElements = slotElement.assignedElements({ flatten: true }); @@ -284,11 +283,9 @@ export class Toolbar implements ComponentInterface { } // Check if slots have content - const slots = ['start', 'end', 'primary', 'secondary']; - const classesToAdd: string[] = []; const classesToRemove: string[] = []; - slots.forEach((slot) => { + this.slotNames.forEach((slot) => { const slotHasContent = this.hasSlotContent(slot); const slotClass = `has-${slot}-content`; if (slotHasContent) { @@ -330,10 +327,14 @@ export class Toolbar implements ComponentInterface { } private hasSlotContent(slotName: string): boolean { - const slotNode = this.el.shadowRoot?.querySelector(`slot[name="${slotName}"]`) as HTMLSlotElement | null; + const slotNode = this.getSlotElement(slotName); return !!slotNode && slotNode.assignedNodes().length > 0; } + private getSlotElement(slotName: string): HTMLSlotElement | null { + return this.el.shadowRoot?.querySelector(`slot[name="${slotName}"]`) ?? null; + } + @Listen('ionStyle') childrenStyle(ev: CustomEvent) { ev.stopPropagation();