text_span.dart 19.5 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 Locale, LocaleStringAttribute, ParagraphBuilder, SpellOutStringAttribute, StringAttribute;
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
// Examples can assume:
// late TextSpan myTextSpan;

18 19
/// An immutable span of text.
///
20 21
/// A [TextSpan] object can be styled using its [style] property. The style will
/// be applied to the [text] and the [children].
22
///
23 24 25 26 27 28 29
/// 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.
30 31
///
/// To paint a [TextSpan] on a [Canvas], use a [TextPainter]. To display a text
32 33
/// span in a widget, use a [RichText]. For text with a single style, consider
/// using the [Text] widget.
34
///
35
/// {@tool snippet}
36 37 38 39
///
/// The text "Hello world!", in black:
///
/// ```dart
40
/// const TextSpan(
41
///   text: 'Hello world!',
42
///   style: TextStyle(color: Colors.black),
43 44
/// )
/// ```
45
/// {@end-tool}
46 47 48 49
///
/// _There is some more detailed sample code in the documentation for the
/// [recognizer] property._
///
50
/// The [TextSpan.text] will be used as the semantics label unless overridden
51
/// by the [TextSpan.semanticsLabel] property. Any [PlaceholderSpan]s in the
52 53
/// [TextSpan.children] list will separate the text before and after it into two
/// semantics nodes.
54
///
55 56
/// See also:
///
57 58 59 60
///  * [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.
61 62
///  * [Text], a widget for showing uniformly-styled text.
///  * [RichText], a widget for finer control of text rendering.
63
///  * [TextPainter], a class for painting [TextSpan] objects on a [Canvas].
64
@immutable
65
class TextSpan extends InlineSpan implements HitTestTarget, MouseTrackerAnnotation {
66 67 68 69 70 71 72
  /// 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,
73
    super.style,
74
    this.recognizer,
75 76 77
    MouseCursor? mouseCursor,
    this.onEnter,
    this.onExit,
78
    this.semanticsLabel,
79 80
    this.locale,
    this.spellOut,
81 82
  }) : mouseCursor = mouseCursor ??
         (recognizer == null ? MouseCursor.defer : SystemMouseCursors.click),
83
       assert(!(text == null && semanticsLabel != null));
84

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

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

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

211
  /// An alternative semantics label for this [TextSpan].
212 213 214 215 216 217 218 219
  ///
  /// 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
220
  /// const TextSpan(text: r'$$', semanticsLabel: 'Double dollars')
221
  /// ```
222
  final String? semanticsLabel;
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 249
  /// 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;

250 251 252 253 254
  @override
  bool get validForMouseTracker => true;

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

260 261 262 263 264 265 266
  /// 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.
267
  @override
268 269 270
  void build(
    ui.ParagraphBuilder builder, {
    double textScaleFactor = 1.0,
271
    List<PlaceholderDimensions>? dimensions,
272
  }) {
273
    assert(debugAssertIsValid());
274
    final bool hasStyle = style != null;
275
    if (hasStyle) {
276
      builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor));
277
    }
278 279 280 281 282 283 284 285 286 287 288 289 290 291
    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');
      }
    }
292
    if (children != null) {
293
      for (final InlineSpan child in children!) {
294
        assert(child != null);
295 296 297 298 299
        child.build(
          builder,
          textScaleFactor: textScaleFactor,
          dimensions: dimensions,
        );
300 301
      }
    }
302
    if (hasStyle) {
303
      builder.pop();
304
    }
305 306
  }

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

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

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

369
  @override
370 371 372 373 374
  void computeSemanticsInformation(
    List<InlineSpanSemanticsInformation> collector, {
    ui.Locale? inheritedLocale,
    bool inheritedSpellOut = false,
  }) {
375
    assert(debugAssertIsValid());
376 377 378
    final ui.Locale? effectiveLocale = locale ?? inheritedLocale;
    final bool effectiveSpellOut = spellOut ?? inheritedSpellOut;

379
    if (text != null) {
380
      final int textLength = semanticsLabel?.length ?? text!.length;
381
      collector.add(InlineSpanSemanticsInformation(
382
        text!,
383
        stringAttributes: <ui.StringAttribute>[
384 385 386 387
          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)),
388
        ],
389 390 391 392 393
        semanticsLabel: semanticsLabel,
        recognizer: recognizer,
      ));
    }
    if (children != null) {
394
      for (final InlineSpan child in children!) {
395 396 397 398 399 400 401 402 403
        if (child is TextSpan) {
          child.computeSemanticsInformation(
            collector,
            inheritedLocale: effectiveLocale,
            inheritedSpellOut: effectiveSpellOut,
          );
        } else {
          child.computeSemanticsInformation(collector);
        }
404 405 406 407
      }
    }
  }

408
  @override
409
  int? codeUnitAtVisitor(int index, Accumulator offset) {
410
    if (text == null) {
411
      return null;
412
    }
413 414
    if (index - offset.value < text!.length) {
      return text!.codeUnitAt(index - offset.value);
415
    }
416
    offset.increment(text!.length);
417 418 419
    return null;
  }

420 421 422 423 424 425 426 427 428
  /// 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.
