summaryrefslogtreecommitdiff
path: root/lib/widgets/common/basic/text
diff options
context:
space:
mode:
Diffstat (limited to 'lib/widgets/common/basic/text')
-rw-r--r--lib/widgets/common/basic/text/animated_diff.dart179
-rw-r--r--lib/widgets/common/basic/text/background_painter.dart77
-rw-r--r--lib/widgets/common/basic/text/change_highlight.dart89
-rw-r--r--lib/widgets/common/basic/text/outlined.dart102
4 files changed, 447 insertions, 0 deletions
diff --git a/lib/widgets/common/basic/text/animated_diff.dart b/lib/widgets/common/basic/text/animated_diff.dart
new file mode 100644
index 0000000..fe37d42
--- /dev/null
+++ b/lib/widgets/common/basic/text/animated_diff.dart
@@ -0,0 +1,179 @@
+import 'dart:math';
+
+import 'package:aves/utils/diff_match.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter/widgets.dart';
+
+class AnimatedDiffText extends StatefulWidget {
+ final String text;
+ final TextStyle? textStyle;
+ final StrutStyle? strutStyle;
+ final Curve curve;
+ final Duration duration;
+
+ const AnimatedDiffText(
+ this.text, {
+ super.key,
+ this.textStyle,
+ this.strutStyle,
+ this.curve = Curves.easeInOutCubic,
+ required this.duration,
+ });
+
+ @override
+ State<AnimatedDiffText> createState() => _AnimatedDiffTextState();
+}
+
+class _AnimatedDiffTextState extends State<AnimatedDiffText> with SingleTickerProviderStateMixin {
+ late final AnimationController _controller;
+ late final CurvedAnimation _animation;
+ final List<_TextDiff> _diffs = [];
+
+ TextStyle get _textStyle {
+ final style = widget.textStyle ?? const TextStyle();
+ // specify `height` for accurate paragraph height measurement
+ return style.copyWith(height: style.height ?? DefaultTextStyle.of(context).style.height);
+ }
+
+ StrutStyle? get _strutStyle => widget.strutStyle;
+
+ @override
+ void initState() {
+ super.initState();
+ _controller = AnimationController(
+ duration: widget.duration,
+ vsync: this,
+ );
+ _animation = CurvedAnimation(parent: _controller, curve: widget.curve);
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ _computeDiff(widget.text, widget.text);
+ }
+
+ @override
+ void didUpdateWidget(covariant AnimatedDiffText oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ final oldText = oldWidget.text;
+ final newText = widget.text;
+ if (oldText != newText) {
+ _computeDiff(oldText, newText);
+ _controller.forward(from: 0);
+ }
+ }
+
+ @override
+ void dispose() {
+ _animation.dispose();
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return AnimatedBuilder(
+ animation: _animation,
+ builder: (context, child) {
+ return Text.rich(
+ TextSpan(
+ children: _diffs.map((diff) {
+ final (oldText, newText, oldSize, newSize) = diff;
+ final text = (_animation.value == 0 ? oldText : newText) ?? '';
+ return WidgetSpan(
+ child: AnimatedSize(
+ key: ValueKey(diff),
+ curve: widget.curve,
+ duration: widget.duration,
+ child: AnimatedSwitcher(
+ duration: widget.duration,
+ switchInCurve: widget.curve,
+ switchOutCurve: widget.curve,
+ layoutBuilder: (currentChild, previousChildren) {
+ return Stack(
+ alignment: Alignment.center,
+ children: [
+ ...previousChildren.map(
+ (child) => ConstrainedBox(
+ constraints: BoxConstraints.tight(Size(
+ min(oldSize.width, newSize.width),
+ min(oldSize.height, newSize.height),
+ )),
+ child: child,
+ ),
+ ),
+ if (currentChild != null) currentChild,
+ ],
+ );
+ },
+ child: Text(
+ text,
+ key: Key(text),
+ style: _textStyle,
+ ),
+ ),
+ ),
+ );
+ }).toList(),
+ ),
+ strutStyle: _strutStyle,
+ );
+ },
+ );
+ }
+
+ Size _textSize(String text) {
+ final paragraph = RenderParagraph(
+ TextSpan(text: text, style: _textStyle),
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ strutStyle: _strutStyle,
+ )..layout(const BoxConstraints(), parentUsesSize: true);
+ final width = paragraph.getMaxIntrinsicWidth(double.infinity);
+ final height = paragraph.getMaxIntrinsicHeight(double.infinity);
+ paragraph.dispose();
+ return Size(width, height);
+ }
+
+ // use an adaptation of Google's `Diff Match and Patch`
+ // as package `diffutil_dart` (as of v3.0.0) is unreliable
+ void _computeDiff(String oldText, String newText) {
+ final oldCharacters = oldText.characters.join();
+ final newCharacters = newText.characters.join();
+
+ final dmp = DiffMatchPatch();
+ final d = dmp.diff_main(oldCharacters, newCharacters);
+ dmp.diff_cleanupSemantic(d);
+
+ _diffs
+ ..clear()
+ ..addAll(d.map((diff) {
+ final text = diff.text;
+ final size = _textSize(text);
+ return switch (diff.operation) {
+ Operation.delete => (text, null, size, Size.zero),
+ Operation.insert => (null, text, Size.zero, size),
+ Operation.equal || _ => (text, text, size, size),
+ };
+ }).fold<List<_TextDiff>>([], (prev, v) {
+ if (prev.isNotEmpty) {
+ final last = prev.last;
+ final prevNewText = last.$2;
+ if (prevNewText == null) {
+ // previous diff is a deletion
+ final thisOldText = v.$1;
+ if (thisOldText == null) {
+ // this diff is an insertion
+ // merge deletion and insertion as a change operation
+ final change = (last.$1, v.$2, last.$3, v.$4);
+ return [...prev.take(prev.length - 1), change];
+ }
+ }
+ }
+ return [...prev, v];
+ }));
+ }
+}
+
+typedef _TextDiff = (String?, String?, Size, Size);
diff --git a/lib/widgets/common/basic/text/background_painter.dart b/lib/widgets/common/basic/text/background_painter.dart
new file mode 100644
index 0000000..e3757c1
--- /dev/null
+++ b/lib/widgets/common/basic/text/background_painter.dart
@@ -0,0 +1,77 @@
+import 'dart:ui' as ui;
+
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+
+// as of Flutter v3.3.7, text style background does not have consistent height
+// when rendering multi-script text, so we paint the background behind via a stack instead
+class TextBackgroundPainter extends StatelessWidget {
+ final List<TextSpan> spans;
+ final TextStyle style;
+ final TextAlign textAlign;
+ final Widget child;
+
+ const TextBackgroundPainter({
+ super.key,
+ required this.spans,
+ required this.style,
+ required this.textAlign,
+ required this.child,
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ final backgroundColor = style.backgroundColor;
+ if (backgroundColor == null || backgroundColor.a == 0) {
+ return child;
+ }
+
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final paragraph = RenderParagraph(
+ TextSpan(
+ children: spans,
+ style: style,
+ ),
+ textAlign: textAlign,
+ textDirection: Directionality.of(context),
+ textScaler: MediaQuery.textScalerOf(context),
+ )..layout(constraints, parentUsesSize: true);
+
+ final textLength = spans.map((v) => v.text?.length ?? 0).sum;
+ final allBoxes = paragraph.getBoxesForSelection(
+ TextSelection(baseOffset: 0, extentOffset: textLength),
+ boxHeightStyle: ui.BoxHeightStyle.max,
+ );
+ paragraph.dispose();
+
+ // merge boxes to avoid artifacts at box edges, from anti-aliasing and rounding hacks
+ final lineRects = groupBy<TextBox, double>(allBoxes, (v) => v.top).entries.map((kv) {
+ final top = kv.key;
+ final lineBoxes = kv.value;
+ return Rect.fromLTRB(
+ lineBoxes.map((v) => v.left).min,
+ top,
+ lineBoxes.map((v) => v.right).max,
+ lineBoxes.first.bottom,
+ );
+ });
+
+ return Stack(
+ children: [
+ ...lineRects.map((rect) {
+ return Positioned.fromRect(
+ rect: rect,
+ child: ColoredBox(
+ color: backgroundColor,
+ ),
+ );
+ }),
+ child,
+ ],
+ );
+ },
+ );
+ }
+}
diff --git a/lib/widgets/common/basic/text/change_highlight.dart b/lib/widgets/common/basic/text/change_highlight.dart
new file mode 100644
index 0000000..cea4737
--- /dev/null
+++ b/lib/widgets/common/basic/text/change_highlight.dart
@@ -0,0 +1,89 @@
+import 'package:collection/collection.dart';
+import 'package:flutter/material.dart';
+
+class ChangeHighlightText extends StatefulWidget {
+ final String data;
+ final TextStyle style, changedStyle;
+ final Curve curve;
+ final Duration duration;
+
+ const ChangeHighlightText(
+ this.data, {
+ super.key,
+ required this.style,
+ required this.changedStyle,
+ this.curve = Curves.linear,
+ required this.duration,
+ });
+
+ @override
+ State<ChangeHighlightText> createState() => _ChangeHighlightTextState();
+}
+
+class _ChangeHighlightTextState extends State<ChangeHighlightText> with SingleTickerProviderStateMixin {
+ late final AnimationController _controller;
+ late final CurvedAnimation _animation;
+ late final Animation<TextStyle> _style;
+
+ @override
+ void initState() {
+ super.initState();
+ _controller = AnimationController(
+ duration: widget.duration,
+ vsync: this,
+ )
+ ..value = 1
+ ..addListener(() => setState(() {}));
+ _animation = CurvedAnimation(
+ parent: _controller,
+ curve: widget.curve,
+ );
+ _style = ShadowedTextStyleTween(begin: widget.changedStyle, end: widget.style).animate(_animation);
+ }
+
+ @override
+ void didUpdateWidget(ChangeHighlightText oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.data != widget.data) {
+ _controller
+ ..value = 0
+ ..forward();
+ }
+ }
+
+ @override
+ void dispose() {
+ _animation.dispose();
+ _controller.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return Text(
+ widget.data,
+ style: _style.value,
+ );
+ }
+}
+
+class ShadowedTextStyleTween extends Tween<TextStyle> {
+ ShadowedTextStyleTween({super.begin, super.end});
+
+ @override
+ TextStyle lerp(double t) {
+ final textStyle = TextStyle.lerp(begin, end, t)!;
+ final beginShadows = begin!.shadows;
+ final endShadows = end!.shadows;
+ if (beginShadows != null && endShadows != null && beginShadows.length == endShadows.length) {
+ return textStyle.copyWith(
+ shadows: beginShadows.mapIndexed((i, a) {
+ final b = endShadows[i];
+ return Shadow.lerp(a, b, t)!;
+ }).toList(),
+ );
+ } else {
+ return textStyle;
+ }
+ }
+}
diff --git a/lib/widgets/common/basic/text/outlined.dart b/lib/widgets/common/basic/text/outlined.dart
new file mode 100644
index 0000000..3ccf145
--- /dev/null
+++ b/lib/widgets/common/basic/text/outlined.dart
@@ -0,0 +1,102 @@
+import 'dart:ui';
+
+import 'package:flutter/material.dart';
+
+class OutlinedText extends StatelessWidget {
+ final List<TextSpan> textSpans;
+ final double outlineWidth;
+ final Color outlineColor;
+ final double outlineBlurSigma;
+ final TextAlign? textAlign;
+ final bool? softWrap;
+ final TextOverflow? overflow;
+ final int? maxLines;
+
+ static const widgetSpanAlignment = PlaceholderAlignment.middle;
+
+ const OutlinedText({
+ super.key,
+ required this.textSpans,
+ double? outlineWidth,
+ Color? outlineColor,
+ double? outlineBlurSigma,
+ this.textAlign,
+ this.softWrap,
+ this.overflow,
+ this.maxLines,
+ }) : outlineWidth = outlineWidth ?? 1,
+ outlineColor = outlineColor ?? Colors.black,
+ outlineBlurSigma = outlineBlurSigma ?? 0;
+
+ @override
+ Widget build(BuildContext context) {
+ // TODO TLAD [subtitles] fix background area for mixed alphabetic-ideographic text
+ // as of Flutter v3.10.0, the area computed for `backgroundColor` has inconsistent height
+ // in case of mixed alphabetic-ideographic text. The painted boxes depend on the script.
+ // Possible workarounds would be to use metrics from:
+ // - `TextPainter.getBoxesForSelection`
+ // - `Paragraph.getBoxesForRange`
+ // and paint the background at the bottom of the `Stack`
+
+ final hasOutline = outlineWidth > 0;
+
+ Widget? outline;
+ if (hasOutline) {
+ outline = Text.rich(
+ TextSpan(
+ children: textSpans.map(_toStrokeSpan).toList(),
+ ),
+ textAlign: textAlign,
+ softWrap: softWrap,
+ overflow: overflow,
+ maxLines: maxLines,
+ );
+ if (outlineBlurSigma > 0) {
+ outline = ImageFiltered(
+ imageFilter: ImageFilter.blur(
+ sigmaX: outlineBlurSigma,
+ sigmaY: outlineBlurSigma,
+ ),
+ child: outline,
+ );
+ }
+ }
+
+ final fill = Text.rich(
+ TextSpan(
+ children: hasOutline ? textSpans.map(_toFillSpan).toList() : textSpans,
+ ),
+ textAlign: textAlign,
+ softWrap: softWrap,
+ overflow: overflow,
+ maxLines: maxLines,
+ );
+
+ return Stack(
+ children: [
+ if (outline != null) outline,
+ fill,
+ ],
+ );
+ }
+
+ TextSpan _toStrokeSpan(TextSpan span) => TextSpan(
+ text: span.text,
+ children: span.children,
+ style: (span.style ?? const TextStyle()).copyWith(
+ foreground: Paint()
+ ..style = PaintingStyle.stroke
+ ..color = outlineColor
+ ..strokeWidth = outlineWidth,
+ ),
+ );
+
+ TextSpan _toFillSpan(TextSpan span) => TextSpan(
+ text: span.text,
+ children: span.children,
+ style: (span.style ?? const TextStyle()).copyWith(
+ backgroundColor: Colors.transparent,
+ shadows: [],
+ ),
+ );
+}