diff --git a/CLAUDE.md b/CLAUDE.md index f4a69d4..37c424e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -172,7 +172,13 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw for in-app controls and won't sample the desktop behind a window. - **The window drags only by its header.** `isMovableByWindowBackground` is off; `WindowMoveArea` (an `NSViewRepresentable` calling `window.performDrag`) is placed behind the header / collapsed - bar. This is what lets task rows be dragged to **reorder** without moving the window. + bar. This is what lets task rows be dragged to **reorder** without moving the window. The title is + plain text **inside** that handle, not a click target: the header row sits in the window's hidden + title-bar strip, where a title taking clicks let a double-click through to macOS's zoom. Renaming is + ⋯ › Rename… (or a new list), via `NoteController.requestRename`, which swaps in a field. +- **The hover reveal is an AppKit tracking area (`HoverArea`), not `.onHover`.** SwiftUI's hover often + didn't reveal the header controls until the note had been clicked into; `HoverArea`'s `.activeAlways` + tracking area goes by geometry alone. (Synthetic `mouseMoved` events drive neither, so tests can't.) - **Reorder uses a direct `DragGesture`, not system `.onDrag`.** System drag has a sluggish pickup; the gesture is immediate. The dragged block (row + subtree) lifts into an overlay (`LiftedRow`) and its head row turns into a ghost `DropPlaceholder` at the drop slot and level; @@ -189,9 +195,21 @@ panels**, and a few responsibilities are deliberately split across the AppKit/Sw are pure in `TaskOutline` (`dropLevels`: never adopt the row below; `levelSteps`: ~70% of an indent step to re-nest). Safe on macOS because scrolling is the wheel/trackpad, so click-drag doesn't fight the `ScrollView`. -- **Roll-up keeps the top edge fixed.** `NoteWindowManager.setCollapsed` resizes the panel to - `NoteLayout.collapsedHeight`, remembers the real height in `expandedHeights`, and - `scheduleFrameSave` persists the *expanded* height/origin while collapsed so nothing is lost. +- **Roll-up keeps the top edge fixed — or the bottom, near the screen's bottom.** + `NoteWindowManager.setCollapsed` resizes the panel to `NoteLayout.collapsedHeight` from the edge + `rolledFrame` picks (pure, tested) — and a bar let go near the bottom glides there too + (`NotePanel.performDrag` returns on mouse-up → `snapToBottom`) — remembers the real height in `expandedHeights`, and + `scheduleFrameSave` persists the *expanded* frame while collapsed so nothing is lost. The bar is + **frameless** (`NotePanel.setRolledUp`; it draws its own capsule) because macOS rounds a titled + window at a fixed 16pt that splits from a thin bar's fill. The bar **is** the note's top row + (`NoteHeaderView`: title + hover controls, `isRolledUp` adds the count and trims the controls), so the + roll is a pure window shade; `NoteView` drops the list only once the window is down to bar height + (`showsBar`). The roll is an `animator()` frame animation, not the blocking + `setFrame(_:display:animate:)` (SwiftUI only swapped the content after it); the system frame returns + before expanding and goes only after rolling up, since a titled window's shadow tracks a resize. The + bar has **no** shadow: a frameless window's traces the capsule with a dark rim that reads as a border. The content has `minHeight: 0` — the hosting view won't let the window be shorter than the + content's minimum (an expand jumped straight to ~150pt) — so the open note's minimum lives in + `windowWillResize`, which also locks the bar's height. - **Theming via roles, not raw colors.** `NoteColor.color(_:on:)` resolves a role (title/task/secondary/completed/checkbox) for a `Surface` (`.solid` uses per-theme tuned inks; `.glass` uses adaptive `.primary`/`.secondary`). Views read a resolved `NoteTheme`, never branch diff --git a/Sources/Tic/Controllers/NoteController.swift b/Sources/Tic/Controllers/NoteController.swift index 7f0df1a..61ed41f 100644 --- a/Sources/Tic/Controllers/NoteController.swift +++ b/Sources/Tic/Controllers/NoteController.swift @@ -133,6 +133,10 @@ final class NoteController { private(set) var pendingThumbnail: CGImage? /// Bumped to ask the quick-add field to take the keyboard (e.g. a paste with nothing focused). private(set) var quickAddFocusRequest = 0 + /// Bumped to ask the header to start renaming the note (a brand-new list starts out that way). + private(set) var renameRequest = 0 + + func requestRename() { renameRequest += 1 } /// Holds a pasted image in the quick-add, replacing any already waiting, and focuses the field. func stageImage(_ data: Data) { diff --git a/Sources/Tic/Views/HoverArea.swift b/Sources/Tic/Views/HoverArea.swift new file mode 100644 index 0000000..1618695 --- /dev/null +++ b/Sources/Tic/Views/HoverArea.swift @@ -0,0 +1,33 @@ +import AppKit +import SwiftUI + +/// Reports the pointer entering and leaving its frame, from an AppKit tracking area. A note's hover reveal +/// uses this, not SwiftUI's `.onHover`, which often didn't fire until the note had been clicked into (most of +/// the header row it reveals is the AppKit drag handle). A tracking area goes by geometry alone — whatever +/// view is under the pointer, key window or not, Tic active or not. It never takes a click. +struct HoverArea: NSViewRepresentable { + var onChange: (Bool) -> Void + + func makeNSView(context: Context) -> TrackingView { TrackingView(onChange: onChange) } + + func updateNSView(_ nsView: TrackingView, context: Context) { nsView.onChange = onChange } + + final class TrackingView: NSView { + var onChange: (Bool) -> Void + + init(onChange: @escaping (Bool) -> Void) { + self.onChange = onChange + super.init(frame: .zero) + addTrackingArea(NSTrackingArea( + rect: .zero, options: [.mouseEnteredAndExited, .activeAlways, .inVisibleRect], owner: self + )) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + + override func mouseEntered(with event: NSEvent) { onChange(true) } + override func mouseExited(with event: NSEvent) { onChange(false) } + override func hitTest(_ point: NSPoint) -> NSView? { nil } + } +} diff --git a/Sources/Tic/Views/ImageViewer.swift b/Sources/Tic/Views/ImageViewer.swift index 74401c5..f56a889 100644 --- a/Sources/Tic/Views/ImageViewer.swift +++ b/Sources/Tic/Views/ImageViewer.swift @@ -52,7 +52,7 @@ struct ImageViewer: View { } } - /// Mirrors `NoteHeaderView`: a control strip, the title, and the accent rule — and it's the drag handle. + /// Dressed like a note's header: its controls, the title, and the accent rule — and it's the drag handle. private var header: some View { VStack(alignment: .leading, spacing: 8) { HStack(spacing: 10) { diff --git a/Sources/Tic/Views/NoteBackground.swift b/Sources/Tic/Views/NoteBackground.swift index e1429a8..2a6e390 100644 --- a/Sources/Tic/Views/NoteBackground.swift +++ b/Sources/Tic/Views/NoteBackground.swift @@ -8,15 +8,18 @@ import AppKit struct NoteBackground: View { let color: NoteColor let material: NoteMaterial + /// The note's own corner rounding — only for a rolled-up bar, which has no system window frame to round it. + var cornerRadius: CGFloat = 0 var body: some View { + let shape = RoundedRectangle(cornerRadius: cornerRadius) switch material { case .solid: - color.fill + shape.fill(color.fill) case .glass: ZStack { - VisualEffectBackground(material: .popover, blending: .behindWindow) - color.fill.opacity(0.18) // a hint of the theme over the glass + VisualEffectBackground(material: .popover, blending: .behindWindow, cornerRadius: cornerRadius) + shape.fill(color.fill.opacity(0.18)) // a hint of the theme over the glass } } } @@ -26,12 +29,12 @@ struct NoteBackground: View { private struct VisualEffectBackground: NSViewRepresentable { let material: NSVisualEffectView.Material let blending: NSVisualEffectView.BlendingMode + let cornerRadius: CGFloat func makeNSView(context: Context) -> NSVisualEffectView { let view = NSVisualEffectView() - view.material = material - view.blendingMode = blending view.state = .active // keep the effect visible even when the window isn't key + updateNSView(view, context: context) return view } @@ -39,5 +42,19 @@ private struct VisualEffectBackground: NSViewRepresentable { nsView.material = material nsView.blendingMode = blending nsView.state = .active + nsView.maskImage = cornerRadius > 0 ? Self.roundedMask(radius: cornerRadius) : nil + } + + /// A stretchable rounded-rect mask: the way to round a behind-window effect view (layer masks don't apply). + private static func roundedMask(radius: CGFloat) -> NSImage { + let side = radius * 2 + 1 + let image = NSImage(size: NSSize(width: side, height: side), flipped: false) { rect in + NSColor.black.setFill() + NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).fill() + return true + } + image.capInsets = NSEdgeInsets(top: radius, left: radius, bottom: radius, right: radius) + image.resizingMode = .stretch + return image } } diff --git a/Sources/Tic/Views/NoteHeaderView.swift b/Sources/Tic/Views/NoteHeaderView.swift index 747a620..a20dea0 100644 --- a/Sources/Tic/Views/NoteHeaderView.swift +++ b/Sources/Tic/Views/NoteHeaderView.swift @@ -1,57 +1,107 @@ +import AppKit import SwiftUI -/// The hover-reveal control strip + editable title for a sticky note. Controls fade in/out via -/// `isRevealed` (driven by `NoteView`'s hover over the whole note), so the affordances stay -/// hidden until the pointer is on the note — keeping the small note uncluttered. +/// A sticky note's top row — the editable title, with roll-up / pin / close and a ⋯ options popover fading +/// in on the right while the pointer is on the note (`isRevealed`, driven by `NoteView`'s hover) — over an +/// accent rule. Rolled up, +/// the bar *is* this row (minus the rule, plus the open-task count), so rolling is a pure window shade. struct NoteHeaderView: View { @Bindable var controller: NoteController let theme: NoteTheme let isRevealed: Bool + /// Drawn as the rolled-up bar: the title can't be edited (a click drags, a double-click expands), and + /// hover shows only expand / pin / close. + var isRolledUp = false @Binding var titleText: String - @FocusState.Binding var titleFocused: Bool + /// The title is being renamed (owned by `NoteView`, which holds back outside title changes meanwhile). + @Binding var isRenaming: Bool - @State private var showColorPopover = false - @State private var showCompletedPopover = false + @State private var showOptions = false @State private var showClearConfirm = false - @State private var hoverClose = false private var note: Note { controller.note } + /// Controls stay up while the options popover is open: it's a separate window, so the pointer leaves + /// the note to reach it. + private var showsControls: Bool { isRevealed || showOptions || showClearConfirm } + var body: some View { - VStack(alignment: .leading, spacing: 8) { - controlStrip - .opacity(isRevealed ? 1 : 0) - .allowsHitTesting(isRevealed) - - TextField("", text: $titleText) - .textFieldStyle(.plain) - .font(.headline.weight(.semibold)) - .foregroundStyle(theme.title) - .focused($titleFocused) - .overlay(alignment: .leading) { - if titleText.isEmpty { - Text("Untitled List") - .font(.headline.weight(.semibold)) - .foregroundStyle(theme.secondary) - .padding(.leading, 2) // align with the field's text/caret inset - .allowsHitTesting(false) - } - } - .onSubmit { commitTitle() } - .onChange(of: titleFocused) { _, focused in - if !focused { commitTitle() } - } + VStack(alignment: .leading, spacing: 0) { + HStack(spacing: 8) { + titleField + Spacer(minLength: 0) + if isRolledUp { remainingCount } + if showsControls { controls.transition(.opacity) } + } + .frame(height: NoteLayout.collapsedHeight) // the rolled-up bar is exactly this row - Rectangle() - .fill(theme.accent.opacity(0.35)) - .frame(height: 1) + if !isRolledUp { + Rectangle() + .fill(theme.accent.opacity(0.35)) + .frame(height: 1) + .padding(.bottom, 8) + } } .padding(.horizontal, 16) - .padding(.top, 12) - .padding(.bottom, 8) - // The header is the window's drag handle; double-clicking its chrome rolls the note up. + // The header is the window's drag handle; double-clicking its chrome rolls the note up or down. .background(WindowMoveArea { controller.toggleCollapsed() }) + .help(isRolledUp ? "Drag to move · double-click to expand" : "") + .task(id: controller.renameRequest) { // also runs on appear, for a list that opens renaming + if controller.renameRequest > 0, !isRolledUp { isRenaming = true } + } + } + + /// Plain text that's part of the drag handle (a press drags, a double-click rolls up — in the window's + /// hidden title-bar strip, a title taking clicks let macOS zoom the window). Renaming — ⋯ › Rename…, or a + /// new list — swaps in an outlined `TitleField`: Return or clicking away saves, Esc restores the old name. + @ViewBuilder private var titleField: some View { + if isRenaming && !isRolledUp { + TitleField( + text: $titleText, + font: .systemFont(ofSize: NSFont.preferredFont(forTextStyle: .headline).pointSize, weight: .semibold), + color: NSColor(theme.title), + onEnd: { saved in + if !saved { titleText = note.title } + commitTitle() + isRenaming = false + } + ) + .overlay(alignment: .leading) { + if titleText.isEmpty { titleLabel.allowsHitTesting(false) } + } + .background( // drawn outside the field, so its text stays where the label's was + RoundedRectangle(cornerRadius: 5) + .fill(Color.white.opacity(0.45)) + .strokeBorder(theme.accent.opacity(0.7)) + .padding(.horizontal, -5) + .padding(.vertical, -2) + ) + } else { + titleLabel.allowsHitTesting(false) + } + } + + private var titleLabel: some View { + Text(titleText.isEmpty ? "Untitled List" : titleText) + .font(.headline.weight(.semibold)) + .foregroundStyle(titleText.isEmpty ? theme.secondary : theme.title) + .lineLimit(1) + .padding(.leading, 2) // where the field draws its text, so starting a rename doesn't shift it + } + + /// The rolled-up bar's count of tasks still to do. + @ViewBuilder private var remainingCount: some View { + let remaining = controller.tasks.filter { !$0.isDone }.count + if remaining > 0 { + Text("\(remaining)") + .font(.caption.weight(.semibold)) + .foregroundStyle(theme.secondary) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(Capsule().fill(theme.accent.opacity(0.18))) + .allowsHitTesting(false) + } } /// Commit the title, normalising the field to the trimmed value so a whitespace-only entry @@ -62,23 +112,17 @@ struct NoteHeaderView: View { controller.commitTitle(trimmed) } - // MARK: - Control strip + // MARK: - Controls - private var controlStrip: some View { - HStack(spacing: 10) { - newNoteButton - colorButton - materialButton - completedButton - if controller.completedCount > 0 { clearButton } - Spacer(minLength: 0) + /// Just the everyday ones in the row — the rest are under ⋯ — so they're easy to hit and the title keeps + /// most of the row. + private var controls: some View { + HStack(spacing: 6) { + if !isRolledUp { optionsButton } collapseButton floatButton closeButton } - .frame(height: 22) - .animation(.easeInOut(duration: 0.15), value: isRevealed) - .animation(.easeInOut(duration: 0.15), value: controller.completedCount > 0) .confirmationDialog( "Delete \(controller.completedCount) completed task\(controller.completedCount == 1 ? "" : "s")? " + "This can't be undone.", @@ -90,34 +134,117 @@ struct NoteHeaderView: View { } } - private var newNoteButton: some View { - iconButton(systemName: "plus", isActive: false, help: "New list") { - controller.requestNewNote() + private var optionsButton: some View { + iconButton(systemName: "ellipsis", isActive: showOptions, help: "List options") { + showOptions.toggle() } + .popover(isPresented: $showOptions, arrowEdge: .bottom) { optionsPopover } } - private var colorButton: some View { + private var collapseButton: some View { + iconButton(systemName: isRolledUp ? "chevron.down" : "chevron.up", isActive: false, + help: isRolledUp ? "Expand" : "Roll up") { + controller.toggleCollapsed() + } + } + + private var floatButton: some View { + let isFloating = note.floatOnTop + return iconButton( + systemName: isFloating ? "pin.fill" : "pin", + isActive: isFloating, + help: isFloating ? "Unpin from top" : "Keep on top" + ) { + controller.toggleFloatOnTop() + } + } + + private var closeButton: some View { Button { - showColorPopover.toggle() + controller.requestClose() } label: { - Circle() - .fill(theme.accent) - .frame(width: 13, height: 13) - .overlay(Circle().strokeBorder(theme.secondary.opacity(0.4), lineWidth: 1)) + Hoverable { hovering in + Image(systemName: "xmark") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(hovering ? Color.red : theme.secondary) + .frame(width: 22, height: 22) + .contentShape(Rectangle()) + } + } + .buttonStyle(.plain) + .help("Close list") + } + + private func iconButton( + systemName: String, + isActive: Bool, + help: String, + action: @escaping () -> Void + ) -> some View { + Button(action: action) { + Hoverable { hovering in + Image(systemName: systemName) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(hovering ? theme.title : isActive ? theme.accent : theme.secondary) + .frame(width: 22, height: 22) + .contentShape(Rectangle()) + } } .buttonStyle(.plain) - .contentShape(Rectangle()) - .help("List color") - .popover(isPresented: $showColorPopover, arrowEdge: .bottom) { colorPicker } + .help(help) + } +} + +// MARK: - Options popover + +extension NoteHeaderView { + /// Everything that isn't an everyday control: colour, material, the completed-task display options, and + /// the note-level actions. `note` is `private(set)`, so each `Toggle` writes through the controller's + /// toggle method (the binding's incoming value is ignored — the method flips + persists). + private var optionsPopover: some View { + VStack(alignment: .leading, spacing: 12) { + popoverAction("Rename…", systemImage: "pencil") { controller.requestRename() } + Divider() + colorSwatches + VStack(alignment: .leading, spacing: 10) { + Toggle("Glass", isOn: Binding( + get: { note.material == .glass }, + set: { _ in controller.toggleMaterial() } + )) + Toggle("Hide completed", isOn: Binding( + get: { note.hideCompleted }, + set: { _ in controller.toggleHideCompleted() } + )) + Toggle("Move completed to bottom", isOn: Binding( + get: { note.moveCompletedToBottom }, + set: { _ in controller.toggleMoveCompletedToBottom() } + )) + } + .toggleStyle(.switch) + .controlSize(.small) + .tint(theme.accent) + + Divider() + + VStack(alignment: .leading, spacing: 8) { + popoverAction("New List", systemImage: "plus") { controller.requestNewNote() } + // A "tidy up" wand rather than a trash can — this clears finished items, it isn't a delete. + let done = controller.completedCount + popoverAction(done > 0 ? "Clean Up \(done) Completed…" : "Clean Up Completed…", + systemImage: "wand.and.sparkles") { showClearConfirm = true } + .disabled(done == 0) + } + } + .font(.callout) + .padding(14) + .frame(width: 240) } - private var colorPicker: some View { - let columns = Array(repeating: GridItem(.fixed(26), spacing: 8), count: 3) - return LazyVGrid(columns: columns, spacing: 8) { + private var colorSwatches: some View { + HStack(spacing: 8) { ForEach(NoteColor.allCases) { swatch in Button { controller.setColor(swatch) - showColorPopover = false } label: { Circle() .fill(swatch.fill) @@ -133,110 +260,97 @@ struct NoteHeaderView: View { .help(swatch.displayName) } } - .padding(12) } - private var materialButton: some View { - let isGlass = note.material == .glass - return iconButton( - systemName: isGlass ? "sparkles" : "circle.hexagongrid", - isActive: isGlass, - help: isGlass ? "Switch to solid" : "Switch to glass" - ) { - controller.toggleMaterial() - } - } - - private var completedButton: some View { - let isActive = note.hideCompleted || note.moveCompletedToBottom - return Button { - showCompletedPopover.toggle() + /// A menu-like row in the popover; it closes the popover, then acts. + private func popoverAction(_ title: String, systemImage: String, action: @escaping () -> Void) -> some View { + Button { + showOptions = false + action() } label: { - Image(systemName: "line.3.horizontal.decrease.circle") - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(isActive ? theme.accent : theme.secondary) - .frame(width: 22, height: 22) + Label(title, systemImage: systemImage) + .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) } .buttonStyle(.plain) - .help("Completed task options") - .popover(isPresented: $showCompletedPopover, arrowEdge: .bottom) { completedOptionsMenu } } +} - /// The two per-note display toggles. `note` is `private(set)`, so each `Toggle` writes through the - /// controller's toggle method (the binding's incoming value is ignored — the method flips + persists). - private var completedOptionsMenu: some View { - VStack(alignment: .leading, spacing: 12) { - Toggle("Hide completed", isOn: Binding( - get: { note.hideCompleted }, - set: { _ in controller.toggleHideCompleted() } - )) - Toggle("Move completed to bottom", isOn: Binding( - get: { note.moveCompletedToBottom }, - set: { _ in controller.toggleMoveCompletedToBottom() } - )) - } - .toggleStyle(.switch) - .controlSize(.small) - .font(.callout) - .tint(theme.accent) - .padding(14) - .frame(width: 240) +/// The title's rename field: an AppKit text field, not a SwiftUI `TextField` focused through `@FocusState`, +/// whose focus set from a view update behaves differently across macOS versions. This one makes itself first +/// responder once it's in the window, and ends — once — on Return or clicking away (`saved`) or Esc (not). +private struct TitleField: NSViewRepresentable { + @Binding var text: String + let font: NSFont + let color: NSColor + let onEnd: (_ saved: Bool) -> Void + + func makeNSView(context: Context) -> Field { + let field = Field(string: text) + field.isBordered = false + field.drawsBackground = false + field.focusRingType = .none + field.usesSingleLineMode = true + field.lineBreakMode = .byTruncatingTail + field.cell?.isScrollable = true + field.delegate = context.coordinator + return field } - private var clearButton: some View { - // A "tidy up" wand rather than a trash can — this clears finished items, it isn't a delete. - iconButton(systemName: "wand.and.sparkles", isActive: false, help: "Clean up completed tasks") { - showClearConfirm = true - } + func updateNSView(_ field: Field, context: Context) { + context.coordinator.parent = self + field.font = font + field.textColor = color + if field.currentEditor() == nil, field.stringValue != text { field.stringValue = text } } - private var collapseButton: some View { - iconButton(systemName: "chevron.up", isActive: false, help: "Roll up") { - controller.toggleCollapsed() + func makeCoordinator() -> Coordinator { Coordinator(self) } + + final class Field: NSTextField { + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + // Deferred: taking first responder mid-update would end editing inside a view update. + Task { @MainActor [weak self] in self?.window?.makeFirstResponder(self) } } } - private var floatButton: some View { - let isFloating = note.floatOnTop - return iconButton( - systemName: isFloating ? "pin.fill" : "pin", - isActive: isFloating, - help: isFloating ? "Unpin from top" : "Keep on top" - ) { - controller.toggleFloatOnTop() + final class Coordinator: NSObject, NSTextFieldDelegate { + var parent: TitleField + private var ended = false + + init(_ parent: TitleField) { self.parent = parent } + + func controlTextDidChange(_ note: Notification) { + if let field = note.object as? NSTextField { parent.text = field.stringValue } } - } - private var closeButton: some View { - Button { - controller.requestClose() - } label: { - Image(systemName: "xmark") - .font(.system(size: 11, weight: .semibold)) - .foregroundStyle(hoverClose ? Color.red : theme.secondary) - .frame(width: 22, height: 22) - .contentShape(Rectangle()) + func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool { + switch selector { + case #selector(NSResponder.insertNewline(_:)): end(saved: true) + case #selector(NSResponder.cancelOperation(_:)): end(saved: false) + default: return false + } + return true } - .buttonStyle(.plain) - .onHover { hoverClose = $0 } - .help("Close list") - } - private func iconButton( - systemName: String, - isActive: Bool, - help: String, - action: @escaping () -> Void - ) -> some View { - Button(action: action) { - Image(systemName: systemName) - .font(.system(size: 12, weight: .medium)) - .foregroundStyle(isActive ? theme.accent : theme.secondary) - .frame(width: 22, height: 22) - .contentShape(Rectangle()) + func controlTextDidEndEditing(_ note: Notification) { end(saved: true) } // clicked away + + private func end(saved: Bool) { + guard !ended else { return } + ended = true + parent.onEnd(saved) } - .buttonStyle(.plain) - .help(help) + } +} + +/// A header control's label, told whether the pointer is on it: its ink eases from the dim secondary to +/// the title's (× goes red). +private struct Hoverable: View { + @ViewBuilder let content: (Bool) -> Content + @State private var hovering = false + + var body: some View { + content(hovering) + .onHover { inside in withAnimation(.easeInOut(duration: 0.1)) { hovering = inside } } } } diff --git a/Sources/Tic/Views/NoteView.swift b/Sources/Tic/Views/NoteView.swift index 7988e77..16197f1 100644 --- a/Sources/Tic/Views/NoteView.swift +++ b/Sources/Tic/Views/NoteView.swift @@ -3,8 +3,11 @@ import SwiftUI /// Shared layout constants so the SwiftUI collapsed bar and the AppKit window resize agree. enum NoteLayout { - /// Height of a rolled-up note (shows only its title bar). - static let collapsedHeight: CGFloat = 44 + /// Height of a rolled-up note — exactly its header's top row (a capsule it draws itself — see + /// `NotePanel.setRolledUp`). + static let collapsedHeight: CGFloat = 34 + /// The shortest an open note can be resized to (`NoteWindowManager.windowWillResize`). + static let minExpandedHeight: CGFloat = 160 /// Horizontal inset added per nesting level, so subtasks step to the right of their parent. static let indentStep: CGFloat = 20 /// Horizontal inset of task rows from the note's edges — room for the drag grip and the drop @@ -37,6 +40,7 @@ struct NoteView: View { @State private var titleText: String @State private var revealed = false + @State private var atBarHeight = false @State private var drag: ReorderDrag // True while a reorder gesture is live. SwiftUI resets it when the gesture ends *or is cancelled*; // a cancel never reaches `onEnded`, so this is what puts the task back instead of leaving it lifted. @@ -54,7 +58,7 @@ struct NoteView: View { @State private var activeSectionID: TaskItem.ID? // The task whose image is under the pointer or being cropped; its row's reorder drag is paused. @State private var imageInteractionTaskID: TaskItem.ID? - @FocusState private var titleFocused: Bool + @State private var renamingTitle = false private static let listSpace = "tic.tasklist" @@ -78,65 +82,41 @@ struct NoteView: View { } var body: some View { - Group { - if note.isCollapsed { - collapsedBar - } else { - expandedBody - } - } - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - .background(NoteBackground(color: note.color, material: note.material)) - .ignoresSafeArea() - .onHover { hovering in - withAnimation(.easeInOut(duration: 0.15)) { revealed = hovering } - } - } - - // MARK: - Collapsed bar - - private var collapsedBar: some View { - let remaining = controller.tasks.filter { !$0.isDone }.count - return HStack(spacing: 8) { - Text(note.title.isEmpty ? "Untitled List" : note.title) - .font(.headline.weight(.semibold)) - .foregroundStyle(theme.title) - .lineLimit(1) - - Spacer(minLength: 8) - - if remaining > 0 { - Text("\(remaining)") - .font(.caption.weight(.semibold)) - .foregroundStyle(theme.secondary) - .padding(.horizontal, 7) - .padding(.vertical, 2) - .background(Capsule().fill(theme.accent.opacity(0.18))) - } - } - .padding(.horizontal, 16) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading) - .allowsHitTesting(false) // let the drag handle below receive all clicks - .background(WindowMoveArea { controller.toggleCollapsed() }) - .help("Drag to move · double-click to expand") - } - - // MARK: - Expanded body - - private var expandedBody: some View { VStack(alignment: .leading, spacing: 0) { NoteHeaderView( controller: controller, theme: theme, isRevealed: revealed, + isRolledUp: showsBar, titleText: $titleText, - titleFocused: $titleFocused + isRenaming: $renamingTitle ) - taskList - QuickAddBar(controller: controller, theme: theme) + // Rolled up, the header's top row is all that's left: the window closes over the rest like a + // shade, and the list leaves only once it's shut, so nothing moves and nothing hidden keeps focus. + if !showsBar { + taskList + QuickAddBar(controller: controller, theme: theme) + } } + // `minHeight: 0`: the window opens from a bar, and the hosting view won't let it be shorter than the + // content's minimum — it jumped straight to ~150pt. The resize delegate keeps open notes taller. + .frame(maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading) + .onGeometryChange(for: Bool.self) { $0.size.height <= NoteLayout.collapsedHeight + 0.5 } action: { + atBarHeight = $0 + } + .background(NoteBackground( + color: note.color, material: note.material, + cornerRadius: note.isCollapsed ? NoteLayout.collapsedHeight / 2 : 0 + )) + .background(HoverArea { hovering in + withAnimation(.easeInOut(duration: 0.15)) { revealed = hovering } + }) + .ignoresSafeArea() } + /// Rolled up and done rolling: the window is down to the bar. + private var showsBar: Bool { note.isCollapsed && atBarHeight } + // MARK: - Task list private var taskList: some View { @@ -198,7 +178,7 @@ struct NoteView: View { } .onChange(of: controller.note.title) { _, newTitle in // An agent (or another writer) renamed the note: reflect it unless the user is mid-edit. - if !titleFocused { titleText = newTitle } + if !renamingTitle { titleText = newTitle } } .overlay(alignment: .top) { if display.isEmpty { diff --git a/Sources/Tic/Views/WindowMoveArea.swift b/Sources/Tic/Views/WindowMoveArea.swift index 0e9f158..487fc84 100644 --- a/Sources/Tic/Views/WindowMoveArea.swift +++ b/Sources/Tic/Views/WindowMoveArea.swift @@ -26,12 +26,25 @@ struct WindowMoveArea: NSViewRepresentable { @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + /// A press that hasn't moved yet. The window drag starts only once it does, so a click or a + /// double-click (roll-up) never counts as a drag — a note snaps when one is let go. + private var pendingPress: NSEvent? + override func mouseDown(with event: NSEvent) { + pendingPress = nil if event.clickCount == 2 { onDoubleClick() return } - window?.performDrag(with: event) // begin a window-move drag loop + pendingPress = event + } + + override func mouseDragged(with event: NSEvent) { + guard let press = pendingPress else { return } + pendingPress = nil + window?.performDrag(with: press) // a note's own drag (`NotePanel`), else the system's } + + override func mouseUp(with event: NSEvent) { pendingPress = nil } } } diff --git a/Sources/Tic/Windows/NotePanel.swift b/Sources/Tic/Windows/NotePanel.swift index f09730f..0d9a0d5 100644 --- a/Sources/Tic/Windows/NotePanel.swift +++ b/Sources/Tic/Windows/NotePanel.swift @@ -8,13 +8,17 @@ import SwiftUI final class NotePanel: NSPanel { let noteID: UUID + private static let noteStyle: NSWindow.StyleMask = [ + .titled, .closable, .resizable, .fullSizeContentView, .nonactivatingPanel, + ] + init(note: Note, content: AnyView) { self.noteID = note.id let rect = NSRect(x: note.frameX, y: note.frameY, width: note.frameW, height: note.frameH) super.init( contentRect: rect, - styleMask: [.titled, .closable, .resizable, .fullSizeContentView, .nonactivatingPanel], + styleMask: Self.noteStyle, backing: .buffered, defer: false ) @@ -30,12 +34,8 @@ final class NotePanel: NSPanel { hasShadow = true isReleasedWhenClosed = false // the window manager owns the lifetime animationBehavior = .utilityWindow - minSize = NSSize(width: 200, height: 160) - // Hide the traffic-light buttons; notes get their own controls in the header. - standardWindowButton(.closeButton)?.isHidden = true - standardWindowButton(.miniaturizeButton)?.isHidden = true - standardWindowButton(.zoomButton)?.isHidden = true + hideWindowButtons() let hosting = NSHostingView(rootView: content) hosting.autoresizingMask = [.width, .height] @@ -44,6 +44,23 @@ final class NotePanel: NSPanel { apply(floatOnTop: note.floatOnTop, showOnAllSpaces: note.showOnAllSpaces) } + /// Rolled up, the note drops the system frame and draws its own capsule (`NoteBackground`): macOS rounds + /// a titled window's corners at a fixed 16pt, too round for a thin bar — the system outline and corner + /// mask split away from the note's fill at both ends. It drops the system shadow too: a frameless + /// window's shadow traces the capsule with a dark rim, which reads as a border on a light desktop. + func setRolledUp(_ rolledUp: Bool) { + styleMask = rolledUp ? [.borderless, .resizable, .nonactivatingPanel] : Self.noteStyle + hasShadow = !rolledUp + hideWindowButtons() // a titled frame comes back with fresh traffic lights + } + + /// Hides the traffic-light buttons; notes get their own controls in the header. + private func hideWindowButtons() { + for button: NSWindow.ButtonType in [.closeButton, .miniaturizeButton, .zoomButton] { + standardWindowButton(button)?.isHidden = true + } + } + /// Applies the float-on-top and show-on-all-Spaces behaviours to the live window. func apply(floatOnTop: Bool, showOnAllSpaces: Bool) { level = floatOnTop ? .floating : .normal @@ -55,6 +72,27 @@ final class NotePanel: NSPanel { /// Borderless/utility panels don't become key by default; we need it for text editing. override var canBecomeKey: Bool { true } + /// Called when a drag by the note's header has been let go. Set by `NoteWindowManager`. + var onDragEnded: (() -> Void)? + + /// Moves the note with the pointer from `press` (the header's mouse-down, `WindowMoveArea`) until mouse-up. + /// Not the system's window drag: that returns at once, macOS settles or tiles a window let go at a screen + /// edge (fighting the bottom snap, issue 18), and its session swallowed a double-click's second click. + /// The top edge stays below the menu bar, as the system drag kept it. + override func performDrag(with press: NSEvent) { + let start = convertPoint(toScreen: press.locationInWindow) + let origin = frame.origin + while let event = nextEvent(matching: [.leftMouseDragged, .leftMouseUp]), event.type == .leftMouseDragged { + let pointer = NSEvent.mouseLocation + var next = NSPoint(x: origin.x + pointer.x - start.x, y: origin.y + pointer.y - start.y) + if let screen = NSScreen.screens.first(where: { $0.frame.contains(pointer) }) { + next.y = min(next.y, screen.visibleFrame.maxY - frame.height) + } + setFrameOrigin(next) + } + onDragEnded?() + } + // MARK: - Paste /// Hands over a pasted image, which waits in the note's quick-add. Reached when nothing in the note diff --git a/Sources/Tic/Windows/NoteWindowManager.swift b/Sources/Tic/Windows/NoteWindowManager.swift index 726d224..fd7a12a 100644 --- a/Sources/Tic/Windows/NoteWindowManager.swift +++ b/Sources/Tic/Windows/NoteWindowManager.swift @@ -91,6 +91,9 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { panel.onPasteImage = { [weak controller] data in controller?.stageImage(data) } + panel.onDragEnded = { [weak self, weak panel] in + if let panel { self?.snapToBottom(panel) } + } place(panel) if makeKey { @@ -124,6 +127,7 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { width: note.frameW, height: note.frameH ) openNote(note) + controllers[note.id]?.requestRename() // a new list starts with its name being typed } catch { NSLog("[Tic] newNote failed: \(error)") } @@ -145,34 +149,50 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { } } - /// Rolls a panel up to just its title bar (or back to its expanded height), keeping the top - /// edge fixed. While collapsed the height is locked so it can't be resized into a sliver. + /// Rolls a panel up to just its title bar (or back to its expanded height), from the edge + /// `rolledFrame` picks. While collapsed the height is locked (`windowWillResize`). private func setCollapsed(_ panel: NotePanel, collapsed: Bool, animate: Bool) { let id = panel.noteID let current = panel.frame - let collapsedHeight = NoteLayout.collapsedHeight - let targetHeight: CGFloat if collapsed { - if current.height > collapsedHeight { expandedHeights[id] = current.height } - targetHeight = collapsedHeight - panel.minSize = NSSize(width: panel.minSize.width, height: collapsedHeight) - panel.maxSize = NSSize(width: .greatestFiniteMagnitude, height: collapsedHeight) + if current.height > NoteLayout.collapsedHeight { expandedHeights[id] = current.height } + targetHeight = NoteLayout.collapsedHeight } else { targetHeight = expandedHeights[id] ?? max(current.height, 240) expandedHeights[id] = nil - panel.minSize = NSSize(width: panel.minSize.width, height: 160) - panel.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) } - - let top = current.origin.y + current.height - let newFrame = NSRect( - x: current.origin.x, y: top - targetHeight, - width: current.width, height: targetHeight - ) - panel.setFrame(newFrame, display: true, animate: animate) + let newFrame = Self.rolledFrame(current, toHeight: targetHeight, screens: Self.visibleFrames) + if collapsed { panel.makeFirstResponder(nil) } // end any edit: the title stays visible in the bar + // The system frame (shadow, corners) tracks a resizing window, so it comes back before expanding and + // goes only once the bar is down to size. + if !collapsed { panel.setRolledUp(false) } + let finish: @MainActor () -> Void = { [weak self, weak panel] in + guard let panel, self?.controllers[id]?.note.isCollapsed == true else { return } // not re-expanded + panel.setRolledUp(true) + } + guard animate else { + panel.setFrame(newFrame, display: true) + finish() + return + } + // Not `setFrame(_:display:animate:)`: that blocks, so SwiftUI swapped the bar for the note only + // once the window was already full height. The animator runs on the run loop, alongside the + // view, which drops its list once the window is down to the bar (`NoteView.showsBar`). + // ponytail: a re-toggle mid-roll remembers the in-between height; track the target if that bites. + NSAnimationContext.runAnimationGroup { context in + context.duration = Self.rollDuration + context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) + panel.animator().setFrame(newFrame, display: true) + } completionHandler: { + MainActor.assumeIsolated { finish() } + } } + private static let rollDuration: TimeInterval = 0.22 + + private static var visibleFrames: [CGRect] { NSScreen.screens.map(\.visibleFrame) } + /// Puts a panel where its saved frame says, as long as some connected display shows it; otherwise /// parks it on the main display (nearest edge, same size). Runs at open and on every display /// change, so unplugging a monitor parks its notes and plugging it back returns them to the exact @@ -180,23 +200,16 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { /// never persists: the saved frame stays the user's. private func place(_ panel: NotePanel) { guard let saved = savedFrames[panel.noteID], let main = NSScreen.main else { return } - let target = Self.placement(for: saved, screens: NSScreen.screens.map(\.visibleFrame), main: main.visibleFrame) - // Keep the live size (a rolled-up note sits at its collapsed height); align the top-left corner. + let screens = Self.visibleFrames + let target = Self.placement(for: saved, screens: screens, main: main.visibleFrame) + // Keep the live size: a rolled-up note sits where rolling up from `target` would put it. + let height = panel.frame.height + let frame = height < target.height ? Self.rolledFrame(target, toHeight: height, screens: screens) : target placing = true - panel.setFrameOrigin(NSPoint(x: target.minX, y: target.maxY - panel.frame.height)) + panel.setFrameOrigin(frame.origin) placing = false } - /// `saved` itself when at least an 80×80 corner lies on one of `screens`; else `saved` shifted the - /// shortest distance that fits it on `main` (a note taller than the screen keeps its top edge on). - nonisolated static func placement(for saved: CGRect, screens: [CGRect], main: CGRect) -> CGRect { - if isVisible(saved, onAnyOf: screens) { return saved } - var frame = saved - frame.origin.x = min(max(saved.minX, main.minX), main.maxX - saved.width) - frame.origin.y = min(max(saved.minY, main.minY), main.maxY - saved.height) - return frame - } - /// A display was plugged in, unplugged, or rearranged. macOS shoves windows off a vanished display /// onto a remaining one, which must not be saved as the user's choice: drop the moves it caused /// (already pending or still to come) and re-place every note from its saved frame. @@ -209,14 +222,6 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { for panel in panels.values { place(panel) } } - /// True when at least an 80×80 corner of `frame` lies on one of `screens` (enough to grab). - nonisolated static func isVisible(_ frame: CGRect, onAnyOf screens: [CGRect]) -> Bool { - screens.contains { screen in - let overlap = screen.intersection(frame) - return overlap.width >= 80 && overlap.height >= 80 - } - } - // MARK: - Image window /// Shows a task's image in the image window, creating the window on first use. It takes the note's @@ -294,6 +299,16 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { // MARK: - NSWindowDelegate func windowDidMove(_ notification: Notification) { scheduleFrameSave(notification) } + + /// The note's height limits, for user resizes only (the hosting view resets `minSize`, and a roll + /// animation doesn't come through here). A rolled-up bar resizes only sideways, so it can't be dragged + /// into a sliver or a blank note; an open note keeps room for its header and quick-add. + func windowWillResize(_ sender: NSWindow, to frameSize: NSSize) -> NSSize { + guard let panel = sender as? NotePanel else { return frameSize } + let collapsed = controllers[panel.noteID]?.note.isCollapsed == true + let height = collapsed ? NoteLayout.collapsedHeight : max(frameSize.height, NoteLayout.minExpandedHeight) + return NSSize(width: frameSize.width, height: height) + } func windowDidResize(_ notification: Notification) { scheduleFrameSave(notification) } func windowWillClose(_ notification: Notification) { @@ -317,15 +332,15 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { let id = panel.noteID let live = panel.frame - // While rolled up, the window is at its collapsed height. Still persist position/width, - // but keep the EXPANDED height in the DB and reconstruct the expanded top (collapse keeps - // the top edge fixed) — otherwise a move/resize done while collapsed is lost on relaunch. + // While rolled up, the window is at its collapsed height. Still persist position/width, but + // save the frame expanding from here would give (EXPANDED height) — otherwise a move/resize + // done while collapsed is lost on relaunch, where rolling up from it puts the bar back. let collapsed = controllers[id]?.note.isCollapsed == true - let height = collapsed ? (expandedHeights[id] ?? live.height) : live.height - let x = live.origin.x - let y = collapsed ? (live.maxY - height) : live.origin.y - let width = live.width - savedFrames[id] = CGRect(x: x, y: y, width: width, height: height) + let frame = collapsed + ? Self.rolledFrame(live, toHeight: expandedHeights[id] ?? live.height, screens: Self.visibleFrames) + : live + let (x, y, width, height) = (frame.minX, frame.minY, frame.width, frame.height) + savedFrames[id] = frame pendingFrameSaves[id]?.cancel() pendingFrameSaves[id] = Task { [appDatabase] in @@ -335,3 +350,59 @@ final class NoteWindowManager: NSObject, NSWindowDelegate { } } } + +// MARK: - Bottom snap + +extension NoteWindowManager { + /// A bar let go within `bottomSnap` of its display's bottom (or past it) glides down flush, where + /// expanding grows upward (issue 18). "Rolling" it to its own height is exactly that move. + private func snapToBottom(_ panel: NotePanel) { + guard controllers[panel.noteID]?.note.isCollapsed == true else { return } + let snapped = Self.rolledFrame(panel.frame, toHeight: panel.frame.height, screens: Self.visibleFrames) + guard snapped != panel.frame else { return } + NSAnimationContext.runAnimationGroup { context in + context.duration = Self.rollDuration + context.timingFunction = CAMediaTimingFunction(name: .easeOut) + panel.animator().setFrame(snapped, display: true) + } + } +} + +// MARK: - Frame geometry (pure, tested) + +extension NoteWindowManager { + /// How far above the bottom of the display (the Dock's top) a note still counts as parked there. + nonisolated static let bottomSnap: CGFloat = 48 + + /// `frame` rolled up to `height` or back down. The top edge stays put, unless the note's bottom is + /// within `bottomSnap` of its display's bottom: then it rolls from there, flush — a bar parked above + /// the Dock stays there and expands upward. Expanding never runs off the bottom or above the top. + nonisolated static func rolledFrame(_ frame: CGRect, toHeight height: CGFloat, screens: [CGRect]) -> CGRect { + var result = frame + result.origin.y = frame.maxY - height + result.size.height = height + let area = { (s: CGRect) in s.intersection(frame).width * s.intersection(frame).height } + guard let screen = screens.max(by: { area($0) < area($1) }), area(screen) > 0 else { return result } + if frame.minY <= screen.minY + bottomSnap { result.origin.y = screen.minY } + result.origin.y = min(max(result.origin.y, screen.minY), screen.maxY - height) + return result + } + + /// `saved` itself when at least an 80×80 corner lies on one of `screens`; else `saved` shifted the + /// shortest distance that fits it on `main` (a note taller than the screen keeps its top edge on). + nonisolated static func placement(for saved: CGRect, screens: [CGRect], main: CGRect) -> CGRect { + if isVisible(saved, onAnyOf: screens) { return saved } + var frame = saved + frame.origin.x = min(max(saved.minX, main.minX), main.maxX - saved.width) + frame.origin.y = min(max(saved.minY, main.minY), main.maxY - saved.height) + return frame + } + + /// True when at least an 80×80 corner of `frame` lies on one of `screens` (enough to grab). + nonisolated static func isVisible(_ frame: CGRect, onAnyOf screens: [CGRect]) -> Bool { + screens.contains { screen in + let overlap = screen.intersection(frame) + return overlap.width >= 80 && overlap.height >= 80 + } + } +} diff --git a/Tests/TicTests/NoteWindowManagerTests.swift b/Tests/TicTests/NoteWindowManagerTests.swift index b8e8b73..4cecc58 100644 --- a/Tests/TicTests/NoteWindowManagerTests.swift +++ b/Tests/TicTests/NoteWindowManagerTests.swift @@ -1,4 +1,5 @@ import Foundation +import SwiftUI import Testing @testable import Tic @@ -43,4 +44,84 @@ struct NoteWindowManagerTests { let parked = NoteWindowManager.placement(for: tall, screens: [main], main: main) #expect(parked.maxY == main.maxY && parked.maxX == main.maxX) } + + // MARK: Roll-up (issue 18) + + private let bar = NoteLayout.collapsedHeight + + @Test("mid-screen: rolls up from the top edge and back to the exact frame") + func rollMidScreen() { + let note = CGRect(x: 100, y: 300, width: 280, height: 360) + let rolled = NoteWindowManager.rolledFrame(note, toHeight: bar, screens: [main]) + #expect(rolled.maxY == note.maxY && rolled.height == bar) + #expect(NoteWindowManager.rolledFrame(rolled, toHeight: note.height, screens: [main]) == note) + } + + @Test("parked at the bottom: rolls up flush with it and expands upward") + func rollAtBottom() { + let note = CGRect(x: 100, y: main.minY + 10, width: 280, height: 360) // within the snap + let rolled = NoteWindowManager.rolledFrame(note, toHeight: bar, screens: [main]) + #expect(rolled.minY == main.minY && rolled.height == bar) + let expanded = NoteWindowManager.rolledFrame(rolled, toHeight: note.height, screens: [main]) + #expect(expanded.minY == main.minY && expanded.height == note.height) + } + + @Test("a low bar expands upward rather than off the bottom; a tall one keeps its header on screen") + func expandStaysOnScreen() { + let low = CGRect(x: 100, y: 100, width: 280, height: bar) // above the snap, too low for 360 + #expect(NoteWindowManager.rolledFrame(low, toHeight: 360, screens: [main]).minY == main.minY) + let tall = NoteWindowManager.rolledFrame(low, toHeight: 1200, screens: [main]) + #expect(tall.maxY == main.maxY) + } + + @Test("a bar let go near the bottom glides down flush; one let go higher up stays put") + @MainActor func dropSnapsToBottom() async throws { + _ = NSApplication.shared + let screen = try #require(NSScreen.main?.visibleFrame) + let db = try AppDatabase.makeInMemory() + let note = Note(isCollapsed: true) + try await db.insert(note) + let manager = NoteWindowManager(appDatabase: db) + let panel = manager.openNote(note, makeKey: false) + defer { panel.close() } + + // Where a header drag let go (`NotePanel.performDrag` ends with `onDragEnded`). + func drop(atHeight y: CGFloat, dragged: Bool = true) async throws { + panel.setFrameOrigin(NSPoint(x: screen.minX + 100, y: screen.minY + y)) + if dragged { panel.onDragEnded?() } + try await Task.sleep(for: .milliseconds(400)) // the whole glide: rounded to points, it lands early + } + try await drop(atHeight: 30) // within the snap + #expect(panel.frame.minY == screen.minY) + try await drop(atHeight: 200) + #expect(panel.frame.minY == screen.minY + 200) + try await drop(atHeight: 30, dragged: false) // moved, not dragged by the user: left alone + #expect(panel.frame.minY == screen.minY + 30) + } + + @Test("a rolled-up bar is frameless and keeps its height; expanding brings the system frame back") + @MainActor func barHeightLock() async throws { + _ = NSApplication.shared + let db = try AppDatabase.makeInMemory() + let note = Note(isCollapsed: true) + try await db.insert(note) + let manager = NoteWindowManager(appDatabase: db) + let panel = manager.openNote(note, makeKey: false) + defer { panel.close() } + // Frameless: no system corners to split from the fill, and no title-bar safe area — the hosting view + // grows the window to the bar's minimum height plus that inset, which bounced a titled bar to ~47pt. + #expect(!panel.styleMask.contains(.titled) && panel.contentView?.safeAreaInsets.top == 0) + #expect(!panel.hasShadow) // a frameless window's shadow rims the capsule like a dark border + #expect(manager.windowWillResize(panel, to: NSSize(width: 320, height: 200)) == NSSize(width: 320, height: bar)) + + try await db.updateNoteFlags(id: note.id, floatOnTop: false, showOnAllSpaces: false, isCollapsed: false) + // The DB echo, then an animated roll: wait for it rather than a fixed time (parallel suites slow it). + for _ in 0..<60 where panel.frame.height <= bar { try await Task.sleep(for: .milliseconds(50)) } + #expect(panel.frame.height > bar && panel.styleMask.contains(.titled) && panel.hasShadow) + #expect(panel.standardWindowButton(.closeButton)?.isHidden == true) + #expect(manager.windowWillResize(panel, to: NSSize(width: 320, height: 200)) == NSSize(width: 320, height: 200)) + // The content has no minimum height (so it can roll open from a bar): the delegate keeps one. + let short = manager.windowWillResize(panel, to: NSSize(width: 320, height: 40)) + #expect(short.height == NoteLayout.minExpandedHeight) + } } diff --git a/Tests/TicTests/ReorderDragTests.swift b/Tests/TicTests/ReorderDragTests.swift index eeff766..8763b40 100644 --- a/Tests/TicTests/ReorderDragTests.swift +++ b/Tests/TicTests/ReorderDragTests.swift @@ -67,7 +67,8 @@ struct ReorderDragTests { /// Presses on the first row and nudges it so the drag starts; returns where the pointer now is. private func pickUpFirstRow(_ h: Harness) throws -> NSPoint { - let start = NSPoint(x: 60, y: h.top - 80) + // A few points into the first row: below the header (its title row, the rule, 8pt) and the list's 4pt. + let start = NSPoint(x: 60, y: h.top - (NoteLayout.collapsedHeight + 20)) // Never press AppKit text or the header's move area: they run tracking loops that would hang. // (SwiftUI's own container class here differs by macOS version, so it can't be matched by name.) let hit = try #require(h.panel.contentView?.hitTest(start)) @@ -157,6 +158,42 @@ struct ReorderDragTests { #expect(h.controller.tasks[index + 1].indentLevel == 1) } + @Test("the title is part of the drag handle; a rename (⋯ › Rename…, a new list) saves on Return, not Esc") + func renameFlow() async throws { + let h = try await makeHarness() + defer { h.panel.orderOut(nil) } + // Not a click target of its own: there, in the window's hidden title-bar strip, a double-click zoomed it. + let title = NSPoint(x: 30, y: h.top - NoteLayout.collapsedHeight / 2) + #expect(h.panel.contentView?.hitTest(title) is WindowMoveArea.MoveView) + + try await rename(h, typing: "Groceries", thenPress: "\r", keyCode: 36) + #expect(h.controller.note.title == "Groceries") + try await rename(h, typing: "Oops", thenPress: "\u{1b}", keyCode: 53) + #expect(h.controller.note.title == "Groceries") + #expect(!(h.panel.firstResponder is NSText), "the rename ended") + } + + /// Waits by awaiting, which frees the main actor: a synchronous `pump` holds it, so the main-actor tasks a + /// rename runs on (SwiftUI's `.task`, the field taking focus) can't run until it returns — on CI, never did. + private func waitUntil(_ done: () -> Bool) async throws { + for _ in 0..<40 where !done() { try await Task.sleep(for: .milliseconds(50)) } + } + + private func rename(_ h: Harness, typing text: String, thenPress key: String, keyCode: UInt16) async throws { + h.controller.requestRename() + try await waitUntil { h.panel.firstResponder is NSTextView } + let editor = try #require(h.panel.firstResponder as? NSTextView, "the rename field took the keyboard") + editor.selectAll(nil) + editor.insertText(text, replacementRange: editor.selectedRange()) + let event = NSEvent.keyEvent( + with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: h.panel.windowNumber, context: nil, characters: key, charactersIgnoringModifiers: key, + isARepeat: false, keyCode: keyCode + )! + h.panel.sendEvent(event) + try await waitUntil { !(h.panel.firstResponder is NSTextView) } // the rename ends + } + #if DEBUG @Test("moving within one slot doesn't rebuild the list every frame") func noPerFrameListRebuild() async throws {