429
  void describeSemantics(Accumulator offset, List<int> semanticsOffsets, List<dynamic> semanticsElements) {
430 431 432 433
    if (
      recognizer != null &&
      (recognizer is TapGestureRecognizer || recognizer is LongPressGestureRecognizer)
    ) {
434
      final int length = semanticsLabel?.length ?? text!.length;
435 436 437 438
      semanticsOffsets.add(offset.value);
      semanticsOffsets.add(offset.value + length);
      semanticsElements.add(recognizer);
    }
439
    offset.increment(text != null ? text!.length : 0);
440 441
  }

442
  /// In debug mode, throws an exception if the object is not in a valid
443
  /// configuration. Otherwise, returns true.
444 445
  ///
  /// This is intended to be used as follows:
446
  ///
447
  /// ```dart
448
  /// assert(myTextSpan.debugAssertIsValid());
449
  /// ```
450
  @override
451
  bool debugAssertIsValid() {
452
    assert(() {
453
      if (children != null) {
454
        for (final InlineSpan child in children!) {
455
          if (child == null) {
456 457 458
            throw FlutterError.fromParts(<DiagnosticsNode>[
              ErrorSummary('TextSpan contains a null child.'),
              ErrorDescription(
459 460 461 462 463 464
                '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,
              ),
465 466
            ]);
          }
467
          assert(child.debugAssertIsValid());
468 469 470
        }
      }
      return true;
471
    }());
472
    return super.debugAssertIsValid();
473 474
  }

475 476
  @override
  RenderComparison compareTo(InlineSpan other) {
477
    if (identical(this, other)) {
478
      return RenderComparison.identical;
479 480
    }
    if (other.runtimeType != runtimeType) {
481
      return RenderComparison.layout;
482
    }
483
    final TextSpan textSpan = other as TextSpan;
484 485
    if (textSpan.text != text ||
        children?.length != textSpan.children?.length ||
486
        (style == null) != (textSpan.style == null)) {
487
      return RenderComparison.layout;
488
    }
489 490 491
    RenderComparison result = recognizer == textSpan.recognizer ?
      RenderComparison.identical :
      RenderComparison.metadata;
492
    if (style != null) {
493
      final RenderComparison candidate = style!.compareTo(textSpan.style!);
494
      if (candidate.index > result.index) {
495
        result = candidate;
496 497
      }
      if (result == RenderComparison.layout) {
498
        return result;
499
      }
500 501
    }
    if (children != null) {
502 503
      for (int index = 0; index < children!.length; index += 1) {
        final RenderComparison candidate = children![index].compareTo(textSpan.children![index]);
504
        if (candidate.index > result.index) {
505
          result = candidate;
506 507
        }
        if (result == RenderComparison.layout) {
508
          return result;
509
        }
510 511 512 513 514
      }
    }
    return result;
  }

515
  @override
516
  bool operator ==(Object other) {
517
    if (identical(this, other)) {
518
      return true;
519 520
    }
    if (other.runtimeType != runtimeType) {
521
      return false;
522 523
    }
    if (super != other) {
524
      return false;
525
    }
526 527 528 529
    return other is TextSpan
        && other.text == text
        && other.recognizer == recognizer
        && other.semanticsLabel == semanticsLabel
530 531 532
        && onEnter == other.onEnter
        && onExit == other.onExit
        && mouseCursor == other.mouseCursor
533
        && listEquals<InlineSpan>(other.children, children);
534 535 536
  }

  @override
537
  int get hashCode => Object.hash(
538 539 540 541
    super.hashCode,
    text,
    recognizer,
    semanticsLabel,
542 543 544
    onEnter,
    onExit,
    mouseCursor,
545
    children == null ? null : Object.hashAll(children!),
546
  );
547 548

  @override
549
  String toStringShort() => objectRuntimeType(this, 'TextSpan');
550

551
  @override
552 553
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
554

555 556 557 558 559 560
    properties.add(
      StringProperty(
        'text',
        text,
        showName: false,
        defaultValue: null,
561
      ),
562
    );
563
    if (style == null && text == null && children == null) {
564
      properties.add(DiagnosticsNode.message('(empty)'));
565
    }
566

567
    properties.add(DiagnosticsProperty<GestureRecognizer>(
568
      'recognizer', recognizer,
569
      description: recognizer?.runtimeType.toString(),
570 571
      defaultValue: null,
    ));
572

573 574 575 576 577 578 579 580 581
    properties.add(FlagsSummary<Function?>(
      'callbacks',
      <String, Function?> {
        'enter': onEnter,
        'exit': onExit,
      },
    ));
    properties.add(DiagnosticsProperty<MouseCursor>('mouseCursor', cursor, defaultValue: MouseCursor.defer));

582 583 584
    if (semanticsLabel != null) {
      properties.add(StringProperty('semanticsLabel', semanticsLabel));
    }
585 586 587 588
  }

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
589
    if (children == null) {
590
      return const <DiagnosticsNode>[];
591
    }
592
    return children!.map<DiagnosticsNode>((InlineSpan child) {
593 594 595
      // `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).
596 597
      if (child != null) {
        return child.toDiagnosticsNode();
598
      } else {
599
        return DiagnosticsNode.message('<null child>');
600 601
      }
    }).toList();
602
  }
603
}