text_span.dart 19.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'dart:ui' as ui show ParagraphBuilder, Locale, StringAttribute, LocaleStringAttribute, SpellOutStringAttribute;
6 7

import 'package:flutter/foundation.dart';
8 9
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
10 11

import 'basic_types.dart';
12 13
import 'inline_span.dart';
import 'text_painter.dart';
14 15 16 17
import 'text_style.dart';

/// An immutable span of text.
///
18 19
/// A [TextSpan] object can be styled using its [style] property. The style will
/// be applied to the [text] and the [children].
20
///
21 22 23 24 25 26 27
/// A [TextSpan] object can just have plain text, or it can have children
/// [TextSpan] objects with their own styles that (possibly only partially)
/// override the [style] of this object. If a [TextSpan] has both [text] and
/// [children], then the [text] is treated as if it was an un-styled [TextSpan]
/// at the start of the [children] list. Leaving the [TextSpan.text] field null
/// results in the [TextSpan] acting as an empty node in the [InlineSpan] tree
/// with a list of children.
28 29
///
/// To paint a [TextSpan] on a [Canvas], use a [TextPainter]. To display a text
30 31
/// span in a widget, use a [RichText]. For text with a single style, consider
/// using the [Text] widget.
32
///
33
/// {@tool snippet}
34 35 36 37
///
/// The text "Hello world!", in black:
///
/// ```dart
38
/// const TextSpan(
39
///   text: 'Hello world!',
40
///   style: TextStyle(color: Colors.black),
41 42
/// )
/// ```
43
/// {@end-tool}
44 45 46 47
///
/// _There is some more detailed sample code in the documentation for the
/// [recognizer] property._
///
48
/// The [TextSpan.text] will be used as the semantics label unless overridden
49
/// by the [TextSpan.semanticsLabel] property. Any [PlaceholderSpan]s in the
50 51
/// [TextSpan.children] list will separate the text before and after it into two
/// semantics nodes.
52
///
53 54
/// See also:
///
55 56 57 58
///  * [WidgetSpan], a leaf node that represents an embedded inline widget in an
///    [InlineSpan] tree. Specify a widget within the [children] list by
///    wrapping the widget with a [WidgetSpan]. The widget will be laid out
///    inline within the paragraph.
59 60
///  * [Text], a widget for showing uniformly-styled text.
///  * [RichText], a widget for finer control of text rendering.
61
///  * [TextPainter], a class for painting [TextSpan] objects on a [Canvas].
62
@immutable
63
class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotation {
64 65 66 67 68 69 70
  /// Creates a [TextSpan] with the given values.
  ///
  /// For the object to be useful, at least one of [text] or
  /// [children] should be set.
  const TextSpan({
    this.text,
    this.children,
71
    TextStyle? style,
72
    this.recognizer,
73 74 75
    MouseCursor? mouseCursor,
    this.onEnter,
    this.onExit,
76
    this.semanticsLabel,
77 78
    this.locale,
    this.spellOut,
79 80 81
  }) : mouseCursor = mouseCursor ??
         (recognizer == null ? MouseCursor.defer : SystemMouseCursors.click),
       assert(!(text == null && semanticsLabel != null)),
82
       super(style: style);
83

84
  /// The text contained in this span.
85
  ///
86
  /// If both [text] and [children] are non-null, the text will precede the
87
  /// children.
88 89
  ///
  /// This getter does not include the contents of its children.
90
  final String? text;
91 92 93

