diff --git a/lib/core/iconography.dart b/lib/core/iconography.dart index 0fdc698..7731ef6 100644 --- a/lib/core/iconography.dart +++ b/lib/core/iconography.dart @@ -351,6 +351,18 @@ class KapyIcons { 0xE092, HugeIcons.strokeRoundedUserMultiple, ); + static const filterRounded = KapyIconData( + 0xE0D0, + HugeIcons.strokeRoundedFilterHorizontal, + ); + static const listViewRounded = KapyIconData( + 0xE0D1, + HugeIcons.strokeRoundedListView, + ); + static const gridViewRounded = KapyIconData( + 0xE0D2, + HugeIcons.strokeRoundedGridView, + ); static const photoLibraryOutlined = KapyIconData( 0xE049, HugeIcons.strokeRoundedImage02, diff --git a/lib/core/theme.dart b/lib/core/theme.dart index 04c9292..3d8ac2d 100644 --- a/lib/core/theme.dart +++ b/lib/core/theme.dart @@ -106,6 +106,11 @@ class CalcPalette extends ThemeExtension { /// A switch that is off: the track reads as a slot, not as a control. final Color switchTrackOff; + /// The title on a note's sticky card or list row, and the sage that marks + /// a link inside the list, such as See all. + final Color cardTitle; + final Color accentText; + /// How much of the desktop the window's chrome lets through: a multiplier on /// the alpha of every [GlassSurface]. 1 is fully opaque. /// @@ -230,6 +235,8 @@ class CalcPalette extends ThemeExtension { required this.cardBackground, required this.paneEdge, required this.switchTrackOff, + required this.cardTitle, + required this.accentText, this.translucency = 1, this.paperTranslucency = 1, }); @@ -292,6 +299,8 @@ class CalcPalette extends ThemeExtension { Color? cardBackground, Color? paneEdge, Color? switchTrackOff, + Color? cardTitle, + Color? accentText, double? translucency, double? paperTranslucency, }) => CalcPalette( @@ -351,6 +360,8 @@ class CalcPalette extends ThemeExtension { cardBackground: cardBackground ?? this.cardBackground, paneEdge: paneEdge ?? this.paneEdge, switchTrackOff: switchTrackOff ?? this.switchTrackOff, + cardTitle: cardTitle ?? this.cardTitle, + accentText: accentText ?? this.accentText, translucency: translucency ?? this.translucency, paperTranslucency: paperTranslucency ?? this.paperTranslucency, ); @@ -419,6 +430,8 @@ class CalcPalette extends ThemeExtension { cardBackground: mix(cardBackground, other.cardBackground), paneEdge: mix(paneEdge, other.paneEdge), switchTrackOff: mix(switchTrackOff, other.switchTrackOff), + cardTitle: mix(cardTitle, other.cardTitle), + accentText: mix(accentText, other.accentText), translucency: translucency + (other.translucency - translucency) * t, paperTranslucency: paperTranslucency + (other.paperTranslucency - paperTranslucency) * t, @@ -1000,6 +1013,8 @@ class KapyTheme { cardBackground: Color(0xFF292621), paneEdge: Color(0xFF2C2924), switchTrackOff: Color(0xFF3A362F), + cardTitle: Color(0xFFD9D3C6), + accentText: Color(0xFF9DB384), ); /// A cool, clean paper palette rather than the previous warm stationery. @@ -1062,6 +1077,8 @@ class KapyTheme { cardBackground: Color(0xFFF2F1ED), paneEdge: Color(0xFFE2E0DA), switchTrackOff: Color(0xFFDAD8D2), + cardTitle: Color(0xFF2A2620), + accentText: Color(0xFF56703C), ); /// Transparency mode. diff --git a/lib/data/layout_prefs.dart b/lib/data/layout_prefs.dart index c733a19..87663d2 100644 --- a/lib/data/layout_prefs.dart +++ b/lib/data/layout_prefs.dart @@ -95,6 +95,7 @@ class LayoutPrefs extends ChangeNotifier { static const String _resultsVisibleKey = 'resultsVisible.v1'; static const String _sidebarKey = 'sidebar.v1'; static const String _hiddenFolderVisibleKey = 'hiddenFolderVisible.v1'; + static const String _noteCardsKey = 'noteCards.v1'; static const String _windowWidthKey = 'windowWidth.v1'; static const String _windowHeightKey = 'windowHeight.v1'; static const String _windowXKey = 'windowX.v1'; @@ -140,6 +141,7 @@ class LayoutPrefs extends ChangeNotifier { double _sidebarWidth = defaultSidebarWidth; bool _sidebarVisible = false; bool _hiddenFolderVisible = true; + bool _noteCards = true; Size _windowSize = defaultWindowSize; Offset? _windowPosition; bool _readyToTypeOnOpen = true; @@ -181,6 +183,10 @@ class LayoutPrefs extends ChangeNotifier { double get sidebarWidth => _sidebarWidth; bool get sidebarVisible => _sidebarVisible; bool get hiddenFolderVisible => _hiddenFolderVisible; + + /// Whether the desktop notes list draws its notes as sticky cards rather + /// than as rows. Cards are how the list first appears. + bool get noteCards => _noteCards; Size get windowSize => _windowSize; Offset? get windowPosition => _windowPosition; @@ -330,6 +336,7 @@ class LayoutPrefs extends ChangeNotifier { // state for this session, not a preference carried into the next one. _sidebarVisible = false; _hiddenFolderVisible = _store.read(_hiddenFolderVisibleKey) ?? true; + _noteCards = _store.read(_noteCardsKey) ?? true; _windowSize = _clampWindowSize( Size( _readDouble(_windowWidthKey) ?? defaultWindowSize.width, @@ -769,6 +776,13 @@ class LayoutPrefs extends ChangeNotifier { void toggleHiddenFolder() => hiddenFolderVisible = !_hiddenFolderVisible; + set noteCards(bool value) { + if (value == _noteCards) return; + _noteCards = value; + _store.putNow(_noteCardsKey, value); + notifyListeners(); + } + void toggleSidebar() { _sidebarVisible = !_sidebarVisible; notifyListeners(); diff --git a/lib/data/notes_store.dart b/lib/data/notes_store.dart index 45e282a..aee40ad 100644 --- a/lib/data/notes_store.dart +++ b/lib/data/notes_store.dart @@ -37,6 +37,10 @@ class NotesStore extends ChangeNotifier { final LocalStore _store; final DateTime Function() _now; + + /// The time the store dates its notes by, for anything that says how long + /// ago they were changed. + DateTime now() => _now(); List _notes = const []; List _activeNotes = const []; List _archivedNotes = const []; diff --git a/lib/ui/home_page.dart b/lib/ui/home_page.dart index cd6e967..e0ef4a9 100644 --- a/lib/ui/home_page.dart +++ b/lib/ui/home_page.dart @@ -62,6 +62,7 @@ import 'empty_state.dart'; import 'hidden_notes_gate.dart'; import 'kapy_header_mascot.dart'; import 'mobile_page_swipe.dart'; +import 'notes_list.dart'; import 'sidebar.dart'; import 'settings_dialog.dart'; import 'sidebar_swipe.dart'; @@ -207,6 +208,16 @@ class _HomePageState extends State with WidgetsBindingObserver { /// wide window: the compact list has no rail to leave it by. bool _drawingsOnly = false; + /// The kinds of media the list beside the rail is narrowed to. Not kept + /// across launches, so a filter left on cannot pass for missing notes. + Set _mediaFilter = NoteMedia.values.toSet(); + + /// Whether that list shows every pinned note, after See all. + bool _pinnedOnly = false; + + bool get _showingPinnedOnly => + _pinnedOnly && !_specialMode && widget.notes.pinnedNoteIds.isNotEmpty; + bool _initialNoteScheduled = false; bool _openSessionScheduled = false; bool _drawerContentReady = false; @@ -2325,6 +2336,7 @@ class _HomePageState extends State with WidgetsBindingObserver { /// are. void _showSpace(LibrarySpace space) { if (space == _space) return; + _pinnedOnly = false; switch (space) { case LibrarySpace.archive: _toggleArchive(); @@ -2343,13 +2355,23 @@ class _HomePageState extends State with WidgetsBindingObserver { } List get _visibleNotes { - final notes = _narrowed( + var notes = _narrowed( _archiveMode ? widget.notes.searchArchived(_query) : _hiddenMode ? widget.notes.searchHidden(_query) : widget.notes.search(_query), ); + final pinnedOnly = _showingPinnedOnly; + if (pinnedOnly || _mediaFilter.length < NoteMedia.values.length) { + final pinned = widget.notes.pinnedNoteIds; + notes = [ + for (final note in notes) + if (NoteMedia.shows(note, _mediaFilter) && + (!pinnedOnly || pinned.contains(note.id))) + note, + ]; + } final recent = widget.prefs.recentlyOpenedNoteIds; if (notes.length < 2 || recent.isEmpty) return notes; @@ -2571,6 +2593,16 @@ class _HomePageState extends State with WidgetsBindingObserver { emptyMessage: space == LibrarySpace.drawings ? 'No drawings yet' : null, + engine: widget.engines.engine, + now: widget.notes.now, + cards: widget.prefs.noteCards, + onCardsChanged: (cards) => widget.prefs.noteCards = cards, + mediaFilter: _mediaFilter, + onMediaFilterChanged: (media) => + setState(() => _mediaFilter = media), + pinnedOnly: _showingPinnedOnly, + onPinnedOnlyChanged: (value) => + setState(() => _pinnedOnly = value), windowBar: SidebarWindowBar( title: space.title, count: _spaceCount, diff --git a/lib/ui/notes_list.dart b/lib/ui/notes_list.dart new file mode 100644 index 0000000..5db8e56 --- /dev/null +++ b/lib/ui/notes_list.dart @@ -0,0 +1,1103 @@ +import 'dart:math' as math; + +import 'package:flutter/services.dart'; +import 'package:material_ui/material_ui.dart'; + +import '../calc/engine.dart'; +import '../core/editor_font.dart'; +import '../core/theme.dart'; +import '../data/note.dart'; +import '../data/note_attachment.dart'; + +/// What a note can hold besides words, in the order the media filter lists +/// them. +enum NoteMedia { + drawing('Drawing', KapyIcons.penRounded), + voice('Voice', KapyIcons.micRounded), + video('Video', KapyIcons.videoOutlined), + image('Image', KapyIcons.photoLibraryOutlined); + + const NoteMedia(this.label, this.icon); + + final String label; + final KapyIconData icon; + + static Set inNote(Note note) => { + if (note.isDrawing) drawing, + for (final ref in note.attachments) + if (ref is NoteVoiceRef) + voice + else if (ref is NoteVideoRef) + video + else if (ref is NoteImageRef) + image, + }; + + /// Whether [note] stays in a list narrowed to [ticked]: every note while + /// every kind is ticked, and otherwise the notes holding a kind still + /// ticked. + static bool shows(Note note, Set ticked) => + ticked.length == values.length || inNote(note).any(ticked.contains); +} + +/// What the notes list shows of a note under its title. +/// +/// Read once per version of a note: notes are immutable, so a card that +/// repaints on hover does not split the body again. +class NoteGlance { + const NoteGlance._({ + required this.line, + required this.result, + required this.done, + required this.boxes, + required this.media, + }); + + /// The first line under the title, without a checkbox or heading mark. + final String? line; + + /// What [line] calculates to, when it is a calculation. + final String? result; + + /// Ticked boxes, of [boxes] checkboxes in the whole note. + final int done; + final int boxes; + final Set media; + + static final _read = Expando<(CalcEngine?, NoteGlance)>(); + static final _marks = RegExp(r'^(#{1,6}\s*|[☐☑•]\s*)'); + + static NoteGlance of(Note note, CalcEngine? engine) { + final cached = _read[note]; + if (cached != null && identical(cached.$1, engine)) return cached.$2; + final lines = note.body.split('\n'); + var titled = false; + int? at; + var done = 0; + var boxes = 0; + for (var i = 0; i < lines.length; i++) { + final text = lines[i] + .replaceAll(NoteAttachmentRef.placeholder, '') + .trim(); + if (text.startsWith('☑')) done++; + if (text.startsWith('☐') || text.startsWith('☑')) boxes++; + if (text.isEmpty) continue; + if (titled) { + at ??= i; + } else { + titled = true; + } + } + final glance = NoteGlance._( + line: at == null + ? null + : lines[at] + .replaceAll(NoteAttachmentRef.placeholder, '') + .trim() + .replaceFirst(_marks, ''), + result: at == null || engine == null + ? null + : engine.evaluateDocument(lines.take(at + 1).join('\n'))[at]?.text, + done: done, + boxes: boxes, + media: NoteMedia.inNote(note), + ); + _read[note] = (engine, glance); + return glance; + } + + /// The line a list row gives the note: how far its checklist has got, then + /// its first line, with the answer when that line is a sum. + String get summary { + final line = this.line; + final result = this.result; + final said = line == null + ? null + : result == null + ? line + : '${line.split('=').first.trim()} = $result'; + return [if (boxes > 0) '$done of $boxes done', ?said].join(' · '); + } +} + +/// Which sticky note a card is drawn on, and how far it leans. Both follow +/// the moment the note was made rather than its place in the list, so a card +/// keeps its colour as the list reorders around it, and on every device. +int _stickySeed(Note note) => + (note.createdAt.millisecondsSinceEpoch ~/ 1000 * 2654435761) & 0x7fffffff; + +const _stickyTilts = [-1.2, 1.0, 0.8, -0.8, -0.6, 1.1, 0.9, -1.1, -0.9, 0.7]; + +Color stickyTint(CalcPalette palette, Note note) => [ + palette.stickyMustard, + palette.stickyTeal, + palette.stickyOlive, + palette.stickyRust, +][_stickySeed(note) % 4]; + +double _stickyTilt(Note note) => + _stickyTilts[_stickySeed(note) ~/ 4 % _stickyTilts.length] * math.pi / 180; + +const _cardRadius = BorderRadius.only( + topLeft: Radius.circular(6), + topRight: Radius.circular(6), + bottomLeft: Radius.circular(6), + bottomRight: Radius.circular(14), +); + +const _cardShadow = [ + BoxShadow(color: Color(0x33000000), offset: Offset(0, 1)), + BoxShadow( + color: Color(0x73000000), + offset: Offset(0, 8), + blurRadius: 14, + spreadRadius: -10, + ), +]; + +TextStyle _handwritten( + double size, + double line, + FontWeight weight, + Color color, +) { + const face = WritingFont.handwritten; + return TextStyle( + fontFamily: face.fontFamily, + fontFamilyFallback: face.fontFamilyFallback, + fontVariations: face.fontVariations, + fontSize: size, + height: line / size, + leadingDistribution: TextLeadingDistribution.even, + fontWeight: weight, + color: color, + ); +} + +TextStyle _figtree(double size, double line, FontWeight weight, Color color) => + TextStyle( + fontSize: size, + height: line / size, + leadingDistribution: TextLeadingDistribution.even, + fontWeight: weight, + color: color, + ); + +/// The small icons a card or row carries before its date: the media in the +/// note, then whether it is read-only or shared. +List _marksOf( + NoteGlance glance, { + required bool locked, + required bool shared, +}) => [ + for (final media in NoteMedia.values.reversed) + if (glance.media.contains(media)) media.icon, + if (locked) KapyIcons.lockRounded, + if (shared) KapyIcons.peopleOutlined, +]; + +/// A tick box: the media menu's, and a note's while the archive is picking +/// notes. +class _PickBox extends StatelessWidget { + const _PickBox({required this.checked}); + + final bool checked; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + return Container( + width: 16, + height: 16, + decoration: BoxDecoration( + color: checked ? palette.selectedBorder : null, + border: checked + ? null + : Border.all(color: palette.textTertiary, width: 1.5), + borderRadius: BorderRadius.circular(4.5), + ), + child: checked + ? KapyIcon( + KapyIcons.checkRounded, + size: 11, + strokeWidth: 2.6, + color: palette.sidebarBackground, + ) + : null, + ); + } +} + +/// A note as a sticky card: its title in the handwriting face, a line of it +/// or how far its checklist has got, and when it was last changed. +class NoteCardFace extends StatelessWidget { + const NoteCardFace({ + super.key, + required this.note, + required this.glance, + required this.date, + required this.selected, + required this.hovering, + this.snippet, + this.ringed = false, + this.locked = false, + this.shared = false, + this.picking, + }); + + static const double height = 84; + + final Note note; + final NoteGlance glance; + + /// When it was changed, or who is in it right now. + final String date; + + /// The line a search matched, in place of the card's own preview. + final String? snippet; + final bool selected; + final bool hovering; + + /// Open in another pane. + final bool ringed; + final bool locked; + final bool shared; + + /// Ticked or not while the archive is picking notes; null otherwise. + final bool? picking; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + final blank = note.isEmpty; + final title = _handwritten(14, 18, FontWeight.w500, palette.cardTitle); + final glance = this.glance; + final result = snippet == null ? glance.result : null; + final preview = + snippet ?? + (blank ? 'Empty' : glance.line ?? (note.isDrawing ? 'Sketch' : null)); + final marks = _marksOf(glance, locked: locked, shared: shared); + final tint = blank ? palette.surfaceBackground : stickyTint(palette, note); + final picking = this.picking; + + return Transform.rotate( + angle: _stickyTilt(note), + child: Container( + padding: const EdgeInsets.fromLTRB(12, 11, 12, 10), + decoration: BoxDecoration( + color: hovering + ? Color.alphaBlend( + palette.textPrimary.withValues(alpha: 0.04), + tint, + ) + : tint, + borderRadius: _cardRadius, + border: selected || picking == true + ? Border.all(color: palette.selectedBorder, width: 1.5) + : ringed + ? Border.all( + color: palette.selectedBorder.withValues(alpha: 0.5), + width: 1.5, + ) + : blank + ? Border.all(color: palette.separator) + : null, + boxShadow: _cardShadow, + ), + child: Stack( + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // The title takes two lines where it needs them and the card + // has room, and a line of the note follows only under a title + // that fits on one. Anything a larger text size pushes past + // the card is cut at its edge rather than overflowing it. + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + final heading = note.title; + final scaler = MediaQuery.textScalerOf(context); + final painter = TextPainter( + text: TextSpan(text: heading, style: title), + textDirection: Directionality.of(context), + textScaler: scaler, + maxLines: 1, + )..layout(maxWidth: constraints.maxWidth); + final oneLine = !painter.didExceedMaxLines; + painter.dispose(); + final roomy = + constraints.maxHeight >= scaler.scale(18 + 3 + 15); + return ClipRect( + child: OverflowBox( + alignment: Alignment.topLeft, + maxHeight: double.infinity, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + heading, + maxLines: + constraints.maxHeight >= scaler.scale(36) + ? 2 + : 1, + overflow: TextOverflow.ellipsis, + style: title, + ), + if (oneLine && roomy && glance.boxes == 0) ...[ + if (result != null) + Text( + result, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontFamily: AppFonts.mono, + fontFamilyFallback: AppFonts.monoFallback, + fontSize: 12, + height: 15 / 12, + leadingDistribution: + TextLeadingDistribution.even, + fontWeight: FontWeight.w600, + color: palette.resultPillText, + ), + ) + else if (preview != null) ...[ + const SizedBox(height: 3), + Text( + preview, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _figtree( + AppTypeScale.caption, + 15, + FontWeight.w500, + blank + ? palette.textTertiary + : palette.textMuted, + ), + ), + ], + ], + ], + ), + ), + ); + }, + ), + ), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (glance.boxes > 0) ...[ + _Progress(done: glance.done, of: glance.boxes), + const SizedBox(height: 6), + ], + Row( + children: [ + for (final mark in marks) ...[ + KapyIcon( + mark, + size: 13, + strokeWidth: 1.8, + color: palette.textMuted, + ), + const SizedBox(width: 5), + ], + Flexible( + child: Text( + date, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _figtree( + AppTypeScale.caption, + 14, + FontWeight.w600, + palette.textMuted, + ), + ), + ), + ], + ), + ], + ), + ], + ), + if (picking != null) + Positioned(top: 0, right: 0, child: _PickBox(checked: picking)), + ], + ), + ), + ); + } +} + +class _Progress extends StatelessWidget { + const _Progress({required this.done, required this.of}); + + final int done; + final int of; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + return Container( + height: 4, + decoration: BoxDecoration( + color: palette.textPrimary.withValues(alpha: 0x1F / 0xFF), + borderRadius: BorderRadius.circular(2), + ), + alignment: Alignment.centerLeft, + child: FractionallySizedBox( + widthFactor: done / of, + child: DecoratedBox( + decoration: BoxDecoration( + color: palette.selectedBorder, + borderRadius: BorderRadius.circular(2), + ), + child: const SizedBox.expand(), + ), + ), + ); + } +} + +/// A note as a row: its title and date, then its media and a line of it. +class NoteListRowFace extends StatelessWidget { + const NoteListRowFace({ + super.key, + required this.note, + required this.glance, + required this.date, + required this.selected, + required this.hovering, + this.snippet, + this.ringed = false, + this.locked = false, + this.shared = false, + this.picking, + }); + + final Note note; + final NoteGlance glance; + final String date; + final String? snippet; + final bool selected; + final bool hovering; + final bool ringed; + final bool locked; + final bool shared; + final bool? picking; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + final marks = _marksOf(glance, locked: locked, shared: shared); + final summary = snippet ?? (note.isEmpty ? 'Empty' : glance.summary); + final picking = this.picking; + final marked = selected || picking == true; + // The border is always there, clear until the row is open or ringed, so + // opening a note does not nudge its text. + return Container( + padding: const EdgeInsets.all(6.5), + decoration: BoxDecoration( + color: marked + ? stickyTint(palette, note) + : hovering + ? palette.hover + : null, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: marked + ? palette.selectedBorder + : ringed + ? palette.selectedBorder.withValues(alpha: 0.5) + : Colors.transparent, + width: 1.5, + ), + ), + child: Row( + children: [ + if (picking != null) ...[ + _PickBox(checked: picking), + const SizedBox(width: 10), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Row( + children: [ + Expanded( + child: Text( + note.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _figtree( + 14, + 18, + FontWeight.w600, + palette.cardTitle, + ), + ), + ), + const SizedBox(width: 8), + Text( + date, + maxLines: 1, + style: _figtree( + AppTypeScale.small, + 16, + FontWeight.w500, + palette.textTertiary, + ), + ), + ], + ), + const SizedBox(height: 3), + Row( + children: [ + for (final mark in marks) ...[ + KapyIcon( + mark, + size: 13, + strokeWidth: 1.8, + color: palette.textMuted, + ), + const SizedBox(width: 5), + ], + Expanded( + child: Text( + summary, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _figtree( + AppTypeScale.body, + 16, + FontWeight.w400, + note.isEmpty + ? palette.textTertiary + : palette.textMuted, + ), + ), + ), + ], + ), + ], + ), + ), + ], + ), + ); + } +} + +/// The heading over a group of notes: Pinned or Notes, with how many there +/// are, and whatever the group offers at its far end. +class NotesListHeading extends StatelessWidget { + const NotesListHeading({ + super.key, + required this.label, + required this.count, + this.height = 24, + this.leading, + this.trailing, + }); + + final String label; + final int count; + final double height; + final Widget? leading; + final Widget? trailing; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + return SizedBox( + height: height, + child: Row( + children: [ + if (leading case final leading?) ...[ + leading, + const SizedBox(width: 6), + ], + Flexible( + child: Semantics( + header: true, + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _handwritten( + 14, + 20, + FontWeight.w600, + palette.textSubheading, + ), + ), + ), + ), + const SizedBox(width: 7), + Tooltip( + message: count == 1 ? '1 note' : '$count notes', + child: Text( + '$count', + style: _figtree( + AppTypeScale.small, + 16, + FontWeight.w600, + palette.textTertiary, + ).copyWith(fontFeatures: const [FontFeature.tabularFigures()]), + ), + ), + const Spacer(), + ?trailing, + ], + ), + ); + } +} + +/// "See all", at the end of the Pinned heading. +class SeeAllLink extends StatelessWidget { + const SeeAllLink({super.key, required this.onPressed}); + + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + return Semantics( + button: true, + label: 'See all pinned notes', + excludeSemantics: true, + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + onTap: onPressed, + behavior: HitTestBehavior.opaque, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'See all', + style: _figtree( + AppTypeScale.small, + 16, + FontWeight.w600, + palette.accentText, + ), + ), + const SizedBox(width: 1), + KapyIcon( + KapyIcons.chevronRightRounded, + size: 13, + strokeWidth: 2, + color: palette.accentText, + ), + ], + ), + ), + ), + ); + } +} + +/// The media filter and the list/cards switch, on one row under the search. +class NotesListControls extends StatelessWidget { + const NotesListControls({ + super.key, + required this.media, + required this.onMediaChanged, + required this.cards, + required this.onCardsChanged, + }); + + final Set media; + final ValueChanged> onMediaChanged; + final bool cards; + final ValueChanged onCardsChanged; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + Widget segment(bool forCards) { + final on = cards == forCards; + return Tooltip( + message: forCards ? 'Card view' : 'List view', + child: Semantics( + button: true, + selected: on, + label: forCards ? 'Cards' : 'List', + excludeSemantics: true, + child: MouseRegion( + cursor: on ? MouseCursor.defer : SystemMouseCursors.click, + child: GestureDetector( + key: ValueKey( + forCards ? 'sidebar-view-cards' : 'sidebar-view-list', + ), + onTap: on ? null : () => onCardsChanged(forCards), + child: Container( + width: 26, + height: 24, + decoration: on + ? BoxDecoration( + color: palette.selectedBackground, + borderRadius: BorderRadius.circular(7), + boxShadow: const [ + BoxShadow( + color: Color(0x4D000000), + offset: Offset(0, 1), + blurRadius: 2, + ), + ], + ) + : null, + alignment: Alignment.center, + child: KapyIcon( + forCards + ? KapyIcons.gridViewRounded + : KapyIcons.listViewRounded, + size: 14, + strokeWidth: 1.8, + color: on ? palette.textPrimary : palette.textTertiary, + ), + ), + ), + ), + ), + ); + } + + return Row( + children: [ + Flexible( + child: _MediaFilter(ticked: media, onChanged: onMediaChanged), + ), + const SizedBox(width: 4), + const Spacer(), + Container( + padding: const EdgeInsets.all(2), + decoration: BoxDecoration( + color: palette.cardBackground, + borderRadius: BorderRadius.circular(9), + ), + child: Row( + children: [segment(false), const SizedBox(width: 2), segment(true)], + ), + ), + ], + ); + } +} + +/// One "All media" dropdown: every kind ticked by default, and unticking +/// kinds narrows the list to notes holding a kind still ticked. +class _MediaFilter extends StatefulWidget { + const _MediaFilter({required this.ticked, required this.onChanged}); + + final Set ticked; + final ValueChanged> onChanged; + + @override + State<_MediaFilter> createState() => _MediaFilterState(); +} + +class _MediaFilterState extends State<_MediaFilter> { + final _menu = OverlayPortalController(); + final _link = LayerLink(); + + bool get _all => widget.ticked.length == NoteMedia.values.length; + + void _toggle() => setState(_menu.isShowing ? _menu.hide : _menu.show); + + void _close() { + if (_menu.isShowing) setState(_menu.hide); + } + + /// A kind is unticked only while another stays ticked: a list narrowed to + /// nothing would look like a library that had lost its notes. + void _tick(NoteMedia? media) { + final ticked = widget.ticked; + if (media == null) { + if (!_all) widget.onChanged(NoteMedia.values.toSet()); + return; + } + if (!ticked.contains(media)) { + widget.onChanged({...ticked, media}); + } else if (ticked.length > 1) { + widget.onChanged({...ticked}..remove(media)); + } + } + + Widget _button({ + required bool open, + required bool narrowed, + required String label, + required Color ink, + required bool roomy, + }) { + final palette = context.palette; + return Semantics( + button: true, + expanded: open, + label: 'Media filter, $label', + excludeSemantics: true, + child: MouseRegion( + cursor: SystemMouseCursors.click, + child: GestureDetector( + key: const ValueKey('sidebar-media-filter'), + onTap: _toggle, + behavior: HitTestBehavior.opaque, + child: Container( + height: 28, + padding: roomy + ? const EdgeInsets.only(left: 9, right: 8) + : const EdgeInsets.symmetric(horizontal: 6), + decoration: BoxDecoration( + color: narrowed + ? palette.tonalBackground + : palette.controlBackground, + border: Border.all( + color: open + ? palette.selectedBorder + : narrowed + ? palette.tonalKeyBackground + : palette.controlBorder, + ), + borderRadius: BorderRadius.circular(9), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + KapyIcon( + KapyIcons.filterRounded, + size: 14, + strokeWidth: 1.8, + color: narrowed ? ink : palette.textSecondary, + ), + if (roomy) ...[ + const SizedBox(width: 6), + Flexible( + child: Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: _figtree( + AppTypeScale.body, + 16, + FontWeight.w600, + ink, + ), + ), + ), + const SizedBox(width: 6), + KapyIcon( + KapyIcons.chevronDownRounded, + size: 13, + strokeWidth: 2, + color: narrowed + ? palette.tonalKeyText + : palette.textTertiary, + ), + ], + ], + ), + ), + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final palette = context.palette; + final open = _menu.isShowing; + final narrowed = !_all; + final label = narrowed + ? [ + for (final media in NoteMedia.values) + if (widget.ticked.contains(media)) media.label, + ].join(', ') + : 'All media'; + final ink = narrowed ? palette.tonalForeground : palette.textSubheading; + final button = LayoutBuilder( + // A list dragged to its narrowest keeps the filter's icon, which still + // opens the menu and still turns sage when the list is narrowed. + builder: (context, constraints) => constraints.maxWidth < 28 + ? const SizedBox.shrink() + : _button( + open: open, + narrowed: narrowed, + label: label, + ink: ink, + roomy: constraints.maxWidth >= 72, + ), + ); + + return TapRegion( + groupId: _menu, + onTapOutside: (_) => _close(), + child: CompositedTransformTarget( + link: _link, + child: OverlayPortal( + controller: _menu, + overlayChildBuilder: (context) => Align( + alignment: Alignment.topLeft, + child: CompositedTransformFollower( + link: _link, + targetAnchor: Alignment.bottomLeft, + offset: const Offset(0, 8), + child: TapRegion( + groupId: _menu, + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.escape): _close, + }, + child: Focus( + autofocus: true, + child: _MediaMenu(ticked: widget.ticked, onTick: _tick), + ), + ), + ), + ), + ), + child: button, + ), + ), + ); + } +} + +class _MediaMenu extends StatelessWidget { + const _MediaMenu({required this.ticked, required this.onTick}); + + final Set ticked; + + /// Null for All media. + final ValueChanged onTick; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + return Container( + key: const ValueKey('media-filter-menu'), + width: 200, + padding: const EdgeInsets.all(6), + decoration: BoxDecoration( + color: palette.controlBackground, + border: Border.all(color: palette.separator), + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Color(0x80000000), + offset: Offset(0, 12), + blurRadius: 28, + spreadRadius: -14, + ), + ], + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _MediaMenuRow( + key: const ValueKey('media-filter-all'), + label: 'All media', + ticked: ticked.length == NoteMedia.values.length, + onTap: () => onTick(null), + ), + Container( + height: 1, + margin: const EdgeInsets.symmetric(horizontal: 6, vertical: 4), + color: palette.separator, + ), + for (final media in NoteMedia.values) ...[ + if (media != NoteMedia.values.first) const SizedBox(height: 1), + _MediaMenuRow( + key: ValueKey('media-filter-${media.name}'), + label: media.label, + icon: media.icon, + ticked: ticked.contains(media), + onTap: () => onTick(media), + ), + ], + ], + ), + ); + } +} + +class _MediaMenuRow extends StatefulWidget { + const _MediaMenuRow({ + super.key, + required this.label, + required this.ticked, + required this.onTap, + this.icon, + }); + + final String label; + final KapyIconData? icon; + final bool ticked; + final VoidCallback onTap; + + @override + State<_MediaMenuRow> createState() => _MediaMenuRowState(); +} + +class _MediaMenuRowState extends State<_MediaMenuRow> { + bool _hovering = false; + + @override + Widget build(BuildContext context) { + final palette = context.palette; + final icon = widget.icon; + return Semantics( + checked: widget.ticked, + label: widget.label, + excludeSemantics: true, + child: MouseRegion( + cursor: SystemMouseCursors.click, + onEnter: (_) => setState(() => _hovering = true), + onExit: (_) => setState(() => _hovering = false), + child: GestureDetector( + onTap: widget.onTap, + behavior: HitTestBehavior.opaque, + child: Container( + height: 30, + padding: const EdgeInsets.symmetric(horizontal: 8), + decoration: BoxDecoration( + color: _hovering ? palette.hover : null, + borderRadius: BorderRadius.circular(7), + ), + child: Row( + children: [ + _PickBox(checked: widget.ticked), + const SizedBox(width: 9), + if (icon != null) ...[ + KapyIcon( + icon, + size: 15, + strokeWidth: 1.8, + color: palette.textSecondary, + ), + const SizedBox(width: 9), + ], + Text( + widget.label, + style: _figtree( + AppTypeScale.control, + 16, + FontWeight.w500, + palette.textSubheading, + ), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/ui/sidebar.dart b/lib/ui/sidebar.dart index 461f989..48a2597 100644 --- a/lib/ui/sidebar.dart +++ b/lib/ui/sidebar.dart @@ -7,6 +7,7 @@ import '../core/editor_font.dart'; import '../core/platform.dart'; import '../core/theme.dart'; import '../core/toast.dart'; +import '../calc/engine.dart'; import '../data/note.dart'; import '../data/shortcut_prefs.dart'; import '../data/update_checker.dart'; @@ -26,6 +27,7 @@ import 'editor_panes.dart'; import 'installed_version.dart'; import 'keycap.dart'; import 'member_avatars.dart'; +import 'notes_list.dart'; import 'safety_dialogs.dart'; import 'sidebar_timestamp.dart'; import 'streak_badge.dart'; @@ -142,6 +144,14 @@ class Sidebar extends StatelessWidget { this.onTabChanged, this.windowBar, this.emptyMessage, + this.engine, + this.now = DateTime.now, + this.cards = false, + this.onCardsChanged, + this.mediaFilter, + this.onMediaFilterChanged, + this.pinnedOnly = false, + this.onPinnedOnlyChanged, }); /// The notes to list, already narrowed to [tab] while the tabs are shown. @@ -266,9 +276,32 @@ class Sidebar extends StatelessWidget { /// still says so. final String? emptyMessage; + /// Works out the sums a card or row shows under a note's title. + final CalcEngine? engine; + + /// The clock a note's "Today" and "Sat" are told by. + final DateTime Function() now; + + /// Whether the list beside the rail draws sticky cards rather than rows. + final bool cards; + final ValueChanged? onCardsChanged; + + /// The kinds of media the list beside the rail is narrowed to, every kind + /// when it is not. Null leaves the filter out, as the compact list does. + final Set? mediaFilter; + final ValueChanged>? onMediaFilterChanged; + + /// Whether the list is showing every pinned note, after See all, rather + /// than the four most recent over the rest. + final bool pinnedOnly; + final ValueChanged? onPinnedOnlyChanged; + @override Widget build(BuildContext context) { final palette = context.palette; + final mediaFilter = this.mediaFilter; + final onMediaFilterChanged = this.onMediaFilterChanged; + final onCardsChanged = this.onCardsChanged; // Solid, rather than the GlassSurface the toolbar and footer use: the // notes list stays put whatever the window is doing behind it. See @@ -298,7 +331,22 @@ class Sidebar extends StatelessWidget { focusNode: searchFocusNode, shortcut: searchShortcut, belowTabs: _showsTabs, + besideRail: _besideRail, + pinnedOnly: pinnedOnly, ), + if (_besideRail && + mediaFilter != null && + onMediaFilterChanged != null && + onCardsChanged != null) + Padding( + padding: const EdgeInsets.fromLTRB(18, 0, 18, 12), + child: NotesListControls( + media: mediaFilter, + onMediaChanged: onMediaFilterChanged, + cards: cards, + onCardsChanged: onCardsChanged, + ), + ), if (archiveMode && (notes.isNotEmpty || selecting)) _ArchiveActions( selecting: selecting, @@ -333,6 +381,8 @@ class Sidebar extends StatelessWidget { archiveShortcut: archiveShortcut, child: notes.isEmpty ? _buildEmpty(context) + : _besideRail + ? _buildBesideRail(context) : _grouped ? _buildGrouped(context) : _buildUngrouped(context), @@ -541,7 +591,11 @@ extension on Sidebar { /// below the current row. void _moveSelected(int delta) { if (selecting) return; - final ordered = _grouped ? _noteGroups.displayOrder : notes; + final ordered = _besideRail + ? _railOrder + : _grouped + ? _noteGroups.displayOrder + : notes; if (ordered.length < 2) return; final current = ordered.indexWhere((note) => note.id == selectedId); final next = current < 0 @@ -561,9 +615,13 @@ extension on Sidebar { Note note, { required bool shared, bool pinned = false, + NoteRowStyle style = NoteRowStyle.compact, }) => NoteRow( key: ValueKey(note.id), note: note, + style: style, + engine: engine, + now: now, query: query, displayTime: displayTime, selected: note.id == selectedId, @@ -618,6 +676,216 @@ extension on Sidebar { tab: _tabbed ? tab : null, ); + /// The pinned notes the list beside the rail shows over the rest: the four + /// most recent, unless See all or a search asks for every one. + List _shownPinned(SidebarNoteGroups groups) => + pinnedOnly || query.trim().isNotEmpty + ? groups.pinned + : groups.pinned.take(_pinnedPreview).toList(); + + static const _pinnedPreview = 4; + + List get _railOrder { + final groups = _noteGroups; + if (pinnedOnly) return groups.pinned; + return [ + ..._shownPinned(groups), + for (final id in groups.spaceOrder) ...groups.bySpace[id]!, + ...groups.mine, + ]; + } + + /// The list beside the spaces rail: Pinned, then each shared space, then + /// Notes, as sticky cards two to a row or as rows, fading out at the foot. + Widget _buildBesideRail(BuildContext context) { + final palette = context.palette; + final groups = _noteGroups; + final pinned = _shownPinned(groups); + final rows = []; + final style = cards ? NoteRowStyle.card : NoteRowStyle.row; + final onPinnedOnlyChanged = this.onPinnedOnlyChanged; + + void gap(double height) => rows.add((_) => SizedBox(height: height)); + + void heading(Widget heading) { + if (rows.isNotEmpty) gap(18); + rows.add( + (_) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 18), + child: heading, + ), + ); + gap(cards ? 12 : 4); + } + + void section(Iterable notes, {bool pinned = false}) { + final list = notes.toList(); + Widget note(Note note) => _row( + note, + shared: sharing != null && note.isShared, + pinned: pinned, + style: style, + ); + if (!cards) { + for (final (index, each) in list.indexed) { + if (index > 0) gap(2); + rows.add( + (_) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: note(each), + ), + ); + } + return; + } + for (var index = 0; index < list.length; index += 2) { + if (index > 0) gap(12); + final pair = list.skip(index).take(2).toList(); + rows.add( + (context) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 18), + child: SizedBox( + height: AppControlMetrics.scaleBar(context, NoteCardFace.height), + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded(child: note(pair.first)), + const SizedBox(width: 12), + Expanded( + child: pair.length > 1 ? note(pair.last) : const SizedBox(), + ), + ], + ), + ), + ), + ); + } + } + + final pin = KapyIcon( + KapyIcons.pinOutlined, + size: 15, + strokeWidth: 1.9, + color: palette.clay, + ); + if (_specialMode) { + section(notes); + } else if (pinnedOnly) { + heading( + NotesListHeading( + label: 'Pinned', + count: groups.pinned.length, + height: 22, + leading: Row( + mainAxisSize: MainAxisSize.min, + children: [ + CompactIconButton( + key: const ValueKey('sidebar-pinned-back'), + tooltip: 'Back to all notes', + extent: 22, + foregroundColor: palette.textSecondary, + onPressed: onPinnedOnlyChanged == null + ? null + : () => onPinnedOnlyChanged(false), + icon: const KapyIcon( + KapyIcons.chevronLeftRounded, + size: 13, + strokeWidth: 2, + ), + ), + const SizedBox(width: 6), + pin, + ], + ), + ), + ); + section(groups.pinned, pinned: true); + } else { + if (pinned.isNotEmpty) { + heading( + NotesListHeading( + key: const ValueKey('sidebar-pinned-heading'), + label: 'Pinned', + count: groups.pinned.length, + height: 22, + leading: pin, + trailing: + pinned.length < groups.pinned.length && + onPinnedOnlyChanged != null + ? SeeAllLink( + key: const ValueKey('sidebar-see-all-pinned'), + onPressed: () => onPinnedOnlyChanged(true), + ) + : null, + ), + ); + section(pinned, pinned: true); + } + for (final id in groups.spaceOrder) { + heading( + _SpaceHeader( + key: ValueKey('space-header-$id'), + space: sharing?.spaceById(id), + currentUserId: sharing?.userId ?? '', + present: { + for (final note in groups.bySpace[id]!) + for (final person in collaborators[note.id] ?? const []) + person.userId, + }, + attention: + id != null && + (sharing?.trust.warningsFor(id).isNotEmpty ?? false), + onTap: id == null || onOpenSpace == null + ? null + : () => onOpenSpace!(id), + ), + ); + section(groups.bySpace[id]!); + } + if (groups.mine.isNotEmpty || groups.pinned.isEmpty) { + heading( + NotesListHeading( + key: const ValueKey('sidebar-notes-heading'), + label: groups.hasSharedSections && !_tabbed ? 'My notes' : 'Notes', + count: groups.mine.length, + ), + ); + section(groups.mine); + } + } + + return Stack( + children: [ + ListView.builder( + padding: const EdgeInsets.only(top: 4, bottom: 40), + itemCount: rows.length, + itemBuilder: (context, index) => rows[index](context), + ), + Positioned( + left: 0, + right: 0, + bottom: 0, + height: 64, + child: IgnorePointer( + child: DecoratedBox( + decoration: BoxDecoration( + gradient: LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + palette.sidebarColor.withValues(alpha: 0), + palette.sidebarColor, + ], + stops: const [0, 0.85], + ), + ), + ), + ), + ), + ], + ); + } + Widget _buildGrouped(BuildContext context) { final groups = _noteGroups; final pinned = groups.pinned; @@ -2193,12 +2461,21 @@ class _SearchField extends StatefulWidget { this.focusNode, this.shortcut, this.belowTabs = false, + this.besideRail = false, + this.pinnedOnly = false, }); /// Sits under the tabs rather than the title bar, and needs less room /// above it to read as part of the same header. final bool belowTabs; + /// Drawn as the list beside the spaces rail draws it: a deeper field with + /// its shortcut on a keycap. + final bool besideRail; + + /// Searching the pinned notes only, after See all. + final bool pinnedOnly; + final String query; final ValueChanged onChanged; @@ -2236,9 +2513,96 @@ class _SearchFieldState extends State<_SearchField> { super.dispose(); } + void _clear() { + _controller.clear(); + widget.onChanged(''); + } + + Widget _buildBesideRail(BuildContext context) { + final palette = context.palette; + final shortcut = widget.shortcut; + final hint = widget.archiveMode + ? 'Find in Archive…' + : widget.hiddenMode + ? 'Find in Hidden…' + : widget.pinnedOnly + ? 'Find in pinned…' + : 'Find a note…'; + return Padding( + padding: const EdgeInsets.fromLTRB(18, 0, 18, 12), + child: Container( + key: const ValueKey('sidebar-search-box'), + height: 40, + padding: const EdgeInsets.only(left: 14, right: 10), + decoration: BoxDecoration( + color: palette.surfaceBackground, + border: Border.all(color: palette.controlBorder, width: 1.5), + borderRadius: BorderRadius.circular(12), + boxShadow: const [ + BoxShadow( + color: Color(0x4D000000), + offset: Offset(0, 1), + blurRadius: 2, + ), + ], + ), + child: Row( + children: [ + KapyIcon( + KapyIcons.searchRounded, + size: 16, + strokeWidth: 1.8, + color: palette.textSecondary, + ), + const SizedBox(width: 9), + Expanded( + child: TextField( + key: const ValueKey('sidebar-search-field'), + controller: _controller, + focusNode: widget.focusNode, + onChanged: widget.onChanged, + textInputAction: TextInputAction.search, + style: TextStyle(fontSize: 14, color: palette.textPrimary), + cursorHeight: 16, + decoration: InputDecoration.collapsed( + hintText: hint, + hintStyle: TextStyle( + fontSize: 14, + color: palette.textTertiary, + ), + ), + ), + ), + if (widget.query.isNotEmpty) + CompactIconButton( + tooltip: 'Clear search', + extent: 20, + foregroundColor: palette.textTertiary, + onPressed: _clear, + icon: KapyIcon( + KapyIcons.cancelRounded, + size: AppControlMetrics.iconAdornment, + ), + ) + else if (shortcut != null) + Tooltip( + message: 'Global search · ${shortcut.displayLabel}', + child: Semantics( + label: 'Global search shortcut ${shortcut.displayLabel}', + excludeSemantics: true, + child: Keycap(shortcut.keycapLabel), + ), + ), + ], + ), + ), + ); + } + @override Widget build(BuildContext context) { final palette = context.palette; + if (widget.besideRail) return _buildBesideRail(context); return Padding( // On a desktop the field keeps the sidebar's 12pt gutter, the edge the @@ -2293,10 +2657,7 @@ class _SearchFieldState extends State<_SearchField> { tooltip: 'Clear search', extent: AppControlMetrics.fieldAdornmentSlot, foregroundColor: palette.textTertiary, - onPressed: () { - _controller.clear(); - widget.onChanged(''); - }, + onPressed: _clear, icon: KapyIcon( KapyIcons.cancelRounded, size: AppControlMetrics.iconAdornment, @@ -2370,6 +2731,10 @@ class _NoteActionChoice { final bool destructive; } +/// How a [NoteRow] draws its note: the compact list's row, or the desktop +/// list's row or sticky card beside the spaces rail. +enum NoteRowStyle { compact, row, card } + /// One row in the note list. class NoteRow extends StatefulWidget { const NoteRow({ @@ -2398,9 +2763,19 @@ class NoteRow extends StatefulWidget { this.selecting = false, this.checked = false, this.onToggleChecked, + this.style = NoteRowStyle.compact, + this.engine, + this.now = DateTime.now, }); final Note note; + final NoteRowStyle style; + + /// Works out the sum a card or row shows under the title. + final CalcEngine? engine; + + /// The clock the card's date is told by. + final DateTime Function() now; final String query; final DateTime Function(DateTime) displayTime; final bool selected; @@ -2676,7 +3051,14 @@ class _NoteRowState extends State { if (AppPlatform.isMobile) { choice = await _showTouchActions(context, actions); } else { - final row = this.context.findRenderObject() as RenderBox?; + // A card is narrower than the menu, so beside the rail the menu keeps + // to the whole list rather than to the note it belongs to. + final row = + (widget.style == NoteRowStyle.compact + ? this.context + : Scrollable.maybeOf(this.context)?.context ?? this.context) + .findRenderObject() + as RenderBox?; final rowOrigin = row?.localToGlobal(Offset.zero); final preferredBounds = row == null || rowOrigin == null ? null @@ -2712,6 +3094,71 @@ class _NoteRowState extends State { if (choice == 'open-side') widget.onOpenToSide?.call(); } + /// The desktop list's row or card, with its actions button while the + /// pointer is over it. + Widget _boardFace({required String? snippet, required bool hasMenu}) { + final note = widget.note; + final people = widget.collaborators; + final date = people.isEmpty + ? SidebarTimestamp.glance( + note.updatedAt, + now: widget.now(), + displayTime: widget.displayTime, + today: widget.style == NoteRowStyle.card, + ) + : typingStatusText([ + for (final person in people) + if (person.typing) person.name, + ]) ?? + presenceStatusText([for (final person in people) person.name])!; + final glance = NoteGlance.of(note, widget.engine); + final picking = widget.selecting ? widget.checked : null; + final ringed = widget.openElsewhere && !widget.selected; + final face = widget.style == NoteRowStyle.card + ? NoteCardFace( + note: note, + glance: glance, + date: date, + snippet: snippet, + selected: widget.selected, + hovering: _hovering, + ringed: ringed, + locked: widget.locked, + shared: widget.shared, + picking: picking, + ) + : NoteListRowFace( + note: note, + glance: glance, + date: date, + snippet: snippet, + selected: widget.selected, + hovering: _hovering, + ringed: ringed, + locked: widget.locked, + shared: widget.shared, + picking: picking, + ); + if (!hasMenu || !_hovering) return face; + return Stack( + children: [ + face, + Positioned( + top: 4, + right: 4, + child: Builder( + builder: (buttonContext) => _RowAction( + key: ValueKey('note-actions-${note.id}'), + icon: KapyIcons.moreVerticalRounded, + tooltip: 'Note actions', + onPressed: () => _showActionsFromButton(buttonContext), + ), + ), + ), + ], + ); + } + void _showActionsFromButton(BuildContext context) { final box = context.findRenderObject() as RenderBox?; final position = box == null @@ -2743,8 +3190,101 @@ class _NoteRowState extends State { widget.onDelete != null || widget.onShare != null); + final compact = widget.style == NoteRowStyle.compact; + final face = compact + ? AnimatedContainer( + duration: const Duration(milliseconds: 120), + curve: Curves.easeOutCubic, + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), + decoration: BoxDecoration( + color: widget.selected || (widget.selecting && widget.checked) + ? palette.selectedBackground + : (_hovering ? palette.hover : Colors.transparent), + borderRadius: BorderRadius.circular(7), + ), + // Open in another pane: ringed rather than filled, so it reads + // as on screen without competing with the focused note's row. + // Painted over the row rather than around it, so nothing moves. + foregroundDecoration: widget.openElsewhere && !widget.selected + ? BoxDecoration( + border: Border.all(color: palette.selectedBorder), + borderRadius: BorderRadius.circular(7), + ) + : null, + child: Row( + children: [ + if (widget.selecting) ...[ + KapyIcon( + widget.checked + ? KapyIcons.checkCircleRounded + : KapyIcons.circleOutlined, + size: AppControlMetrics.iconControl, + color: widget.checked + ? Theme.of(context).colorScheme.primary + : palette.textTertiary, + ), + const SizedBox(width: 10), + ], + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + widget.note.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: AppTypeScale.control, + fontWeight: FontWeight.w400, + color: foreground, + ), + ), + const SizedBox(height: 2), + if (snippet != null) + Text( + snippet, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: AppTypeScale.caption, + color: secondary, + ), + ) + else + _UpdatedAtMetadata( + updatedAt: widget.note.updatedAt, + displayTime: widget.displayTime, + shared: widget.shared, + locked: widget.locked, + collaborators: widget.collaborators, + sharedWith: widget.sharedWith, + currentUserId: widget.currentUserId, + ), + ], + ), + ), + // One discoverable affordance owns every secondary action. + // It stays visible on every platform; right-click and long + // press remain shortcuts to the same labeled choices. + if (!widget.selecting && hasMenu) ...[ + const SizedBox(width: 4), + Builder( + builder: (buttonContext) => _RowAction( + key: ValueKey('note-actions-${widget.note.id}'), + icon: KapyIcons.moreVerticalRounded, + tooltip: 'Note actions', + onPressed: () => _showActionsFromButton(buttonContext), + ), + ), + ], + ], + ), + ) + : _boardFace(snippet: snippet, hasMenu: hasMenu); + final row = Padding( - padding: const EdgeInsets.symmetric(vertical: 1), + padding: EdgeInsets.symmetric(vertical: compact ? 1 : 0), child: MouseRegion( // The row is the main click target in the sidebar; matching the // settings rows, which are InkWells and already say so. @@ -2768,95 +3308,7 @@ class _NoteRowState extends State { : (details) => _showContextMenu(context, details.globalPosition), behavior: HitTestBehavior.opaque, - child: AnimatedContainer( - duration: const Duration(milliseconds: 120), - curve: Curves.easeOutCubic, - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5), - decoration: BoxDecoration( - color: widget.selected || (widget.selecting && widget.checked) - ? palette.selectedBackground - : (_hovering ? palette.hover : Colors.transparent), - borderRadius: BorderRadius.circular(7), - ), - // Open in another pane: ringed rather than filled, so it reads - // as on screen without competing with the focused note's row. - // Painted over the row rather than around it, so nothing moves. - foregroundDecoration: widget.openElsewhere && !widget.selected - ? BoxDecoration( - border: Border.all(color: palette.selectedBorder), - borderRadius: BorderRadius.circular(7), - ) - : null, - child: Row( - children: [ - if (widget.selecting) ...[ - KapyIcon( - widget.checked - ? KapyIcons.checkCircleRounded - : KapyIcons.circleOutlined, - size: AppControlMetrics.iconControl, - color: widget.checked - ? Theme.of(context).colorScheme.primary - : palette.textTertiary, - ), - const SizedBox(width: 10), - ], - Expanded( - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Text( - widget.note.title, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: AppTypeScale.control, - fontWeight: FontWeight.w400, - color: foreground, - ), - ), - const SizedBox(height: 2), - if (snippet != null) - Text( - snippet, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: TextStyle( - fontSize: AppTypeScale.caption, - color: secondary, - ), - ) - else - _UpdatedAtMetadata( - updatedAt: widget.note.updatedAt, - displayTime: widget.displayTime, - shared: widget.shared, - locked: widget.locked, - collaborators: widget.collaborators, - sharedWith: widget.sharedWith, - currentUserId: widget.currentUserId, - ), - ], - ), - ), - // One discoverable affordance owns every secondary action. - // It stays visible on every platform; right-click and long - // press remain shortcuts to the same labeled choices. - if (!widget.selecting && hasMenu) ...[ - const SizedBox(width: 4), - Builder( - builder: (buttonContext) => _RowAction( - key: ValueKey('note-actions-${widget.note.id}'), - icon: KapyIcons.moreVerticalRounded, - tooltip: 'Note actions', - onPressed: () => _showActionsFromButton(buttonContext), - ), - ), - ], - ], - ), - ), + child: face, ), ), ), diff --git a/lib/ui/sidebar_timestamp.dart b/lib/ui/sidebar_timestamp.dart index 7ee6e86..d78e124 100644 --- a/lib/ui/sidebar_timestamp.dart +++ b/lib/ui/sidebar_timestamp.dart @@ -32,4 +32,43 @@ class SidebarTimestamp { final minute = displayed.minute.toString().padLeft(2, '0'); return '${displayed.day} ${_months[displayed.month - 1]} ${displayed.year} · $hour:$minute'; } + + static const _weekdays = [ + 'Mon', + 'Tue', + 'Wed', + 'Thu', + 'Fri', + 'Sat', + 'Sun', + ]; + + /// When a note was changed, as briefly as the notes list can say it: the + /// time today, Yesterday, the weekday within the week, then the date, with + /// the year only when it is not this one. [today] spells out "Today" before + /// the time, for a card, where the time stands without a column of dates + /// around it. + static String glance( + DateTime timestamp, { + required DateTime now, + required DateTime Function(DateTime) displayTime, + bool today = false, + }) { + final shown = displayTime(timestamp); + final current = displayTime(now); + final days = DateTime.utc( + current.year, + current.month, + current.day, + ).difference(DateTime.utc(shown.year, shown.month, shown.day)).inDays; + if (days <= 0) { + final hour = shown.hour.toString().padLeft(2, '0'); + final minute = shown.minute.toString().padLeft(2, '0'); + return today ? 'Today · $hour:$minute' : '$hour:$minute'; + } + if (days == 1) return 'Yesterday'; + if (days < 7) return _weekdays[shown.weekday - 1]; + final day = '${shown.day} ${_months[shown.month - 1]}'; + return shown.year == current.year ? day : '$day ${shown.year}'; + } } diff --git a/test/app_test.dart b/test/app_test.dart index ef137a9..2b6a2f3 100644 --- a/test/app_test.dart +++ b/test/app_test.dart @@ -38,6 +38,7 @@ import 'package:kapy_notes/ui/keycap.dart'; import 'package:kapy_notes/core/window_chrome.dart'; import 'package:kapy_notes/ui/settings_dialog.dart'; import 'package:kapy_notes/ui/settings_rows.dart'; +import 'package:kapy_notes/ui/notes_list.dart'; import 'package:kapy_notes/ui/sidebar.dart'; import 'package:kapy_notes/ui/sidebar_swipe.dart'; import 'package:kapy_notes/ui/spaces_rail.dart'; @@ -222,8 +223,23 @@ Future showNotesList(WidgetTester tester) async { await tester.pumpAndSettle(); } +/// Rests the pointer on a note in the list, where the desktop list shows the +/// note's actions button. +Future hoverNote(WidgetTester tester, String noteId) async { + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer( + location: tester.getCenter( + find.byWidgetPredicate((w) => w is NoteRow && w.note.id == noteId), + ), + ); + await tester.pumpAndSettle(); + return mouse; +} + Future openNoteActions(WidgetTester tester, String noteId) async { + final mouse = await hoverNote(tester, noteId); await tester.tap(find.byKey(ValueKey('note-actions-$noteId'))); + await mouse.removePointer(); await tester.pumpAndSettle(); } @@ -737,20 +753,9 @@ void main() { closeTo(12, 0.01), ); - final noteRow = find.byType(NoteRow).first; - expect(tester.getSize(noteRow).height, 54); expect( - tester - .getSize( - find - .descendant( - of: noteRow, - matching: find.byType(AnimatedContainer), - ) - .first, - ) - .height, - 52, + tester.getSize(find.byType(NoteRow).first).height, + NoteCardFace.height, ); }); @@ -2441,7 +2446,7 @@ void main() { findsOneWidget, ); final menuRect = tester.getRect(menu); - final rowRect = tester.getRect(find.byType(NoteRow).first); + final rowRect = tester.getRect(find.byType(Sidebar)); expect(menuRect.width, lessThanOrEqualTo(208)); expect(menuRect.left, greaterThanOrEqualTo(rowRect.left)); expect(menuRect.right, lessThanOrEqualTo(rowRect.right)); @@ -2560,7 +2565,7 @@ void main() { await pumpApp(tester); final binding = shortcuts.bindingFor(ShortcutAction.findNotes)!; - final search = find.byKey(const ValueKey('sidebar-search-field')); + final search = find.byKey(const ValueKey('sidebar-search-box')); final field = tester.getRect(search); final searchKeycap = find.descendant( of: search, @@ -2579,7 +2584,7 @@ void main() { expect(field.right - keycap.right, lessThanOrEqualTo(12)); expect(keycap.center.dy, closeTo(field.center.dy, 1)); // The hint used to fill the field and leave the placeholder no width. - expect(tester.getSize(find.text('Search notes')).width, greaterThan(40)); + expect(tester.getSize(find.text('Find a note…')).width, greaterThan(40)); }, ); @@ -2912,9 +2917,9 @@ void main() { .map((row) => row.note.title) .toList(); expect(rowTitles(), ['Latest', 'Older']); - expect(find.text('2 Sep 2026 · 08:05'), findsOneWidget); - expect(find.text('1 Sep 2026 · 12:00'), findsOneWidget); - expect(find.widgetWithText(NoteRow, 'latest details'), findsNothing); + expect(find.text('Yesterday'), findsOneWidget); + expect(find.text('Tue'), findsOneWidget); + expect(find.widgetWithText(NoteRow, 'latest details'), findsOneWidget); await tester.tap(find.widgetWithText(NoteRow, 'Older')); await tester.pumpAndSettle(); @@ -2926,7 +2931,7 @@ void main() { expect(rowTitles(), ['Older', 'Latest']); expect(notes.notes.map((note) => note.id), ['older', 'latest']); - expect(find.text('3 Sep 2026 · 09:10'), findsOneWidget); + expect(find.text('Today · 09:10'), findsOneWidget); }); testWidgets('pins notes into a top section and allows unpinning', ( @@ -4027,7 +4032,9 @@ void main() { final note = notes.notes.single; expect(find.byKey(ValueKey('delete-note-${note.id}')), findsNothing); expect(find.byKey(const ValueKey('archive-delete-all')), findsNothing); + final mouse = await hoverNote(tester, note.id); expect(find.byKey(ValueKey('note-actions-${note.id}')), findsOneWidget); + await mouse.removePointer(); }); }); @@ -4945,6 +4952,94 @@ void main() { expect(find.byTooltip('1-day writing streak'), findsOneWidget); expect(find.byKey(const ValueKey('sidebar-streak')), findsNothing); }); + + testWidgets( + 'the media filter keeps the notes holding a kind still ticked', + (tester) async { + await notes.load(); + final at = DateTime(2026, 11, 16, 9); + notes.importNotes([ + Note(id: 'plain', body: 'Groceries', createdAt: at, updatedAt: at), + Note( + id: 'sketch', + body: 'Floor plan', + drawing: NoteDrawing.empty, + createdAt: at, + updatedAt: at, + ), + ]); + await pumpApp(tester); + final filter = find.byKey(const ValueKey('sidebar-media-filter')); + Future tick(String kind) async { + await tester.tap(find.byKey(ValueKey('media-filter-$kind'))); + await tester.pumpAndSettle(); + } + + await tester.tap(filter); + await tester.pumpAndSettle(); + await tick('voice'); + await tick('video'); + await tick('image'); + expect(rowTitles(tester), ['Floor plan']); + expect( + find.descendant(of: filter, matching: find.text('Drawing')), + findsOneWidget, + ); + + // The last kind ticked stays ticked: nothing ticked would read as a + // library that had lost its notes. + await tick('drawing'); + expect(rowTitles(tester), ['Floor plan']); + + await tick('all'); + expect(rowTitles(tester).toSet(), {'Groceries', 'Floor plan'}); + expect( + find.descendant(of: filter, matching: find.text('All media')), + findsOneWidget, + ); + expect(spaceCount(tester), '2'); + }, + ); + + testWidgets('Pinned shows four notes, and See all the rest', ( + tester, + ) async { + await notes.load(); + for (var i = 1; i <= 6; i++) { + notes.togglePinned(notes.create(body: 'Pinned $i').id); + } + await pumpApp(tester); + + expect(rowTitles(tester), hasLength(4)); + await tester.tap(find.byKey(const ValueKey('sidebar-see-all-pinned'))); + await tester.pumpAndSettle(); + expect(rowTitles(tester), hasLength(6)); + expect(find.text('Find in pinned…'), findsOneWidget); + + await tester.tap(find.byKey(const ValueKey('sidebar-pinned-back'))); + await tester.pumpAndSettle(); + expect(rowTitles(tester), hasLength(4)); + expect(find.text('Find a note…'), findsOneWidget); + }); + + testWidgets('the list and cards switch holds for the whole list', ( + tester, + ) async { + await notes.load(); + notes.togglePinned(notes.create(body: 'Pinned').id); + notes.create(body: 'Loose'); + await pumpApp(tester); + List styles() => tester + .widgetList(find.byType(NoteRow)) + .map((row) => row.style) + .toList(); + + expect(styles(), [NoteRowStyle.card, NoteRowStyle.card]); + await tester.tap(find.byKey(const ValueKey('sidebar-view-list'))); + await tester.pumpAndSettle(); + expect(styles(), [NoteRowStyle.row, NoteRowStyle.row]); + expect(prefs.noteCards, isFalse); + }); }); group('window chrome', () { diff --git a/test/golden_test.dart b/test/golden_test.dart index 793bfbf..3af0f8f 100644 --- a/test/golden_test.dart +++ b/test/golden_test.dart @@ -419,6 +419,12 @@ void main() { brightness: Brightness.dark, ); final note = goldenNotes.notes.single; + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer( + location: tester.getCenter(find.byKey(ValueKey(note.id)).first), + ); + addTearDown(mouse.removePointer); + await tester.pumpAndSettle(); await tester.tap(find.byKey(ValueKey('note-actions-${note.id}'))); await tester.pumpAndSettle(); await expectLater( diff --git a/test/goldens/desktop_dark.png b/test/goldens/desktop_dark.png index 6602e1c..f2d0b3f 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 82bb46d..230101f 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 16d1ada..78053b9 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 4fdd70b..a7726f0 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_editor_context_menu.png b/test/goldens/desktop_dark_editor_context_menu.png index fd7c211..27a09f7 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_empty.png b/test/goldens/desktop_dark_empty.png index cb9ba1a..6f4df58 100644 Binary files a/test/goldens/desktop_dark_empty.png and b/test/goldens/desktop_dark_empty.png differ diff --git a/test/goldens/desktop_dark_header_hover.png b/test/goldens/desktop_dark_header_hover.png index a2ac184..42be8f4 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 23a853e..cb4ecbe 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 df9e755..652619c 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_note_actions.png b/test/goldens/desktop_dark_note_actions.png index 68269dd..b2dce09 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 a8762bb..66bb9b3 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 3e94976..76551cb 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 index 8df24ae..1be27ab 100644 Binary files a/test/goldens/desktop_dark_results_divider_hover.png and b/test/goldens/desktop_dark_results_divider_hover.png differ diff --git a/test/goldens/desktop_dark_results_restore_hover.png b/test/goldens/desktop_dark_results_restore_hover.png index e7814c4..637b83f 100644 Binary files a/test/goldens/desktop_dark_results_restore_hover.png and b/test/goldens/desktop_dark_results_restore_hover.png differ diff --git a/test/goldens/desktop_dark_update_ready.png b/test/goldens/desktop_dark_update_ready.png index ffde3ce..93af8a2 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 950cf23..6f6f8fc 100644 Binary files a/test/goldens/desktop_light.png and b/test/goldens/desktop_light.png differ diff --git a/test/sidebar_timestamp_test.dart b/test/sidebar_timestamp_test.dart index 650c8ef..c38408e 100644 --- a/test/sidebar_timestamp_test.dart +++ b/test/sidebar_timestamp_test.dart @@ -21,4 +21,24 @@ void main() { '1 Sep 2026 · 14:45', ); }); + + test('glances at a date as briefly as the notes list can say it', () { + final now = DateTime.utc(2026, 11, 16, 11, 20); + String glance(DateTime at, {bool today = false}) => SidebarTimestamp.glance( + at, + now: now, + displayTime: (value) => value, + today: today, + ); + + expect(glance(DateTime.utc(2026, 11, 16, 9, 5)), '09:05'); + expect( + glance(DateTime.utc(2026, 11, 16, 9, 5), today: true), + 'Today · 09:05', + ); + expect(glance(DateTime.utc(2026, 11, 15, 23)), 'Yesterday'); + expect(glance(DateTime.utc(2026, 11, 14, 8)), 'Sat'); + expect(glance(DateTime.utc(2026, 11, 2, 8)), '2 Nov'); + expect(glance(DateTime.utc(2025, 12, 30, 8)), '30 Dec 2025'); + }); }