diff --git a/apple/Sources/Logseq/LGSidebarOverlay.swift b/apple/Sources/Logseq/LGSidebarOverlay.swift index be35d15b..492ea5c3 100644 --- a/apple/Sources/Logseq/LGSidebarOverlay.swift +++ b/apple/Sources/Logseq/LGSidebarOverlay.swift @@ -107,6 +107,7 @@ private struct LGPhoneSidebar: View { var body: some View { GeometryReader { geometry in let panelWidth = min(width, geometry.size.width * 0.80) + let slideWidth = max(1, min(panelWidth, geometry.size.width * 0.38)) let settingsInsets = EdgeInsets( top: 0, leading: 0, bottom: max(geometry.safeAreaInsets.bottom, LGNavigationSurfacePolicy.collapsedComposerCenterFromBottom - 22), @@ -114,7 +115,8 @@ private struct LGPhoneSidebar: View { ) LGSidebarLayers( main: AnyView(main.safeAreaPadding(.top, geometry.safeAreaInsets.top)), - panel: panel, settings: settings, settingsInsets: settingsInsets, panelWidth: panelWidth, + panel: panel, settings: settings, settingsInsets: settingsInsets, + panelWidth: panelWidth, slideWidth: slideWidth, progress: progress, presentation: presentation, open: open, hasOpened: hasOpened, reduceMotion: reduceMotion, dismissLabel: dismissLabel, dismiss: { select(false) } @@ -125,28 +127,28 @@ private struct LGPhoneSidebar: View { canStart: { velocity in guard abs(velocity.x) > 2 * abs(velocity.y) else { return false } let visible = presentation.progress - return open ? velocity.x < 0 && visible > 0.01 + return open ? visible > 0.01 : enabled && velocity.x > 0 && visible < 0.99 }, isClosed: { presentation.progress == 0 }, exclusions: panExclusions, changed: { translation in - if dragStart == nil { dragStart = presentation.progress } + if dragStart == nil { + dragStart = LGSidebarDrag.position(from: presentation.progress) + } guard let dragStart else { return } hasOpened = true - let fraction = translation / max(panelWidth, 1) - if fraction > 0 { - // Reveal the rows before their leading edge has crossed the whole panel width. - progress = 1 - (1 - dragStart) * pow(max(0, 1 - fraction), 5) - } else { - progress = max(0, dragStart + fraction) - } + progress = LGSidebarDrag.displayed(dragStart + translation / slideWidth) }, ended: { translation, velocity in guard let dragStart else { return } self.dragStart = nil - let projected = dragStart + (translation + velocity * 0.16) / max(panelWidth, 1) - select(projected >= 0.5) + let releasePosition = dragStart + translation / slideWidth + let dragVelocity = velocity / slideWidth + let threshold = min(0.67, max(0.33, dragStart)) + let projected = releasePosition + dragVelocity * 0.16 + select(projected >= threshold, + dragVelocity: LGSidebarDrag.displayedVelocity(dragVelocity, at: releasePosition)) }, cancelled: { dragStart = nil @@ -156,7 +158,7 @@ private struct LGPhoneSidebar: View { } } .ignoresSafeArea(.container) - .sensoryFeedback(.selection, trigger: open) + .sensoryFeedback(.impact(flexibility: .soft, intensity: 0.75), trigger: open) .onAppear { progress = open ? 1 : 0 hasOpened = open @@ -167,20 +169,57 @@ private struct LGPhoneSidebar: View { } } - private func select(_ value: Bool) { + private func select(_ value: Bool, dragVelocity: CGFloat? = nil) { guard !value || enabled || open else { settle(open) return } if value != open { toggle(value) } - settle(value) + settle(value, dragVelocity: dragVelocity) } - private func settle(_ value: Bool) { + private func settle(_ value: Bool, dragVelocity: CGFloat? = nil) { if value { hasOpened = true } - withAnimation(reduceMotion ? .easeOut(duration: 0.15) : .spring(duration: 0.30, bounce: 0)) { - progress = value ? 1 : 0 + let target: CGFloat = value ? 1 : 0 + let distance = target - progress + let animation: Animation + if reduceMotion { + animation = .easeOut(duration: 0.15) + } else if let dragVelocity, abs(distance) > 0.001 { + // The spring measures velocity relative to the travel left after the drag. + let initialVelocity = min(12, max(-12, dragVelocity / distance)) + // A stretched panel takes slightly longer to return to rest. + let duration = progress > 1 ? 0.30 : 0.28 + animation = .interpolatingSpring(duration: duration, bounce: 0, initialVelocity: initialVelocity) + } else { + animation = .spring(duration: 0.30, bounce: 0) } + withAnimation(animation) { + progress = target + } + } +} + +private enum LGSidebarDrag { + private static let resistance: CGFloat = 0.55 + + static func displayed(_ position: CGFloat) -> CGFloat { + guard position > 1 else { return max(0, position) } + let stretch = (position - 1) * resistance + return 1 + stretch / (1 + stretch) + } + + static func position(from displayed: CGFloat) -> CGFloat { + guard displayed > 1 else { return displayed } + // Recover the undamped start when a new drag catches the spring in its stretched range. + let stretch = min(displayed - 1, 0.95) + return 1 + stretch / ((1 - stretch) * resistance) + } + + static func displayedVelocity(_ velocity: CGFloat, at position: CGFloat) -> CGFloat { + guard position > 1 else { return velocity } + let scale = 1 + (position - 1) * resistance + return velocity * resistance / (scale * scale) } } @@ -190,8 +229,8 @@ private final class LGSidebarPresentation { private(set) var progress: CGFloat = 0 func sample(_ value: CGFloat) -> CGFloat { - progress = min(1, max(0, value)) - return progress + progress = max(0, value) + return min(1, progress) } } @@ -201,6 +240,7 @@ private struct LGSidebarLayers: View, Animatable { let settings: AnyView let settingsInsets: EdgeInsets let panelWidth: CGFloat + let slideWidth: CGFloat nonisolated var progress: CGFloat let presentation: LGSidebarPresentation let open: Bool @@ -220,6 +260,11 @@ private struct LGSidebarLayers: View, Animatable { var body: some View { let visible = presentation.sample(progress) + // Keep the blur at its endpoint while the open panel stretches. + let panelOffset = (max(0, progress) - 1) * slideWidth + let hidden = 1 - visible + // Ease the blur at both ends so text sharpens smoothly as the panel settles. + let panelBlur = 12 * hidden * hidden * (3 - 2 * hidden) let blocksMain = open || visible > 0.001 let panelInteractive = open && visible > 0.95 let dark = colorScheme == .dark @@ -255,9 +300,9 @@ private struct LGSidebarLayers: View, Animatable { dismiss: dismiss )) .frame(maxWidth: .infinity, maxHeight: .infinity) - .blur(radius: reduceTransparency || visible == 0 ? 0 : 12 * (1 - visible).squareRoot()) + .blur(radius: reduceTransparency || visible == 0 ? 0 : panelBlur) .opacity(visible) - .offset(x: reduceMotion ? 0 : (visible - 1) * panelWidth) + .offset(x: reduceMotion ? 0 : panelOffset) .allowsHitTesting(panelInteractive) .accessibilityHidden(!open) .accessibilityAction(.escape, dismiss) diff --git a/apple/Tests/UI/sidebar-slow-swipe.swift b/apple/Tests/UI/sidebar-slow-swipe.swift new file mode 100644 index 00000000..6eb3cd33 --- /dev/null +++ b/apple/Tests/UI/sidebar-slow-swipe.swift @@ -0,0 +1,111 @@ +import SwiftUI +import UIKit +import Logseq + +@MainActor +private final class SidebarTestPan: UIPanGestureRecognizer { + var distance: CGFloat = 0 + var speed: CGFloat = 0 + var phase: UIGestureRecognizer.State = .possible + + override var state: UIGestureRecognizer.State { + get { phase } + set { phase = newValue } + } + + override func translation(in view: UIView?) -> CGPoint { CGPoint(x: distance, y: 0) } + override func velocity(in view: UIView?) -> CGPoint { CGPoint(x: speed, y: 0) } +} + +@main +struct SidebarSlowSwipeCheck { + struct Failure: Error, CustomStringConvertible { + let description: String + } + + @MainActor static func main() async throws { + let recentPages = (0..<20).map { ["uuid": "recent-\($0)", "title": "Recent page \($0)"] } + let result: [String: Any] = [ + "graphName": "Sidebar slow swipe", "selectedGraphId": "sidebar-swipe", + "isGraphUnlocked": true, "recentPages": recentPages + ] + let snapshot = String(decoding: try JSONSerialization.data(withJSONObject: ["ok": true, "result": result]), as: UTF8.self) + let runtime = LGRuntime(native: LGCoreNativeCaller(), effectExecutor: LGCoreEffectExecutor(callCore: { _ in snapshot })) + try runtime.applyCoreResponse(snapshot) + try runtime.start(platformCode: 2, hostCode: 2, authenticationCode: 3) + try runtime.applyHostUpdate(kind: "graph-loading", payload: "false") + guard let scene = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }).first else { + throw Failure(description: "Missing window scene") + } + let window = UIWindow(windowScene: scene) + window.rootViewController = UIHostingController(rootView: LGRendererRoot(renderer: runtime.renderer)) + window.makeKeyAndVisible() + defer { window.isHidden = true; runtime.stop() } + try await Task.sleep(for: .milliseconds(500)) + + func views(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap(views) } + let initialViews = views(window) + guard let target = initialViews.flatMap({ $0.gestureRecognizers ?? [] }) + .first(where: { $0.name == "logseq.sidebar" })?.delegate as? UIView else { + throw Failure(description: "Missing phone sidebar recognizer") + } + let pan = SidebarTestPan() + func drag(_ phase: UIGestureRecognizer.State, distance: CGFloat, speed: CGFloat = 0) { + pan.phase = phase + pan.distance = distance + pan.speed = speed + target.perform(NSSelectorFromString("dragged:"), with: pan) + } + func flick(_ direction: CGFloat) async throws { + drag(.began, distance: 0) + drag(.changed, distance: 90 * direction) + try await Task.sleep(for: .milliseconds(35)) + drag(.ended, distance: 90 * direction, speed: 1_500 * direction) + try await Task.sleep(for: .milliseconds(550)) + } + + let initialScrolls = Set(initialViews.compactMap { ($0 as? UIScrollView).map(ObjectIdentifier.init) }) + try await flick(1) + guard let scroll = views(window).compactMap({ $0 as? UIScrollView }).first(where: { + !initialScrolls.contains(ObjectIdentifier($0)) && $0.isScrollEnabled && $0.bounds.height > 100 + }) else { throw Failure(description: "Missing sidebar scroller") } + func position() -> CGFloat { scroll.convert(scroll.bounds, to: window).minX } + let open = position() + try await flick(-1) + let closed = position() + let travel = open - closed + let expectedTravel = window.bounds.width * 0.38 + guard abs(travel - expectedTravel) < 2 else { + throw Failure(description: "Expected the sidebar to travel \(expectedTravel) points, measured \(travel)") + } + + func slowSwipe(_ fraction: CGFloat, to endpoint: CGFloat, speed: CGFloat = 0, + displayedFraction: CGFloat? = nil) async throws { + let start = position() + let distance = fraction * travel + drag(.began, distance: 0) + for step in 1...8 { + drag(.changed, distance: distance * CGFloat(step) / 8) + try await Task.sleep(for: .milliseconds(35)) + } + if speed == 0 { try await Task.sleep(for: .milliseconds(100)) } + let beforeRelease = position() + drag(.ended, distance: distance, speed: speed) + try await Task.sleep(for: .milliseconds(550)) + let displayedDistance = (displayedFraction ?? fraction) * travel + guard abs(beforeRelease - start - displayedDistance) < 2 else { + throw Failure(description: "A \(distance)-point swipe moved the sidebar \(beforeRelease - start) points") + } + guard abs(position() - endpoint) < 1 else { + throw Failure(description: "Sidebar settled at \(position()) after a \(fraction) swipe with speed \(speed). Expected \(endpoint)") + } + } + try await slowSwipe(0.25, to: closed) + try await slowSwipe(0.37, to: open) + try await slowSwipe(-0.25, to: open) + try await slowSwipe(0.50, to: open, displayedFraction: 0.216) + try await slowSwipe(-0.37, to: closed) + try await slowSwipe(0.08, to: open, speed: 350) + print("PASS: Phone sidebar tracks slow swipes, settles from release velocity, and resists beyond its open position") + } +}