  /// Additional spans to include as children.
  ///
94
  /// If both [text] and [children] are non-null, the text will precede the
95 96
  /// children.
  ///
97 98
  /// Modifying the list after the [TextSpan] has been created is not supported
  /// and may have unexpected results.
99 100
  ///
  /// The list must not contain any nulls.
101
  final List<InlineSpan>? children;
102

103
  /// A gesture recognizer that will receive events that hit this span.
104
  ///
105 106
  /// [InlineSpan] itself does not implement hit testing or event dispatch. The
  /// object that manages the [InlineSpan] painting is also responsible for
107 108
  /// dispatching events. In the rendering library, that is the
  /// [RenderParagraph] object, which corresponds to the [RichText] widget in
109 110 111
  /// the widgets layer; these objects do not bubble events in [InlineSpan]s,
  /// so a [recognizer] is only effective for events that directly hit the
  /// [text] of that [InlineSpan], not any of its [children].
112
  ///
113
  /// [InlineSpan] also does not manage the lifetime of the gesture recognizer.
114
  /// The code that owns the [GestureRecognizer] object must call
115 116
  /// [GestureRecognizer.dispose] when the [InlineSpan] object is no longer
  /// used.
117
  ///
118
  /// {@tool snippet}
119 120
  ///
  /// This example shows how to manage the lifetime of a gesture recognizer
121 122
  /// provided to an [InlineSpan] object. It defines a `BuzzingText` widget
  /// which uses the [HapticFeedback] class to vibrate the device when the user
123
  /// long-presses the "find the" span, which is underlined in wavy green. The
124 125
  /// hit-testing is handled by the [RichText] widget. It also changes the
  /// hovering mouse cursor to `precise`.
126 127 128
  ///
  /// ```dart
  /// class BuzzingText extends StatefulWidget {
129 130
  ///   const BuzzingText({Key? key}) : super(key: key);
  ///
131
  ///   @override
132
  ///   State<BuzzingText> createState() => _BuzzingTextState();
133 134 135
  /// }
  ///
  /// class _BuzzingTextState extends State<BuzzingText> {
136
  ///   late LongPressGestureRecognizer _longPressRecognizer;
137 138 139 140
  ///
  ///   @override
  ///   void initState() {
  ///     super.initState();
141
  ///     _longPressRecognizer = LongPressGestureRecognizer()
142 143 144 145 146 147 148 149
  ///       ..onLongPress = _handlePress;
  ///   }
  ///
  ///   @override
  ///   void dispose() {
  ///     _longPressRecognizer.dispose();
  ///     super.dispose();
  ///   }
150
  ///
151 152 153 154 155 156
  ///   void _handlePress() {
  ///     HapticFeedback.vibrate();
  ///   }
  ///
  ///   @override
  ///   Widget build(BuildContext context) {
157 158
  ///     return Text.rich(
  ///       TextSpan(
159
  ///         text: 'Can you ',
160
  ///         style: const TextStyle(color: Colors.black),
161
  ///         children: <InlineSpan>[
162
  ///           TextSpan(
163
  ///             text: 'find the',
164
  ///             style: const TextStyle(
165 166 167 168 169
  ///               color: Colors.green,
  ///               decoration: TextDecoration.underline,
  ///               decorationStyle: TextDecorationStyle.wavy,
  ///             ),
  ///             recognizer: _longPressRecognizer,
170
  ///             mouseCursor: SystemMouseCursors.precise,
171
  ///           ),
172
  ///           const TextSpan(
173 174 175 176 177 178 179 180
  ///             text: ' secret?',
  ///           ),
  ///         ],
  ///       ),
  ///     );
  ///   }
  /// }
  /// ```
181
  /// {@end-tool}
182
  final GestureRecognizer? recognizer;
183

184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
  /// Mouse cursor when the mouse hovers over this span.
  ///
  /// The default value is [SystemMouseCursors.click] if [recognizer] is not
  /// null, or [MouseCursor.defer] otherwise.
  ///
  /// [TextSpan] itself does not implement hit testing or cursor changing.
  /// The object that manages the [TextSpan] painting is responsible
  /// to return the [TextSpan] in its hit test, as well as providing the
  /// correct mouse cursor when the [TextSpan]'s mouse cursor is
  /// [MouseCursor.defer].
  final MouseCursor mouseCursor;

  @override
  final PointerEnterEventListener? onEnter;

  @override
  final PointerExitEventListener? onExit;

  /// Returns the value of [mouseCursor].
  ///
  /// This field, required by [MouseTrackerAnnotation], is hidden publicly to
  /// avoid the confusion as a text cursor.
  @protected
  @override
  MouseCursor get cursor => mouseCursor;

210
  /// An alternative semantics label for this [TextSpan].
211 212 213 214 215 216 217 218 219 220
  ///
  /// If present, the semantics of this span will contain this value instead
  /// of the actual text.
  ///
  /// This is useful for replacing abbreviations or shorthands with the full
  /// text value:
  ///
  /// ```dart
  /// TextSpan(text: r'$$', semanticsLabel: 'Double dollars')
  /// ```
221
  final String? semanticsLabel;
222

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
  /// The language of the text in this span and its span children.
  ///
  /// Setting the locale of this text span affects the way that assistive
  /// technologies, such as VoiceOver or TalkBack, pronounce the text.
  ///
  /// If this span contains other text span children, they also inherit the
  /// locale from this span unless explicitly set to different locales.
  final ui.Locale? locale;

