Repository navigation
[iOS] Label: Reduce initial attributed-text formatting work - #37840
Conversation
Map native text and font before attributed-text formatting during initial iOS and Mac Catalyst handler connection, avoiding recursive formatting passes while preserving dynamic updates. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 5a03e13d-1a41-4652-a8c6-099eeb79cd50
|
🚀 Dogfood this PR with:
curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 37840Or
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 37840" |
|
Azure Pipelines: Successfully started running 1 pipeline(s). There may be pipelines that require an authorized user to comment /azp run to run. |
There was a problem hiding this comment.
Pull request overview
This PR optimizes iOS/MacCatalyst Label initialization by changing mapper ordering and suppressing redundant attributed-text formatting work during handler connection, aiming to reduce extra formatting passes while preserving runtime formatting updates.
Changes:
- Skip
MapFormattinginside iOSMapTextduring initial handler connection to avoid double-applying formatting. - Reorder iOS/MacCatalyst
LabelHandler.Mapperentries soText/Font/CharacterSpacingare applied earlier in the initial mapping pass. - Apply the same “skip formatting during connect” behavior for the Controls
LabeliOS mapper.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
| src/Core/src/Handlers/Label/LabelHandler.iOS.cs | Avoids reapplying formatting from MapText during initial connect. |
| src/Core/src/Handlers/Label/LabelHandler.cs | Reorders iOS/MacCatalyst mapper entries to reduce redundant formatting work during initialization. |
| src/Controls/src/Core/Label/Label.iOS.cs | Mirrors the “skip formatting during connect” behavior for Controls Label on iOS. |
| #if IOS || MACCATALYST | ||
| // Attributed-text formatting must run after Text creates the native attributed string. | ||
| [nameof(ILabel.Text)] = MapText, | ||
| [nameof(ITextStyle.Font)] = MapFont, | ||
| [nameof(ITextStyle.CharacterSpacing)] = MapCharacterSpacing, | ||
| #else | ||
| [nameof(ITextStyle.CharacterSpacing)] = MapCharacterSpacing, | ||
| [nameof(ITextStyle.Font)] = MapFont, | ||
| #endif | ||
| [nameof(ITextAlignment.HorizontalTextAlignment)] = MapHorizontalTextAlignment, | ||
| [nameof(ITextAlignment.VerticalTextAlignment)] = MapVerticalTextAlignment, | ||
| [nameof(ILabel.LineHeight)] = MapLineHeight, | ||
| [nameof(ILabel.Padding)] = MapPadding, | ||
| #if !IOS && !MACCATALYST | ||
| [nameof(ILabel.Text)] = MapText, | ||
| #endif | ||
| [nameof(ITextStyle.TextColor)] = MapTextColor, | ||
| [nameof(ILabel.TextDecorations)] = MapTextDecorations, |
| handler.PlatformView?.UpdateTextPlainText(label); | ||
|
|
||
| // Any text update requires that we update any attributed string formatting | ||
| MapFormatting(handler, label); | ||
| if (!handler.IsConnectingHandler()) | ||
| { | ||
| // Text changes can replace the attributed string, so reapply its formatting. | ||
| MapFormatting(handler, label); | ||
| } | ||
| } |
| public static void MapText(ILabelHandler handler, Label label) | ||
| { | ||
| Platform.LabelExtensions.UpdateText(handler.PlatformView, label); | ||
|
|
||
| MapFormatting(handler, label); | ||
| if (!handler.IsConnectingHandler()) | ||
| { | ||
| MapFormatting(handler, label); | ||
| } | ||
| } |
This comment has been minimized.
This comment has been minimized.
|
/azp run |
|
Azure Pipelines: Successfully started running 3 pipeline(s). |
This comment has been minimized.
This comment has been minimized.
MauiBot
left a comment
There was a problem hiding this comment.
Expert Review — 2 findings
See inline comments for details.
| [nameof(ITextStyle.CharacterSpacing)] = MapCharacterSpacing, | ||
| [nameof(ITextStyle.Font)] = MapFont, | ||
| #endif | ||
| [nameof(ITextAlignment.HorizontalTextAlignment)] = MapHorizontalTextAlignment, |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[major] Handler Mapper and Property Patterns / Logic and Correctness — With MapFormatting now skipped while IsConnectingHandler() is true (LabelHandler.iOS.cs:51, Label.iOS.cs:26), the initial mapping pass is the only thing that applies attributed-text formatting, but its order does not preserve the invariant MapFormatting was written to enforce. MapFormatting deliberately re-applies HorizontalTextAlignment last ("Setting any of those may have removed text alignment settings, so we need to make sure those are applied, too", LabelHandler.iOS.cs:104-107). In the new iOS/MacCatalyst mapper order, HorizontalTextAlignment (this line) runs before LineHeight (line 42) and TextDecorations (line 48). Both of those re-assign UILabel.AttributedText with a paragraph style built from WithLineHeight/WithDecorations; when the source attributed string carries no ParagraphStyle attribute, WithLineHeight creates a fresh NSMutableParagraphStyle (default/natural alignment) and applies it over the whole range, dropping the alignment set moments earlier. Concrete scenario: <Label Text="abc" LineHeight="1.5" HorizontalTextAlignment="Center" /> renders left-aligned on first display until some other property change re-triggers MapFormatting. Moving HorizontalTextAlignment after LineHeight/TextDecorations (or keeping an explicit alignment re-apply at the end of the connect pass) restores the documented ordering.
|
|
||
| // Any text update requires that we update any attributed string formatting | ||
| MapFormatting(handler, label); | ||
| if (!handler.IsConnectingHandler()) |
There was a problem hiding this comment.
🔍 AI-Generated Review (multi-model)
[moderate] Regression Prevention and Test Coverage — This changes connect-time behavior (formatting is no longer re-applied from MapText during the initial mapping pass; correctness now depends entirely on the new iOS/MacCatalyst mapper key order in LabelHandler.cs), yet the PR adds no test. The at-risk scenarios are exactly the ones that regress silently on first render only: initial values of LineHeight, TextDecorations, CharacterSpacing and HorizontalTextAlignment combined (plain text, FormattedText spans, and TextType="Html"), plus handler re-connection (Reconnecting state, where IsConnectingHandler() is false and formatting still runs). A device test asserting the native attributed-string attributes right after CreateHandlerAsync — for a label that sets alignment together with LineHeight/TextDecorations — would pin this ordering contract, which is otherwise only expressed by mapper insertion order and can be broken by any future re-ordering.
MauiBot
left a comment
There was a problem hiding this comment.
AI Review Summary
@StephaneDelcroix — new AI review results are available based on commit
894a08b.
🗂️ Review Sessions — click to expand
🚦 Gate — Test Before & After Fix
Gate Result: ⚠️ SKIPPED
No tests were detected in this PR.
Recommendation: Add tests to verify the fix using the write-tests-agent.
📋 Pre-Flight — Context & Validation
PR #37840 Pre-Flight
Context
- Title:
[iOS] Label: Reduce initial attributed-text formatting work - Base / head:
net11.0(c127c3f350) /894a08bef9 - Review worktree: PR is materialized as commit
e63ce46494onpr-review-37840. - Platform: iOS (the
.iOS.cspaths also compile for Mac Catalyst). - Gate: Skipped because the PR adds no tests. The gate must not be rerun or overwritten.
Existing Fix
The PR changes three files:
src/Core/src/Handlers/Label/LabelHandler.cs- Gives iOS/Mac Catalyst a platform-specific mapper order with
Text,Font, andCharacterSpacingfirst. - Leaves
HorizontalTextAlignmentbeforeLineHeightandTextDecorations.
- Gives iOS/Mac Catalyst a platform-specific mapper order with
src/Core/src/Handlers/Label/LabelHandler.iOS.cs- Suppresses the recursive
MapFormattingcall fromMapTextonly whileIsConnectingHandler()is true.
- Suppresses the recursive
src/Controls/src/Core/Label/Label.iOS.cs- Applies the same connection-only suppression around Controls
Label.MapFormatting.
- Applies the same connection-only suppression around Controls
The intended effect is to create native text first, then let the normal mapper pass apply attributed formatting once. Runtime text updates continue to reapply formatting.
Risks an Alternative Must Address
- iOS attributed formatting can reset native horizontal alignment. The current mapper order applies
HorizontalTextAlignmentbeforeLineHeightandTextDecorations, unlikeMapFormatting, which deliberately applies alignment last. - Reconnection is a full property-mapping pass (
IsMappingProperties()is true), butIsConnectingHandler()is false. The current implementation therefore performs redundant nested formatting during reconnect. Fontmust precedeCharacterSpacing, andTextmust exist before attributed formatting.- Plain text, formatted spans, HTML text, initial connection, reconnection, and runtime text updates must retain their existing formatting behavior and mapper extensibility.
- The earlier broad optimization in #35892 introduced a parent
TextMapperand was reverted by #37087; candidates must not simply recreate that reverted mechanism without addressing its regression surface.
Target Files
src/Controls/src/Core/Label/Label.iOS.cssrc/Core/src/Handlers/Label/LabelHandler.cssrc/Core/src/Handlers/Label/LabelHandler.iOS.cs
Only files admitted by .github/.baseline-state.json after EstablishBrokenBaseline.ps1 may be modified.
Bounded Validation
No primary test was detected in the PR. Use only these existing targeted iOS regressions:
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Core -Platform ios -IncludeClasses "Microsoft.Maui.DeviceTests.LabelHandlerTests" -IncludeMethods "CanSetAlignmentAndLineHeight,CharacterSpacingInitializesCorrectly,TextDecorationsInitializesCorrectly,LineHeightInitializesCorrectly,TextDoesNotAffectCharacterSpacing,TextDecorationsAppliedWhenTextAdded"
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project Controls -Platform ios -IncludeClasses "Microsoft.Maui.DeviceTests.LabelTests" -IncludeMethods "CharacterSpacingWithLineHeightWithTextDecorationsWorksCorrectly"Each candidate gets one implementation/test pass and at most one focused correction and rerun. A missing simulator or workload is Blocked, not Pass.
Worktree Constraint
The worktree contains pre-existing, unrelated modifications under .github/ and eng/. They are not part of PR #37840 and must not be modified, restored, deleted, stashed, or included in candidate diffs. Candidate cleanup must use only:
pwsh .github/scripts/EstablishBrokenBaseline.ps1 -Restore🔬 Code Review — Deep Analysis
Code Review — PR #37840
Independent Assessment
What this changes: On iOS and Mac Catalyst, the submitted fix moves Text and Font earlier in LabelHandler.Mapper and suppresses MapText's recursive attributed-text formatting while the handler is initially connecting. Subsequent text changes continue to reapply formatting.
Inferred motivation: Avoid applying line height, decorations, character spacing, and alignment twice during initial property mapping while preserving formatting after later text replacement.
Approach assessment: Skipping the recursive formatting pass during initial connection is a sound optimization only if the one remaining mapper pass preserves all ordering dependencies. The submitted order does not: it maps HorizontalTextAlignment before LineHeight and TextDecorations, while MapFormatting explicitly reapplies alignment last because attributed-string updates can invalidate it.
Findings
❌ Error — Initial line-height formatting can discard horizontal alignment
src/Core/src/Handlers/Label/LabelHandler.cs:40 maps HorizontalTextAlignment before LineHeight at line 42. During initial connection, both MapText implementations now skip MapFormatting, so no final alignment update repairs the paragraph style. A label initialized with centered/end alignment and non-default line height can render with the attributed string's default alignment until another update occurs. This violates the ordering contract documented by LabelHandler.MapFormatting and regresses the scenario covered by the existing iOS CanSetAlignmentAndLineHeight device test.
Required correction: Keep Text first and Font before CharacterSpacing, then apply LineHeight, TextDecorations, and CharacterSpacing before HorizontalTextAlignment.
⚠️ Warning — No regression test accompanies the connect-time behavior change
The PR adds no test that pins the new initial-mapping order. Existing tests cover individual formatting properties and the alignment-plus-line-height interaction, but the submitted change does not add focused coverage for the optimized connect path across plain, formatted, and HTML text.
Failure-Mode Probing
- Initial plain text with alignment and line height:
Textcreates native text, alignment is applied, then line height replaces attributed paragraph styling; no final alignment mapping runs. This is the concrete failing path. - Later text changes:
IsConnectingHandler()is false, soMapTextstill callsMapFormattingand restores alignment last. - Handler reconnection:
IsConnectingHandler()only identifies the firstConnectingstate; reconnect mapping continues through the existing formatting path, so the defect is localized to first connection. - Formatted/HTML text: Their text creation and property-specific formatting paths remain order-sensitive. The proposed correction preserves the intended text/font prerequisites without relying on the removed recursive pass.
- Other platforms: Conditional mapper entries preserve their existing order and behavior.
Blast Radius
The change runs for every iOS and Mac Catalyst Label during initial handler connection. It adds no static/shared state and does not affect other platforms, but it changes platform-specific handler initialization and attributed-text rendering.
CI / Gate Status
Gate was skipped because the PR contains no tests. Relevant automated coverage is therefore undetermined for this review, and confidence in merge safety is capped despite the concrete ordering analysis.
Verdict: NEEDS_CHANGES
Confidence: medium
Summary: The optimization direction is reasonable, but the submitted mapper order removes a correctness safeguard and can regress initial horizontal alignment when line height is set. Correct the order and validate the existing focused iOS Label formatting tests before merge.
🛠️ Try-Fix — Analysis & Comparison
PR #37840 Try-Fix Aggregate
Candidate 1 — Pass-Scoped Formatting Marker
Approach: Preserve the shared mapper and unconditional MapText → MapFormatting relationship. Track when the canonical attributed-formatting sequence has completed, then skip only the redundant later MapTextDecorations call during a full mapping pass.
Mechanism-level difference: Unlike PR #37840 and reverted #35892 mapper reordering, this records completed work. It preserves alignment-last behavior, applies to reconnect through IsMappingProperties(), and leaves standalone runtime updates unchanged.
Result: Fail. All selected Core and Controls assertions passed in XHarness, and inline self-review found 0 issues, but both mandatory runner commands ended in XHarness did not produce the expected fresh result 'testResults.xml'. Under the try-fix contract, a command error is a failure even when timestamped XML shows the target assertions passed.
Diff: Full candidate diff is recorded in ../try-fix-1/content.md and attempt-1/fix.diff. It adds a per-handler _attributedFormattingApplied marker in LabelHandler.iOS.cs, resets/sets it from the Core and Controls text formatting paths, and guards the redundant MapTextDecorations call. LabelHandler.cs remains at the base implementation.
Failure analysis: Candidate behavior is supported by the targeted results, but the required test wrapper could not complete its fresh-result validation. The build also regenerated src/Core/src/Handlers/HybridWebView/HybridWebView.js outside the candidate allow-list; that side effect is excluded from the candidate diff.
Status: Done; Candidate 2 must not repeat, reopen, or rerun the formatting-marker mechanism.
Candidate 2 — Stateless Canonical Full-Pass Ordering
Approach: Introduce an iOS/Mac Catalyst mapper subclass that defers attributed-formatting keys until all Core and Controls text-producing keys run. During a full property pass, Core and Controls MapText omit nested formatting; deferred keys then run once in the canonical Font → LineHeight → TextDecorations → CharacterSpacing → HorizontalTextAlignment order.
Mechanism-level difference: This candidate uses no per-handler marker and no parent TextMapper. It derives a stateless full-pass order from mapper keys, uses IsMappingProperties() for initial mapping and reconnect, and preserves immediate formatting for runtime text changes.
Result: Fail. Core reported 94 run / 93 passed / 0 failed / 1 ignored, and Controls reported 53 run / 48 passed / 0 failed / 5 ignored. Every requested target passed and inline self-review found 0 issues. Both required wrappers nevertheless exited 1 because they expected testResults.xml rather than the timestamped XHarness XML, so the attempt cannot be classified as Pass.
Diff: Full candidate diff is recorded in ../try-fix-2/content.md and attempt-2/fix.diff. It adds LabelPropertyMapper.GetKeys() ordering on Apple targets and changes both Core and Controls MapText guards to !IsMappingProperties().
Failure analysis: The candidate implementation did not trigger an assertion failure and needed no correction, but validation remained unsuccessful at the required command boundary. Fixing the dirty runner was outside the candidate allow-list and prohibited by the bounded test contract.
Status: Done.
STEP 5a Comparison
| Candidate | Mechanism | Target assertions | Contract result | Self-review |
|---|---|---|---|---|
| 1 | Per-handler completed-formatting marker; skip one redundant mapper | All passed | Fail — runner exit 1 | 0 |
| 2 | Stateless canonical full-pass mapper ordering | All passed | Fail — runner exit 1 | 0 |
Both alternatives have encouraging targeted XML evidence but neither is a passing candidate because the mandatory runner failed after execution. Candidate 1 is smaller in mapper impact but adds mutable handler state; Candidate 2 is stateless but changes mapper enumeration semantics and is substantially more complex. STEP 5a is complete with exactly two candidates.
🏁 Report — Final Recommendation
⚠️ Final Recommendation: REQUEST CHANGES
Winner: pr-plus-reviewer
pr-plus-reviewer is the strongest candidate because it preserves the submitted optimization while restoring the existing iOS attributed-text ordering contract with one localized mapper reorder. It fixes the expert review's concrete first-render alignment regression without adding mutable handler state, a custom mapper type, or broader mapping semantics.
Comparative Ranking
| Rank | Candidate | Correctness and design | Targeted validation | Disposition |
|---|---|---|---|---|
| 1 | pr-plus-reviewer |
Restores the canonical Text → Font → LineHeight → TextDecorations → CharacterSpacing → HorizontalTextAlignment order. Other platforms and runtime text-update behavior remain unchanged. |
Core: 94 run, 93 passed, 0 failed, 1 ignored. Controls: 53 run, 48 passed, 0 failed, 5 ignored. Both required commands nevertheless exited 1 after XHarness success because the wrapper expected testResults.xml instead of the emitted timestamped XML. |
Winner, with validation uncertainty recorded. |
| 2 | try-fix-1 |
Preserves canonical formatting and mapper order, but introduces mutable per-handler formatting state plus reset/set helpers across Core and Controls paths. This is more lifecycle-sensitive and complex than the winning reorder. | All selected assertions passed; both required wrappers exited 1 on the same result-file mismatch. Contract result: Fail. | Viable behavior, unnecessarily stateful. |
| 3 | try-fix-2 |
Stateless and covers full mapping/reconnection, but adds an Apple-specific PropertyMapper subclass that overrides key enumeration and changes broader mapper-order semantics. It is substantially more invasive than required. |
All selected assertions passed; both required wrappers exited 1 on the same result-file mismatch. Contract result: Fail. | Viable behavior, excessive mechanism and blast radius. |
| 4 | pr |
Removes the connect-time final formatting pass but leaves HorizontalTextAlignment before LineHeight and TextDecorations. This contradicts MapFormatting's alignment-last invariant and can render initially centered/end-aligned text with the attributed paragraph style's default alignment. |
Gate skipped because the PR adds no tests; no raw-PR regression run was available. | Rejected due to a concrete correctness defect. |
No candidate produced a regression assertion failure. The three refined alternatives all have encouraging XHarness results, but none receives a formal validation pass because their required wrapper commands failed at the result-file boundary. This uncertainty does not erase the code-level distinction: the raw PR retains a verified ordering flaw, while pr-plus-reviewer fixes it with the smallest and clearest change.
Expert Findings Reconciliation
- Blocking:
LabelHandler.Mappermust applyHorizontalTextAlignmentafter attributed-string mutations such as line height and text decorations during initial connection. - Coverage: The submitted PR adds no test. The winning candidate relies on existing focused iOS device coverage, including
CanSetAlignmentAndLineHeight; adding or updating test source was not necessary for the bounded candidate patch. - Reconnect and dynamic updates: The winner intentionally retains the submitted
IsConnectingHandler()scope. Reconnection may still repeat formatting work, but runtime and reconnect correctness continue throughMapFormatting; this is a non-blocking optimization opportunity rather than a reason to prefer the more invasive STEP 5a mechanisms.
Required PR Change
Apply the pr-plus-reviewer mapper ordering from reviewer.patch to the submitted branch. The current PR should not be approved as-is because the winning correction is not present in PR HEAD.
📱 UI Tests — Label,ViewBaseTests
Detected UI test categories: Label,ViewBaseTests
✅ Deep UI tests — 202 passed, 0 failed, 2 skipped across 2 categories on platform-pool agent (replaces in-process counts above).
🧪 UI Test Execution Results (deep, platform pool)
| Category | Tests | Snapshot diffs |
|---|---|---|
Label |
90/92 (2 skipped) ✓ | — |
ViewBaseTests |
112/112 ✓ | — |
📎 Download drop-deep-uitests artifact (TRX + snapshot diffs) |
🧭 Next Steps — reviewer changes required
The reviewer-enhanced candidate identified changes that are not yet in the submitted PR.
Why: The reviewer-refined PR preserves the submitted iOS Label optimization while restoring the canonical alignment-last formatting order. It is the smallest candidate that removes the raw PR's concrete first-render alignment regression, with all selected XHarness assertions passing despite the required wrappers failing on result-file discovery.
Address the actionable findings in this review before merging.
kubaflo
left a comment
There was a problem hiding this comment.
Could you please check the ai's suggestions?
Note
Are you waiting for the changes in this PR to be merged?
It would be very helpful if you could test the resulting artifacts from this PR and let us know in a comment if this change resolves your issue. Thank you!
Description
Reorders iOS and Mac Catalyst Label initialization so native text and font are established before attributed-text formatting. During initial connection, the individual formatting mapper entries then apply character spacing, line height, decorations, and alignment once instead of
MapTextrecursively applying them and the initialization loop applying them again.Dynamic text changes still reapply formatting. Other platforms retain their existing mapper order.
Benchmark
The local Sandbox harness is not included in this PR. Release iOS simulator, iPhone 16 Pro / iOS 18.4:
net11.0baseToPlatform(55 elements)ToPlatform(14 elements)A native
UILabelprobe verified that underline, character spacing, and line height all survived initialization:label-formatting|PASS. The revised run completed all 70 benchmark results withrun-end|ok.Review
Independent GPT, Claude, and Gemini reviews covered initialization, reconnect, formatted spans, HTML text, alignment, and the prior #35892 / #37087 regression history. Review identified that
Fontmust precedeCharacterSpacing; the mapper order was corrected and the native formatting probe was rerun successfully.