-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathcode_field.dart
More file actions
674 lines (590 loc) · 19.3 KB
/
code_field.dart
File metadata and controls
674 lines (590 loc) · 19.3 KB
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
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:linked_scroll_controller/linked_scroll_controller.dart';
import '../code_theme/code_theme.dart';
import '../gutter/gutter.dart';
import '../line_numbers/gutter_style.dart';
import '../search/widget/search_widget.dart';
import '../sizes.dart';
import '../wip/autocomplete/popup.dart';
import 'actions/comment_uncomment.dart';
import 'actions/enter_key.dart';
import 'actions/indent.dart';
import 'actions/outdent.dart';
import 'actions/search.dart';
import 'actions/tab.dart';
import 'code_controller.dart';
import 'default_styles.dart';
import 'js_workarounds/js_workarounds.dart';
final _shortcuts = <ShortcutActivator, Intent>{
// Copy
LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyC,
): CopySelectionTextIntent.copy,
const SingleActivator(
LogicalKeyboardKey.keyC,
meta: true,
): CopySelectionTextIntent.copy,
LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.insert,
): CopySelectionTextIntent.copy,
// Cut
LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyX,
): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard),
const SingleActivator(
LogicalKeyboardKey.keyX,
meta: true,
): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard),
LogicalKeySet(
LogicalKeyboardKey.shift,
LogicalKeyboardKey.delete,
): const CopySelectionTextIntent.cut(SelectionChangedCause.keyboard),
// Undo
LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyZ,
): const UndoTextIntent(SelectionChangedCause.keyboard),
const SingleActivator(
LogicalKeyboardKey.keyZ,
meta: true,
): const UndoTextIntent(SelectionChangedCause.keyboard),
// Redo
LogicalKeySet(
LogicalKeyboardKey.shift,
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyZ,
): const RedoTextIntent(SelectionChangedCause.keyboard),
LogicalKeySet(
LogicalKeyboardKey.shift,
LogicalKeyboardKey.meta,
LogicalKeyboardKey.keyZ,
): const RedoTextIntent(SelectionChangedCause.keyboard),
// Indent
LogicalKeySet(
LogicalKeyboardKey.tab,
): const IndentIntent(),
// Outdent
LogicalKeySet(
LogicalKeyboardKey.shift,
LogicalKeyboardKey.tab,
): const OutdentIntent(),
// Comment Uncomment
LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.slash,
): const CommentUncommentIntent(),
const SingleActivator(
LogicalKeyboardKey.slash,
meta: true,
): const CommentUncommentIntent(),
// Search
LogicalKeySet(
LogicalKeyboardKey.control,
LogicalKeyboardKey.keyF,
): const SearchIntent(),
const SingleActivator(
LogicalKeyboardKey.keyF,
meta: true,
): const SearchIntent(),
// Dismiss
LogicalKeySet(
LogicalKeyboardKey.escape,
): const DismissIntent(),
// EnterKey
LogicalKeySet(
LogicalKeyboardKey.enter,
): const EnterKeyIntent(),
// TabKey
LogicalKeySet(
LogicalKeyboardKey.tab,
): const TabKeyIntent(),
};
class CodeField extends StatefulWidget {
/// {@macro flutter.widgets.textField.minLines}
final int? minLines;
/// {@macro flutter.widgets.textField.maxLInes}
final int? maxLines;
/// {@macro flutter.widgets.textField.expands}
final bool expands;
/// Whether overflowing lines should wrap around
/// or make the field scrollable horizontally.
final bool wrap;
/// A CodeController instance to apply
/// language highlight, themeing and modifiers.
final CodeController controller;
/// An UndoHistoryController instance
/// to control TextField history.
final UndoHistoryController? undoController;
@Deprecated('Use gutterStyle instead')
final GutterStyle lineNumberStyle;
/// {@macro flutter.widgets.textField.cursorColor}
final Color? cursorColor;
/// {@macro flutter.widgets.textField.textStyle}
final TextStyle? textStyle;
/// {@macro flutter.widgets.textField.smartDashesType}
final SmartDashesType smartDashesType;
/// {@macro flutter.widgets.textField.smartQuotesType}
final SmartQuotesType smartQuotesType;
/// A way to replace specific line numbers by a custom TextSpan
final TextSpan Function(int, TextStyle?)? lineNumberBuilder;
/// {@macro flutter.widgets.textField.enabled}
final bool? enabled;
/// {@macro flutter.widgets.editableText.onChanged}
final void Function(String)? onChanged;
/// {@macro flutter.widgets.editableText.readOnly}
///
/// This is just passed as a parameter to a [TextField].
/// See also [CodeController.readOnly].
final bool readOnly;
final Color? background;
final EdgeInsets padding;
final Decoration? decoration;
final TextDirection textDirection;
final TextSelectionThemeData? textSelectionTheme;
final FocusNode? focusNode;
@Deprecated('Use gutterStyle instead')
final bool? lineNumbers;
final GutterStyle gutterStyle;
const CodeField({
super.key,
required this.controller,
this.undoController,
this.minLines,
this.maxLines,
this.expands = false,
this.wrap = false,
this.background,
this.decoration,
this.textStyle,
this.smartDashesType = SmartDashesType.disabled,
this.smartQuotesType = SmartQuotesType.disabled,
this.padding = EdgeInsets.zero,
GutterStyle? gutterStyle,
this.textDirection = TextDirection.ltr,
this.enabled,
this.readOnly = false,
this.cursorColor,
this.textSelectionTheme,
this.lineNumberBuilder,
this.focusNode,
this.onChanged,
@Deprecated('Use gutterStyle instead') this.lineNumbers,
@Deprecated('Use gutterStyle instead')
this.lineNumberStyle = const GutterStyle(),
}) : assert(
gutterStyle == null || lineNumbers == null,
'Can not provide gutterStyle and lineNumbers at the same time. '
'Please use gutterStyle and provide necessary columns to show/hide'),
gutterStyle = gutterStyle ??
((lineNumbers == false) ? GutterStyle.none : lineNumberStyle);
@override
State<CodeField> createState() => _CodeFieldState();
}
class _CodeFieldState extends State<CodeField> {
// Add a controller
LinkedScrollControllerGroup? _controllers;
ScrollController? _numberScroll;
ScrollController? _codeScroll;
ScrollController? _horizontalCodeScroll;
final _codeFieldKey = GlobalKey();
OverlayEntry? _suggestionsPopup;
OverlayEntry? _searchPopup;
Offset _normalPopupOffset = Offset.zero;
Offset _flippedPopupOffset = Offset.zero;
double painterWidth = 0;
double painterHeight = 0;
FocusNode? _focusNode;
String? lines;
String longestLine = '';
Size? windowSize;
late TextStyle textStyle;
Color? _backgroundCol;
final _editorKey = GlobalKey();
Offset? _editorOffset;
@override
void initState() {
super.initState();
_controllers = LinkedScrollControllerGroup();
_numberScroll = _controllers?.addAndGet();
_codeScroll = _controllers?.addAndGet();
widget.controller.addListener(_onTextChanged);
widget.controller.addListener(_updatePopupOffset);
widget.controller.popupController.addListener(_onPopupStateChanged);
widget.controller.searchController.addListener(
_onSearchControllerChange,
);
_horizontalCodeScroll = ScrollController();
_focusNode = widget.focusNode ?? FocusNode();
_focusNode!.attach(context, onKeyEvent: _onKeyEvent);
widget.controller.searchController.codeFieldFocusNode = _focusNode;
// Workaround for disabling spellchecks in FireFox
// https://github.com/akvelon/flutter-code-editor/issues/197
disableSpellCheckIfWeb();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) {
return;
}
final double width = _codeFieldKey.currentContext!.size!.width;
final double height = _codeFieldKey.currentContext!.size!.height;
windowSize = Size(width, height);
});
_onTextChanged();
}
KeyEventResult _onKeyEvent(FocusNode node, KeyEvent event) {
return widget.controller.onKey(event);
}
@override
void dispose() {
widget.controller.searchController.codeFieldFocusNode = null;
widget.controller.removeListener(_onTextChanged);
widget.controller.removeListener(_updatePopupOffset);
widget.controller.popupController.removeListener(_onPopupStateChanged);
_suggestionsPopup?.remove();
widget.controller.searchController.removeListener(
_onSearchControllerChange,
);
_searchPopup?.remove();
_searchPopup = null;
_numberScroll?.dispose();
_codeScroll?.dispose();
_horizontalCodeScroll?.dispose();
super.dispose();
}
@override
void didUpdateWidget(covariant CodeField oldWidget) {
super.didUpdateWidget(oldWidget);
oldWidget.controller.removeListener(_onTextChanged);
oldWidget.controller.removeListener(_updatePopupOffset);
oldWidget.controller.popupController.removeListener(_onPopupStateChanged);
oldWidget.controller.searchController.removeListener(
_onSearchControllerChange,
);
widget.controller.searchController.codeFieldFocusNode = _focusNode;
widget.controller.addListener(_onTextChanged);
widget.controller.addListener(_updatePopupOffset);
widget.controller.popupController.addListener(_onPopupStateChanged);
widget.controller.searchController.addListener(
_onSearchControllerChange,
);
}
void rebuild() {
setState(() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) {
return;
}
// For some reason _codeFieldKey.currentContext is null in tests
// so check first.
final context = _codeFieldKey.currentContext;
if (context != null) {
final double width = context.size!.width;
final double height = context.size!.height;
windowSize = Size(width, height);
}
});
});
}
void _onTextChanged() {
// Rebuild line number
final str = widget.controller.text.split('\n');
final buf = <String>[];
for (var k = 0; k < str.length; k++) {
buf.add((k + 1).toString());
}
// Find longest line
longestLine = '';
widget.controller.text.split('\n').forEach((line) {
if (line.length > longestLine.length) longestLine = line;
});
if (_codeScroll != null && _editorKey.currentContext != null) {
final box = _editorKey.currentContext!.findRenderObject() as RenderBox?;
_editorOffset = box?.localToGlobal(Offset.zero);
if (_editorOffset != null) {
var fixedOffset = _editorOffset!;
fixedOffset += Offset(0, _codeScroll!.offset);
_editorOffset = fixedOffset;
}
}
rebuild();
}
// Wrap the codeField in a horizontal scrollView
Widget _wrapInScrollView(
Widget codeField,
TextStyle textStyle,
double minWidth,
) {
final intrinsic = IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ConstrainedBox(
constraints: BoxConstraints(
maxHeight: 0,
minWidth: minWidth,
),
child: Padding(
padding: const EdgeInsets.only(right: 16),
child: Text(longestLine, style: textStyle),
), // Add extra padding
),
widget.expands ? Expanded(child: codeField) : codeField,
],
),
);
return SingleChildScrollView(
padding: EdgeInsets.only(
right: widget.padding.right,
),
scrollDirection: Axis.horizontal,
controller: _horizontalCodeScroll,
child: intrinsic,
);
}
@override
Widget build(BuildContext context) {
// Default color scheme
const rootKey = 'root';
final themeData = Theme.of(context);
final styles = CodeTheme.of(context)?.styles;
_backgroundCol = widget.background ??
styles?[rootKey]?.backgroundColor ??
DefaultStyles.backgroundColor;
if (widget.decoration != null) {
_backgroundCol = null;
}
final defaultTextStyle = TextStyle(
color: styles?[rootKey]?.color ?? DefaultStyles.textColor,
fontSize: themeData.textTheme.titleMedium?.fontSize,
height: themeData.textTheme.titleMedium?.height,
);
textStyle = defaultTextStyle.merge(widget.textStyle);
final codeField = TextField(
focusNode: _focusNode,
scrollPadding: widget.padding,
style: textStyle,
smartDashesType: widget.smartDashesType,
smartQuotesType: widget.smartQuotesType,
controller: widget.controller,
undoController: widget.undoController,
minLines: widget.minLines,
maxLines: widget.maxLines,
expands: widget.expands,
scrollController: _codeScroll,
textDirection: widget.textDirection,
decoration: const InputDecoration(
isCollapsed: true,
contentPadding: EdgeInsets.symmetric(vertical: 16),
disabledBorder: InputBorder.none,
border: InputBorder.none,
focusedBorder: InputBorder.none,
),
cursorColor: widget.cursorColor ?? defaultTextStyle.color,
autocorrect: false,
enableSuggestions: false,
enabled: widget.enabled,
onChanged: widget.onChanged,
readOnly: widget.readOnly,
);
final editingField = Theme(
data: Theme.of(context).copyWith(
textSelectionTheme: widget.textSelectionTheme,
),
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
// Control horizontal scrolling
return _wrapInScrollView(codeField, textStyle, constraints.maxWidth);
},
),
);
return FocusableActionDetector(
actions: widget.controller.actions,
shortcuts: _shortcuts,
child: Directionality(
textDirection: widget.textDirection,
child: Container(
decoration: widget.decoration,
color: _backgroundCol,
key: _codeFieldKey,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.gutterStyle.showGutter) _buildGutter(),
Expanded(key: _editorKey, child: editingField),
],
),
),
),
);
}
Widget _buildGutter() {
final lineNumberSize = textStyle.fontSize;
final lineNumberColor =
widget.gutterStyle.textStyle?.color ?? textStyle.color?.withOpacity(.5);
final lineNumberTextStyle =
(widget.gutterStyle.textStyle ?? textStyle).copyWith(
color: lineNumberColor,
fontFamily: textStyle.fontFamily,
fontSize: lineNumberSize,
);
final gutterStyle = widget.gutterStyle.copyWith(
textStyle: lineNumberTextStyle,
errorPopupTextStyle: widget.gutterStyle.errorPopupTextStyle ??
CodeTheme.of(context)?.styles['root'] ??
textStyle.copyWith(
fontSize: DefaultStyles.errorPopupTextSize,
backgroundColor: DefaultStyles.backgroundColor,
fontStyle: DefaultStyles.fontStyle,
),
);
return GutterWidget(
codeController: widget.controller,
style: gutterStyle,
scrollController: _numberScroll,
);
}
void _updatePopupOffset() {
final textPainter = _getTextPainter(widget.controller.text);
final caretHeight = _getCaretHeight(textPainter);
final leftOffset = _getPopupLeftOffset(textPainter);
final normalTopOffset = _getPopupTopOffset(textPainter, caretHeight);
final flippedTopOffset = normalTopOffset -
(Sizes.autocompletePopupMaxHeight + caretHeight + Sizes.caretPadding);
setState(() {
_normalPopupOffset = Offset(leftOffset, normalTopOffset);
_flippedPopupOffset = Offset(leftOffset, flippedTopOffset);
});
}
TextPainter _getTextPainter(String text) {
return TextPainter(
textDirection: TextDirection.ltr,
text: TextSpan(text: text, style: textStyle),
)..layout();
}
Offset _getCaretOffset(TextPainter textPainter) {
return textPainter.getOffsetForCaret(
widget.controller.selection.base,
Rect.zero,
);
}
double _getCaretHeight(TextPainter textPainter) {
final double? caretFullHeight = textPainter.getFullHeightForCaret(
widget.controller.selection.base,
Rect.zero,
);
return caretFullHeight ?? 0;
}
double _getPopupLeftOffset(TextPainter textPainter) {
return max(
_getCaretOffset(textPainter).dx +
widget.padding.left -
_horizontalCodeScroll!.offset +
(_editorOffset?.dx ?? 0),
0,
);
}
double _getPopupTopOffset(TextPainter textPainter, double caretHeight) {
return max(
_getCaretOffset(textPainter).dy +
caretHeight +
16 +
widget.padding.top -
_codeScroll!.offset +
(_editorOffset?.dy ?? 0),
0,
);
}
void _onPopupStateChanged() {
final shouldShow =
widget.controller.popupController.shouldShow && windowSize != null;
if (!shouldShow) {
_suggestionsPopup?.remove();
_suggestionsPopup = null;
return;
}
if (_suggestionsPopup == null) {
_suggestionsPopup = _buildSuggestionOverlay();
Overlay.of(context).insert(_suggestionsPopup!);
}
_suggestionsPopup!.markNeedsBuild();
}
void _onSearchControllerChange() {
final shouldShow = widget.controller.searchController.shouldShow;
if (!shouldShow) {
_searchPopup?.remove();
_searchPopup = null;
return;
}
if (_searchPopup == null) {
_searchPopup = _buildSearchOverlay();
Overlay.of(context).insert(_searchPopup!);
}
}
OverlayEntry _buildSearchOverlay() {
final colorScheme = Theme.of(context).colorScheme;
final borderColor = _getTextColorFromTheme() ?? colorScheme.onBackground;
return OverlayEntry(
builder: (context) {
return Positioned(
bottom: 10,
right: 10,
child: Container(
clipBehavior: Clip.antiAlias,
decoration: BoxDecoration(
border: Border.all(
color: borderColor,
),
borderRadius: const BorderRadius.all(
Radius.circular(5),
),
),
child: Material(
child: SearchWidget(
searchController: widget.controller.searchController,
),
),
),
);
},
);
}
Color? _getTextColorFromTheme() {
final textTheme = Theme.of(context).textTheme;
return textTheme.bodyLarge?.color ??
textTheme.bodyMedium?.color ??
textTheme.bodySmall?.color ??
textTheme.displayLarge?.color ??
textTheme.displayMedium?.color ??
textTheme.displaySmall?.color ??
textTheme.headlineLarge?.color ??
textTheme.headlineMedium?.color ??
textTheme.headlineSmall?.color ??
textTheme.labelLarge?.color ??
textTheme.labelMedium?.color ??
textTheme.labelSmall?.color ??
textTheme.titleLarge?.color ??
textTheme.titleMedium?.color ??
textTheme.titleSmall?.color;
}
OverlayEntry _buildSuggestionOverlay() {
return OverlayEntry(
builder: (context) {
return Popup(
normalOffset: _normalPopupOffset,
flippedOffset: _flippedPopupOffset,
controller: widget.controller.popupController,
editingWindowSize: windowSize!,
style: textStyle,
backgroundColor: _backgroundCol,
parentFocusNode: _focusNode!,
editorOffset: _editorOffset,
);
},
);
}
}