  /// Whether the assistive technologies should spell out this text character
  /// by character.
  ///
  /// If the text is 'hello world', setting this to true causes the assistive
  /// technologies, such as VoiceOver or TalkBack, to pronounce
  /// 'h-e-l-l-o-space-w-o-r-l-d' instead of complete words. This is useful for
  /// texts, such as passwords or verification codes.
  ///
  /// If this span contains other text span children, they also inherit the
  /// property from this span unless explicitly set.
  ///
  /// If the property is not set, this text span inherits the spell out setting
  /// from its parent. If this text span does not have a parent or the parent
  /// does not have a spell out setting, this text span does not spell out the
  /// text by default.
  final bool? spellOut;

249 250 251 252 253 254 255 256 257
  @override
  bool get validForMouseTracker => true;

  @override
  void handleEvent(PointerEvent event, HitTestEntry entry) {
    if (event is PointerDownEvent)
      recognizer?.addPointer(event);
  }

258 259 260 261 262 263 264
  /// Apply the [style], [text], and [children] of this object to the
  /// given [ParagraphBuilder], from which a [Paragraph] can be obtained.
  /// [Paragraph] objects can be drawn on [Canvas] objects.
  ///
  /// Rather than using this directly, it's simpler to use the
  /// [TextPainter] class to paint [TextSpan] objects onto [Canvas]
  /// objects.
265
  @override
266 267 268
  void build(
    ui.ParagraphBuilder builder, {
    double textScaleFactor = 1.0,
269
    List<PlaceholderDimensions>? dimensions,
270
  }) {
271
    assert(debugAssertIsValid());
272 273
    final bool hasStyle = style != null;
    if (hasStyle)
274
      builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor));
275 276 277 278 279 280 281 282 283 284 285 286 287 288
    if (text != null) {
      try {
        builder.addText(text!);
      } on ArgumentError catch (exception, stack) {
        FlutterError.reportError(FlutterErrorDetails(
          exception: exception,
          stack: stack,
          library: 'painting library',
          context: ErrorDescription('while building a TextSpan'),
        ));
        // Use a Unicode replacement character as a substitute for invalid text.
        builder.addText('\uFFFD');
      }
    }
289
    if (children != null) {
290
      for (final InlineSpan child in children!) {
291
        assert(child != null);
292 293 294 295 296
        child.build(
          builder,
          textScaleFactor: textScaleFactor,
          dimensions: dimensions,
        );
297 298 299 300 301 302
      }
    }
    if (hasStyle)
      builder.pop();
  }

303
  /// Walks this [TextSpan] and its descendants in pre-order and calls [visitor]
304
  /// for each span that has text.
305
  ///
306 307
  /// When `visitor` returns true, the walk will continue. When `visitor`
  /// returns false, then the walk will end.
308 309 310 311 312 313 314
  @override
  bool visitChildren(InlineSpanVisitor visitor) {
    if (text != null) {
      if (!visitor(this))
        return false;
    }
    if (children != null) {
315
      for (final InlineSpan child in children!) {
316 317 318 319 320 321 322
        if (!child.visitChildren(visitor))
          return false;
      }
    }
    return true;
  }

323
  /// Returns the text span that contains the given position in the text.
324
  @override
325
  InlineSpan? getSpanForPositionVisitor(TextPosition position, Accumulator offset) {
326 327 328
    if (text == null) {
      return null;
    }
329 330
    final TextAffinity affinity = position.affinity;
    final int targetOffset = position.offset;
331
    final int endOffset = offset.value + text!.length;
332 333 334 335 336
    if (offset.value == targetOffset && affinity == TextAffinity.downstream ||
        offset.value < targetOffset && targetOffset < endOffset ||
        endOffset == targetOffset && affinity == TextAffinity.upstream) {
      return this;
    }
337
    offset.increment(text!.length);
338
    return null;
339 340
  }

341
  @override
