-
Notifications
You must be signed in to change notification settings - Fork 857
/
Copy pathtext_line.dart
1584 lines (1403 loc) · 47.2 KB
/
text_line.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
208
209
210
211
212
213
214
215
216
217
218
219
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:collection';
import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/gestures.dart'
show GestureRecognizer, LongPressGestureRecognizer, TapGestureRecognizer;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart'
show BoxParentData, PipelineOwner, BoxHitTestResult, RenderObjectVisitor;
import 'package:flutter/services.dart' show ClipboardData, Clipboard;
import 'package:url_launcher/url_launcher_string.dart' show launchUrlString;
import '../../../../flutter_quill.dart';
import '../../../common/utils/color.dart';
import '../../../common/utils/font.dart';
import '../../../common/utils/platform.dart';
import '../../../document/nodes/container.dart' as container_node;
import '../../../document/nodes/leaf.dart' as leaf;
import '../box.dart';
import '../delegate.dart';
import '../keyboard_listener.dart';
import '../proxy.dart';
import 'text_selection.dart';
class TextLine extends StatefulWidget {
const TextLine({
required this.line,
required this.embedBuilder,
required this.styles,
required this.readOnly,
required this.controller,
required this.onLaunchUrl,
required this.linkActionPicker,
required this.composingRange,
this.textDirection,
this.customStyleBuilder,
this.customRecognizerBuilder,
this.customLinkPrefixes = const <String>[],
super.key,
});
final Line line;
final TextDirection? textDirection;
final EmbedsBuilder embedBuilder;
final DefaultStyles styles;
final bool readOnly;
final QuillController controller;
final CustomStyleBuilder? customStyleBuilder;
final CustomRecognizerBuilder? customRecognizerBuilder;
final ValueChanged<String>? onLaunchUrl;
final LinkActionPicker linkActionPicker;
final List<String> customLinkPrefixes;
final TextRange composingRange;
@override
State<TextLine> createState() => _TextLineState();
}
class _TextLineState extends State<TextLine> {
bool _metaOrControlPressed = false;
UniqueKey _richTextKey = UniqueKey();
final _linkRecognizers = <Node, GestureRecognizer>{};
QuillPressedKeys? _pressedKeys;
void _pressedKeysChanged() {
final newValue = _pressedKeys!.metaPressed || _pressedKeys!.controlPressed;
if (_metaOrControlPressed != newValue) {
setState(() {
_metaOrControlPressed = newValue;
_linkRecognizers
..forEach((key, value) {
value.dispose();
})
..clear();
});
}
}
bool get canLaunchLinks {
// In readOnly mode users can launch links
// by simply tapping (clicking) on them
if (widget.readOnly) return true;
// In editing mode it depends on the platform:
// Desktop platforms (macOS, Linux, Windows):
// only allow Meta (Control) + Click combinations
if (isDesktopApp) {
return _metaOrControlPressed;
}
// Mobile platforms (ios, android): always allow but we install a
// long-press handler instead of a tap one. LongPress is followed by a
// context menu with actions.
return true;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_pressedKeys == null) {
_pressedKeys = QuillPressedKeys.of(context);
_pressedKeys!.addListener(_pressedKeysChanged);
} else {
_pressedKeys!.removeListener(_pressedKeysChanged);
_pressedKeys = QuillPressedKeys.of(context);
_pressedKeys!.addListener(_pressedKeysChanged);
}
}
@override
void didUpdateWidget(covariant TextLine oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.readOnly != widget.readOnly) {
_richTextKey = UniqueKey();
_linkRecognizers
..forEach((key, value) {
value.dispose();
})
..clear();
}
}
@override
void dispose() {
_pressedKeys?.removeListener(_pressedKeysChanged);
_linkRecognizers
..forEach((key, value) => value.dispose())
..clear();
super.dispose();
}
/// Check if this line contains the placeholder attribute
bool get isPlaceholderLine =>
widget.line.toDelta().first.attributes?.containsKey('placeholder') ??
false;
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
if (widget.line.hasEmbed && widget.line.childCount == 1) {
// Single child embeds can be expanded
var embed = widget.line.children.single as Embed;
// Creates correct node for custom embed
if (embed.value.type == BlockEmbed.customType) {
embed = Embed(
CustomBlockEmbed.fromJsonString(embed.value.data),
);
}
final embedBuilder = widget.embedBuilder(embed);
if (embedBuilder.expanded) {
// Creates correct node for custom embed
final lineStyle = _getLineStyle(widget.styles);
return EmbedProxy(
embedBuilder.build(
context,
widget.controller,
embed,
widget.readOnly,
false,
lineStyle,
),
);
}
}
final textSpan = _getTextSpanForWholeLine();
final strutStyle =
StrutStyle.fromTextStyle(textSpan.style ?? const TextStyle());
final textAlign = _getTextAlign();
final child = RichText(
key: _richTextKey,
text: textSpan,
textAlign: textAlign,
textDirection: widget.textDirection,
strutStyle: strutStyle,
textScaler: MediaQuery.textScalerOf(context),
);
return RichTextProxy(
textStyle: textSpan.style ?? const TextStyle(),
textAlign: textAlign,
textDirection: widget.textDirection!,
strutStyle: strutStyle,
locale: Localizations.localeOf(context),
textScaler: MediaQuery.textScalerOf(context),
child: child,
);
}
InlineSpan _getTextSpanForWholeLine() {
var lineStyle = _getLineStyle(widget.styles);
if (!widget.line.hasEmbed) {
return _buildTextSpan(widget.styles, widget.line.children, lineStyle);
}
// The line could contain more than one Embed & more than one Text
final textSpanChildren = <InlineSpan>[];
var textNodes = LinkedList<Node>();
for (var child in widget.line.children) {
if (child is Embed) {
if (textNodes.isNotEmpty) {
textSpanChildren
.add(_buildTextSpan(widget.styles, textNodes, lineStyle));
textNodes = LinkedList<Node>();
}
// Creates correct node for custom embed
if (child.value.type == BlockEmbed.customType) {
child = Embed(CustomBlockEmbed.fromJsonString(child.value.data))
..applyStyle(child.style);
}
if (child.value.type == BlockEmbed.formulaType) {
lineStyle = lineStyle.merge(_getInlineTextStyle(
child.style,
widget.styles,
widget.line.style,
false,
));
}
final embedBuilder = widget.embedBuilder(child);
final embedWidget = EmbedProxy(
embedBuilder.build(
context,
widget.controller,
child,
widget.readOnly,
true,
lineStyle,
),
);
final embed = embedBuilder.buildWidgetSpan(embedWidget);
textSpanChildren.add(embed);
continue;
}
// here child is Text node and its value is cloned
textNodes.add(child.clone());
}
if (textNodes.isNotEmpty) {
textSpanChildren.add(_buildTextSpan(widget.styles, textNodes, lineStyle));
}
return TextSpan(style: lineStyle, children: textSpanChildren);
}
TextAlign _getTextAlign() {
final alignment = widget.line.style.attributes[Attribute.align.key];
if (alignment == Attribute.leftAlignment) {
return TextAlign.start;
} else if (alignment == Attribute.centerAlignment) {
return TextAlign.center;
} else if (alignment == Attribute.rightAlignment) {
return TextAlign.end;
} else if (alignment == Attribute.justifyAlignment) {
return TextAlign.justify;
}
return TextAlign.start;
}
TextSpan _buildTextSpan(
DefaultStyles defaultStyles,
LinkedList<Node> nodes,
TextStyle lineStyle,
) {
if (nodes.isEmpty && kIsWeb) {
nodes = LinkedList<Node>()..add(leaf.QuillText('\u{200B}'));
}
final isComposingRangeOutOfLine = !widget.composingRange.isValid ||
widget.composingRange.isCollapsed ||
(widget.composingRange.start < widget.line.documentOffset ||
widget.composingRange.end >
widget.line.documentOffset + widget.line.length);
if (isComposingRangeOutOfLine) {
final children = nodes
.map((node) =>
_getTextSpanFromNode(defaultStyles, node, widget.line.style))
.toList(growable: false);
return TextSpan(children: children, style: lineStyle);
}
final children = nodes.expand((node) {
final child =
_getTextSpanFromNode(defaultStyles, node, widget.line.style);
final isNodeInComposingRange =
node.documentOffset <= widget.composingRange.start &&
widget.composingRange.end <= node.documentOffset + node.length;
if (isNodeInComposingRange) {
return _splitAndApplyComposingStyle(node, child);
} else {
return [child];
}
}).toList(growable: false);
return TextSpan(children: children, style: lineStyle);
}
// split the text nodes into composing and non-composing nodes
// and apply the composing style to the composing nodes
List<InlineSpan> _splitAndApplyComposingStyle(Node node, InlineSpan child) {
assert(widget.composingRange.isValid && !widget.composingRange.isCollapsed);
final composingStart = widget.composingRange.start - node.documentOffset;
final composingEnd = widget.composingRange.end - node.documentOffset;
final text = child.toPlainText();
final textBefore = text.substring(0, composingStart);
final textComposing = text.substring(composingStart, composingEnd);
final textAfter = text.substring(composingEnd);
final composingStyle = child.style
?.merge(const TextStyle(decoration: TextDecoration.underline)) ??
const TextStyle(decoration: TextDecoration.underline);
return [
TextSpan(
text: textBefore,
style: child.style,
),
TextSpan(
text: textComposing,
style: composingStyle,
),
TextSpan(
text: textAfter,
style: child.style,
),
];
}
TextStyle _getLineStyle(DefaultStyles defaultStyles) {
var textStyle = const TextStyle();
if (widget.line.style.containsKey(Attribute.placeholder.key)) {
return defaultStyles.placeHolder!.style;
}
final header = widget.line.style.attributes[Attribute.header.key];
final m = <Attribute, TextStyle>{
Attribute.h1: defaultStyles.h1!.style,
Attribute.h2: defaultStyles.h2!.style,
Attribute.h3: defaultStyles.h3!.style,
Attribute.h4: defaultStyles.h4!.style,
Attribute.h5: defaultStyles.h5!.style,
Attribute.h6: defaultStyles.h6!.style,
};
textStyle = textStyle.merge(m[header] ?? defaultStyles.paragraph!.style);
// Only retrieve exclusive block format for the line style purpose
Attribute? block;
widget.line.style.getBlocksExceptHeader().forEach((key, value) {
if (Attribute.exclusiveBlockKeys.contains(key)) {
block = value;
}
});
TextStyle? toMerge;
if (block == Attribute.blockQuote) {
toMerge = defaultStyles.quote!.style;
} else if (block == Attribute.codeBlock) {
toMerge = defaultStyles.code!.style;
} else if (block?.key == Attribute.list.key) {
toMerge = defaultStyles.lists!.style;
}
textStyle = textStyle.merge(toMerge);
final lineHeight = widget.line.style.attributes[Attribute.lineHeight.key];
final x = <Attribute, TextStyle>{
LineHeightAttribute.lineHeightNormal:
defaultStyles.lineHeightNormal!.style,
LineHeightAttribute.lineHeightTight: defaultStyles.lineHeightTight!.style,
LineHeightAttribute.lineHeightOneAndHalf:
defaultStyles.lineHeightOneAndHalf!.style,
LineHeightAttribute.lineHeightDouble:
defaultStyles.lineHeightDouble!.style,
};
// If the lineHeight attribute isn't null, then get just the height param instead whole TextStyle
// to avoid modify the current style of the text line
textStyle =
textStyle.merge(textStyle.copyWith(height: x[lineHeight]?.height));
textStyle = _applyCustomAttributes(textStyle, widget.line.style.attributes);
if (isPlaceholderLine) {
final oldStyle = textStyle;
textStyle = defaultStyles.placeHolder!.style;
textStyle = textStyle.merge(oldStyle.copyWith(
color: textStyle.color,
backgroundColor: textStyle.backgroundColor,
background: textStyle.background,
));
}
return textStyle;
}
TextStyle _applyCustomAttributes(
TextStyle textStyle, Map<String, Attribute> attributes) {
if (widget.customStyleBuilder == null) {
return textStyle;
}
for (final key in attributes.keys) {
final attr = attributes[key];
if (attr != null) {
/// Custom Attribute
final customAttr = widget.customStyleBuilder!.call(attr);
textStyle = textStyle.merge(customAttr);
}
}
return textStyle;
}
/// Processes subscript and superscript attributed text.
///
/// Reduces text fontSize and shifts down or up. Increases fontWeight to maintain balance with normal text.
/// Outputs characters individually to allow correct caret positioning and text selection.
InlineSpan _scriptSpan(String text, bool superScript, TextStyle style,
DefaultStyles defaultStyles) {
assert(text.isNotEmpty);
//
final lineStyle = style.fontSize == null || style.fontWeight == null
? _getLineStyle(defaultStyles)
: null;
final fontWeight = FontWeight.lerp(
style.fontWeight ?? lineStyle?.fontWeight ?? FontWeight.normal,
FontWeight.w900,
0.25);
final fontSize = style.fontSize ?? lineStyle?.fontSize ?? 16;
final y = (superScript ? -0.4 : 0.14) * fontSize;
final charStyle = style.copyWith(
fontFeatures: <FontFeature>[],
fontWeight: fontWeight,
fontSize: fontSize * 0.7);
//
final offset = Offset(0, y);
final children = <WidgetSpan>[];
for (final c in text.characters) {
children.add(WidgetSpan(
child: Transform.translate(
offset: offset,
child: Text(
c,
style: charStyle,
))));
}
//
if (children.length > 1) {
return TextSpan(children: children);
}
return children[0];
}
InlineSpan _getTextSpanFromNode(
DefaultStyles defaultStyles, Node node, Style lineStyle) {
final textNode = node as leaf.QuillText;
final nodeStyle = textNode.style;
final isLink = nodeStyle.containsKey(Attribute.link.key) &&
nodeStyle.attributes[Attribute.link.key]!.value != null;
final style =
_getInlineTextStyle(nodeStyle, defaultStyles, lineStyle, isLink);
if (widget.controller.configurations.requireScriptFontFeatures == false &&
textNode.value.isNotEmpty) {
if (nodeStyle.containsKey(Attribute.script.key)) {
final attr = nodeStyle.attributes[Attribute.script.key];
if (attr == Attribute.superscript || attr == Attribute.subscript) {
return _scriptSpan(textNode.value, attr == Attribute.superscript,
style, defaultStyles);
}
}
}
if (!isLink &&
!widget.readOnly &&
!widget.line.style.attributes.containsKey('code-block') &&
!widget.line.style.attributes.containsKey('placeholder') &&
!isPlaceholderLine) {
// ignore: deprecated_member_use_from_same_package
final service = SpellCheckerServiceProvider.instance;
final spellcheckedSpans = service.checkSpelling(textNode.value);
if (spellcheckedSpans != null && spellcheckedSpans.isNotEmpty) {
return TextSpan(
children: spellcheckedSpans,
style: style,
mouseCursor: null,
);
}
}
final recognizer = _getRecognizer(node, isLink);
return TextSpan(
text: textNode.value,
style: style,
recognizer: recognizer,
mouseCursor: (recognizer != null) ? SystemMouseCursors.click : null,
);
}
TextStyle _getInlineTextStyle(Style nodeStyle, DefaultStyles defaultStyles,
Style lineStyle, bool isLink) {
var res = const TextStyle(); // This is inline text style
final color = nodeStyle.attributes[Attribute.color.key];
<String, TextStyle?>{
Attribute.bold.key: defaultStyles.bold,
Attribute.italic.key: defaultStyles.italic,
Attribute.small.key: defaultStyles.small,
Attribute.link.key: defaultStyles.link,
Attribute.underline.key: defaultStyles.underline,
Attribute.strikeThrough.key: defaultStyles.strikeThrough,
}.forEach((k, s) {
if (nodeStyle.values.any((v) => v.key == k)) {
if (k == Attribute.underline.key || k == Attribute.strikeThrough.key) {
var textColor = defaultStyles.color;
if (color?.value is String) {
textColor = stringToColor(color?.value, textColor, defaultStyles);
}
res = _merge(res.copyWith(decorationColor: textColor),
s!.copyWith(decorationColor: textColor));
} else if (k == Attribute.link.key && !isLink) {
// null value for link should be ignored
// i.e. nodeStyle.attributes[Attribute.link.key]!.value == null
} else {
res = _merge(res, s!);
}
}
});
if (nodeStyle.containsKey(Attribute.script.key)) {
if (nodeStyle.attributes.values.contains(Attribute.subscript)) {
res = _merge(res, defaultStyles.subscript!);
} else if (nodeStyle.attributes.values.contains(Attribute.superscript)) {
res = _merge(res, defaultStyles.superscript!);
}
}
if (nodeStyle.containsKey(Attribute.inlineCode.key)) {
res = _merge(res, defaultStyles.inlineCode!.styleFor(lineStyle));
}
final font = nodeStyle.attributes[Attribute.font.key];
if (font != null && font.value != null) {
res = res.merge(TextStyle(fontFamily: font.value));
}
final size = nodeStyle.attributes[Attribute.size.key];
if (size != null && size.value != null) {
switch (size.value) {
case 'small':
res = res.merge(defaultStyles.sizeSmall);
break;
case 'large':
res = res.merge(defaultStyles.sizeLarge);
break;
case 'huge':
res = res.merge(defaultStyles.sizeHuge);
break;
default:
res = res.merge(TextStyle(
fontSize: getFontSize(
size.value,
),
));
}
}
if (color != null && color.value != null) {
var textColor = defaultStyles.color;
if (color.value is String) {
textColor = stringToColor(color.value, null, defaultStyles);
}
if (textColor != null) {
res = res.merge(TextStyle(color: textColor));
}
}
final background = nodeStyle.attributes[Attribute.background.key];
if (background != null && background.value != null) {
final backgroundColor =
stringToColor(background.value, null, defaultStyles);
res = res.merge(TextStyle(backgroundColor: backgroundColor));
}
res = _applyCustomAttributes(res, nodeStyle.attributes);
return res;
}
GestureRecognizer? _getRecognizer(Node segment, bool isLink) {
if (_linkRecognizers.containsKey(segment)) {
return _linkRecognizers[segment]!;
}
if (widget.customRecognizerBuilder != null) {
final textNode = segment as leaf.QuillText;
final nodeStyle = textNode.style;
nodeStyle.attributes.forEach((key, value) {
final recognizer = widget.customRecognizerBuilder!.call(value, segment);
if (recognizer != null) {
_linkRecognizers[segment] = recognizer;
return;
}
});
}
if (_linkRecognizers.containsKey(segment)) {
return _linkRecognizers[segment]!;
}
if (isLink && canLaunchLinks) {
if (isDesktop || widget.readOnly) {
_linkRecognizers[segment] = TapGestureRecognizer()
..onTap = () => _tapNodeLink(segment);
} else {
_linkRecognizers[segment] = LongPressGestureRecognizer()
..onLongPress = () => _longPressLink(segment);
}
}
return _linkRecognizers[segment];
}
Future<void> _launchUrl(String url) async {
await launchUrlString(url);
}
void _tapNodeLink(Node node) {
final link = node.style.attributes[Attribute.link.key]!.value;
_tapLink(link);
}
void _tapLink(String? link) {
if (link == null) {
return;
}
var launchUrl = widget.onLaunchUrl;
launchUrl ??= _launchUrl;
link = link.trim();
if (!(widget.customLinkPrefixes + linkPrefixes)
.any((linkPrefix) => link!.toLowerCase().startsWith(linkPrefix))) {
link = 'https://$link';
}
launchUrl(link);
}
Future<void> _longPressLink(Node node) async {
final link = node.style.attributes[Attribute.link.key]!.value!;
final action = await widget.linkActionPicker(node);
switch (action) {
case LinkMenuAction.launch:
_tapLink(link);
break;
case LinkMenuAction.copy:
Clipboard.setData(ClipboardData(text: link));
break;
case LinkMenuAction.remove:
final range = getLinkRange(node);
widget.controller
.formatText(range.start, range.end - range.start, Attribute.link);
break;
case LinkMenuAction.none:
break;
}
}
TextStyle _merge(TextStyle a, TextStyle b) {
final decorations = <TextDecoration?>[];
if (a.decoration != null) {
decorations.add(a.decoration);
}
if (b.decoration != null) {
decorations.add(b.decoration);
}
return a.merge(b).apply(
decoration: TextDecoration.combine(
List.castFrom<dynamic, TextDecoration>(decorations)));
}
}
class EditableTextLine extends RenderObjectWidget {
const EditableTextLine(
this.line,
this.leading,
this.body,
this.horizontalSpacing,
this.verticalSpacing,
this.textDirection,
this.textSelection,
this.color,
this.enableInteractiveSelection,
this.hasFocus,
this.devicePixelRatio,
this.cursorCont,
this.inlineCodeStyle,
{super.key});
final Line line;
final Widget? leading;
final Widget body;
final HorizontalSpacing horizontalSpacing;
final VerticalSpacing verticalSpacing;
final TextDirection textDirection;
final TextSelection textSelection;
final Color color;
final bool enableInteractiveSelection;
final bool hasFocus;
final double devicePixelRatio;
final CursorCont cursorCont;
final InlineCodeStyle inlineCodeStyle;
@override
RenderObjectElement createElement() {
return _TextLineElement(this);
}
@override
RenderObject createRenderObject(BuildContext context) {
return RenderEditableTextLine(
line,
textDirection,
textSelection,
enableInteractiveSelection,
hasFocus,
devicePixelRatio,
_getPadding(),
color,
cursorCont,
inlineCodeStyle);
}
@override
void updateRenderObject(
BuildContext context, covariant RenderEditableTextLine renderObject) {
renderObject
..setLine(line)
..setPadding(_getPadding())
..setTextDirection(textDirection)
..setTextSelection(textSelection)
..setColor(color)
..setEnableInteractiveSelection(enableInteractiveSelection)
..hasFocus = hasFocus
..setDevicePixelRatio(devicePixelRatio)
..setCursorCont(cursorCont)
..setInlineCodeStyle(inlineCodeStyle);
}
EdgeInsetsGeometry _getPadding() {
return EdgeInsetsDirectional.only(
start: horizontalSpacing.left,
end: horizontalSpacing.right,
top: verticalSpacing.top,
bottom: verticalSpacing.bottom);
}
}
enum TextLineSlot { leading, body }
class RenderEditableTextLine extends RenderEditableBox {
/// Creates new editable paragraph render box.
RenderEditableTextLine(
this.line,
this.textDirection,
this.textSelection,
this.enableInteractiveSelection,
this.hasFocus,
this.devicePixelRatio,
this.padding,
this.color,
this.cursorCont,
this.inlineCodeStyle,
);
RenderBox? _leading;
RenderContentProxyBox? _body;
Line line;
TextDirection textDirection;
TextSelection textSelection;
Color color;
bool enableInteractiveSelection;
bool hasFocus = false;
double devicePixelRatio;
EdgeInsetsGeometry padding;
CursorCont cursorCont;
EdgeInsets? _resolvedPadding;
bool? _containsCursor;
List<TextBox>? _selectedRects;
late Rect _caretPrototype;
InlineCodeStyle inlineCodeStyle;
final Map<TextLineSlot, RenderBox> children = <TextLineSlot, RenderBox>{};
Iterable<RenderBox> get _children sync* {
if (_leading != null) {
yield _leading!;
}
if (_body != null) {
yield _body!;
}
}
void setCursorCont(CursorCont c) {
if (cursorCont == c) {
return;
}
cursorCont = c;
markNeedsLayout();
}
void setDevicePixelRatio(double d) {
if (devicePixelRatio == d) {
return;
}
devicePixelRatio = d;
markNeedsLayout();
}
void setEnableInteractiveSelection(bool val) {
if (enableInteractiveSelection == val) {
return;
}
markNeedsLayout();
markNeedsSemanticsUpdate();
}
void setColor(Color c) {
if (color == c) {
return;
}
color = c;
if (containsTextSelection()) {
safeMarkNeedsPaint();
}
}
void setTextSelection(TextSelection t) {
if (textSelection == t) {
return;
}
final containsSelection = containsTextSelection();
if (_attachedToCursorController) {
cursorCont.removeListener(markNeedsLayout);
cursorCont.color.removeListener(safeMarkNeedsPaint);
_attachedToCursorController = false;
}
textSelection = t;
_selectedRects = null;
_containsCursor = null;
if (attached && containsCursor()) {
cursorCont.addListener(markNeedsLayout);
cursorCont.color.addListener(safeMarkNeedsPaint);
_attachedToCursorController = true;
}
if (containsSelection || containsTextSelection()) {
safeMarkNeedsPaint();
}
}
void setTextDirection(TextDirection t) {
if (textDirection == t) {
return;
}
textDirection = t;
_resolvedPadding = null;
markNeedsLayout();
}
void setLine(Line l) {
if (line == l) {
return;
}
line = l;
_containsCursor = null;
markNeedsLayout();
}
void setPadding(EdgeInsetsGeometry p) {
assert(p.isNonNegative);
if (padding == p) {
return;
}
padding = p;
_resolvedPadding = null;
markNeedsLayout();
}
void setLeading(RenderBox? l) {
_leading = _updateChild(_leading, l, TextLineSlot.leading);
}
void setBody(RenderContentProxyBox? b) {
_body = _updateChild(_body, b, TextLineSlot.body) as RenderContentProxyBox?;
}
void setInlineCodeStyle(InlineCodeStyle newStyle) {
if (inlineCodeStyle == newStyle) return;
inlineCodeStyle = newStyle;
markNeedsLayout();
}
// Start selection implementation
bool containsTextSelection() {
return line.documentOffset <= textSelection.end &&
textSelection.start <= line.documentOffset + line.length - 1;
}
bool containsCursor() {
return _containsCursor ??= cursorCont.isFloatingCursorActive
? line
.containsOffset(cursorCont.floatingCursorTextPosition.value!.offset)
: textSelection.isCollapsed &&
line.containsOffset(textSelection.baseOffset);
}
RenderBox? _updateChild(
RenderBox? old,
RenderBox? newChild,
TextLineSlot slot,
) {
if (old != null) {
dropChild(old);
children.remove(slot);
}
if (newChild != null) {
children[slot] = newChild;
adoptChild(newChild);
}
return newChild;
}
List<TextBox> _getBoxes(TextSelection textSelection) {
final parentData = _body!.parentData as BoxParentData?;
return _body!.getBoxesForSelection(textSelection).map((box) {
return TextBox.fromLTRBD(
box.left + parentData!.offset.dx,
box.top + parentData.offset.dy,
box.right + parentData.offset.dx,
box.bottom + parentData.offset.dy,
box.direction,
);
}).toList(growable: false);
}
void _resolvePadding() {
if (_resolvedPadding != null) {
return;
}
_resolvedPadding = padding.resolve(textDirection);
assert(_resolvedPadding!.isNonNegative);
}
@override
TextSelectionPoint getBaseEndpointForSelection(TextSelection textSelection) {
return _getEndpointForSelection(textSelection, true);
}
@override
TextSelectionPoint getExtentEndpointForSelection(
TextSelection textSelection) {
return _getEndpointForSelection(textSelection, false);
}
TextSelectionPoint _getEndpointForSelection(
TextSelection textSelection, bool first) {
if (textSelection.isCollapsed) {
return TextSelectionPoint(
Offset(0, preferredLineHeight(textSelection.extent)) +
getOffsetForCaret(textSelection.extent),
null);
}
final boxes = _getBoxes(textSelection);
assert(boxes.isNotEmpty);
final targetBox = first ? boxes.first : boxes.last;
return TextSelectionPoint(
Offset(first ? targetBox.start : targetBox.end, targetBox.bottom),
targetBox.direction,
);
}
@override
TextRange getLineBoundary(TextPosition position) {
final lineDy = getOffsetForCaret(position)
.translate(0, 0.5 * preferredLineHeight(position))
.dy;
final lineBoxes =
_getBoxes(TextSelection(baseOffset: 0, extentOffset: line.length - 1))
.where((element) => element.top < lineDy && element.bottom > lineDy)