text_span.dart 18.1 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
import 'text_scaler.dart';
15

16 17 18
// Examples can assume:
// late TextSpan myTextSpan;

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

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

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

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

212
  /// An alternative semantics label for this [TextSpan].
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
221
  /// const TextSpan(text: r'$$', semanticsLabel: 'Double dollars')
222
  /// ```
223
  final String? semanticsLabel;
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 250
  /// 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;

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

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

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

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

  @override
  bool visitDirectChildren(InlineSpanVisitor visitor) {
331 332 333 334 335 336
    final List<InlineSpan>? children = this.children;
    if (children != null) {
      for (final InlineSpan child in children) {
        if (!visitor(child)) {
          return false;
        }
337 338 339 340 341
      }
    }
    return true;
  }

342
  /// Returns the text span that contains the given position in the text.
343
  @override
344
  InlineSpan? getSpanForPositionVisitor(TextPosition position, Accumulator offset) {
345 346 347
    if (text == null) {
      return null;
    }
348 349
    final TextAffinity affinity = position.affinity;
    final int targetOffset = position.offset;
350
    final int endOffset = offset.value + text!.length;
351 352 353 354 355
    if (offset.value == targetOffset && affinity == TextAffinity.downstream ||
        offset.value < targetOffset && targetOffset < endOffset ||
        endOffset == targetOffset && affinity == TextAffinity.upstream) {
      return this;
    }
356
    offset.increment(text!.length);
357
    return null;
358 359
  }

360
  @override
361 362 363
  void computeToPlainText(
    StringBuffer buffer, {
    bool includeSemanticsLabels = true,
364
    bool includePlaceholders = true,
365
  }) {
366
    assert(debugAssertIsValid());
367 368 369 370 371 372
    if (semanticsLabel != null && includeSemanticsLabels) {
      buffer.write(semanticsLabel);
    } else if (text != null) {
      buffer.write(text);
    }
    if (children != null) {
373
      for (final InlineSpan child in children!) {
374 375 376 377
        child.computeToPlainText(buffer,
          includeSemanticsLabels: includeSemanticsLabels,
          includePlaceholders: includePlaceholders,
        );
378
      }
379
    }
380 381
  }

382
  @override
383 384 385 386 387
  void computeSemanticsInformation(
    List<InlineSpanSemanticsInformation> collector, {
    ui.Locale? inheritedLocale,
    bool inheritedSpellOut = false,
  }) {
388
    assert(debugAssertIsValid());
389 390 391
    final ui.Locale? effectiveLocale = locale ?? inheritedLocale;
    final bool effectiveSpellOut = spellOut ?? inheritedSpellOut;

392
    if (text != null) {
393
      final int textLength = semanticsLabel?.length ?? text!.length;
394
      collector.add(InlineSpanSemanticsInformation(
395
        text!,
396
        stringAttributes: <ui.StringAttribute>[
397 398 399 400
          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)),
401
        ],
402 403 404 405
        semanticsLabel: semanticsLabel,
        recognizer: recognizer,
      ));
    }
406 407 408 409 410 411 412 413 414 415 416 417
    final List<InlineSpan>? children = this.children;
    if (children != null) {
      for (final InlineSpan child in children) {
        if (child is TextSpan) {
          child.computeSemanticsInformation(
            collector,
            inheritedLocale: effectiveLocale,
            inheritedSpellOut: effectiveSpellOut,
          );
        } else {
          child.computeSemanticsInformation(collector);
        }
418 419 420 421
      }
    }
  }

422
  @override
423
  int? codeUnitAtVisitor(int index, Accumulator offset) {
424
    final String? text = this.text;
425
    if (text == null) {
426
      return null;
427
    }
428 429 430 431
    final int localOffset = index - offset.value;
    assert(localOffset >= 0);
    offset.increment(text.length);
    return localOffset < text.length ? text.codeUnitAt(localOffset) : null;
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
          assert(child.debugAssertIsValid());
448 449 450
        }
      }
      return true;
451
    }());
452
    return super.debugAssertIsValid();
453 454
  }

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

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

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

  @override
529
  String toStringShort() => objectRuntimeType(this, 'TextSpan');
530

531
  @override
532 533
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
534

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

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

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

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

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
569
    return children?.map<DiagnosticsNode>((InlineSpan child) {
570
      return child.toDiagnosticsNode();
571
    }).toList() ?? const <DiagnosticsNode>[];
572
  }
573
}