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

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

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

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

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

182 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
  /// 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;

208
  /// An alternative semantics label for this [TextSpan].
209 210 211 212 213 214 215 216 217 218
  ///
  /// 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')
  /// ```
219
  final String? semanticsLabel;
220

221 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
  /// 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;

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

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

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

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

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

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

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

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

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

412 413 414 415 416 417 418 419 420
  /// 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.
421
  void describeSemantics(Accumulator offset, List<int> semanticsOffsets, List<dynamic> semanticsElements) {
422 423 424 425
    if (
      recognizer != null &&
      (recognizer is TapGestureRecognizer || recognizer is LongPressGestureRecognizer)
    ) {
426
      final int length = semanticsLabel?.length ?? text!.length;
427 428 429 430
      semanticsOffsets.add(offset.value);
      semanticsOffsets.add(offset.value + length);
      semanticsElements.add(recognizer);
    }
431
    offset.increment(text != null ? text!.length : 0);
432 433
  }

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

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

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

  @override
519
  int get hashCode => Object.hash(
520 521 522 523
    super.hashCode,
    text,
    recognizer,
    semanticsLabel,
524 525 526
    onEnter,
    onExit,
    mouseCursor,
527
    children == null ? null : Object.hashAll(children!),
528
  );
529 530

  @override
531
  String toStringShort() => objectRuntimeType(this, 'TextSpan');
532

533
  @override
534 535
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
536

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

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

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

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

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
570 571
    if (children == null)
      return const <DiagnosticsNode>[];
572
    return children!.map<DiagnosticsNode>((InlineSpan child) {
573 574 575
      // `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).
576 577
      if (child != null) {
        return child.toDiagnosticsNode();
578
      } else {
579
        return DiagnosticsNode.message('<null child>');
580 581
      }
    }).toList();
582
  }
583
}