diff --git a/README.md b/README.md index ccc3f4a..2702d53 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Offline-first notes where every line is also a live calculator. Write freely; any line that looks like arithmetic is worked out as you type and its result -appears in a gutter beside it. +appears at the end of the line. ``` Lisbon trip budget @@ -388,10 +388,10 @@ mirrored-div stack a browser forces on you. Results are aligned by laying the note out a second time with the same width, style and strut the field uses, and reading each line's offset from it. The -gutter and the field share one `ScrollController`. That combination is what +results and the field share one `ScrollController`. That combination is what keeps a result pinned to its line through wrapping, scrolling and text scaling — and it is asserted directly in `test/note_editor_test.dart`, which compares -chip positions against the field's own `RenderEditable` geometry. +result positions against the field's own `RenderEditable` geometry. Clicking a result copies it at full precision. @@ -542,8 +542,8 @@ The spec described an Electron build. These changed for Flutter: most recently edited note when no launch text was entered. A launch draft becomes a new note, unless the app was opened from a widget, which carries it into the note being written instead. Search and the full note - list are built only when the hamburger drawer first opens; the gutter is - fixed-width and the divider is hidden. + list are built only when the hamburger drawer first opens; results keep + a fixed-width column beside the text. - **The widgets (iOS / Android)** — two of them, offering three actions: **Write**, **Dictate** and **Capture**. The square widget is one cell and one action, chosen when it is placed and changed afterwards — iOS through *Edit diff --git a/lib/calc/engine.dart b/lib/calc/engine.dart index 371857f..f72968d 100644 --- a/lib/calc/engine.dart +++ b/lib/calc/engine.dart @@ -20,6 +20,11 @@ class LineResult { final DigitGrouping grouping; + /// Whether the line reads the note's running total, `total` or `sum`, or + /// converts it, as `total in eur` does: the figure a list of amounts + /// builds up to. + final bool isTotal; + /// Number-system-aware words and scale context, prepared only if a visible /// chip needs them. Long notes should not spell every off-screen result on /// each keystroke. @@ -34,6 +39,7 @@ class LineResult { required this.text, required this.copyText, this.grouping = DigitGrouping.international, + this.isTotal = false, }); ResultKind get kind => value.kind; @@ -149,6 +155,16 @@ class CalcEngine { _ => false, }; + /// The readouts of the running total itself, as against `prev` or `avg`. + static bool _isTotalReadout(Node node, Map variables) => + switch (node) { + IdentifierNode() => + !variables.containsKey(node.name) && + const {'sum', 'total'}.contains(node.name.toLowerCase()), + ConvertNode() => _isTotalReadout(node.value, variables), + _ => false, + }; + _EvaluatedLine? _evaluateLine( String rawLine, int index, @@ -365,6 +381,7 @@ class CalcEngine { text: ResultFormatter.display(value, grouping: grouping), copyText: ResultFormatter.copy(value), grouping: grouping, + isTotal: _isTotalReadout(node, scope.variables), ), isAggregateReadout: _isAggregateReadout(node, scope.variables), ); diff --git a/lib/core/theme.dart b/lib/core/theme.dart index fe85f38..c356a25 100644 --- a/lib/core/theme.dart +++ b/lib/core/theme.dart @@ -832,18 +832,13 @@ class AppTypeScale { ? 13.5 : 12.5; - /// The result chip in the gutter. + /// A calculation's result: its pill at the end of the line, or a figure in + /// a phone's results column. /// - /// Its own step rather than [body], because it is monospace figures inside a - /// fixed column: the width the note gives up to it is a layout decision, so - /// the type has to be chosen against that column rather than against the - /// prose elsewhere. Touch gains what the column can actually seat without - /// pushing the writing area below half the screen. - static double get result => _touch - ? 14 - : _windows - ? 13 - : 12.5; + /// Its own step rather than [body], because it is monospace figures set + /// against the writing rather than prose. Touch gains what a phone's column + /// can actually seat without pushing the writing area below half the screen. + static double get result => _touch ? 14 : 13; /// Control labels: buttons, list rows, fields, menu items. static double get control => _touch diff --git a/lib/data/layout_prefs.dart b/lib/data/layout_prefs.dart index bf72f4a..6d5a4f1 100644 --- a/lib/data/layout_prefs.dart +++ b/lib/data/layout_prefs.dart @@ -87,16 +87,13 @@ class LayoutPrefs extends ChangeNotifier { /// and wide enough for the page's toolbar beside the rail. static const Size minimumWindowSize = Size(520, 520); - static const double minGutterWidth = 72; - static const double maxGutterWidth = 480; - static const double defaultGutterWidth = 190; - static const double minSidebarWidth = 150; static const double maxSidebarWidth = 420; static const double defaultSidebarWidth = 336; - static const String _gutterKey = 'gutter.v1'; - static const String _resultsVisibleKey = 'resultsVisible.v1'; + /// v1 recorded the old results column folded away to make room. Results + /// now take no width, so they start out shown again. + static const String _resultsVisibleKey = 'resultsVisible.v2'; static const String _sidebarKey = 'sidebar.v1'; static const String _hiddenFolderVisibleKey = 'hiddenFolderVisible.v1'; static const String _noteCardsKey = 'noteCards.v1'; @@ -140,7 +137,6 @@ class LayoutPrefs extends ChangeNotifier { /// locale", which is what this did before it could ask. String? _region; - double _gutterWidth = defaultGutterWidth; bool _resultsVisible = true; double _sidebarWidth = defaultSidebarWidth; bool _sidebarVisible = false; @@ -182,7 +178,6 @@ class LayoutPrefs extends ChangeNotifier { }) : _locale = locale ?? (() => PlatformDispatcher.instance.locale), _readRegion = region ?? SystemRegion.read; - double get gutterWidth => _gutterWidth; bool get resultsVisible => _resultsVisible; double get sidebarWidth => _sidebarWidth; bool get sidebarVisible => _sidebarVisible; @@ -331,7 +326,6 @@ class LayoutPrefs extends ChangeNotifier { ResultFormatter.sample(system.resolve(_locale(), region: _region)); void load() { - _gutterWidth = _clampGutter(_readDouble(_gutterKey) ?? defaultGutterWidth); _resultsVisible = _store.read(_resultsVisibleKey) ?? true; _sidebarWidth = _clampSidebar( _readDouble(_sidebarKey) ?? defaultSidebarWidth, @@ -399,14 +393,6 @@ class LayoutPrefs extends ChangeNotifier { notifyListeners(); } - set gutterWidth(double value) { - final clamped = _clampGutter(value); - if (clamped == _gutterWidth) return; - _gutterWidth = clamped; - _store.putNow(_gutterKey, clamped); - notifyListeners(); - } - set resultsVisible(bool value) { if (value == _resultsVisible) return; _resultsVisible = value; @@ -735,22 +721,9 @@ class LayoutPrefs extends ChangeNotifier { return null; } - void resetGutterWidth() => gutterWidth = defaultGutterWidth; - - void resetPanelWidths() { - if (_gutterWidth == defaultGutterWidth && - _sidebarWidth == defaultSidebarWidth && - _resultsVisible) { - return; - } - _gutterWidth = defaultGutterWidth; - _sidebarWidth = defaultSidebarWidth; - _resultsVisible = true; - _store.putNow(_gutterKey, _gutterWidth); - _store.putNow(_sidebarKey, _sidebarWidth); - _store.putNow(_resultsVisibleKey, _resultsVisible); - notifyListeners(); - } + /// The notes list is the one panel left with a width of its own: results + /// sit at the ends of their lines. + void resetPanelWidths() => sidebarWidth = defaultSidebarWidth; /// Records that the login-item default has had its one chance, whether or /// not the OS accepted it. A machine whose policy forbids login items would @@ -766,9 +739,7 @@ class LayoutPrefs extends ChangeNotifier { void toggleAlwaysOnTop() => alwaysOnTop = !_alwaysOnTop; - /// The right-hand column's counterpart to [toggleSidebar]. The divider's - /// own handle already collapses and restores it; this is the same door for - /// anyone whose hands are on the keyboard. + /// Hides the results at the ends of calculating lines, or brings them back. void toggleResults() => resultsVisible = !_resultsVisible; set hiddenFolderVisible(bool value) { @@ -877,10 +848,6 @@ class LayoutPrefs extends ChangeNotifier { return clean.isEmpty ? null : clean; } - static double _clampGutter(double value) => value.isFinite - ? value.clamp(minGutterWidth, maxGutterWidth) - : defaultGutterWidth; - static double _clampSidebar(double value) => value.isFinite ? value.clamp(minSidebarWidth, maxSidebarWidth) : defaultSidebarWidth; diff --git a/lib/data/shortcut_prefs.dart b/lib/data/shortcut_prefs.dart index 9a4dbe6..a20cf43 100644 --- a/lib/data/shortcut_prefs.dart +++ b/lib/data/shortcut_prefs.dart @@ -49,7 +49,7 @@ extension ShortcutActionCopy on ShortcutAction { ShortcutAction.focusThirdPane => 'Focus pane 3', ShortcutAction.toggleSidebar => 'Toggle notes list', ShortcutAction.toggleHiddenFolder => 'Toggle Hidden Notes folder', - ShortcutAction.toggleResults => 'Toggle results column', + ShortcutAction.toggleResults => 'Toggle results', ShortcutAction.toggleAlwaysOnTop => 'Keep window on top', ShortcutAction.deleteNote => 'Archive current note', ShortcutAction.openSettings => 'Open settings', @@ -85,7 +85,7 @@ extension ShortcutActionCopy on ShortcutAction { ShortcutAction.toggleHiddenFolder => 'Reveal or hide Hidden Notes in the notes list', ShortcutAction.toggleResults => - 'Show or hide the results column on the right', + 'Show or hide the results at the ends of calculating lines', ShortcutAction.toggleAlwaysOnTop => 'Float the window over other apps, or let it fall behind again', ShortcutAction.deleteNote => diff --git a/lib/ui/editor/inline_results.dart b/lib/ui/editor/inline_results.dart new file mode 100644 index 0000000..fb150ff --- /dev/null +++ b/lib/ui/editor/inline_results.dart @@ -0,0 +1,171 @@ +import 'dart:math' as math; + +import 'package:material_ui/material_ui.dart'; + +import '../../calc/engine.dart'; +import '../../core/theme.dart'; +import 'line_metrics.dart'; +import 'results_gutter.dart'; +import 'scroll_passthrough.dart'; + +/// Each result at the right-hand end of its own line: a pill on the line's +/// last visual row, with a faint leader running to it from where the writing +/// stops. +/// +/// Laid over the text field rather than inside it, and placed from the same +/// measurement of the note the field's own layout produces, so nothing here +/// is ever part of the note's text: the caret, the selection, copy and paste +/// and undo never meet it. Only the pills take the pointer. Everything around +/// them, the leaders included, reaches the field underneath. +class InlineResults extends StatelessWidget { + const InlineResults({ + super.key, + required this.results, + required this.offsets, + required this.scroll, + required this.padding, + required this.columnWidth, + }); + + final Map results; + + /// Must have been measured with every line in [results] in its + /// `lastRowsOf`. + final LineOffsets offsets; + + /// The field's own, so the pills move with the text. + final ScrollController scroll; + + /// Where the field's text starts inside this layer, and the bands above and + /// below it that the text scrolls under. + final EdgeInsets padding; + + /// How wide the text wraps. A pill's right edge sits on it. + final double columnWidth; + + /// Between the end of the writing and the leader, and between the leader + /// and the pill. + static const double gap = 12; + + @override + Widget build(BuildContext context) { + final leader = context.palette.textTertiary.withValues(alpha: 0.3); + return Padding( + padding: EdgeInsets.only(top: padding.top, bottom: padding.bottom), + // Top and bottom only: a pill scrolls under the padding as the text + // does, but may run on into the margin beside the column. + child: ClipRect( + clipper: const VerticalClipper(), + child: LayoutBuilder( + builder: (context, constraints) => ListenableBuilder( + listenable: scroll, + builder: (context, _) { + final scrolled = scroll.hasClients ? scroll.offset : 0.0; + return Stack( + clipBehavior: Clip.none, + children: [ + for (final MapEntry(key: line, value: result) + in results.entries) + if (offsets.lastRows[line] case final row?) + // Only what can be seen; a long note stays cheap. + if (row.bottom - scrolled >= 0 && + row.top - scrolled <= constraints.maxHeight) + Positioned( + key: ValueKey(line), + left: 0, + right: 0, + top: row.top - scrolled, + height: row.height, + child: CustomMultiChildLayout( + delegate: _ResultLineLayout( + textEnd: padding.left + row.right, + columnRight: padding.left + columnWidth, + ), + children: [ + LayoutId( + id: _Part.leader, + child: IgnorePointer( + child: CustomPaint( + key: ValueKey('result-leader-$line'), + painter: _LeaderPainter(leader), + ), + ), + ), + LayoutId( + id: _Part.pill, + child: ScrollPassthrough( + controller: scroll, + child: ResultChip( + result: result, + collapsedWidth: columnWidth / 2, + look: ResultChipLook.pill, + ), + ), + ), + ], + ), + ), + ], + ); + }, + ), + ), + ), + ); + } +} + +enum _Part { leader, pill } + +/// Puts a line's pill at the right-hand end of the column and runs the +/// leader up to it. +/// +/// The writing always wins the row. When it already reaches past where the +/// pill would go, the pill follows the writing instead, out into the margin +/// as far as the page allows, and only once there is no margin left does it +/// cover the end of the line. +class _ResultLineLayout extends MultiChildLayoutDelegate { + _ResultLineLayout({required this.textEnd, required this.columnRight}); + + final double textEnd; + final double columnRight; + + @override + void performLayout(Size size) { + final pill = layoutChild(_Part.pill, BoxConstraints(maxWidth: size.width)); + final start = textEnd + InlineResults.gap; + var left = columnRight - pill.width; + if (left < start) left = math.min(start, size.width - pill.width); + left = math.max(0.0, left); + positionChild(_Part.pill, Offset(left, (size.height - pill.height) / 2)); + + final length = math.max(0.0, left - InlineResults.gap - start); + layoutChild(_Part.leader, BoxConstraints.tight(Size(length, size.height))); + positionChild(_Part.leader, Offset(start, 0)); + } + + @override + bool shouldRelayout(_ResultLineLayout oldDelegate) => + oldDelegate.textEnd != textEnd || oldDelegate.columnRight != columnRight; +} + +/// A dotted rule across the middle of the row: square dots a dot apart. +class _LeaderPainter extends CustomPainter { + const _LeaderPainter(this.color); + + final Color color; + + static const double _dot = 1; + + @override + void paint(Canvas canvas, Size size) { + final paint = Paint()..color = color; + final top = (size.height - _dot) / 2; + for (var x = 0.0; x + _dot <= size.width; x += _dot * 2) { + canvas.drawRect(Rect.fromLTWH(x, top, _dot, _dot), paint); + } + } + + @override + bool shouldRepaint(_LeaderPainter oldDelegate) => oldDelegate.color != color; +} diff --git a/lib/ui/editor/line_metrics.dart b/lib/ui/editor/line_metrics.dart index b50b873..5c37375 100644 --- a/lib/ui/editor/line_metrics.dart +++ b/lib/ui/editor/line_metrics.dart @@ -1,3 +1,7 @@ +import 'dart:math' as math; +import 'dart:ui' show BoxHeightStyle; + +import 'package:flutter/foundation.dart' show listEquals; import 'package:material_ui/material_ui.dart'; /// Where each logical line of the note sits vertically inside the text field. @@ -10,10 +14,17 @@ class LineOffsets { final double totalHeight; + /// The last visual row of each line [LineMeasurer.measure] was asked + /// about, in text-local coordinates: from the row's top to its bottom, and + /// from where its writing starts to where it stops. A line that wraps ends + /// on its last row, which is where its result goes. + final Map lastRows; + const LineOffsets({ required this.tops, required this.lineHeight, required this.totalHeight, + this.lastRows = const {}, }); static const LineOffsets empty = LineOffsets( @@ -35,6 +46,7 @@ class LineMeasurer { TextScaler? _scaler; Object? _layoutKey; int? _placeholderKey; + List? _lastRowLines; LineOffsets? _cached; /// [span] must be the very span the field renders — styled runs can differ @@ -44,6 +56,9 @@ class LineMeasurer { /// [TextPainter] refuses to lay out a span containing placeholders it has /// not been given dimensions for, and an image is a placeholder — so a note /// with pictures measures wrong, or not at all, without this. + /// + /// [lastRowsOf] names the lines whose last visual row is wanted as well, in + /// [LineOffsets.lastRows]. Only those lines pay for it. LineOffsets measure({ required InlineSpan span, required String text, @@ -52,16 +67,19 @@ class LineMeasurer { required TextScaler textScaler, required Object layoutKey, List placeholders = const [], + Iterable lastRowsOf = const [], }) { final placeholderKey = Object.hashAll([ for (final placeholder in placeholders) Object.hash(placeholder.size.width, placeholder.size.height), ]); + final lastRowLines = List.unmodifiable(lastRowsOf); if (_text == text && _width == maxWidth && _scaler == textScaler && _layoutKey == layoutKey && _placeholderKey == placeholderKey && + listEquals(_lastRowLines, lastRowLines) && _cached != null) { return _cached!; } @@ -77,18 +95,31 @@ class LineMeasurer { painter.layout(maxWidth: maxWidth); final tops = []; + final starts = []; var offset = 0; for (final line in text.split('\n')) { + starts.add(offset); tops.add( painter.getOffsetForCaret(TextPosition(offset: offset), Rect.zero).dy, ); offset += line.length + 1; } + final lastRows = {}; + for (final index in lastRowLines) { + if (index < 0 || index >= starts.length) continue; + final start = starts[index]; + final end = index + 1 < starts.length + ? starts[index + 1] - 1 + : text.length; + lastRows[index] = _lastRow(painter, start, end, tops[index]); + } + final result = LineOffsets( tops: tops, lineHeight: painter.preferredLineHeight, totalHeight: painter.height, + lastRows: lastRows, ); painter.dispose(); @@ -97,7 +128,28 @@ class LineMeasurer { _scaler = textScaler; _layoutKey = layoutKey; _placeholderKey = placeholderKey; + _lastRowLines = lastRowLines; _cached = result; return result; } + + /// The last row the text from [start] to [end] is drawn on: that row's full + /// height, and as wide as the writing on it. + static Rect _lastRow(TextPainter painter, int start, int end, double top) { + final empty = Rect.fromLTWH(0, top, 0, painter.preferredLineHeight); + if (end <= start) return empty; + final boxes = painter.getBoxesForSelection( + TextSelection(baseOffset: start, extentOffset: end), + boxHeightStyle: BoxHeightStyle.max, + ); + if (boxes.isEmpty) return empty; + final rowTop = boxes.map((box) => box.top).reduce(math.max); + final row = boxes.where((box) => (box.top - rowTop).abs() < 0.5); + return Rect.fromLTRB( + row.map((box) => box.left).reduce(math.min), + rowTop, + row.map((box) => box.right).reduce(math.max), + row.map((box) => box.bottom).reduce(math.max), + ); + } } diff --git a/lib/ui/editor/note_editor.dart b/lib/ui/editor/note_editor.dart index 396fe30..8e1d976 100644 --- a/lib/ui/editor/note_editor.dart +++ b/lib/ui/editor/note_editor.dart @@ -74,6 +74,7 @@ import 'voice_insertion.dart'; import 'note_image_view.dart'; import 'note_video_view.dart'; import 'remote_carets.dart'; +import 'inline_results.dart'; import 'results_gutter.dart'; import 'scroll_passthrough.dart'; import 'selection_formatting_toolbar.dart'; @@ -112,8 +113,8 @@ typedef ImagePrepared = typedef AttachmentUploadProgressFor = ValueListenable Function(String hash); -/// The note surface: one syntax-coloured text field with a live results -/// column pinned to it. +/// The note surface: one syntax-coloured text field with each line's live +/// result at the end of that line, or on a phone in a column beside it. /// /// The two are kept in step by measuring the note's layout with the same /// width, style and strut the field uses, and by sharing one scroll @@ -156,13 +157,10 @@ class NoteEditor extends StatefulWidget { this.onReadOnlyPressed, required this.engine, required this.highlighter, - required this.gutterWidth, + this.gutterWidth, required this.resultsVisible, required this.onDocumentChanged, this.storedDocument, - required this.onGutterWidthChanged, - required this.onResultsVisibilityChanged, - required this.onGutterWidthReset, required this.onSettingsPressed, required this.writingFont, this.editorTextScale = 1, @@ -170,8 +168,6 @@ class NoteEditor extends StatefulWidget { this.spellCheckEnabled = true, this.markdownEnabled = false, this.onMarkdownEnabledChanged, - this.showDivider = true, - this.hideEmptyResults = false, this.autofocus = false, this.startAtEnd = false, this.initialCaret, @@ -296,7 +292,10 @@ class NoteEditor extends StatefulWidget { final CalcEngine engine; final Highlighter highlighter; - final double gutterWidth; + + /// How wide a phone's results gutter is. Null puts each result at the end + /// of its own line instead, which takes no width from the writing. + final double? gutterWidth; final bool resultsVisible; final NoteDocumentChanged onDocumentChanged; @@ -306,9 +305,6 @@ class NoteEditor extends StatefulWidget { /// never written over words the editor has not shown yet. Null reads this /// widget's own fields. final StoredNoteDocument? Function()? storedDocument; - final ValueChanged onGutterWidthChanged; - final ValueChanged onResultsVisibilityChanged; - final VoidCallback onGutterWidthReset; /// What the open-settings shortcut does. The footer has no gear of its own: /// settings live in the notes list, and this is the key that gets there @@ -331,8 +327,6 @@ class NoteEditor extends StatefulWidget { /// Optional for small editor harnesses; production supplies the persisted /// preference setter. final ValueChanged? onMarkdownEnabledChanged; - final bool showDivider; - final bool hideEmptyResults; final bool autofocus; final bool startAtEnd; @@ -4489,13 +4483,6 @@ class NoteEditorState extends State with WidgetsBindingObserver { _totalText = evaluation.totalText; } - void _dragGutter(double width) => widget.onGutterWidthChanged(width); - - void _restoreGutter(double? width) { - if (width != null) widget.onGutterWidthChanged(width); - widget.onResultsVisibilityChanged(true); - } - static DateTime _localTime(DateTime value) => value.toLocal(); /// Sizes and builds every image in this note, keyed by its anchor. @@ -5448,27 +5435,21 @@ class NoteEditorState extends State with WidgetsBindingObserver { Expanded( child: LayoutBuilder( builder: (context, constraints) { - // Compact and touch layouts reserve the results rail only when - // a line calculates, so prose, checklists, and journals keep - // the full writing width. Desktop preserves its saved panel. - final hasResults = _results.isNotEmpty; - final emptyResultsSuppressed = - !hasResults && - (!widget.showDivider || widget.hideEmptyResults); + // Results sit at the ends of their lines and take no width + // from the writing. A phone reserves its gutter only when a + // line calculates, so prose, checklists, and journals keep the + // full writing width. final resultsVisible = - !emptyResultsSuppressed && - (!widget.showDivider || widget.resultsVisible); - final dividerWidth = widget.showDivider && resultsVisible - ? GutterDivider.width - : 0.0; + widget.resultsVisible && _results.isNotEmpty; + final inlineResults = + resultsVisible && widget.gutterWidth == null; final gutterWidth = resultsVisible - ? widget.gutterWidth.clamp( + ? (widget.gutterWidth ?? 0).clamp( 0.0, (constraints.maxWidth - 160).clamp(0.0, 480.0), ) : 0.0; - final textPaneWidth = - constraints.maxWidth - gutterWidth - dividerWidth; + final textPaneWidth = constraints.maxWidth - gutterWidth; // Must match the text field's own content box exactly, right // down to the sliver it holds back for the caret. @@ -5580,6 +5561,7 @@ class NoteEditorState extends State with WidgetsBindingObserver { concealment.key, ), placeholders: _controller.placeholderDimensions(), + lastRowsOf: inlineResults ? _results.keys : const [], ); _lineOffsets = offsets; @@ -5672,15 +5654,7 @@ class NoteEditorState extends State with WidgetsBindingObserver { ), ), ), - if (widget.showDivider && resultsVisible) - GutterDivider( - gutterWidth: gutterWidth, - onDrag: _dragGutter, - onHide: () => - widget.onResultsVisibilityChanged(false), - onReset: widget.onGutterWidthReset, - ), - if (resultsVisible) + if (gutterWidth > 0) SizedBox( width: gutterWidth, // The gutter has no scrollable of its own, so a @@ -5705,14 +5679,15 @@ class NoteEditorState extends State with WidgetsBindingObserver { ], ), ), - if (widget.showDivider && - !resultsVisible && - !emptyResultsSuppressed) - Positioned( - top: 0, - right: 0, - bottom: 0, - child: ResultsRestoreHandle(onRestore: _restoreGutter), + if (inlineResults) + Positioned.fill( + child: InlineResults( + results: _results, + offsets: offsets, + scroll: _scrollController, + padding: padding, + columnWidth: contentWidth, + ), ), ], ); diff --git a/lib/ui/editor/results_gutter.dart b/lib/ui/editor/results_gutter.dart index 13ce9f5..adf8278 100644 --- a/lib/ui/editor/results_gutter.dart +++ b/lib/ui/editor/results_gutter.dart @@ -2,12 +2,13 @@ import 'package:material_ui/material_ui.dart'; import 'package:flutter/services.dart'; import '../../calc/engine.dart'; -import '../../calc/value.dart'; import '../../core/theme.dart'; import '../../core/toast.dart'; import 'line_metrics.dart'; -/// The right-hand column of live results, one chip per calculated line. +/// The fixed column of live results a phone keeps beside its text, one chip +/// per calculated line. Everywhere else results sit at the ends of their +/// lines; see `InlineResults`. class ResultsGutter extends StatelessWidget { const ResultsGutter({ super.key, @@ -73,7 +74,7 @@ class ResultsGutter extends StatelessWidget { // note scrolls, but leave the left edge open so an expanded chip can // reach across the text. child: ClipRect( - clipper: const _VerticalClipper(), + clipper: const VerticalClipper(), clipBehavior: Clip.hardEdge, child: Stack(clipBehavior: Clip.none, children: chips), ), @@ -82,8 +83,8 @@ class ResultsGutter extends StatelessWidget { } /// Clips top and bottom only. -class _VerticalClipper extends CustomClipper { - const _VerticalClipper(); +class VerticalClipper extends CustomClipper { + const VerticalClipper(); @override Rect getClip(Size size) => Rect.fromLTRB(-4000, 0, size.width, size.height); @@ -92,20 +93,32 @@ class _VerticalClipper extends CustomClipper { bool shouldReclip(covariant CustomClipper oldClipper) => false; } -/// One result. Truncates to fit the column, expands on hover to reveal the -/// full value, and copies full precision when clicked. +/// How a result is drawn. +enum ResultChipLook { + /// A quiet annotation in the phone's results column. + rail, + + /// A pill at the end of its line. A total's pill is the strongest. + pill, +} + +/// One result. Truncates to fit the room it is given, expands on hover to +/// reveal the full value, and copies full precision when clicked. class ResultChip extends StatefulWidget { const ResultChip({ super.key, required this.result, required this.collapsedWidth, + this.look = ResultChipLook.rail, }); final LineResult result; - /// Width of the results column. A chip is truncated to this until hovered. + /// The widest the chip is until hovered. final double collapsedWidth; + final ResultChipLook look; + @override State createState() => _ResultChipState(); } @@ -114,21 +127,6 @@ class _ResultChipState extends State { bool _hovering = false; bool _justCopied = false; - Color _colorFor(CalcPalette palette) { - switch (widget.result.kind) { - case ResultKind.currency: - return palette.chipCurrency; - case ResultKind.unit: - return palette.chipUnit; - case ResultKind.number: - return palette.chipNumber; - case ResultKind.boolean: - return palette.chipBoolean; - case ResultKind.other: - return palette.chipOther; - } - } - /// Copies the full-precision value, not the truncated chip text. Future _copy() async { final value = widget.result.copyText; @@ -154,17 +152,35 @@ class _ResultChipState extends State { @override Widget build(BuildContext context) { final palette = context.palette; - final color = _colorFor(palette); + final pill = widget.look == ResultChipLook.pill; + // The figure a list of amounts builds up to gets the strongest pill. + final total = pill && widget.result.isTotal; + final ink = total ? palette.totalPillText : palette.resultPillText; + final background = total + ? palette.totalPillBackground + : palette.resultPillBackground; + final Color fill; + if (pill) { + fill = KapyTheme.fillStates( + background, + ink: ink, + disabled: background, + ).resolve({if (_hovering) WidgetState.hovered}); + } else { + // Results read like quiet annotations on the page. The pill only + // appears under the pointer to make the copy target clear. + fill = _hovering ? background : Colors.transparent; + } final chip = AnimatedContainer( duration: const Duration(milliseconds: 130), curve: Curves.easeOutCubic, - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + padding: pill + ? const EdgeInsets.symmetric(horizontal: 10, vertical: 5) + : const EdgeInsets.symmetric(horizontal: 8, vertical: 3), decoration: BoxDecoration( - // Results read like quiet annotations on the page. A small wash only - // appears under the pointer to make the copy target clear. - color: _hovering ? color.withValues(alpha: 0.12) : Colors.transparent, - borderRadius: BorderRadius.circular(5), + color: fill, + borderRadius: BorderRadius.circular(pill ? 999 : 5), ), child: Row( mainAxisSize: MainAxisSize.min, @@ -173,7 +189,7 @@ class _ResultChipState extends State { KapyIcon( KapyIcons.checkRounded, size: AppControlMetrics.iconInline, - color: color, + color: ink, ), const SizedBox(width: 4), ], @@ -190,8 +206,14 @@ class _ResultChipState extends State { fontFamily: AppFonts.mono, fontFamilyFallback: AppFonts.monoFallback, fontSize: AppTypeScale.result, - height: 1.2, - color: color, + fontWeight: !pill + ? null + : total + ? FontWeight.w600 + : FontWeight.w500, + height: pill ? 16 / 13 : 1.2, + leadingDistribution: TextLeadingDistribution.even, + color: ink, fontFeatures: const [FontFeature.tabularFigures()], ), ), @@ -224,234 +246,3 @@ class _ResultChipState extends State { ); } } - -/// The draggable edge between the text and its results. -class GutterDivider extends StatefulWidget { - const GutterDivider({ - super.key, - required this.gutterWidth, - required this.onDrag, - required this.onHide, - required this.onReset, - }); - - final double gutterWidth; - final ValueChanged onDrag; - final VoidCallback onHide; - final VoidCallback onReset; - - /// A forgiving hit target around a deliberately thin visual divider. - static const double width = 15; - - @override - State createState() => _GutterDividerState(); -} - -class _GutterDividerState extends State { - bool _hovering = false; - bool _dragging = false; - double _dragStartX = 0; - double _dragStartWidth = 0; - - @override - Widget build(BuildContext context) { - final palette = context.palette; - final accent = Theme.of(context).colorScheme.primary; - final active = _hovering || _dragging; - - return Semantics( - button: true, - label: 'Resize results column', - hint: 'Drag left or right to resize. Click to hide. Double tap to reset.', - child: Tooltip( - message: 'Drag to resize. Click to hide.', - child: MouseRegion( - key: const ValueKey('results-divider-hover'), - cursor: SystemMouseCursors.resizeLeftRight, - onEnter: (_) => setState(() => _hovering = true), - onExit: (_) => setState(() => _hovering = false), - child: GestureDetector( - key: const ValueKey('results-divider'), - behavior: HitTestBehavior.opaque, - onHorizontalDragStart: (details) { - _dragStartX = details.globalPosition.dx; - _dragStartWidth = widget.gutterWidth; - setState(() => _dragging = true); - }, - onHorizontalDragUpdate: (details) => widget.onDrag( - _dragStartWidth - (details.globalPosition.dx - _dragStartX), - ), - onHorizontalDragEnd: (_) => setState(() => _dragging = false), - onHorizontalDragCancel: () => setState(() => _dragging = false), - onTap: widget.onHide, - onDoubleTap: widget.onReset, - child: AnimatedContainer( - duration: const Duration(milliseconds: 120), - width: GutterDivider.width, - color: Colors.transparent, - child: Stack( - alignment: Alignment.center, - children: [ - Center( - child: AnimatedContainer( - key: const ValueKey('results-divider-line'), - duration: const Duration(milliseconds: 120), - width: active ? 2 : 0.75, - height: double.infinity, - decoration: BoxDecoration( - color: active ? accent : palette.separator, - borderRadius: BorderRadius.circular(999), - ), - ), - ), - IgnorePointer( - child: AnimatedOpacity( - key: const ValueKey('results-divider-grip-opacity'), - duration: const Duration(milliseconds: 100), - opacity: active ? 1 : 0, - child: _EdgeGrip( - key: const ValueKey('results-divider-grip'), - icon: KapyIcons.dragRounded, - ), - ), - ), - ], - ), - ), - ), - ), - ), - ); - } -} - -/// The narrow recovery target left at the far right when results are hidden. -/// Clicking restores the saved width; dragging left restores to the distance -/// the pointer travelled. -class ResultsRestoreHandle extends StatefulWidget { - const ResultsRestoreHandle({super.key, required this.onRestore}); - - final ValueChanged onRestore; - - static const double width = 15; - - @override - State createState() => _ResultsRestoreHandleState(); -} - -class _ResultsRestoreHandleState extends State { - bool _hovering = false; - bool _dragging = false; - double _dragStartX = 0; - double _dragExtent = 0; - - void _finishDrag() { - final extent = _dragExtent; - setState(() { - _dragging = false; - _dragExtent = 0; - }); - if (extent > 0) widget.onRestore(extent); - } - - @override - Widget build(BuildContext context) { - final palette = context.palette; - final accent = Theme.of(context).colorScheme.primary; - final active = _hovering || _dragging; - - return Semantics( - button: true, - label: 'Show results column', - hint: 'Click to restore results or drag left to resize them.', - child: Tooltip( - message: 'Show results. Drag left to resize.', - child: MouseRegion( - key: const ValueKey('results-restore-hover'), - cursor: SystemMouseCursors.resizeLeftRight, - onEnter: (_) => setState(() => _hovering = true), - onExit: (_) => setState(() => _hovering = false), - child: GestureDetector( - key: const ValueKey('results-restore-handle'), - behavior: HitTestBehavior.opaque, - onTap: () => widget.onRestore(null), - onHorizontalDragStart: (details) { - _dragStartX = details.globalPosition.dx; - _dragExtent = 0; - setState(() => _dragging = true); - }, - onHorizontalDragUpdate: (details) { - final extent = _dragStartX - details.globalPosition.dx; - setState(() => _dragExtent = extent.clamp(0.0, 480.0)); - }, - onHorizontalDragEnd: (_) => _finishDrag(), - onHorizontalDragCancel: () => setState(() { - _dragging = false; - _dragExtent = 0; - }), - child: SizedBox( - width: ResultsRestoreHandle.width, - child: Stack( - alignment: Alignment.center, - children: [ - Align( - alignment: Alignment.centerRight, - child: AnimatedContainer( - key: const ValueKey('results-restore-line'), - duration: const Duration(milliseconds: 120), - width: active ? 2 : 0.75, - height: double.infinity, - decoration: BoxDecoration( - color: active ? accent : palette.separator, - borderRadius: BorderRadius.circular(999), - ), - ), - ), - IgnorePointer( - child: AnimatedOpacity( - key: const ValueKey('results-restore-grip-opacity'), - duration: const Duration(milliseconds: 100), - opacity: active ? 1 : 0, - child: const _EdgeGrip( - key: ValueKey('results-restore-grip'), - icon: KapyIcons.chevronLeftRounded, - ), - ), - ), - ], - ), - ), - ), - ), - ), - ); - } -} - -/// One compact handle shape for both resize and restore states. Keeping it -/// inside the divider's 15px hit target avoids the oversized hover pills used -/// by touch-first component defaults. -class _EdgeGrip extends StatelessWidget { - const _EdgeGrip({super.key, required this.icon}); - - final KapyIconData icon; - - @override - Widget build(BuildContext context) { - final palette = context.palette; - return Container( - width: 13, - height: 24, - decoration: BoxDecoration( - color: palette.controlBackground, - border: Border.all(color: palette.controlBorder, width: 0.5), - borderRadius: BorderRadius.circular(6.5), - ), - child: KapyIcon( - icon, - size: AppControlMetrics.iconInline, - color: palette.textSecondary, - ), - ); - } -} diff --git a/lib/ui/editor/scroll_passthrough.dart b/lib/ui/editor/scroll_passthrough.dart index f211461..90317b2 100644 --- a/lib/ui/editor/scroll_passthrough.dart +++ b/lib/ui/editor/scroll_passthrough.dart @@ -1,20 +1,23 @@ -import 'package:flutter/gestures.dart' show Drag; +import 'package:flutter/gestures.dart' + show Drag, GestureBinding, PointerScrollEvent, PointerSignalEvent; import 'package:material_ui/material_ui.dart'; -/// Makes a vertical drag anywhere inside it scroll somebody else's scrollable. +/// Makes a vertical drag or a scroll wheel anywhere inside it scroll somebody +/// else's scrollable. /// -/// The results gutter is a sibling of the text field rather than part of it: -/// its chips are positioned from the field's scroll offset instead of being -/// laid out inside the field's scroll view. That is what keeps a long note -/// cheap — only the chips that can be seen are built — but it also leaves the -/// gutter with no scrollable of its own, so a drag that began over it had -/// nothing to move. On a phone the gutter is a third of the width, which made -/// a third of the screen a place where scrolling quietly did nothing. +/// Results are siblings of the text field rather than part of it: they are +/// positioned from the field's scroll offset instead of being laid out inside +/// the field's scroll view. That is what keeps a long note cheap — only the +/// results that can be seen are built — but it also leaves them with no +/// scrollable of their own, so a drag that began over one had nothing to +/// move. On a phone the results column is a third of the width, which made a +/// third of the screen a place where scrolling quietly did nothing. /// /// Handing the drag to [ScrollPosition.drag], rather than nudging `offset` on /// each update, is what buys the real thing: momentum after the finger /// leaves, the platform's own overscroll, and a fling that stops where the -/// note does. It is the same call [Scrollable] makes for its own gestures. +/// note does. It is the same call [Scrollable] makes for its own gestures, +/// as [ScrollPosition.pointerScroll] is for a wheel. class ScrollPassthrough extends StatefulWidget { const ScrollPassthrough({ super.key, @@ -59,16 +62,29 @@ class _ScrollPassthroughState extends State { super.dispose(); } + void _wheel(PointerSignalEvent event) { + if (event is! PointerScrollEvent || !widget.controller.hasClients) return; + GestureBinding.instance.pointerSignalResolver.register(event, (event) { + if (!widget.controller.hasClients) return; + widget.controller.position.pointerScroll( + (event as PointerScrollEvent).scrollDelta.dy, + ); + }); + } + @override - Widget build(BuildContext context) => GestureDetector( - // Opaque so a drag starting on the gutter's empty background counts, not - // only one that starts on a chip. Children still hit-test first, so a tap - // on a chip is still the chip's. - behavior: HitTestBehavior.opaque, - onVerticalDragStart: _start, - onVerticalDragUpdate: _update, - onVerticalDragEnd: _end, - onVerticalDragCancel: _cancel, - child: widget.child, + Widget build(BuildContext context) => Listener( + onPointerSignal: _wheel, + child: GestureDetector( + // Opaque so a drag starting on the gutter's empty background counts, not + // only one that starts on a chip. Children still hit-test first, so a + // tap on a chip is still the chip's. + behavior: HitTestBehavior.opaque, + onVerticalDragStart: _start, + onVerticalDragUpdate: _update, + onVerticalDragEnd: _end, + onVerticalDragCancel: _cancel, + child: widget.child, + ), ); } diff --git a/lib/ui/home_page.dart b/lib/ui/home_page.dart index 74fd8a9..b6ff666 100644 --- a/lib/ui/home_page.dart +++ b/lib/ui/home_page.dart @@ -3121,7 +3121,6 @@ class _HomePageState extends State with WidgetsBindingObserver { // enough of one for a grouped currency and its three-letter code. gutterWidth: MediaQuery.sizeOf(context).width >= 400 ? 152 : 132, resultsVisible: true, - showDivider: false, autofocus: _readyToTypeIn(note), startAtEnd: _readyToTypeIn(note), initialCaret: _resumeCaretIn(note), @@ -3160,9 +3159,6 @@ class _HomePageState extends State with WidgetsBindingObserver { onDocumentChanged: (body, formats, attachments) => _updateDocument(note.id, body, formats, attachments), storedDocument: () => _storedDocument(note.id), - onGutterWidthChanged: (_) {}, - onResultsVisibilityChanged: (_) {}, - onGutterWidthReset: () {}, onSettingsPressed: _showSettings, ), ), @@ -3208,7 +3204,6 @@ class _HomePageState extends State with WidgetsBindingObserver { _publishPreparedImage(note.id, staged, prepared), engine: widget.engines.engine, highlighter: widget.engines.highlighter, - gutterWidth: widget.prefs.gutterWidth, resultsVisible: widget.prefs.resultsVisible, autofocus: active && !_selectionAutofocusSuppressed && _readyToTypeIn(note), @@ -3255,12 +3250,7 @@ class _HomePageState extends State with WidgetsBindingObserver { onDocumentChanged: (body, formats, attachments) => _updateDocument(note.id, body, formats, attachments), storedDocument: () => _storedDocument(note.id), - onGutterWidthChanged: (value) => widget.prefs.gutterWidth = value, - onResultsVisibilityChanged: (value) => - widget.prefs.resultsVisible = value, - onGutterWidthReset: widget.prefs.resetGutterWidth, onSettingsPressed: _showSettings, - hideEmptyResults: AppPlatform.isMobile, ), ), ); diff --git a/lib/ui/notebook_paper.dart b/lib/ui/notebook_paper.dart index 7117705..de46f68 100644 --- a/lib/ui/notebook_paper.dart +++ b/lib/ui/notebook_paper.dart @@ -10,7 +10,7 @@ import '../core/theme.dart'; /// The fibers are deterministic, so the paper never shimmers between frames. /// /// Only the marks are painted here. The colour under them belongs to the -/// editor's page, which also runs under the gutter and its divider; painting +/// editor's page, which also runs under a phone's results column; painting /// it twice was harmless while it was opaque and would double up the moment /// transparency thinned it. class NotebookPaper extends StatelessWidget { diff --git a/packaging/SUBMISSION.md b/packaging/SUBMISSION.md index e3030f7..5d2a678 100644 --- a/packaging/SUBMISSION.md +++ b/packaging/SUBMISSION.md @@ -186,7 +186,7 @@ compact phone layout there: one column, a hamburger drawer, and most of a 13-inch display left empty. That is the shape of a Guideline 4.0 rejection. The compact/wide switch is now decided by width alone, so iPad gets the same -sidebar, editor and results columns the desktop build uses. Two insets come +sidebar and editor the desktop build uses. Two insets come with that, because the wide layout is its own chrome rather than a `Scaffold`: it takes the bottom safe area so the running total clears the home indicator, and it lifts both panes over the software keyboard. Both are covered by tests diff --git a/test/app_test.dart b/test/app_test.dart index ebe056a..e9cfc28 100644 --- a/test/app_test.dart +++ b/test/app_test.dart @@ -30,6 +30,7 @@ import 'package:kapy_notes/ui/app_logo.dart'; import 'package:kapy_notes/ui/draw/drawing_canvas.dart'; import 'package:kapy_notes/ui/editor/note_editor.dart'; import 'package:kapy_notes/ui/editor/note_footer.dart'; +import 'package:kapy_notes/ui/editor/inline_results.dart'; import 'package:kapy_notes/ui/editor/results_gutter.dart'; import 'package:kapy_notes/ui/editor_panes.dart'; import 'package:kapy_notes/ui/empty_state.dart'; @@ -808,8 +809,6 @@ void main() { testWidgets('opens footer settings and resets desktop panel widths', ( tester, ) async { - store.data['gutter.v1'] = 320.0; - store.data['resultsVisible.v1'] = false; store.data['sidebar.v1'] = 360.0; await pumpApp(tester); await tester.tap(emptyStateNewNote()); @@ -848,8 +847,6 @@ void main() { await tester.ensureVisible(reset); await tester.tap(reset); await tester.pumpAndSettle(); - expect(prefs.gutterWidth, LayoutPrefs.defaultGutterWidth); - expect(prefs.resultsVisible, isTrue); expect(prefs.sidebarWidth, LayoutPrefs.defaultSidebarWidth); }); @@ -2307,9 +2304,7 @@ void main() { expect(panes(), ['Delta', 'Charlie', 'Bravo']); }); - testWidgets('the results column has a shortcut like the notes list', ( - tester, - ) async { + testWidgets('results have a shortcut like the notes list', (tester) async { await pumpApp(tester); notes.create(body: '2 + 2'); await tester.pumpAndSettle(); @@ -2324,18 +2319,17 @@ void main() { await tester.pumpAndSettle(); } - // Cmd+R folds the right-hand column away, leaving the handle that brings - // it back; Cmd+S does the same for the list on the left. Notes autosave, - // so the conventional save chord is free for the pane itself. + // Cmd+R hides the results at the ends of their lines and brings them + // back; Cmd+S does the same for the list on the left. Notes autosave, so + // the conventional save chord is free for the pane itself. + expect(find.widgetWithText(ResultChip, '4'), findsOneWidget); await press(LogicalKeyboardKey.keyR); expect(prefs.resultsVisible, isFalse); - expect( - find.byKey(const ValueKey('results-restore-handle')), - findsOneWidget, - ); + expect(find.byType(ResultChip), findsNothing); await press(LogicalKeyboardKey.keyR); expect(prefs.resultsVisible, isTrue); + expect(find.widgetWithText(ResultChip, '4'), findsOneWidget); await press(LogicalKeyboardKey.keyS); expect(prefs.sidebarVisible, isFalse); @@ -4065,31 +4059,29 @@ void main() { }); group('compact editor', () { - testWidgets('keeps the results divider in a narrow desktop window', ( - tester, - ) async { - store.data['notes.v1'] = [ - { - 'id': 'desktop-compact', - 'body': 'Compact budget\n6 * 7', - 'createdAt': 1000, - 'updatedAt': 1000, - }, - ]; + testWidgets( + 'puts results at the ends of lines in a narrow desktop window', + (tester) async { + store.data['notes.v1'] = [ + { + 'id': 'desktop-compact', + 'body': 'Compact budget\n6 * 7', + 'createdAt': 1000, + 'updatedAt': 1000, + }, + ]; - await pumpApp(tester, size: const Size(600, 630)); + await pumpApp(tester, size: const Size(600, 630)); - expect(find.widgetWithText(ResultChip, '42'), findsOneWidget); - expect(find.byType(GutterDivider), findsOneWidget); - expect( - tester - .widget( - find.byKey(const ValueKey('results-divider-hover')), - ) - .cursor, - SystemMouseCursors.resizeLeftRight, - ); - }); + expect(find.widgetWithText(ResultChip, '42'), findsOneWidget); + expect(find.byType(InlineResults), findsOneWidget); + expect(find.byType(ResultsGutter), findsNothing); + // The writing keeps the whole pane: nothing beside it but its margin. + final field = tester.getRect(find.byType(EditableText)); + final pane = tester.getRect(find.byType(NoteEditor)); + expect(pane.right - field.right, lessThan(20)); + }, + ); testWidgets( 'Windows keeps the results shortcut at its minimum client width', @@ -4112,23 +4104,18 @@ void main() { size: Size(LayoutPrefs.minimumWindowSize.width - 12, 630), ); - expect(find.byType(GutterDivider), findsOneWidget); + expect(find.widgetWithText(ResultChip, '42'), findsOneWidget); await pressShortcut( tester, shortcuts.bindingFor(ShortcutAction.toggleResults)!, ); expect(prefs.resultsVisible, isFalse); - expect( - find.byKey(const ValueKey('results-restore-handle')), - findsOneWidget, - ); + expect(find.byType(ResultChip), findsNothing); }, ); - testWidgets('keeps the results divider out of phone-sized layouts', ( - tester, - ) async { + testWidgets('keeps the results column on phones', (tester) async { AppPlatform.debugTargetPlatformOverride = TargetPlatform.iOS; addTearDown(() => AppPlatform.debugTargetPlatformOverride = null); store.data['notes.v1'] = [ @@ -4143,7 +4130,8 @@ void main() { await pumpApp(tester, size: const Size(420, 800)); expect(find.widgetWithText(ResultChip, '42'), findsOneWidget); - expect(find.byType(GutterDivider), findsNothing); + expect(find.byType(ResultsGutter), findsOneWidget); + expect(find.byType(InlineResults), findsNothing); }); testWidgets('gives prose-only phone notes the full writing width', ( @@ -4188,7 +4176,7 @@ void main() { await pumpApp(tester, size: const Size(1100, 760)); expect(find.byType(ResultsGutter), findsNothing); - expect(find.byType(GutterDivider), findsNothing); + expect(find.byType(InlineResults), findsNothing); final field = tester.widget( find.descendant( of: find.byType(NoteEditor), diff --git a/test/golden_test.dart b/test/golden_test.dart index eafb4bc..6f0af7a 100644 --- a/test/golden_test.dart +++ b/test/golden_test.dart @@ -557,45 +557,15 @@ void main() { ); }); - testWidgets('desktop dark results divider hover', (tester) async { - await pumpForGolden( - tester, - size: const Size(760, 520), - brightness: Brightness.dark, - ); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo( - tester.getCenter(find.byKey(const ValueKey('results-divider-hover'))), - ); - await tester.pumpAndSettle(); - - await expectLater( - find.byType(KapyNotesApp), - matchesGoldenFile('goldens/desktop_dark_results_divider_hover.png'), - ); - }); - - testWidgets('desktop dark narrow results divider hover', (tester) async { + testWidgets('desktop dark narrow, results at line ends', (tester) async { await pumpForGolden( tester, size: const Size(600, 630), brightness: Brightness.dark, ); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo( - tester.getCenter(find.byKey(const ValueKey('results-divider-hover'))), - ); - await tester.pumpAndSettle(); - await expectLater( find.byType(KapyNotesApp), - matchesGoldenFile( - 'goldens/desktop_dark_narrow_results_divider_hover.png', - ), + matchesGoldenFile('goldens/desktop_dark_narrow_results.png'), ); }); @@ -621,29 +591,6 @@ void main() { ); }); - testWidgets('desktop dark results restore hover', (tester) async { - await pumpForGolden( - tester, - size: const Size(760, 520), - brightness: Brightness.dark, - ); - goldenPrefs.resultsVisible = false; - await tester.pumpAndSettle(); - - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo( - tester.getCenter(find.byKey(const ValueKey('results-restore-hover'))), - ); - await tester.pumpAndSettle(); - - await expectLater( - find.byType(KapyNotesApp), - matchesGoldenFile('goldens/desktop_dark_results_restore_hover.png'), - ); - }); - testWidgets('desktop dark compact header hover', (tester) async { await pumpForGolden( tester, diff --git a/test/goldens/desktop_dark.png b/test/goldens/desktop_dark.png index 539dde9..3469dbd 100644 Binary files a/test/goldens/desktop_dark.png and b/test/goldens/desktop_dark.png differ diff --git a/test/goldens/desktop_dark_archive.png b/test/goldens/desktop_dark_archive.png index 427d137..091d606 100644 Binary files a/test/goldens/desktop_dark_archive.png and b/test/goldens/desktop_dark_archive.png differ diff --git a/test/goldens/desktop_dark_archive_selecting.png b/test/goldens/desktop_dark_archive_selecting.png index 8b5dd74..604b2fa 100644 Binary files a/test/goldens/desktop_dark_archive_selecting.png and b/test/goldens/desktop_dark_archive_selecting.png differ diff --git a/test/goldens/desktop_dark_blank_note.png b/test/goldens/desktop_dark_blank_note.png index d8f974a..d24abc8 100644 Binary files a/test/goldens/desktop_dark_blank_note.png and b/test/goldens/desktop_dark_blank_note.png differ diff --git a/test/goldens/desktop_dark_collapsed.png b/test/goldens/desktop_dark_collapsed.png index 7f90fa4..fb531b7 100644 Binary files a/test/goldens/desktop_dark_collapsed.png and b/test/goldens/desktop_dark_collapsed.png differ diff --git a/test/goldens/desktop_dark_editor_context_menu.png b/test/goldens/desktop_dark_editor_context_menu.png index 100b827..3fb719e 100644 Binary files a/test/goldens/desktop_dark_editor_context_menu.png and b/test/goldens/desktop_dark_editor_context_menu.png differ diff --git a/test/goldens/desktop_dark_header_hover.png b/test/goldens/desktop_dark_header_hover.png index 28122ed..ce9d0c3 100644 Binary files a/test/goldens/desktop_dark_header_hover.png and b/test/goldens/desktop_dark_header_hover.png differ diff --git a/test/goldens/desktop_dark_hover_surfaces.png b/test/goldens/desktop_dark_hover_surfaces.png index f07464b..aab5c9e 100644 Binary files a/test/goldens/desktop_dark_hover_surfaces.png and b/test/goldens/desktop_dark_hover_surfaces.png differ diff --git a/test/goldens/desktop_dark_images.png b/test/goldens/desktop_dark_images.png index 5c5a7a2..12a39cf 100644 Binary files a/test/goldens/desktop_dark_images.png and b/test/goldens/desktop_dark_images.png differ diff --git a/test/goldens/desktop_dark_narrow_list.png b/test/goldens/desktop_dark_narrow_list.png index d1ecfa5..c2fcce4 100644 Binary files a/test/goldens/desktop_dark_narrow_list.png and b/test/goldens/desktop_dark_narrow_list.png differ diff --git a/test/goldens/desktop_dark_narrow_results.png b/test/goldens/desktop_dark_narrow_results.png new file mode 100644 index 0000000..1351bd3 Binary files /dev/null and b/test/goldens/desktop_dark_narrow_results.png differ diff --git a/test/goldens/desktop_dark_narrow_results_divider_hover.png b/test/goldens/desktop_dark_narrow_results_divider_hover.png deleted file mode 100644 index a71aa40..0000000 Binary files a/test/goldens/desktop_dark_narrow_results_divider_hover.png and /dev/null differ diff --git a/test/goldens/desktop_dark_note_actions.png b/test/goldens/desktop_dark_note_actions.png index a0e99fc..170bd68 100644 Binary files a/test/goldens/desktop_dark_note_actions.png and b/test/goldens/desktop_dark_note_actions.png differ diff --git a/test/goldens/desktop_dark_note_pinned.png b/test/goldens/desktop_dark_note_pinned.png index 3378963..ed4333e 100644 Binary files a/test/goldens/desktop_dark_note_pinned.png and b/test/goldens/desktop_dark_note_pinned.png differ diff --git a/test/goldens/desktop_dark_pinned.png b/test/goldens/desktop_dark_pinned.png index 539dde9..3469dbd 100644 Binary files a/test/goldens/desktop_dark_pinned.png and b/test/goldens/desktop_dark_pinned.png differ diff --git a/test/goldens/desktop_dark_results_divider_hover.png b/test/goldens/desktop_dark_results_divider_hover.png deleted file mode 100644 index 72c4bef..0000000 Binary files a/test/goldens/desktop_dark_results_divider_hover.png and /dev/null differ diff --git a/test/goldens/desktop_dark_results_restore_hover.png b/test/goldens/desktop_dark_results_restore_hover.png deleted file mode 100644 index f2f1640..0000000 Binary files a/test/goldens/desktop_dark_results_restore_hover.png and /dev/null differ diff --git a/test/goldens/desktop_dark_settings.png b/test/goldens/desktop_dark_settings.png index a677eb3..10de57a 100644 Binary files a/test/goldens/desktop_dark_settings.png and b/test/goldens/desktop_dark_settings.png differ diff --git a/test/goldens/desktop_dark_settings_appearance_end.png b/test/goldens/desktop_dark_settings_appearance_end.png index 5e5b472..368493f 100644 Binary files a/test/goldens/desktop_dark_settings_appearance_end.png and b/test/goldens/desktop_dark_settings_appearance_end.png differ diff --git a/test/goldens/desktop_dark_settings_shortcuts.png b/test/goldens/desktop_dark_settings_shortcuts.png index 348623b..72c6dd8 100644 Binary files a/test/goldens/desktop_dark_settings_shortcuts.png and b/test/goldens/desktop_dark_settings_shortcuts.png differ diff --git a/test/goldens/desktop_dark_settings_updates.png b/test/goldens/desktop_dark_settings_updates.png index e27d29c..ac80288 100644 Binary files a/test/goldens/desktop_dark_settings_updates.png and b/test/goldens/desktop_dark_settings_updates.png differ diff --git a/test/goldens/desktop_dark_update_ready.png b/test/goldens/desktop_dark_update_ready.png index cd20e9e..90158f0 100644 Binary files a/test/goldens/desktop_dark_update_ready.png and b/test/goldens/desktop_dark_update_ready.png differ diff --git a/test/goldens/desktop_light.png b/test/goldens/desktop_light.png index ef13f89..1ddd2ed 100644 Binary files a/test/goldens/desktop_light.png and b/test/goldens/desktop_light.png differ diff --git a/test/goldens/desktop_light_settings_appearance.png b/test/goldens/desktop_light_settings_appearance.png index ab3a7fb..c65a980 100644 Binary files a/test/goldens/desktop_light_settings_appearance.png and b/test/goldens/desktop_light_settings_appearance.png differ diff --git a/test/goldens/desktop_windows_dark_settings.png b/test/goldens/desktop_windows_dark_settings.png index 3f90449..f0d22b2 100644 Binary files a/test/goldens/desktop_windows_dark_settings.png and b/test/goldens/desktop_windows_dark_settings.png differ diff --git a/test/goldens/desktop_windows_dark_update.png b/test/goldens/desktop_windows_dark_update.png index 7925bef..13a1509 100644 Binary files a/test/goldens/desktop_windows_dark_update.png and b/test/goldens/desktop_windows_dark_update.png differ diff --git a/test/goldens/welcome_desktop_dark.png b/test/goldens/welcome_desktop_dark.png index e59fbc3..46431df 100644 Binary files a/test/goldens/welcome_desktop_dark.png and b/test/goldens/welcome_desktop_dark.png differ diff --git a/test/goldens/welcome_phone_light.png b/test/goldens/welcome_phone_light.png index 4e3afe5..6f136d0 100644 Binary files a/test/goldens/welcome_phone_light.png and b/test/goldens/welcome_phone_light.png differ diff --git a/test/images/note_image_editor_test.dart b/test/images/note_image_editor_test.dart index 53937d5..1666a25 100644 --- a/test/images/note_image_editor_test.dart +++ b/test/images/note_image_editor_test.dart @@ -238,15 +238,11 @@ Widget harness( readOnly: readOnly, engine: engine, highlighter: Highlighter(engine.registry), - gutterWidth: 160, resultsVisible: true, writingFont: WritingFont.handwritten, shortcuts: shortcutPrefs, onDocumentChanged: (body, formats, refs) => onAttachmentsChanged?.call(refs), - onGutterWidthChanged: (_) {}, - onResultsVisibilityChanged: (_) {}, - onGutterWidthReset: () {}, onSettingsPressed: () {}, ), ), @@ -318,6 +314,11 @@ void main() { }); testWidgets('one image fills the column; three become tiles', (tester) async { + // Tall enough that one image fills the column rather than stopping at its + // height cap. + tester.view.physicalSize = const Size(800, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); final single = at(0); await tester.pumpWidget(harness(anchor, attachments: [single])); await tester.pump(); diff --git a/test/note_editor_markdown_test.dart b/test/note_editor_markdown_test.dart index 75f7649..6513887 100644 --- a/test/note_editor_markdown_test.dart +++ b/test/note_editor_markdown_test.dart @@ -66,7 +66,6 @@ Widget harness( initialFormats: initialFormats, engine: engine, highlighter: Highlighter(engine.registry), - gutterWidth: 200, resultsVisible: true, markdownEnabled: markdown, readOnly: readOnly, @@ -76,9 +75,6 @@ Widget harness( onBodyChanged?.call(body); onFormatsChanged?.call(formats); }, - onGutterWidthChanged: (_) {}, - onResultsVisibilityChanged: (_) {}, - onGutterWidthReset: () {}, onSettingsPressed: () {}, writingFont: WritingFont.handwritten, shortcuts: shortcutPrefs, diff --git a/test/note_editor_remote_test.dart b/test/note_editor_remote_test.dart index 938bf12..851330e 100644 --- a/test/note_editor_remote_test.dart +++ b/test/note_editor_remote_test.dart @@ -68,16 +68,12 @@ Widget harness( initialFormats: formats, engine: engine, highlighter: Highlighter(engine.registry), - gutterWidth: 200, resultsVisible: true, onDocumentChanged: (body, formats, attachments) { store?.body = body; onBodyChanged?.call(body); }, storedDocument: store?.read, - onGutterWidthChanged: (_) {}, - onResultsVisibilityChanged: (_) {}, - onGutterWidthReset: () {}, onSettingsPressed: () {}, writingFont: WritingFont.handwritten, shortcuts: shortcutPrefs, diff --git a/test/note_editor_test.dart b/test/note_editor_test.dart index a0aef98..89a51f7 100644 --- a/test/note_editor_test.dart +++ b/test/note_editor_test.dart @@ -17,6 +17,7 @@ import 'package:kapy_notes/data/shortcut_prefs.dart'; import 'package:kapy_notes/data/time_zones.dart'; import 'package:kapy_notes/ui/editor/blank_line_highlight.dart'; import 'package:kapy_notes/ui/editor/editor_formatting.dart'; +import 'package:kapy_notes/ui/editor/inline_results.dart'; import 'package:kapy_notes/ui/celebrate.dart'; import 'package:kapy_notes/ui/kapy_cursor_peek.dart'; import 'package:kapy_notes/ui/editor/note_editor.dart'; @@ -63,8 +64,9 @@ Offset _centerOf(WidgetTester tester, String body, String linkText) { Widget harness( String body, { List initialFormats = const [], - double gutterWidth = 200, + double? gutterWidth, bool resultsVisible = true, + double? width, DateTime? lastUpdatedAt, bool dailySeparatorsEnabled = false, DateTime Function()? now, @@ -76,50 +78,56 @@ Widget harness( TargetPlatform? platform, ValueChanged? onBodyChanged, ValueChanged>? onFormatsChanged, - ValueChanged? onGutterWidthChanged, - ValueChanged? onResultsVisibilityChanged, - VoidCallback? onGutterWidthReset, VoidCallback? onSettingsPressed, VoidCallback? onRecordVoice, WritingFont writingFont = WritingFont.handwritten, double editorTextScale = 1, ShortcutPrefs? shortcuts, }) { + final editor = NoteEditor( + // Keyed by body so re-pumping with different text remounts the editor, + // the way switching notes does in the app. + key: ValueKey(body), + noteId: 'test', + initialBody: body, + initialFormats: initialFormats, + engine: engine, + highlighter: Highlighter(engine.registry), + gutterWidth: gutterWidth, + resultsVisible: resultsVisible, + lastUpdatedAt: lastUpdatedAt, + dailySeparatorsEnabled: dailySeparatorsEnabled, + now: now, + displayTime: displayTime, + startAtEnd: startAtEnd, + autofocus: autofocus, + ensureKeyboardVisible: ensureKeyboardVisible, + readOnly: readOnly, + onDocumentChanged: (body, formats, attachments) { + onBodyChanged?.call(body); + onFormatsChanged?.call(formats); + }, + onSettingsPressed: onSettingsPressed ?? () {}, + onRecordVoice: onRecordVoice, + writingFont: writingFont, + editorTextScale: editorTextScale, + shortcuts: shortcuts ?? shortcutPrefs, + ); return MaterialApp( theme: KapyTheme.dark().copyWith(platform: platform), home: Scaffold( - body: NoteEditor( - // Keyed by body so re-pumping with different text remounts the - // editor, the way switching notes does in the app. - key: ValueKey(body), - noteId: 'test', - initialBody: body, - initialFormats: initialFormats, - engine: engine, - highlighter: Highlighter(engine.registry), - gutterWidth: gutterWidth, - resultsVisible: resultsVisible, - lastUpdatedAt: lastUpdatedAt, - dailySeparatorsEnabled: dailySeparatorsEnabled, - now: now, - displayTime: displayTime, - startAtEnd: startAtEnd, - autofocus: autofocus, - ensureKeyboardVisible: ensureKeyboardVisible, - readOnly: readOnly, - onDocumentChanged: (body, formats, attachments) { - onBodyChanged?.call(body); - onFormatsChanged?.call(formats); - }, - onGutterWidthChanged: onGutterWidthChanged ?? (_) {}, - onResultsVisibilityChanged: onResultsVisibilityChanged ?? (_) {}, - onGutterWidthReset: onGutterWidthReset ?? () {}, - onSettingsPressed: onSettingsPressed ?? () {}, - onRecordVoice: onRecordVoice, - writingFont: writingFont, - editorTextScale: editorTextScale, - shortcuts: shortcuts ?? shortcutPrefs, - ), + // A narrower editor where a test needs one, with the rest of the + // window left empty beside it. + body: width == null + ? editor + : Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: width, + height: double.infinity, + child: editor, + ), + ), ), ); } @@ -149,6 +157,27 @@ Rect lineRect(WidgetTester tester, String body, int index) { return origin & Size(first.right - first.left, first.bottom - first.top); } +/// The last row the text field draws line [index] on: the same row as +/// [lineRect] unless the line wraps. +Rect lastRowRect(WidgetTester tester, String body, int index) { + final start = startOfLine(body, index); + final line = body.split('\n')[index]; + final editable = tester + .state(find.byType(EditableText)) + .renderEditable; + final boxes = editable.getBoxesForSelection( + TextSelection(baseOffset: start, extentOffset: start + line.length), + ); + expect(boxes, isNotEmpty, reason: 'line $index has no text box'); + final last = boxes.last; + final row = [ + for (final box in boxes) + if ((box.top - last.top).abs() < 0.5) box.toRect(), + ].reduce((a, b) => a.expandToInclude(b)); + final box = tester.renderObject(find.byType(EditableText)); + return row.shift(box.localToGlobal(Offset.zero)); +} + /// Character offset at which line [index] starts. int startOfLine(String body, int index) { var offset = 0; @@ -837,28 +866,31 @@ void main() { } }); - testWidgets('keeps alignment when a line wraps onto two rows', ( - tester, - ) async { + testWidgets('puts a wrapped line\'s result on its last row', (tester) async { // Long enough to wrap in the narrow text pane, which pushes every // following line down by one row. const long = '1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1'; const body = 'first\n$long\nafter = 9'; // The handwriting face is proportionally spaced and fits more of this - // expression than the - // old mono default, so keep the pane narrow enough to preserve the wrap. - await tester.pumpWidget(harness(body, gutterWidth: 320)); + // expression than the old mono default, so keep the pane narrow enough + // to preserve the wrap. + await tester.pumpWidget(harness(body, width: 465)); await tester.pumpAndSettle(); final wrappedLine = lineRect(tester, body, 1); + final lastRow = lastRowRect(tester, body, 1); final afterLine = lineRect(tester, body, 2); // Confirm the line really did wrap before asserting anything about it. expect(afterLine.top - wrappedLine.top, greaterThan(wrappedLine.height)); + expect(lastRow.top, greaterThan(wrappedLine.top)); + final wrapped = tester.getRect(chipWithText('18')); + expect(wrapped.center.dy, closeTo(lastRow.center.dy, 1.5)); expect( - tester.getRect(chipWithText('18')).center.dy, - closeTo(wrappedLine.center.dy, 1.5), + wrapped.left, + greaterThan(lastRow.right), + reason: 'after the writing on that row, not over it', ); expect( tester.getRect(chipWithText('9')).center.dy, @@ -878,7 +910,7 @@ void main() { 'daily = 55\n' 'daily * 7\n' 'total'; - await tester.pumpWidget(harness(body, gutterWidth: 320)); + await tester.pumpWidget(harness(body, width: 465)); await tester.pumpAndSettle(); final commented = lineRect(tester, body, 0); @@ -1769,7 +1801,7 @@ void main() { group('scrolling from the results gutter', () { /// A note long enough that the field has somewhere to scroll to. String longBody() => - [for (var i = 1; i <= 80; i++) 'line $i = $i * 2'].join('\n'); + [for (var i = 1; i <= 80; i++) 'line$i = $i * 2'].join('\n'); ScrollController fieldScroll(WidgetTester tester) => tester.widget(find.byType(TextField)).scrollController!; @@ -1829,6 +1861,33 @@ void main() { ); }); + testWidgets('a drag or a wheel over a pill scrolls the note', ( + tester, + ) async { + // A pill sits over the field, so the field never sees what lands on it. + await tester.pumpWidget(harness(longBody())); + await tester.pumpAndSettle(); + + final scroll = fieldScroll(tester); + final pill = tester.getCenter(find.byType(ResultChip).first); + await tester.dragFrom(pill, const Offset(0, -160)); + await tester.pumpAndSettle(); + final dragged = scroll.offset; + expect(dragged, greaterThan(0)); + + // The first pill on screen now: one scrolled half under the top edge + // is clipped there and takes no pointer. + final wheel = TestPointer(1, PointerDeviceKind.mouse); + await tester.sendEventToBinding( + wheel.hover( + tester.getCenter(find.byType(ResultChip).hitTestable().first), + ), + ); + await tester.sendEventToBinding(wheel.scroll(const Offset(0, 120))); + await tester.pumpAndSettle(); + expect(scroll.offset, greaterThan(dragged)); + }); + testWidgets('tapping a chip still copies rather than scrolling', ( tester, ) async { @@ -2812,13 +2871,9 @@ void main() { .size .width; - const baseGutter = 200.0; + const baseEditor = 600.0; await tester.pumpWidget( - harness( - 'seed', - gutterWidth: baseGutter, - writingFont: WritingFont.monospace, - ), + harness('seed', width: baseEditor, writingFont: WritingFont.monospace), ); await tester.pumpAndSettle(); final baseWidth = fieldWidth(tester); @@ -2837,16 +2892,16 @@ void main() { final advance = probe.width; probe.dispose(); - // Widen the gutter just enough that the line lands inside the reserved + // Narrow the editor just enough that the line lands inside the reserved // sliver: too long for the text area, short enough for the field. final chars = (baseWidth / advance).floor(); final lineWidth = chars * advance; final targetWidth = lineWidth + EditorMetrics.caretMargin / 2; - final gutter = baseGutter + (baseWidth - targetWidth); + final editorWidth = baseEditor - (baseWidth - targetWidth); final body = '${'a' * chars}\n6 * 7'; await tester.pumpWidget( - harness(body, gutterWidth: gutter, writingFont: WritingFont.monospace), + harness(body, width: editorWidth, writingFont: WritingFont.monospace), ); await tester.pumpAndSettle(); @@ -3003,180 +3058,273 @@ void main() { ); }); - testWidgets('results divider advertises and reports horizontal dragging', ( + testWidgets('puts each result at the right-hand end of its own line', ( tester, ) async { - final widths = []; - final visibility = []; - await tester.pumpWidget( - harness( - '2 + 2', - onGutterWidthChanged: widths.add, - onResultsVisibilityChanged: visibility.add, - ), - ); + const body = + 'Tool costs per month\n' + 'ahrefs = 129 usd\n' + 'looker = 29 usd\n' + 'outreach = 3 * 49 usd\n' + 'total'; + await tester.pumpWidget(harness(body)); await tester.pumpAndSettle(); - final divider = find.byType(GutterDivider); - final region = find.byKey(const ValueKey('results-divider-hover')); - final gripOpacity = find.byKey( - const ValueKey('results-divider-grip-opacity'), - ); - expect( - tester.widget(region).cursor, - SystemMouseCursors.resizeLeftRight, - ); - expect(tester.widget(gripOpacity).opacity, 0); + expect(find.byType(InlineResults), findsOneWidget); + expect(find.byType(ResultsGutter), findsNothing); + final editable = tester + .state(find.byType(EditableText)) + .renderEditable; + final columnRight = + editable.localToGlobal(Offset.zero).dx + + EditorMetrics.textLayoutWidth(editable.size.width); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo(tester.getCenter(divider)); - await tester.pumpAndSettle(); - expect(tester.widget(gripOpacity).opacity, 1); - await tester.pump(const Duration(milliseconds: 600)); - await tester.pumpAndSettle(); - expect(find.text('Drag to resize. Click to hide.'), findsOneWidget); - expect( - tester.getSize(find.byKey(const ValueKey('results-divider-line'))).width, - 2, - ); + for (final entry in { + 1: '129.00 USD', + 2: '29.00 USD', + 3: '147.00 USD', + 4: '305.00 USD', + }.entries) { + final row = lastRowRect(tester, body, entry.key); + final pill = tester.getRect(chipWithText(entry.value)); + expect( + pill.center.dy, + closeTo(row.center.dy, 1.5), + reason: '"${entry.value}" should sit on line ${entry.key}', + ); + expect(pill.right, closeTo(columnRight, 1)); - await mouse.down(tester.getCenter(divider)); - // The first move clears the gesture slop; the second is the resize delta. - await mouse.moveBy(const Offset(-20, 0)); - await tester.pump(); - await mouse.moveBy(const Offset(-20, 0)); - await mouse.up(); - await tester.pumpAndSettle(); + final leader = tester.getRect( + find.byKey(ValueKey('result-leader-${entry.key}')), + ); + expect(leader.left, closeTo(row.right + InlineResults.gap, 1)); + expect(leader.right, closeTo(pill.left - InlineResults.gap, 1)); + expect(leader.center.dy, closeTo(row.center.dy, 1.5)); + } + }); - expect(widths, isNotEmpty); - expect(widths.last, greaterThan(200)); + testWidgets('fills in the pill of the line that reads the total', ( + tester, + ) async { + await tester.pumpWidget(harness('a = 12\nb = 30\ntotal')); + await tester.pumpAndSettle(); + + Color fillOf(String text) => + (tester + .widget( + find.descendant( + of: chipWithText(text), + matching: find.byType(AnimatedContainer), + ), + ) + .decoration! + as BoxDecoration) + .color!; + TextStyle styleOf(String text) => + tester.widget(find.text(text)).style!; + const palette = KapyTheme.darkPalette; + + expect(fillOf('42'), palette.totalPillBackground); + expect(styleOf('42').color, palette.totalPillText); + expect(styleOf('42').fontWeight, FontWeight.w600); + for (final text in ['12', '30']) { + expect(fillOf(text), palette.resultPillBackground); + expect(styleOf(text).color, palette.resultPillText); + expect(styleOf(text).fontWeight, FontWeight.w500); + } + }); - widths.clear(); - await mouse.moveTo(tester.getCenter(divider)); - await mouse.down(tester.getCenter(divider)); - await mouse.moveBy(const Offset(20, 0)); - await tester.pump(); - await mouse.moveBy(const Offset(20, 0)); - await mouse.up(); + testWidgets('a pill steps past the column rather than cover the writing', ( + tester, + ) async { + await tester.pumpWidget( + harness('seed', writingFont: WritingFont.monospace), + ); await tester.pumpAndSettle(); + var editable = tester + .state(find.byType(EditableText)) + .renderEditable; + final width = EditorMetrics.textLayoutWidth(editable.size.width); + final probe = TextPainter( + text: TextSpan( + text: 'x', + style: EditorMetrics.textStyle( + const Color(0xFF000000), + WritingFont.monospace, + ), + ), + textDirection: TextDirection.ltr, + strutStyle: EditorMetrics.strut(WritingFont.monospace), + )..layout(); + final advance = probe.width; + probe.dispose(); - expect(widths, isNotEmpty); - expect(widths.last, lessThan(200)); - - widths.clear(); - await mouse.moveTo(tester.getCenter(divider)); - await mouse.down(tester.getCenter(divider)); - await mouse.moveBy(const Offset(20, 0)); - await tester.pump(); - await mouse.moveBy(const Offset(220, 0)); - await mouse.up(); + // A calculating line that stops 40px short of the column's edge: too + // close for its pill to sit there with a gap before it, with room enough + // in the margin to step out into. + const tail = ' = 6 * 7'; + final chars = ((width - 40) / advance).floor() - tail.length; + final body = '${'x' * chars}$tail'; + await tester.pumpWidget(harness(body, writingFont: WritingFont.monospace)); await tester.pumpAndSettle(); + editable = tester + .state(find.byType(EditableText)) + .renderEditable; + final columnRight = editable.localToGlobal(Offset.zero).dx + width; - expect(widths, isNotEmpty); - expect(widths.last, lessThan(100)); + final row = lastRowRect(tester, body, 0); + expect(row.top, lineRect(tester, body, 0).top, reason: 'one row only'); + final pill = tester.getRect(chipWithText('42')); + expect(pill.left, closeTo(row.right + InlineResults.gap, 1)); + expect(pill.right, greaterThan(columnRight)); expect( - visibility, - isEmpty, - reason: 'dragging only resizes; it never hides the results column', + pill.right, + lessThanOrEqualTo(tester.getRect(find.byType(NoteEditor)).right), ); }); - testWidgets('clicking the results divider collapses to a restore edge', ( - tester, - ) async { - final visibility = []; - await tester.pumpWidget( - harness('2 + 2', onResultsVisibilityChanged: visibility.add), + testWidgets('a result is never part of the note', (tester) async { + AppPlatform.debugTargetPlatformOverride = TargetPlatform.windows; + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + addTearDown(() { + AppPlatform.debugTargetPlatformOverride = null; + debugDefaultTargetPlatformOverride = null; + }); + final clipboard = []; + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async { + switch (call.method) { + case 'Clipboard.hasStrings': + return {'value': clipboard.isNotEmpty}; + case 'Clipboard.getData': + return clipboard.isEmpty ? null : {'text': clipboard.last}; + case 'Clipboard.setData': + clipboard.add((call.arguments as Map)['text'] as String); + } + return null; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(SystemChannels.platform, null), ); - await tester.pumpAndSettle(); - - await tester.tap(find.byKey(const ValueKey('results-divider'))); - // The divider also reserves double-click for width reset, so its single - // click resolves after the platform double-click window. - await tester.pump(const Duration(milliseconds: 400)); - - expect(visibility, [false]); + Future control(LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent( + LogicalKeyboardKey.controlLeft, + platform: 'windows', + ); + await tester.sendKeyEvent(key, platform: 'windows'); + await tester.sendKeyUpEvent( + LogicalKeyboardKey.controlLeft, + platform: 'windows', + ); + await tester.pump(); + } - visibility.clear(); + const body = 'rent = 1200 usd\nrent * 12\n'; + String? latest; await tester.pumpWidget( - harness( - '2 + 2', - resultsVisible: false, - onResultsVisibilityChanged: visibility.add, - ), + harness(body, autofocus: true, onBodyChanged: (value) => latest = value), ); - await tester.pumpAndSettle(); + await tester.pump(); + // Let EditableText commit the initial value as the undo baseline. + await tester.pump(const Duration(milliseconds: 600)); + expect(chipWithText('1,200.00 USD'), findsOneWidget); + expect(chipWithText('14,400.00 USD'), findsOneWidget); - expect(find.byType(GutterDivider), findsNothing); - expect(find.byType(ResultsGutter), findsNothing); - expect(find.byType(ResultsRestoreHandle), findsOneWidget); - expect( - find.byTooltip('Show results. Drag left to resize.'), - findsOneWidget, + final field = tester.state(find.byType(EditableText)); + final controller = tester + .widget(find.byType(TextField)) + .controller!; + expect(controller.text, body); + // What the field lays out and paints is the note and nothing more. + expect(field.renderEditable.text!.toPlainText(), body); + + // Copying all of it copies the note alone, and pasting it back adds the + // note alone. + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: body.length, ); - expect( - tester - .widget( - find.byKey(const ValueKey('results-restore-hover')), - ) - .cursor, - SystemMouseCursors.resizeLeftRight, + await tester.pump(); + await control(LogicalKeyboardKey.keyC); + expect(clipboard, [body]); + controller.selection = const TextSelection.collapsed(offset: body.length); + await tester.pump(); + await control(LogicalKeyboardKey.keyV); + await tester.pumpAndSettle(); + expect(controller.text, '$body$body'); + expect(latest, '$body$body'); + + // An edit at the end of a calculating line goes into the line, its pill + // follows it live, and undo takes it back out. + await tester.pump(const Duration(milliseconds: 600)); + await tester.enterText( + find.byType(TextField), + 'rent = 1300 usd\nrent * 12', ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(controller.text, 'rent = 1300 usd\nrent * 12'); + expect(chipWithText('1,300.00 USD'), findsOneWidget); + expect(chipWithText('15,600.00 USD'), findsOneWidget); - final restore = find.byKey(const ValueKey('results-restore-handle')); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: Offset.zero); - await mouse.moveTo(tester.getCenter(restore)); + await control(LogicalKeyboardKey.keyZ); await tester.pumpAndSettle(); - expect( - tester - .widget( - find.byKey(const ValueKey('results-restore-grip-opacity')), - ) - .opacity, - 1, + expect(controller.text, '$body$body'); + expect(chipWithText('14,400.00 USD'), findsNWidgets(2)); + await tester.pump(const Duration(seconds: 2)); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('says so when a result cannot be copied', (tester) async { + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + throw PlatformException(code: 'unavailable'); + } + return null; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(SystemChannels.platform, null), ); - await tester.pump(const Duration(milliseconds: 600)); + await tester.pumpWidget(harness('rev = 4 * 3')); await tester.pumpAndSettle(); - expect(find.text('Show results. Drag left to resize.'), findsOneWidget); - await tester.tap(restore); + await tester.tap(chipWithText('12')); await tester.pump(); - expect(visibility, [true]); + + expect(find.text("Couldn't copy to clipboard"), findsOneWidget); + await tester.pump(const Duration(seconds: 3)); + await tester.pumpAndSettle(); }); - testWidgets('dragging left from the restore edge chooses its width', ( + testWidgets('hidden results leave the writing exactly as wide', ( tester, ) async { - final widths = []; - final visibility = []; - await tester.pumpWidget( - harness( - '2 + 2', - resultsVisible: false, - onGutterWidthChanged: widths.add, - onResultsVisibilityChanged: visibility.add, - ), - ); + await tester.pumpWidget(harness('Budget\n6 * 7')); await tester.pumpAndSettle(); + expect(chipWithText('42'), findsOneWidget); + final shown = tester.getSize(find.byType(EditableText)).width; - final restore = find.byKey(const ValueKey('results-restore-handle')); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - addTearDown(mouse.removePointer); - await mouse.addPointer(location: tester.getCenter(restore)); - await mouse.down(tester.getCenter(restore)); - await mouse.moveBy(const Offset(-20, 0)); - await tester.pump(); - await mouse.moveBy(const Offset(-180, 0)); - await mouse.up(); + await tester.pumpWidget(harness('Budget\n6 * 7', resultsVisible: false)); await tester.pumpAndSettle(); - expect(widths, isNotEmpty); - expect(widths.last, closeTo(180, 1)); - expect(visibility, [true]); + expect(find.byType(ResultChip), findsNothing); + expect(find.byType(InlineResults), findsNothing); + expect(tester.getSize(find.byType(EditableText)).width, shown); + }); + + testWidgets('a phone keeps its results in a column beside the text', ( + tester, + ) async { + await tester.pumpWidget(harness('Budget\n6 * 7', gutterWidth: 140)); + await tester.pumpAndSettle(); + + expect(find.byType(ResultsGutter), findsOneWidget); + expect(find.byType(InlineResults), findsNothing); + expect( + tester.getCenter(chipWithText('42')).dy, + closeTo(lineRect(tester, 'Budget\n6 * 7', 1).center.dy, 1.5), + ); }); testWidgets('keeps results pinned to their lines while scrolling', ( diff --git a/test/preferences_test.dart b/test/preferences_test.dart index c2801c4..8b25ec5 100644 --- a/test/preferences_test.dart +++ b/test/preferences_test.dart @@ -64,7 +64,6 @@ void main() { prefs.rememberWindowBounds(const Rect.fromLTWH(-120, 84, 684, 712)); prefs.sidebarWidth = 318; - prefs.gutterWidth = 224; prefs.resultsVisible = false; prefs.readyToTypeOnOpen = false; prefs.dailySeparatorsEnabled = false; @@ -79,7 +78,6 @@ void main() { expect(restored.windowPosition, const Offset(-120, 84)); expect(restored.windowBounds, const Rect.fromLTWH(-120, 84, 684, 712)); expect(restored.sidebarWidth, 318); - expect(restored.gutterWidth, 224); expect(restored.resultsVisible, isFalse); expect(restored.readyToTypeOnOpen, isFalse); expect(restored.dailySeparatorsEnabled, isFalse); @@ -102,24 +100,31 @@ void main() { expect((LayoutPrefs(invalid)..load()).windowPosition, isNull); }); - test('resetting panel widths also brings a hidden results pane back', () { - final prefs = LayoutPrefs(_MemoryStore())..load(); - prefs.gutterWidth = 320; + test('resetting panel widths resets the notes list and nothing else', () { + final store = _MemoryStore(); + final prefs = LayoutPrefs(store)..load(); + prefs.sidebarWidth = 360; prefs.resultsVisible = false; prefs.resetPanelWidths(); - expect(prefs.gutterWidth, LayoutPrefs.defaultGutterWidth); - expect(prefs.resultsVisible, isTrue); + expect(prefs.sidebarWidth, LayoutPrefs.defaultSidebarWidth); + expect( + prefs.resultsVisible, + isFalse, + reason: 'results have no width to reset, and hiding them is a choice', + ); + expect( + (LayoutPrefs(store)..load()).sidebarWidth, + LayoutPrefs.defaultSidebarWidth, + ); }); test('panel widths stop at compact usable sizes without hiding', () { final prefs = LayoutPrefs(_MemoryStore())..load(); - prefs.gutterWidth = 1; prefs.sidebarWidth = 1; - expect(prefs.gutterWidth, LayoutPrefs.minGutterWidth); expect(prefs.sidebarWidth, LayoutPrefs.minSidebarWidth); expect(prefs.resultsVisible, isTrue); expect(prefs.sidebarVisible, isFalse, reason: 'closed until asked for'); @@ -1087,7 +1092,7 @@ void main() { ); }); - test('the results column remembers being folded away', () { + test('hidden results stay hidden after a restart', () { final store = _MemoryStore(); final prefs = LayoutPrefs(store)..load(); expect(prefs.resultsVisible, isTrue); @@ -1098,6 +1103,13 @@ void main() { expect((LayoutPrefs(store)..load()).resultsVisible, isFalse); }); + test('results folded away as a column come back at the ends of lines', () { + // The column is gone, and with it the handle that brought it back. + final store = _MemoryStore()..data['resultsVisible.v1'] = false; + + expect((LayoutPrefs(store)..load()).resultsVisible, isTrue); + }); + test('the pin is off for a new install and survives a restart', () { final store = _MemoryStore(); final prefs = LayoutPrefs(store)..load(); diff --git a/test/remote_carets_test.dart b/test/remote_carets_test.dart index 636e96a..9909920 100644 --- a/test/remote_carets_test.dart +++ b/test/remote_carets_test.dart @@ -59,13 +59,9 @@ Widget harness(String body, FakeCaretSource source) => MaterialApp( initialBody: body, engine: engine, highlighter: Highlighter(engine.registry), - gutterWidth: 200, resultsVisible: true, remoteCarets: source, onDocumentChanged: (_, _, _) {}, - onGutterWidthChanged: (_) {}, - onResultsVisibilityChanged: (_) {}, - onGutterWidthReset: () {}, onSettingsPressed: () {}, writingFont: WritingFont.handwritten, shortcuts: shortcutPrefs, diff --git a/test/speech/voice_editor_test.dart b/test/speech/voice_editor_test.dart index 141a50c..5b0582c 100644 --- a/test/speech/voice_editor_test.dart +++ b/test/speech/voice_editor_test.dart @@ -111,7 +111,6 @@ Widget harness( onOpenVoiceNote: onOpenVoiceNote, engine: engine, highlighter: Highlighter(engine.registry), - gutterWidth: 160, resultsVisible: true, lastUpdatedAt: lastUpdatedAt, dailySeparatorsEnabled: dailySeparatorsEnabled, @@ -120,9 +119,6 @@ Widget harness( writingFont: WritingFont.handwritten, shortcuts: shortcutPrefs, onDocumentChanged: (body, formats, refs) => onChanged?.call(body, refs), - onGutterWidthChanged: (_) {}, - onResultsVisibilityChanged: (_) {}, - onGutterWidthReset: () {}, onSettingsPressed: () {}, ), ),