342 343 344
  void computeToPlainText(
    StringBuffer buffer, {
    bool includeSemanticsLabels = true,
345
    bool includePlaceholders = true,
346
  }) {
347
    assert(debugAssertIsValid());
348 349 350 351 352 353
    if (semanticsLabel != null && includeSemanticsLabels) {
      buffer.write(semanticsLabel);
    } else if (text != null) {
      buffer.write(text);
    }
    if (children != null) {
354
      for (final InlineSpan child in children!) {
355 356 357 358
        child.computeToPlainText(buffer,
          includeSemanticsLabels: includeSemanticsLabels,
          includePlaceholders: includePlaceholders,
        );
359
      }
360
    }
361 362
  }

363
  @override
364 365 366 367 368
  void computeSemanticsInformation(
    List<InlineSpanSemanticsInformation> collector, {
    ui.Locale? inheritedLocale,
    bool inheritedSpellOut = false,
  }) {
369
    assert(debugAssertIsValid());
370 371 372
    final ui.Locale? effectiveLocale = locale ?? inheritedLocale;
    final bool effectiveSpellOut = spellOut ?? inheritedSpellOut;

373
    if (text != null) {
374
      final int textLength = semanticsLabel?.length ?? text!.length;
375
      collector.add(InlineSpanSemanticsInformation(
376
        text!,
377
        stringAttributes: <ui.StringAttribute>[
378 379 380 381
          if (effectiveSpellOut && textLength > 0)
            ui.SpellOutStringAttribute(range: TextRange(start: 0, end: textLength)),
          if (effectiveLocale != null && textLength > 0)
            ui.LocaleStringAttribute(locale: effectiveLocale, range: TextRange(start: 0, end: textLength)),
382
        ],
383 384 385 386 387
        semanticsLabel: semanticsLabel,
        recognizer: recognizer,
      ));
    }
    if (children != null) {
388
      for (final InlineSpan child in children!) {
389 390 391 392 393 394 395 396 397
        if (child is TextSpan) {
          child.computeSemanticsInformation(
            collector,
            inheritedLocale: effectiveLocale,
            inheritedSpellOut: effectiveSpellOut,
          );
        } else {
          child.computeSemanticsInformation(collector);
        }
398 399 400 401
      }
    }
  }

402
  @override
403
  int? codeUnitAtVisitor(int index, Accumulator offset) {
404
    if (text == null) {
405
      return null;
406
    }
407 408
    if (index - offset.value < text!.length) {
      return text!.codeUnitAt(index - offset.value);
409
    }
410
    offset.increment(text!.length);
411 412 413
    return null;
  }

414 415 416 417 418 419 420 421 422
  /// Populates the `semanticsOffsets` and `semanticsElements` with the appropriate data
  /// to be able to construct a [SemanticsNode].
  ///
  /// If applicable, the beginning and end text offset are added to [semanticsOffsets].
  /// [PlaceholderSpan]s have a text length of 1, which corresponds to the object
  /// replacement character (0xFFFC) that is inserted to represent it.
  ///
  /// Any [GestureRecognizer]s are added to `semanticsElements`. Null is added to
  /// `semanticsElements` for [PlaceholderSpan]s.
423
  void describeSemantics(Accumulator offset, List<int> semanticsOffsets, List<dynamic> semanticsElements) {
424 425 426 427
    if (
      recognizer != null &&
      (recognizer is TapGestureRecognizer || recognizer is LongPressGestureRecognizer)
    ) {
428
      final int length = semanticsLabel?.length ?? text!.length;
429 430 431 432
      semanticsOffsets.add(offset.value);
      semanticsOffsets.add(offset.value + length);
      semanticsElements.add(recognizer);
    }
433
    offset.increment(text != null ? text!.length : 0);
434 435
  }

436
  /// In debug mode, throws an exception if the object is not in a valid
437
  /// configuration. Otherwise, returns true.
438 439
  ///
  /// This is intended to be used as follows:
440
  ///
441
  /// ```dart
442
  /// assert(myTextSpan.debugAssertIsValid());
443
  /// ```
444
  @override
