text_span.dart 15.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

6 7 8
import 'dart:ui' as ui show ParagraphBuilder;

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

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

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

77
  /// The text contained in this span.
78
  ///
79
  /// If both [text] and [children] are non-null, the text will precede the
80
  /// children.
81 82 83
  ///
  /// This getter does not include the contents of its children.
  @override
84
  final String? text;
85

86

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

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

177
  /// An alternative semantics label for this [TextSpan].
178 179 180 181 182 183 184 185 186 187
  ///
  /// 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')
  /// ```
188
  final String? semanticsLabel;
189

190 191 192 193 194 195 196
  /// 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.
197
  @override
198 199 200
  void build(
    ui.ParagraphBuilder builder, {
    double textScaleFactor = 1.0,
201
    List<PlaceholderDimensions>? dimensions,
202
  }) {
203
    assert(debugAssertIsValid());
204 205
    final bool hasStyle = style != null;
    if (hasStyle)
206
      builder.pushStyle(style!.getTextStyle(textScaleFactor: textScaleFactor));
207
    if (text != null)
208
      builder.addText(text!);
209
    if (children != null) {
210
      for (final InlineSpan child in children!) {
211
        assert(child != null);
212 213 214 215 216
        child.build(
          builder,
          textScaleFactor: textScaleFactor,
          dimensions: dimensions,
        );
217 218 219 220 221 222
      }
    }
    if (hasStyle)
      builder.pop();
  }

223
  /// Walks this [TextSpan] and its descendants in pre-order and calls [visitor]
224
  /// for each span that has text.
225
  ///
226 227
  /// When `visitor` returns true, the walk will continue. When `visitor`
  /// returns false, then the walk will end.
228 229 230 231 232 233 234
  @override
  bool visitChildren(InlineSpanVisitor visitor) {
    if (text != null) {
      if (!visitor(this))
        return false;
    }
    if (children != null) {
235
      for (final InlineSpan child in children!) {
236 237 238 239 240 241 242 243 244 245 246
        if (!child.visitChildren(visitor))
          return false;
      }
    }
    return true;
  }

  // TODO(garyq): Remove this after next stable release.
  /// Walks this [TextSpan] and any descendants in pre-order and calls `visitor`
  /// for each span that has content.
  ///
247 248
  /// When `visitor` returns true, the walk will continue. When `visitor`
  /// returns false, then the walk will end.
249
  @override
250 251 252 253
  @Deprecated(
    'Use to visitChildren instead. '
    'This feature was deprecated after v1.7.3.'
  )
254
  bool visitTextSpan(bool visitor(TextSpan span)) {
255 256 257 258 259
    if (text != null) {
      if (!visitor(this))
        return false;
    }
    if (children != null) {
260
      for (final InlineSpan child in children!) {
261 262 263 264
        assert(
          child is TextSpan,
          'visitTextSpan is deprecated. Use visitChildren to support InlineSpans',
        );
265
        final TextSpan textSpanChild = child as TextSpan;
266
        if (!textSpanChild.visitTextSpan(visitor))
267 268 269 270 271 272 273
          return false;
      }
    }
    return true;
  }

  /// Returns the text span that contains the given position in the text.
274
  @override
275
  InlineSpan? getSpanForPositionVisitor(TextPosition position, Accumulator offset) {
276 277 278
    if (text == null) {
      return null;
    }
279 280
    final TextAffinity affinity = position.affinity;
    final int targetOffset = position.offset;
281
    final int endOffset = offset.value + text!.length;
282 283 284 285 286
    if (offset.value == targetOffset && affinity == TextAffinity.downstream ||
        offset.value < targetOffset && targetOffset < endOffset ||
        endOffset == targetOffset && affinity == TextAffinity.upstream) {
      return this;
    }
287
    offset.increment(text!.length);
288
    return null;
289 290
  }

291
  @override
292 293 294 295 296
  void computeToPlainText(
    StringBuffer buffer, {
    bool includeSemanticsLabels = true,
    bool includePlaceholders = true
  }) {
297
    assert(debugAssertIsValid());
298 299 300 301 302 303
    if (semanticsLabel != null && includeSemanticsLabels) {
      buffer.write(semanticsLabel);
    } else if (text != null) {
      buffer.write(text);
    }
    if (children != null) {
304
      for (final InlineSpan child in children!) {
305 306 307 308
        child.computeToPlainText(buffer,
          includeSemanticsLabels: includeSemanticsLabels,
          includePlaceholders: includePlaceholders,
        );
309
      }
310
    }
311 312
  }

313 314 315 316 317
  @override
  void computeSemanticsInformation(List<InlineSpanSemanticsInformation> collector) {
    assert(debugAssertIsValid());
    if (text != null || semanticsLabel != null) {
      collector.add(InlineSpanSemanticsInformation(
318
        text!,
319 320 321 322 323
        semanticsLabel: semanticsLabel,
        recognizer: recognizer,
      ));
    }
    if (children != null) {
324
      for (final InlineSpan child in children!) {
325 326 327 328 329
        child.computeSemanticsInformation(collector);
      }
    }
  }

