forked from akvelon/flutter-code-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_field.dart
More file actions
463 lines (403 loc) · 13.1 KB
/
Copy pathcode_field.dart
File metadata and controls
463 lines (403 loc) · 13.1 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
import 'dart:async';
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/line_number_style.dart';
import '../sizes.dart';
import '../wip/autocomplete/popup.dart';
import 'actions/comment_uncomment.dart';
import 'actions/indent.dart';
import 'actions/outdent.dart';
import 'code_controller.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(),
};
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;
/// A LineNumberStyle instance to tweak the line number column styling
final LineNumberStyle lineNumberStyle;
/// {@macro flutter.widgets.textField.cursorColor}
final Color? cursorColor;
/// {@macro flutter.widgets.textField.textStyle}
final TextStyle? textStyle;
/// 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}
final bool readOnly;
final Color? background;
final EdgeInsets padding;
final Decoration? decoration;
final TextSelectionThemeData? textSelectionTheme;
final FocusNode? focusNode;
final bool lineNumbers;
const CodeField({
super.key,
required this.controller,
this.minLines,
this.maxLines,
this.expands = false,
this.wrap = false,
this.background,
this.decoration,
this.textStyle,
this.padding = EdgeInsets.zero,
this.lineNumberStyle = const LineNumberStyle(),
this.enabled,
this.readOnly = false,
this.cursorColor,
this.textSelectionTheme,
this.lineNumberBuilder,
this.focusNode,
this.onChanged,
this.lineNumbers = true,
});
@override
State<CodeField> createState() => _CodeFieldState();
}
class _CodeFieldState extends State<CodeField> {
// Add a controller
LinkedScrollControllerGroup? _controllers;
ScrollController? _numberScroll;
ScrollController? _codeScroll;
ScrollController? _horizontalCodeScroll;
final _codeFieldKey = GlobalKey();
Offset _normalPopupOffset = Offset.zero;
Offset _flippedPopupOffset = Offset.zero;
double painterWidth = 0;
double painterHeight = 0;
StreamSubscription<bool>? _keyboardVisibilitySubscription;
FocusNode? _focusNode;
String? lines;
String longestLine = '';
late Size windowSize;
late TextStyle textStyle;
@override
void initState() {
super.initState();
_controllers = LinkedScrollControllerGroup();
_numberScroll = _controllers?.addAndGet();
_codeScroll = _controllers?.addAndGet();
widget.controller.addListener(_onTextChanged);
widget.controller.addListener(_updatePopupOffset);
_horizontalCodeScroll = ScrollController();
_focusNode = widget.focusNode ?? FocusNode();
_focusNode!.attach(context, onKeyEvent: _onKeyEvent);
WidgetsBinding.instance.addPostFrameCallback((_) {
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.removeListener(_onTextChanged);
widget.controller.removeListener(_updatePopupOffset);
_numberScroll?.dispose();
_codeScroll?.dispose();
_horizontalCodeScroll?.dispose();
unawaited(_keyboardVisibilitySubscription?.cancel());
super.dispose();
}
void rebuild() {
setState(() {
WidgetsBinding.instance.addPostFrameCallback((_) {
// 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;
});
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
),
// ignore: prefer_if_elements_to_conditional_expressions
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 defaultBg = Colors.grey.shade900;
final defaultText = Colors.grey.shade200;
final themeData = Theme.of(context);
final styles = CodeTheme.of(context)?.styles;
Color? backgroundCol =
widget.background ?? styles?[rootKey]?.backgroundColor ?? defaultBg;
if (widget.decoration != null) {
backgroundCol = null;
}
final defaultTextStyle = TextStyle(
color: styles?[rootKey]?.color ?? defaultText,
fontSize: themeData.textTheme.subtitle1?.fontSize,
);
textStyle = defaultTextStyle.merge(widget.textStyle);
final lineNumberSize = textStyle.fontSize;
final lineNumberColor = widget.lineNumberStyle.textStyle?.color ??
textStyle.color?.withOpacity(.5);
final lineNumberTextStyle =
(widget.lineNumberStyle.textStyle ?? textStyle).copyWith(
color: lineNumberColor,
fontFamily: textStyle.fontFamily,
fontSize: lineNumberSize,
);
final lineNumberStyle = widget.lineNumberStyle.copyWith(
textStyle: lineNumberTextStyle,
);
Widget? numberCol;
if (widget.lineNumbers) {
numberCol = GutterWidget(
codeController: widget.controller,
style: lineNumberStyle,
);
}
final codeField = TextField(
focusNode: _focusNode,
scrollPadding: widget.padding,
style: textStyle,
controller: widget.controller,
minLines: widget.minLines,
maxLines: widget.maxLines,
expands: widget.expands,
scrollController: _codeScroll,
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: Container(
decoration: widget.decoration,
color: backgroundCol,
key: _codeFieldKey,
padding: !widget.lineNumbers ? const EdgeInsets.only(left: 8) : null,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (widget.lineNumbers && numberCol != null) numberCol,
Expanded(
child: Stack(
children: [
editingField,
if (widget.controller.popupController.isPopupShown)
Popup(
normalOffset: _normalPopupOffset,
flippedOffset: _flippedPopupOffset,
controller: widget.controller.popupController,
editingWindowSize: windowSize,
style: textStyle,
backgroundColor: backgroundCol,
parentFocusNode: _focusNode!,
),
],
),
),
],
),
),
);
}
void _updatePopupOffset() {
final TextPainter textPainter = _getTextPainter(widget.controller.text);
final caretHeight = _getCaretHeight(textPainter);
final double leftOffset = _getPopupLeftOffset(textPainter);
final double normalTopOffset = _getPopupTopOffset(textPainter, caretHeight);
final double 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 (widget.controller.selection.base.offset > 0) ? caretFullHeight! : 0;
}
double _getPopupLeftOffset(TextPainter textPainter) {
return max(
_getCaretOffset(textPainter).dx +
widget.padding.left -
_horizontalCodeScroll!.offset,
0,
);
}
double _getPopupTopOffset(TextPainter textPainter, double caretHeight) {
return max(
_getCaretOffset(textPainter).dy +
caretHeight +
16 +
widget.padding.top -
_codeScroll!.offset,
0,
);
}
}