This commit is contained in:
LZX committed 2026-09-17 16:32:27 +08:00
1 parent 5ac164b407
commit f93f6095af
94 files changed
+7877 -4018

No files matched your search

@@ -136,6 +136,14 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> {
ValueChanged<CodeAutocompleteResult>? _onAutocomplete;
OverlayEntry? _overlayEntry;
ValueNotifier<CodeAutocompleteEditingValue>? _notifier;
Offset? _position;
double? _lineHeight;
LayerLink? _layerLink;
final GlobalKey _menuKey = GlobalKey();
Offset? _pointerDownPosition;
DateTime? _pointerDownTime;
bool _isPointerSliding = false;
@override
void initState() {
@@ -180,6 +188,68 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> {
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
dismiss();
super.dispose();
}
void _handleEditorPointerDown(PointerDownEvent event) {
if (_overlayEntry == null) return;
_pointerDownPosition = event.position;
_pointerDownTime = DateTime.now();
_isPointerSliding = false;
}
void _handleEditorPointerMove(PointerMoveEvent event) {
if (_overlayEntry == null || _pointerDownPosition == null) return;
if ((event.position - _pointerDownPosition!).distance > kTouchSlop) {
_isPointerSliding = true;
}
}
void _handleEditorPointerUp(PointerUpEvent event) {
if (_overlayEntry == null || _pointerDownPosition == null) {
_pointerDownPosition = null;
_isPointerSliding = false;
return;
}
// 用户在编辑区滑动(例如上下或左右滚动代码),坚决不关闭菜单
if (_isPointerSliding) {
_pointerDownPosition = null;
_isPointerSliding = false;
return;
}
final duration = DateTime.now().difference(_pointerDownTime ?? DateTime.now());
_pointerDownPosition = null;
_isPointerSliding = false;
// 轻触点击判定:时长小于 500ms 且无位移
if (duration.inMilliseconds > 500) {
return;
}
// 检查点击位置是否在补全菜单内
final RenderBox? menuBox = _menuKey.currentContext?.findRenderObject() as RenderBox?;
if (menuBox != null && menuBox.hasSize) {
final localPos = menuBox.globalToLocal(event.position);
if (menuBox.paintBounds.contains(localPos)) {
// 点击在菜单内部,由菜单自身交互逻辑处理,不关闭
return;
}
}
// 只有在菜单区域外的编辑区执行了点击(Tap),才关闭菜单
dismiss();
}
void _handleEditorPointerCancel(PointerCancelEvent event) {
_pointerDownPosition = null;
_isPointerSliding = false;
}
@override
Widget build(BuildContext context) {
return Actions(
@@ -187,10 +257,19 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> {
CodeShortcutCursorMoveIntent: _navigateAction,
CodeShortcutNewLineIntent: _selectAction,
},
child: widget.child
child: Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: _handleEditorPointerDown,
onPointerMove: _handleEditorPointerMove,
onPointerUp: _handleEditorPointerUp,
onPointerCancel: _handleEditorPointerCancel,
child: widget.child,
),
);
}
int _showVersion = 0;
void show({
required LayerLink layerLink,
required Offset position,
@@ -198,28 +277,84 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> {
required CodeLineEditingValue value,
required ValueChanged<CodeAutocompleteResult> onAutocomplete,
}) {
dismiss();
final CodeAutocompleteEditingValue? autocompleteEditingValue = widget.promptsBuilder.build(
final int version = ++_showVersion;
final dynamic result = widget.promptsBuilder.build(
context,
value.codeLines[value.selection.extentIndex],
value.selection,
);
if (autocompleteEditingValue == null) {
if (result is Future) {
result.then((resolved) {
if (!mounted || version != _showVersion) return;
if (resolved is CodeAutocompleteEditingValue) {
_displayPrompts(
layerLink: layerLink,
position: position,
lineHeight: lineHeight,
editingValue: resolved,
onAutocomplete: onAutocomplete,
);
} else {
dismiss();
}
});
return;
}
_notifier = ValueNotifier(autocompleteEditingValue);
if (result is CodeAutocompleteEditingValue) {
_displayPrompts(
layerLink: layerLink,
position: position,
lineHeight: lineHeight,
editingValue: result,
onAutocomplete: onAutocomplete,
);
} else {
dismiss();
}
}
void _displayPrompts({
required LayerLink layerLink,
required Offset position,
required double lineHeight,
required CodeAutocompleteEditingValue editingValue,
required ValueChanged<CodeAutocompleteResult> onAutocomplete,
}) {
_position = position;
_lineHeight = lineHeight;
_layerLink = layerLink;
_onAutocomplete = onAutocomplete;
if (_overlayEntry != null && _notifier != null) {
// 已经处于展开状态,原地更新候选列表并重绘 OverlayEntry 计算自适应高度
_notifier!.value = editingValue;
_overlayEntry!.markNeedsBuild();
return;
}
dismiss();
_position = position;
_lineHeight = lineHeight;
_layerLink = layerLink;
_notifier = ValueNotifier(editingValue);
_onAutocomplete = onAutocomplete;
_overlayEntry = OverlayEntry(
builder:(context) {
return _buildWidget(context, layerLink, position, lineHeight);
builder: (context) {
return _buildWidget(context);
},
);
Overlay.of(context, rootOverlay: true).insert(_overlayEntry!);
final overlay = Overlay.maybeOf(context, rootOverlay: false) ?? Overlay.of(context, rootOverlay: true);
overlay.insert(_overlayEntry!);
_navigateAction.setEnabled(true);
_selectAction.setEnabled(true);
}
void dismiss() {
_position = null;
_lineHeight = null;
_layerLink = null;
_notifier = null;
_onAutocomplete = null;
_overlayEntry?.remove();
@@ -228,39 +363,64 @@ class _CodeAutocompleteState extends State<_CodeAutocomplete> {
_selectAction.setEnabled(false);
}
Widget _buildWidget(BuildContext context, LayerLink layerLink, Offset position, double lineHeight) {
Widget _buildWidget(BuildContext context) {
if (_position == null || _layerLink == null || _notifier == null) {
return const SizedBox.shrink();
}
final PreferredSizeWidget child = widget.viewBuilder(context, _notifier!, (result) {
_onAutocomplete?.call(result);
});
final Size screenSize = MediaQuery.of(context).size;
final double offsetX;
if (position.dx + child.preferredSize.width > screenSize.width) {
offsetX = screenSize.width - (position.dx + child.preferredSize.width);
} else {
offsetX = 0;
final mediaQuery = MediaQuery.of(context);
final Size screenSize = mediaQuery.size;
final position = _position!;
// 水平方向:允许菜单水平自然超出编辑区
const double offsetX = 0.0;
// 计算小键盘及局部 Overlay 的底部边界
final overlay = Overlay.maybeOf(context, rootOverlay: false) ?? Overlay.of(context, rootOverlay: true);
final RenderBox? overlayBox = overlay.context.findRenderObject() as RenderBox?;
double overlayBottomY = screenSize.height;
if (overlayBox != null && overlayBox.hasSize) {
final overlayTopLeft = overlayBox.localToGlobal(Offset.zero);
overlayBottomY = overlayTopLeft.dy + overlayBox.size.height;
}
final double offsetY;
if (position.dy + child.preferredSize.height > screenSize.height) {
offsetY = -child.preferredSize.height - lineHeight;
final double systemKeyboardTop = screenSize.height - mediaQuery.viewInsets.bottom;
final double effectiveBottom = min(overlayBottomY, systemKeyboardTop);
// 计算光标所在行下方的可用高度,并预留 4.0 像素防顶边距
const double safetyMargin = 4.0;
final double availableHeight = effectiveBottom - position.dy - safetyMargin;
// 显示位置坚决锁定在当前行下方,绝不在光标上方翻转显示
const double offsetY = 0.0;
// 高度自适应:如果顶到了小键盘,那么高度变小,剩余项在内部滑动
final double desiredHeight = child.preferredSize.height;
const double minSensibleHeight = 44.0;
final double finalHeight;
if (availableHeight < desiredHeight) {
finalHeight = max(minSensibleHeight, availableHeight);
} else {
offsetY = 0;
finalHeight = desiredHeight;
}
return CompositedTransformFollower(
link: layerLink,
link: _layerLink!,
showWhenUnlinked: false,
offset: Offset(offsetX, offsetY),
child: Align(
alignment: Alignment.topLeft,
child: Material(
color: Colors.transparent,
child: TapRegion(
onTapOutside: (event) {
dismiss();
},
child: CodeEditorTapRegion(
child: ExcludeSemantics(
child: CodeEditorTapRegion(
child: ExcludeSemantics(
child: SizedBox(
key: _menuKey,
width: child.preferredSize.width,
height: finalHeight,
child: child,
)
),
)
),
)
+26 -5
View File
@@ -401,10 +401,17 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli
return;
}
widget.onChanged?.call(widget.controller.value);
final isTextChanged = widget.controller.codeLines != widget.controller.preValue?.codeLines;
if (widget.controller.codeLines != widget.controller.preValue?.codeLines &&
widget.controller.preValue != null) {
widget.selectionOverlayController.hideHandle();
widget.selectionOverlayController.hideToolbar();
}
if (isTextChanged) {
// 文本发生变更(包括输入字符与退格删除字符),触发补全提示列表自适应重算与刷新
Future.delayed(const Duration(milliseconds: 50), () {
_updateAutoCompleteState(true);
});
} else {
_updateAutoCompleteState(false);
}
@@ -473,7 +480,11 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli
return;
}
if (!isCodeLineChanged) {
autocompleteState.dismiss();
if (!widget.controller.selection.isCollapsed ||
(widget.controller.preValue != null &&
widget.controller.selection.extentIndex != widget.controller.preValue!.selection.extentIndex)) {
autocompleteState.dismiss();
}
return;
}
if (widget.controller.isComposing || !widget.controller.selection.isCollapsed) {
@@ -514,6 +525,7 @@ class _CodeEditableState extends State<_CodeEditable> with AutomaticKeepAliveCli
class _CodeCursorBlinkController extends ValueNotifier<bool> {
Timer? _timer;
bool _isDisposed = false;
_CodeCursorBlinkController() : super(false);
@@ -525,10 +537,14 @@ class _CodeCursorBlinkController extends ValueNotifier<bool> {
if (kIsAndroid || kIsIOS) {
// Wait selection position to update
Future.delayed(const Duration(milliseconds: 100), () {
value = true;
if (!_isDisposed) {
value = true;
}
});
} else {
value = true;
if (!_isDisposed) {
value = true;
}
}
}
@@ -538,15 +554,20 @@ class _CodeCursorBlinkController extends ValueNotifier<bool> {
}
_timer?.cancel();
_timer = null;
value = false;
if (!_isDisposed) {
value = false;
}
}
void _cursorTick(Timer timer) {
value = !value;
if (!_isDisposed) {
value = !value;
}
}
@override
void dispose() {
_isDisposed = true;
stopBlink();
super.dispose();
}
+1 -5
View File
@@ -1484,12 +1484,8 @@ class _CodeFieldRender extends RenderBox implements MouseTrackerAnnotation {
}
void _drawHandleLayer(PaintingContext context, LayerLink layer, Offset position, Offset offset) {
final Offset point = Offset(
clampDouble(position.dx, 0.0, size.width),
clampDouble(position.dy, 0.0, size.height),
);
context.pushLayer(
LeaderLayer(link: layer, offset: point + offset),
LeaderLayer(link: layer, offset: position + offset),
super.paint,
Offset.zero,
);
@@ -9,7 +9,8 @@ class CodeLineNumberRenderObject extends RenderBox {
int _minNumberCount;
int _allLineCount;
final String Function(int lineIndex)? _customLineIndex2Text;
String Function(int lineIndex)? _customLineIndex2Text;
Decoration? Function(int lineIndex)? _lineDecorationBuilder;
final TextPainter _textPainter;
CodeLineNumberRenderObject({
@@ -19,6 +20,7 @@ class CodeLineNumberRenderObject extends RenderBox {
required TextStyle focusedTextStyle,
required int minNumberCount,
String Function(int lineIndex)? custonLineIndex2Text,
Decoration? Function(int lineIndex)? lineDecorationBuilder,
}) : _controller = controller,
_notifier = notifier,
_textStyle = textStyle,
@@ -26,6 +28,7 @@ class CodeLineNumberRenderObject extends RenderBox {
_minNumberCount = minNumberCount,
_allLineCount = controller.lineCount,
_customLineIndex2Text = custonLineIndex2Text,
_lineDecorationBuilder = lineDecorationBuilder,
_textPainter = TextPainter(
textDirection: TextDirection.ltr,
);
@@ -82,6 +85,22 @@ class CodeLineNumberRenderObject extends RenderBox {
markNeedsLayout();
}
set customLineIndex2Text(String Function(int lineIndex)? value) {
if (_customLineIndex2Text == value) {
return;
}
_customLineIndex2Text = value;
markNeedsPaint();
}
set lineDecorationBuilder(Decoration? Function(int lineIndex)? value) {
if (_lineDecorationBuilder == value) {
return;
}
_lineDecorationBuilder = value;
markNeedsPaint();
}
@override
bool hitTestSelf(Offset position) => true;
@@ -136,6 +155,19 @@ class CodeLineNumberRenderObject extends RenderBox {
int firstLineIndex = _controller.index2lineIndex(value.paragraphs.first.index);
for (final CodeLineRenderParagraph paragraph in value.paragraphs) {
final lineIndexText = _customLineIndex2Text?.call(firstLineIndex) ?? (firstLineIndex + 1).toString();
final decoration = _lineDecorationBuilder?.call(firstLineIndex);
if (decoration != null) {
final painter = decoration.createBoxPainter(markNeedsPaint);
final lineRect = Rect.fromLTWH(
offset.dx,
offset.dy + paragraph.offset.dy,
size.width,
paragraph.preferredLineHeight,
);
painter.paint(canvas, lineRect.topLeft, ImageConfiguration(size: lineRect.size));
}
_textPainter.text = TextSpan(
text: lineIndexText,
style: paragraph.index == value.focusedIndex ? _focusedTextStyle : _textStyle
+8 -4
View File
@@ -30,20 +30,24 @@ class _CodeLineEditingControllerImpl extends ValueNotifier<CodeLineEditingValue>
}
factory _CodeLineEditingControllerImpl.fromText(String? text, [
CodeLineOptions options = const CodeLineOptions()
CodeLineOptions options = const CodeLineOptions(),
CodeLineSpanBuilder? spanBuilder,
]) {
return _CodeLineEditingControllerImpl(
codeLines: text?.codeLines ?? _kInitialCodeLines,
options: options
options: options,
spanBuilder: spanBuilder,
);
}
factory _CodeLineEditingControllerImpl.fromTextAsync(String? text, [
CodeLineOptions options = const CodeLineOptions()
CodeLineOptions options = const CodeLineOptions(),
CodeLineSpanBuilder? spanBuilder,
]) {
final _CodeLineEditingControllerImpl controller = _CodeLineEditingControllerImpl(
codeLines: _kInitialCodeLines,
options: options
options: options,
spanBuilder: spanBuilder,
);
if (text != null && text.isNotEmpty) {
text.codeLinesAsync.then((value) => controller.codeLines = value);
@@ -229,7 +229,7 @@ typedef CodeAutocompleteWidgetBuilder = PreferredSizeWidget Function(
abstract class CodeAutocompletePromptsBuilder {
/// Build the prompts with the current code.
CodeAutocompleteEditingValue? build(
FutureOr<CodeAutocompleteEditingValue?> build(
BuildContext context,
CodeLine codeLine,
CodeLineSelection selection,
@@ -53,6 +53,7 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget {
final TextStyle? focusedTextStyle;
final int? minNumberCount;
final String Function(int lineIndex)? customLineIndex2Text;
final Decoration? Function(int lineIndex)? lineDecorationBuilder;
const DefaultCodeLineNumber({
super.key,
@@ -62,6 +63,7 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget {
this.focusedTextStyle,
this.minNumberCount,
this.customLineIndex2Text,
this.lineDecorationBuilder,
});
@override
@@ -72,6 +74,7 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget {
focusedTextStyle: focusedTextStyle ?? _useCodeTextStyle(context, true),
minNumberCount: minNumberCount ?? _kDefaultMinNumberCount,
custonLineIndex2Text: customLineIndex2Text,
lineDecorationBuilder: lineDecorationBuilder,
);
@override
@@ -81,7 +84,9 @@ class DefaultCodeLineNumber extends LeafRenderObjectWidget {
..notifier = notifier
..textStyle = textStyle ?? _useCodeTextStyle(context, false)
..focusedTextStyle = focusedTextStyle ?? _useCodeTextStyle(context, true)
..minNumberCount = minNumberCount ?? _kDefaultMinNumberCount;
..minNumberCount = minNumberCount ?? _kDefaultMinNumberCount
..customLineIndex2Text = customLineIndex2Text
..lineDecorationBuilder = lineDecorationBuilder;
super.updateRenderObject(context, renderObject);
}
+6 -4
View File
@@ -61,13 +61,15 @@ abstract class CodeLineEditingController extends ValueNotifier<CodeLineEditingVa
/// Creates a controller for a given text.
factory CodeLineEditingController.fromText(String? text, [
CodeLineOptions options = const CodeLineOptions()
]) => _CodeLineEditingControllerImpl.fromText(text, options);
CodeLineOptions options = const CodeLineOptions(),
CodeLineSpanBuilder? spanBuilder,
]) => _CodeLineEditingControllerImpl.fromText(text, options, spanBuilder);
/// Creates a controller for a given file path. The file content will read async.
factory CodeLineEditingController.fromTextAsync(String? text, [
CodeLineOptions options = const CodeLineOptions()
]) => _CodeLineEditingControllerImpl.fromTextAsync(text, options);
CodeLineOptions options = const CodeLineOptions(),
CodeLineSpanBuilder? spanBuilder,
]) => _CodeLineEditingControllerImpl.fromTextAsync(text, options, spanBuilder);
/// Set the current editor codes.
///