445
  bool debugAssertIsValid() {
446
    assert(() {
447
      if (children != null) {
448
        for (final InlineSpan child in children!) {
449
          if (child == null) {
450 451 452
            throw FlutterError.fromParts(<DiagnosticsNode>[
              ErrorSummary('TextSpan contains a null child.'),
              ErrorDescription(
453 454 455 456 457 458
                'A TextSpan object with a non-null child list should not have any nulls in its child list.',
              ),
              toDiagnosticsNode(
                name: 'The full text in question was',
                style: DiagnosticsTreeStyle.errorProperty,
              ),
459 460
            ]);
          }
461
          assert(child.debugAssertIsValid());
462 463 464
        }
      }
      return true;
465
    }());
466
    return super.debugAssertIsValid();
467 468
  }

469 470
  @override
  RenderComparison compareTo(InlineSpan other) {
471 472
    if (identical(this, other))
      return RenderComparison.identical;
473
    if (other.runtimeType != runtimeType)
474
      return RenderComparison.layout;
475
    final TextSpan textSpan = other as TextSpan;
476 477 478 479
    if (textSpan.text != text ||
        children?.length != textSpan.children?.length ||
        (style == null) != (textSpan.style == null))
      return RenderComparison.layout;
480 481 482
    RenderComparison result = recognizer == textSpan.recognizer ?
      RenderComparison.identical :
      RenderComparison.metadata;
483
    if (style != null) {
484
      final RenderComparison candidate = style!.compareTo(textSpan.style!);
485 486 487 488 489 490
      if (candidate.index > result.index)
        result = candidate;
      if (result == RenderComparison.layout)
        return result;
    }
    if (children != null) {
491 492
      for (int index = 0; index < children!.length; index += 1) {
        final RenderComparison candidate = children![index].compareTo(textSpan.children![index]);
493 494 495 496 497 498 499 500 501
        if (candidate.index > result.index)
          result = candidate;
        if (result == RenderComparison.layout)
          return result;
      }
    }
    return result;
  }

502
  @override
503
  bool operator ==(Object other) {
504 505
    if (identical(this, other))
      return true;
506
    if (other.runtimeType != runtimeType)
507
      return false;
508 509
    if (super != other)
      return false;
510 511 512 513
    return other is TextSpan
        && other.text == text
        && other.recognizer == recognizer
        && other.semanticsLabel == semanticsLabel
514 515 516
        && onEnter == other.onEnter
        && onExit == other.onExit
        && mouseCursor == other.mouseCursor
517
        && listEquals<InlineSpan>(other.children, children);
518 519 520
  }

  @override
521 522 523 524 525
  int get hashCode => hashValues(
    super.hashCode,
    text,
    recognizer,
    semanticsLabel,
526 527 528
    onEnter,
    onExit,
    mouseCursor,
529 530
    hashList(children),
  );
531 532

  @override
533
  String toStringShort() => objectRuntimeType(this, 'TextSpan');
534

535
  @override
536 537
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
538

539 540 541 542 543 544
    properties.add(
      StringProperty(
        'text',
        text,
        showName: false,
        defaultValue: null,
545
      ),
546
    );
547 548
    if (style == null && text == null && children == null)
      properties.add(DiagnosticsNode.message('(empty)'));
549

550
    properties.add(DiagnosticsProperty<GestureRecognizer>(
551
      'recognizer', recognizer,
552
      description: recognizer?.runtimeType.toString(),
553 554
      defaultValue: null,
    ));
555

556 557 558 559 560 561 562 563 564
    properties.add(FlagsSummary<Function?>(
      'callbacks',
      <String, Function?> {
        'enter': onEnter,
        'exit': onExit,
      },
    ));
    properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', cursor, defaultValue: MouseCursor.defer));

565 566 567
    if (semanticsLabel != null) {
      properties.add(StringProperty('semanticsLabel', semanticsLabel));
    }
568 569 570 571
  }

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
572 573
    if (children == null)
      return const <DiagnosticsNode>[];
574
    return children!.map<DiagnosticsNode>((InlineSpan child) {
575 576 577
      // `child` has a non-nullable return type, but might be null when running
      // with weak checking, so we need to null check it anyway (and ignore the
      // warning that the null-handling logic is dead code).
578 579
      if (child != null) {
        return child.toDiagnosticsNode();
580
      } else {
581
        return DiagnosticsNode.message('<null child>');
582 583
      }
    }).toList();
584
  }
585
}