330
  @override
331
  int? codeUnitAtVisitor(int index, Accumulator offset) {
332
    if (text == null) {
333
      return null;
334
    }
335 336
    if (index - offset.value < text!.length) {
      return text!.codeUnitAt(index - offset.value);
337
    }
338
    offset.increment(text!.length);
339 340 341 342 343
    return null;
  }

  @override
  void describeSemantics(Accumulator offset, List<int> semanticsOffsets, List<dynamic> semanticsElements) {
344 345 346 347
    if (
      recognizer != null &&
      (recognizer is TapGestureRecognizer || recognizer is LongPressGestureRecognizer)
    ) {
348
      final int length = semanticsLabel?.length ?? text!.length;
349 350 351 352
      semanticsOffsets.add(offset.value);
      semanticsOffsets.add(offset.value + length);
      semanticsElements.add(recognizer);
    }
353
    offset.increment(text != null ? text!.length : 0);
354 355
  }

356 357
  /// In checked mode, throws an exception if the object is not in a valid
  /// configuration. Otherwise, returns true.
358 359
  ///
  /// This is intended to be used as follows:
360
  ///
361
  /// ```dart
362
  /// assert(myTextSpan.debugAssertIsValid());
363
  /// ```
364
  @override
365
  bool debugAssertIsValid() {
366
    assert(() {
367
      if (children != null) {
368
        for (final InlineSpan child in children!) {
369 370 371 372
          // `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).
          if (child == null) { // ignore: dead_code
373 374 375 376 377 378 379 380
            throw FlutterError.fromParts(<DiagnosticsNode>[
              ErrorSummary('TextSpan contains a null child.'),
              ErrorDescription(
                  '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),
            ]);
          }
381
          assert(child.debugAssertIsValid());
382 383 384
        }
      }
      return true;
385
    }());
386
    return super.debugAssertIsValid();
387 388
  }

389 390
  @override
  RenderComparison compareTo(InlineSpan other) {
391 392
    if (identical(this, other))
      return RenderComparison.identical;
393
    if (other.runtimeType != runtimeType)
394
      return RenderComparison.layout;
395
    final TextSpan textSpan = other as TextSpan;
396 397 398 399
    if (textSpan.text != text ||
        children?.length != textSpan.children?.length ||
        (style == null) != (textSpan.style == null))
      return RenderComparison.layout;
400 401 402
    RenderComparison result = recognizer == textSpan.recognizer ?
      RenderComparison.identical :
      RenderComparison.metadata;
403
    if (style != null) {
404
      final RenderComparison candidate = style!.compareTo(textSpan.style!);
405 406 407 408 409 410
      if (candidate.index > result.index)
        result = candidate;
      if (result == RenderComparison.layout)
        return result;
    }
    if (children != null) {
411 412
      for (int index = 0; index < children!.length; index += 1) {
        final RenderComparison candidate = children![index].compareTo(textSpan.children![index]);
413 414 415 416 417 418 419 420 421
        if (candidate.index > result.index)
          result = candidate;
        if (result == RenderComparison.layout)
          return result;
      }
    }
    return result;
  }

422
  @override
423
  bool operator ==(Object other) {
424 425
    if (identical(this, other))
      return true;
426
    if (other.runtimeType != runtimeType)
427
      return false;
428 429
    if (super != other)
      return false;
430 431 432 433 434
    return other is TextSpan
        && other.text == text
        && other.recognizer == recognizer
        && other.semanticsLabel == semanticsLabel
        && listEquals<InlineSpan>(other.children, children);
435 436 437
  }

  @override
438 439 440 441 442 443 444
  int get hashCode => hashValues(
    super.hashCode,
    text,
    recognizer,
    semanticsLabel,
    hashList(children),
  );
445 446

  @override
447
  String toStringShort() => objectRuntimeType(this, 'TextSpan');
448

449
  @override
450 451
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
452

453 454 455 456 457 458 459 460
    properties.add(
      StringProperty(
        'text',
        text,
        showName: false,
        defaultValue: null,
      )
    );
461 462
    if (style == null && text == null && children == null)
      properties.add(DiagnosticsNode.message('(empty)'));
463

464
    properties.add(DiagnosticsProperty<GestureRecognizer>(
465
      'recognizer', recognizer,
466
      description: recognizer?.runtimeType.toString(),
467 468
      defaultValue: null,
    ));
469

470 471 472
    if (semanticsLabel != null) {
      properties.add(StringProperty('semanticsLabel', semanticsLabel));
    }
473 474 475 476
  }

  @override
  List<DiagnosticsNode> debugDescribeChildren() {
477 478
    if (children == null)
      return const <DiagnosticsNode>[];
479
    return children!.map<DiagnosticsNode>((InlineSpan child) {
480 481 482
      // `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).
483 484
      if (child != null) {
        return child.toDiagnosticsNode();
485
      } else { // ignore: dead_code
486
        return DiagnosticsNode.message('<null child>');
487 488
      }
    }).toList();
489
  }
490
}