From f9b8aee908da522c7b1eed6c4ca6d0c5982ecf02 Mon Sep 17 00:00:00 2001 From: Mouad Debbar Date: Thu, 10 Dec 2020 13:52:10 -0800 Subject: [PATCH] [web] Align offset for lines of rich text --- .../lib/src/engine/text/layout_service.dart | 25 +++++++++++++++++-- .../test/text/layout_service_plain_test.dart | 5 ++-- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/lib/web_ui/lib/src/engine/text/layout_service.dart b/lib/web_ui/lib/src/engine/text/layout_service.dart index f1bc16fc86235..30bea1fbda213 100644 --- a/lib/web_ui/lib/src/engine/text/layout_service.dart +++ b/lib/web_ui/lib/src/engine/text/layout_service.dart @@ -318,6 +318,28 @@ class LineBuilder { bool get isEmpty => _segments.isEmpty; bool get isNotEmpty => _segments.isNotEmpty; + /// The horizontal offset necessary for the line to be correctly aligned. + double get alignOffset { + final double emptySpace = maxWidth - width; + final ui.TextDirection textDirection = + paragraph.paragraphStyle._textDirection ?? ui.TextDirection.ltr; + final ui.TextAlign textAlign = + paragraph.paragraphStyle._textAlign ?? ui.TextAlign.start; + + switch (textAlign) { + case ui.TextAlign.center: + return emptySpace / 2.0; + case ui.TextAlign.right: + return emptySpace; + case ui.TextAlign.start: + return textDirection == ui.TextDirection.rtl ? emptySpace : 0.0; + case ui.TextAlign.end: + return textDirection == ui.TextDirection.rtl ? 0.0 : emptySpace; + default: + return 0.0; + } + } + /// Measures the width of text between the end of this line and [newEnd]. double getAdditionalWidthTo(LineBreakResult newEnd) { // If the extension is all made of space characters, it shouldn't add @@ -509,8 +531,7 @@ class LineBuilder { hardBreak: end.isHard, width: width + ellipsisWidth, widthWithTrailingSpaces: widthIncludingSpace + ellipsisWidth, - // TODO(mdebbar): Calculate actual align offset. - left: 0.0, + left: alignOffset, lineNumber: lineNumber, ); } diff --git a/lib/web_ui/test/text/layout_service_plain_test.dart b/lib/web_ui/test/text/layout_service_plain_test.dart index 1bafe38f511c5..837ada96b512a 100644 --- a/lib/web_ui/test/text/layout_service_plain_test.dart +++ b/lib/web_ui/test/text/layout_service_plain_test.dart @@ -11,7 +11,6 @@ import 'package:ui/ui.dart' as ui; import 'layout_service_helper.dart'; -const bool skipTextAlign = true; const bool skipWordSpacing = true; final EngineParagraphStyle ahemStyle = EngineParagraphStyle( @@ -641,7 +640,7 @@ void testMain() async { l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0), l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0), ]); - }, skip: skipTextAlign); + }); test('handles rtl with textAlign', () { CanvasParagraph paragraph; @@ -694,5 +693,5 @@ void testMain() async { l('defgh', 4, 9, hardBreak: false, width: 50.0, left: 0.0), l('i', 9, 10, hardBreak: true, width: 10.0, left: 40.0), ]); - }, skip: skipTextAlign); + }); }