diff --git a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt index f55fe1ad..54cab9b2 100644 --- a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt +++ b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/LogseqExtensions.kt @@ -263,7 +263,7 @@ fun logseqExtensionRegistry( registerOutlinerBlockRow(resolveAssetPath, youtubeStarts, onOpenImage, loadImage) register( "bottom-tab-strip", - "lui-extension-v1|16:bottom-tab-strip|profiles:android/kotlin,ios/swiftui|standard-children:1|children:|properties:10:cell-width:int:required:none,14:selected-index:int:required:none,5:inset:int:required:none,5:items:string:required:none|events:15:home-double-tap[],6:select[5:index:int:required]", + "lui-extension-v1|16:bottom-tab-strip|profiles:android/kotlin,ios/swiftui|standard-children:1|children:|properties:10:cell-width:int:required:none,14:selected-index:int:required:none,5:inset:int:required:none,5:items:string:required:none|events:6:select[5:index:int:required]", acceptsStandardChildren = true, properties = listOf( LuiExtensionProperty("cell-width", LuiExtensionValueKind.INTEGER, required = true), @@ -272,7 +272,6 @@ fun logseqExtensionRegistry( LuiExtensionProperty("items", LuiExtensionValueKind.STRING, required = true), ), events = listOf( - LuiExtensionEventSchema("home-double-tap", emptyList()), LuiExtensionEventSchema("select", listOf(LuiExtensionProperty("index", LuiExtensionValueKind.INTEGER, required = true))), ), ) { diff --git a/apple/Sources/Logseq/LGBottomTabStrip.swift b/apple/Sources/Logseq/LGBottomTabStrip.swift index f08c0ce8..1022ef4a 100644 --- a/apple/Sources/Logseq/LGBottomTabStrip.swift +++ b/apple/Sources/Logseq/LGBottomTabStrip.swift @@ -19,7 +19,7 @@ struct LGBottomTabStrip: View { static func register(in registry: LUIAppleExtensionRegistry) throws { try registry.register(LUIAppleExtension( identifier: "bottom-tab-strip", - fingerprint: "lui-extension-v1|16:bottom-tab-strip|profiles:android/kotlin,ios/swiftui|standard-children:1|children:|properties:10:cell-width:int:required:none,14:selected-index:int:required:none,5:inset:int:required:none,5:items:string:required:none|events:15:home-double-tap[],6:select[5:index:int:required]", + fingerprint: "lui-extension-v1|16:bottom-tab-strip|profiles:android/kotlin,ios/swiftui|standard-children:1|children:|properties:10:cell-width:int:required:none,14:selected-index:int:required:none,5:inset:int:required:none,5:items:string:required:none|events:6:select[5:index:int:required]", acceptsStandardChildren: true, properties: [ .init(name: "selected-index", kind: .int, isRequired: true), @@ -29,7 +29,6 @@ struct LGBottomTabStrip: View { ], events: [ .init(name: "select", fields: [.init(name: "index", kind: .int, isRequired: true)]), - .init(name: "home-double-tap", fields: []), ] ) { AnyView(LGBottomTabStrip(context: $0)) }) } @@ -42,7 +41,7 @@ struct LGBottomTabStrip: View { LGNativeBottomTabBar( items: items, selectedIndex: selectedIndex, tint: colors["link"], foreground: colors["foreground"], layoutDirection: layoutDirection, - horizontalMargin: horizontalMargin, context: context + context: context ) // UITabBar reserves horizontal margins around its floating capsule. .frame(width: CGFloat(items.count) * tabWidth + inset * 2 + 2 * horizontalMargin, height: 58) @@ -80,11 +79,6 @@ struct LGBottomTabStrip: View { .onGeometryChange(for: CGSize.self, of: \.size) { size = $0 } .contentShape(Capsule()) .highPriorityGesture(tabDrag(count: count, cellWidth: cellWidth, inset: inset)) - .simultaneousGesture(SpatialTapGesture(count: 2).onEnded { tap in - guard cellWidth > 0, horizontalPosition(tap.location.x) < inset + cellWidth, - context.isUserInteractionEnabled else { return } - try? context.emit(name: "home-double-tap") - }) .onChange(of: selected) { pendingSelection = nil } #if os(iOS) .background(LGSidebarPanExclusion()) @@ -206,22 +200,15 @@ private struct LGNativeBottomTabBar: UIViewRepresentable { let tint: Color? let foreground: Color? let layoutDirection: LayoutDirection - let horizontalMargin: CGFloat let context: LUIAppleExtensionViewContext func makeCoordinator() -> Coordinator { - Coordinator(context: context, horizontalMargin: horizontalMargin) + Coordinator(context: context) } func makeUIView(context: Context) -> UITabBar { let bar = UITabBar() bar.delegate = context.coordinator - let doubleTap = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.doubleTapHome)) - doubleTap.numberOfTapsRequired = 2 - doubleTap.cancelsTouchesInView = false - doubleTap.delaysTouchesEnded = false - doubleTap.delegate = context.coordinator - bar.addGestureRecognizer(doubleTap) return bar } @@ -254,16 +241,14 @@ private struct LGNativeBottomTabBar: UIViewRepresentable { bar.semanticContentAttribute = layoutDirection == .rightToLeft ? .forceRightToLeft : .forceLeftToRight } - @MainActor final class Coordinator: NSObject, UITabBarDelegate, UIGestureRecognizerDelegate { + @MainActor final class Coordinator: NSObject, UITabBarDelegate { var context: LUIAppleExtensionViewContext var items: [Item] = [] var unreadColors: [UIColor] = [] var selectedIndex: Int? - let horizontalMargin: CGFloat - init(context: LUIAppleExtensionViewContext, horizontalMargin: CGFloat) { + init(context: LUIAppleExtensionViewContext) { self.context = context - self.horizontalMargin = horizontalMargin } func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { @@ -273,24 +258,6 @@ private struct LGNativeBottomTabBar: UIViewRepresentable { tabBar.selectedItem = tabBar.items?.first(where: { $0.tag == selectedIndex }) } } - - func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { - guard let bar = gestureRecognizer.view as? UITabBar, items.first?.name == "home" else { return false } - let x = touch.location(in: bar).x - let leadingX = bar.effectiveUserInterfaceLayoutDirection == .rightToLeft ? bar.bounds.width - x : x - let itemWidth = (bar.bounds.width - 2 * horizontalMargin) / CGFloat(items.count) - return leadingX >= horizontalMargin && leadingX < horizontalMargin + itemWidth - } - - func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, - shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { - true - } - - @objc func doubleTapHome() { - guard context.isUserInteractionEnabled else { return } - try? context.emit(name: "home-double-tap") - } } } #endif diff --git a/apple/Sources/Logseq/LGComposerAttachmentRemove.swift b/apple/Sources/Logseq/LGComposerAttachmentRemove.swift new file mode 100644 index 00000000..d419ee8a --- /dev/null +++ b/apple/Sources/Logseq/LGComposerAttachmentRemove.swift @@ -0,0 +1,49 @@ +#if os(iOS) +import LUIAppleBackend +import SwiftUI + +struct LGComposerAttachmentRemove: View { + let context: LUIAppleExtensionViewContext + + static func register(in registry: LUIAppleExtensionRegistry) throws { + try registry.register(LUIAppleExtension( + identifier: "composer-attachment-remove", + fingerprint: "lui-extension-v1|26:composer-attachment-remove|profiles:ios/swiftui|standard-children:1|children:|properties:5:label:string:required:none|events:6:remove[]", + acceptsStandardChildren: true, + properties: [.init(name: "label", kind: .string, isRequired: true)], + events: [.init(name: "remove", fields: [])] + ) { AnyView(LGComposerAttachmentRemove(context: $0)) }) + } + + var body: some View { + let _ = context.revision + context.content + .allowsHitTesting(false) + .overlay(alignment: .topTrailing) { removeButton } + } + + private var removeButton: some View { + Button { + guard context.isUserInteractionEnabled else { return } + try? context.emit(name: "remove") + } label: { + Image(systemName: "xmark") + .font(.system(size: 11, weight: .semibold)) + .foregroundStyle(.white) + .frame(width: 22, height: 22) + .background(.black.opacity(0.6), in: Circle()) + .padding([.top, .trailing], 8) + .frame(width: 44, height: 44, alignment: .topTrailing) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .accessibilityLabel(Text(verbatim: label)) + .accessibilityIdentifier("composer.asset.remove") + } + + private var label: String { + guard case let .string(label) = context.property("label") else { return "Remove attachment" } + return label + } +} +#endif diff --git a/apple/Sources/Logseq/LGLiquidGlassTweak.swift b/apple/Sources/Logseq/LGLiquidGlassTweak.swift index 7ec8961a..7e9e12d1 100644 --- a/apple/Sources/Logseq/LGLiquidGlassTweak.swift +++ b/apple/Sources/Logseq/LGLiquidGlassTweak.swift @@ -99,10 +99,17 @@ struct LGBottomChromeSwitch: View { private struct LGBottomBarActions: ViewModifier { @Environment(\.lgUsesSideCaptureActions) private var usesSideCaptureActions + #if os(iOS) + @Environment(\.lgPlatformPresentation) private var presentation + #endif func body(content: Content) -> some View { if !usesSideCaptureActions { content.modifier(LGBottomBarGlass(surface: .trailing)) + #if os(iOS) + // A held Capture button can release after the picker has opened. + .disabled(presentation?.attachmentService == .quickPhotos) + #endif } } } diff --git a/apple/Sources/Logseq/LGMediaPanel.swift b/apple/Sources/Logseq/LGMediaPanel.swift index 86415eb5..682ce960 100644 --- a/apple/Sources/Logseq/LGMediaPanel.swift +++ b/apple/Sources/Logseq/LGMediaPanel.swift @@ -1,11 +1,82 @@ #if os(iOS) import AVFoundation -import PhotosUI +@preconcurrency import PhotosUI import SwiftUI import UIKit import UniformTypeIdentifiers import ImageIO +struct LGQuickPhotoPicker: View { + let onPhoto: (Data, String) async throws -> Void + @Environment(\.dismiss) private var dismiss + @State private var selection: [PhotosPickerItem] = [] + @State private var showAllPhotos = false + @State private var isImporting = false + @State private var importError: String? + @State private var pickerID = UUID() + + var body: some View { + VStack(spacing: 4) { + HStack { + Button(role: .cancel) { dismiss() } label: { + Text("Cancel").frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) + } + Spacer() + if isImporting { + ProgressView() + } + Spacer() + Button { showAllPhotos = true } label: { + Text("All Photos").frame(minWidth: 44, minHeight: 44) + .contentShape(Rectangle()) + } + .photosPicker(isPresented: $showAllPhotos, selection: $selection, + maxSelectionCount: 1, matching: .images) + } + .padding(.horizontal, 20) + LGEmbeddedPhotos(importedIDs: [], compact: true) { results in + guard let photo = results.first else { return } + importPhoto { try await loadEmbeddedPhoto(photo) } + } + .id(pickerID) + .frame(height: 104) + .clipShape(.rect(cornerRadius: 14)) + .padding(.horizontal, 12) + } + .frame(maxHeight: .infinity) + .disabled(isImporting) + .interactiveDismissDisabled(isImporting) + .onChange(of: selection) { _, items in + guard let item = items.first else { return } + importPhoto { try await item.loadImageForAttachment() } + } + .alert("Photo import failed", isPresented: Binding( + get: { importError != nil }, set: { if !$0 { importError = nil } } + )) { + Button("OK") { importError = nil } + } message: { + Text(importError ?? "") + } + } + + private func importPhoto(load: @escaping () async throws -> (Data, String)) { + guard !isImporting else { return } + isImporting = true + Task { + do { + let (data, fileExtension) = try await load() + try await onPhoto(data, fileExtension) + } catch { + selection = [] + pickerID = UUID() + importError = error.localizedDescription + } + isImporting = false + } + } +} + struct LGMediaPanel: View { let initialService: LGAttachmentService let onPhotos: ([PhotosPickerItem]) -> Void @@ -137,21 +208,8 @@ struct LGMediaPanel: View { Task { @MainActor in for photo in photos { do { - let provider = photo.itemProvider - guard let type = provider.registeredTypeIdentifiers.compactMap(UTType.init) - .first(where: { $0.conforms(to: .image) }) else { - throw CocoaError(.fileReadUnknown) - } - let data: Data = try await withCheckedThrowingContinuation { continuation in - provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, error in - if let data { continuation.resume(returning: data) } - else { continuation.resume(throwing: error ?? CocoaError(.fileReadUnknown)) } - } - } - let imageType = CGImageSourceCreateWithData(data as CFData, nil) - .flatMap(CGImageSourceGetType).flatMap { UTType($0 as String) } - onPhotoData(data, imageType?.preferredFilenameExtension - ?? type.preferredFilenameExtension ?? "jpg") + let (data, fileExtension) = try await loadEmbeddedPhoto(photo) + onPhotoData(data, fileExtension) if let id = photo.assetIdentifier { importedPhotoIDs.insert(id) } selectedPhotos.removeAll { $0.assetIdentifier == photo.assetIdentifier } } catch { @@ -179,13 +237,31 @@ struct LGMediaPanel: View { } +@MainActor private func loadEmbeddedPhoto(_ photo: PHPickerResult) async throws -> (Data, String) { + let provider = photo.itemProvider + guard let type = provider.registeredTypeIdentifiers.compactMap(UTType.init) + .first(where: { $0.conforms(to: .image) }) else { + throw CocoaError(.fileReadUnknown) + } + let data: Data = try await withCheckedThrowingContinuation { continuation in + provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, error in + if let data { continuation.resume(returning: data) } + else { continuation.resume(throwing: error ?? CocoaError(.fileReadUnknown)) } + } + } + let imageType = CGImageSourceCreateWithData(data as CFData, nil) + .flatMap(CGImageSourceGetType).flatMap { UTType($0 as String) } + return (data, imageType?.preferredFilenameExtension ?? type.preferredFilenameExtension ?? "jpg") +} + // Isolate the embedded picker from the surrounding SwiftUI sheet's presentation traits. private struct LGEmbeddedPhotos: UIViewControllerRepresentable { let importedIDs: Set + var compact = false let onSelection: ([PHPickerResult]) -> Void func makeUIViewController(context: Context) -> Container { - Container(onSelection: onSelection) + Container(compact: compact, onSelection: onSelection) } func updateUIViewController(_ controller: Container, context: Context) { @@ -193,11 +269,13 @@ private struct LGEmbeddedPhotos: UIViewControllerRepresentable { } final class Container: UIViewController, PHPickerViewControllerDelegate { + let compact: Bool let onSelection: ([PHPickerResult]) -> Void private var picker: PHPickerViewController? private var importedIDs: Set = [] - init(onSelection: @escaping ([PHPickerResult]) -> Void) { + init(compact: Bool, onSelection: @escaping ([PHPickerResult]) -> Void) { + self.compact = compact self.onSelection = onSelection super.init(nibName: nil, bundle: nil) } @@ -208,8 +286,9 @@ private struct LGEmbeddedPhotos: UIViewControllerRepresentable { super.viewDidLoad() var configuration = PHPickerConfiguration(photoLibrary: .shared()) configuration.filter = .images - configuration.selectionLimit = 20 - configuration.selection = .continuousAndOrdered + configuration.selectionLimit = compact ? 1 : 20 + configuration.selection = compact ? .continuous : .continuousAndOrdered + configuration.mode = compact ? .compact : .default configuration.edgesWithoutContentMargins = .all configuration.disabledCapabilities = [.selectionActions] let picker = PHPickerViewController(configuration: configuration) @@ -225,7 +304,7 @@ private struct LGEmbeddedPhotos: UIViewControllerRepresentable { picker.view.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) picker.didMove(toParent: self) - picker.zoomIn() + if !compact { picker.zoomIn() } } func deselectImported(_ identifiers: Set) { diff --git a/apple/Sources/Logseq/LGPlatformPresentation.swift b/apple/Sources/Logseq/LGPlatformPresentation.swift index 64e70e2f..53f32eec 100644 --- a/apple/Sources/Logseq/LGPlatformPresentation.swift +++ b/apple/Sources/Logseq/LGPlatformPresentation.swift @@ -14,6 +14,18 @@ public enum LGAttachmentService: String, CaseIterable, Sendable { case camera case photos case audio + #if os(iOS) + case quickPhotos = "quick-photos" + #endif +} + +extension PhotosPickerItem { + func loadImageForAttachment() async throws -> (Data, String) { + guard let data = try await loadTransferable(type: Data.self) else { + throw CocoaError(.fileReadUnknown) + } + return (data, supportedContentTypes.first?.preferredFilenameExtension ?? "jpg") + } } struct LGAttachmentRequest { @@ -247,16 +259,20 @@ struct LGPlatformPresentationHost: ViewModifier { importPhotos(items) } #endif - .alert(deletionTitle, isPresented: deletionBinding) { - Button("Delete", role: .destructive) { - confirmOutlinerDelete() - coordinator.dismissDeletion() - } - Button("Cancel", role: .cancel) { - coordinator.dismissDeletion() - } - } message: { - Text("This deletes the block and all of its children. Pages use Recycle instead.") + .background { + Color.clear + .alert(deletionTitle, isPresented: deletionBinding) { + Button("Delete", role: .destructive) { + confirmOutlinerDelete() + coordinator.dismissDeletion() + } + Button("Cancel", role: .cancel) { + coordinator.dismissDeletion() + } + } message: { + Text("This deletes the block and all of its children. Pages use Recycle instead.") + } + .tint(.primary) } #if os(iOS) .environment(\.lgPlatformPresentation, coordinator) @@ -316,6 +332,16 @@ struct LGPlatformPresentationHost: ViewModifier { .presentationDragIndicator(.hidden) .presentationCornerRadius(32) } + .sheet(isPresented: presentationBinding(for: .quickPhotos)) { + LGQuickPhotoPicker { data, fileExtension in + try await importPhoto(data, fileExtension: fileExtension, targetBlockID: request.targetBlockID) + coordinator.completeAttachment(requestID: request.id) + } + .id(request.id) + .modifier(LGSheetSurface()) + .presentationDetents([.height(164)]) + .presentationDragIndicator(.hidden) + } .sheet(isPresented: presentationBinding(for: .audio)) { AudioRecorderSheet( targetBlockID: request.targetBlockID @@ -401,13 +427,8 @@ struct LGPlatformPresentationHost: ViewModifier { Task { for item in items { do { - guard let data = try await item.loadTransferable(type: Data.self) else { continue } - let fileExtension = item.supportedContentTypes.first?.preferredFilenameExtension ?? "jpg" - let title = "Photo-\(UUID().uuidString).\(fileExtension)" - try addImportedAsset( - try await LGAssetImporter.persist(data: data, title: title), - targetBlockID: request.targetBlockID - ) + let (data, fileExtension) = try await item.loadImageForAttachment() + try await importPhoto(data, fileExtension: fileExtension, targetBlockID: request.targetBlockID) } catch { logger.error("Photo import failed: \(String(describing: error))") } @@ -416,6 +437,12 @@ struct LGPlatformPresentationHost: ViewModifier { } } + private func importPhoto(_ data: Data, fileExtension: String, targetBlockID: String?) async throws { + let title = "Photo-\(UUID().uuidString).\(fileExtension)" + let asset = try await LGAssetImporter.persist(data: data, title: title) + try addImportedAsset(asset, targetBlockID: targetBlockID) + } + #if os(iOS) private func importCapturedData(_ data: Data, targetBlockID: String?, title: String = "Camera-\(UUID().uuidString).jpg") { diff --git a/apple/Sources/Logseq/LGRichBlockExtension.swift b/apple/Sources/Logseq/LGRichBlockExtension.swift index b87d846b..9404582d 100644 --- a/apple/Sources/Logseq/LGRichBlockExtension.swift +++ b/apple/Sources/Logseq/LGRichBlockExtension.swift @@ -28,6 +28,7 @@ enum LGExtensionRegistry { ) try OutlinerRowExtension.register(in: registry, playback: LGYouTubePlaybackState()) #if os(iOS) + try LGComposerAttachmentRemove.register(in: registry) try OutlinerSelectionToolbar.register(in: registry) try LGReactionPickerExtension.register(in: registry) #endif diff --git a/apple/Tests/UI/journal-home-double-tap.swift b/apple/Tests/UI/journal-home-reselect.swift similarity index 90% rename from apple/Tests/UI/journal-home-double-tap.swift rename to apple/Tests/UI/journal-home-reselect.swift index 1316cb16..04b033f6 100644 --- a/apple/Tests/UI/journal-home-double-tap.swift +++ b/apple/Tests/UI/journal-home-reselect.swift @@ -1,5 +1,5 @@ // Run with run-simulator-runtime-check.py in --interactive mode and an empty -// fixture directory, then run journal-home-double-tap.yaml on that simulator. +// fixture directory, then run journal-home-reselect.yaml on that simulator. import SwiftUI @testable import Logseq @@ -9,7 +9,7 @@ import SwiftUI } } -@main struct JournalHomeDoubleTapFixture: App { +@main struct JournalHomeReselectFixture: App { private let runtime = LGRuntime(native: LGCoreNativeCaller(), effectExecutor: JournalHomeTapEffects()) init() { diff --git a/apple/Tests/UI/journal-home-double-tap.yaml b/apple/Tests/UI/journal-home-reselect.yaml similarity index 90% rename from apple/Tests/UI/journal-home-double-tap.yaml rename to apple/Tests/UI/journal-home-reselect.yaml index 46f1622a..d8f97b00 100644 --- a/apple/Tests/UI/journal-home-double-tap.yaml +++ b/apple/Tests/UI/journal-home-reselect.yaml @@ -9,7 +9,8 @@ appId: com.logseq.logseq.PageBenchmark timeout: 20000 - assertNotVisible: id: outliner.block-action.home-tap-0 -- doubleTapOn: +- tapOn: + retryTapIfNoChange: false id: tab.bottom.home - assertVisible: id: outliner.block-action.home-tap-0 diff --git a/apple/Tests/UI/journal-scroll-to-top.swift b/apple/Tests/UI/journal-scroll-to-top.swift index bd75d4e1..c3ed5b55 100644 --- a/apple/Tests/UI/journal-scroll-to-top.swift +++ b/apple/Tests/UI/journal-scroll-to-top.swift @@ -83,10 +83,10 @@ import UIKit scroll.setContentOffset(CGPoint(x: 0, y: scroll.contentSize.height * fraction), animated: false) try await Task.sleep(for: .milliseconds(400)) let halfway = scroll.contentOffset.y / 2 - try backend.performExtensionEvent(node: strip, name: "home-double-tap", values: [:]) - try await wait("Double-tapping Home must jump directly to the top") { scroll.contentOffset.y < halfway } + try backend.performExtensionEvent(node: strip, name: "select", values: ["index": .int(0)]) + try await wait("Reselecting Home must jump directly to the top") { scroll.contentOffset.y < halfway } guard scroll.contentOffset.y <= -scroll.adjustedContentInset.top + 1 else { - throw failure("Double-tapping Home moved through an intermediate position") + throw failure("Reselecting Home moved through an intermediate position") } try await wait("Home must mount the first block before returning to the top") { views(window).compactMap { $0 as? UILabel }.contains { label in @@ -94,7 +94,7 @@ import UIKit } } } - print("PASS: repeated Home double-taps jump directly to the first journal block, and status-bar returns retain their platform behavior") + print("PASS: repeated Home taps jump directly to the first journal block, and status-bar returns retain their platform behavior") } @MainActor private static func delegateContract() throws { diff --git a/apple/Tests/UI/native-menu-presentation.swift b/apple/Tests/UI/native-menu-presentation.swift index 148fd334..4f7ff410 100644 --- a/apple/Tests/UI/native-menu-presentation.swift +++ b/apple/Tests/UI/native-menu-presentation.swift @@ -1,33 +1,21 @@ -import UIKit import SwiftUI @testable import LUIAppleBackend @testable import Logseq -@main struct NativeMenuPresentationCheck { - static func main() { - UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(NativeMenuPresentationDelegate.self)) - } -} +@main struct NativeMenuPresentationCheck: App { + private let fixture = NativeMenuPresentationFixture() -@MainActor private final class MenuTouchWindow: UIWindow { - var recordTouch: (String) -> Void = { _ in } - override func sendEvent(_ event: UIEvent) { - for touch in event.allTouches ?? [] where touch.phase == .began { - let point = touch.location(in: self) - var ancestors: [String] = [] - var view = touch.view - while let current = view { - ancestors.append(String(describing: type(of: current))) - view = current.superview - } - recordTouch("TOUCH \(point) " + ancestors.joined(separator: " > ")) + var body: some Scene { + WindowGroup { + LGRendererRoot(renderer: fixture.runtime.renderer) + .modifier(LGPlatformPresentationHost( + coordinator: fixture.coordinator, confirmOutlinerDelete: {}, stageAsset: fixture.stageAsset + )) } - super.sendEvent(event) } } -@MainActor final class NativeMenuPresentationDelegate: UIResponder, UIApplicationDelegate { - var window: UIWindow? +@MainActor private final class NativeMenuPresentationFixture { let coordinator = LGPlatformPresentationCoordinator() var runtime: LGRuntime! @@ -40,7 +28,12 @@ import SwiftUI } catch { fatalError("Cannot record menu presentation events: \(error)") } } - func application(_ application: UIApplication, didFinishLaunchingWithOptions options: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + func stageAsset(_ payload: String) throws { + record("STAGED " + payload) + try runtime.applyHostUpdate(kind: "composer-asset", payload: payload) + } + + init() { do { record("READY") let snapshot = #"{"ok":true,"result":{"revision":1,"graphName":"Work","selectedGraphId":"work","graphs":[{"id":"work","name":"Work","isReady":true,"isEncrypted":false},{"id":"other","name":"Other","isReady":true,"isEncrypted":false}],"blocks":[],"outlinerRows":[],"outlinerState":{"selectedBlockIds":[]}}}"# @@ -61,17 +54,6 @@ import SwiftUI record("EVENT \(event.kind) " + detail) receive?(event) } - let host = LGRendererRoot(renderer: runtime.renderer) - .modifier(LGPlatformPresentationHost(coordinator: coordinator, confirmOutlinerDelete: {}, stageAsset: { [self] payload in - record("STAGED " + payload) - try runtime.applyHostUpdate(kind: "composer-asset", payload: payload) - })) - let window = MenuTouchWindow(frame: UIScreen.main.bounds) - window.recordTouch = { [weak self] in self?.record($0) } - window.rootViewController = UIHostingController(rootView: host) - self.window = window - window.makeKeyAndVisible() } catch { fatalError("Native menu presentation fixture failed: \(error)") } - return true } } diff --git a/scripts/test-ios-native-menus.py b/scripts/test-ios-native-menus.py index a34e3b23..d19967a4 100644 --- a/scripts/test-ios-native-menus.py +++ b/scripts/test-ios-native-menus.py @@ -46,7 +46,7 @@ def run(arguments, **kwargs): assert "EVENT extension native-navigation-stack dismiss-composer" not in events, events print("PASS: composer blank space receives its tap and a single menu selection presents Files") sys.exit(0) - for service, count in (("photos", 3), ("audio", 3), ("camera", 1), ("files", 1)): + for service, count in (("quick-photos", 1), ("photos", 3), ("audio", 3), ("camera", 1), ("files", 1)): assert events.count("REQUEST " + service) == count, (service, events) assets = [json.loads(line.removeprefix("STAGED ")) for line in events if line.startswith("STAGED ")] assert any(asset["assetType"] == "m4a" and asset["assetSize"] > 0 for asset in assets), assets diff --git a/shared/src/logseq/model.ml b/shared/src/logseq/model.ml index 34b935f7..e4fe74b0 100644 --- a/shared/src/logseq/model.ml +++ b/shared/src/logseq/model.ml @@ -1579,6 +1579,7 @@ let valid_base_url_ value = let valid_attachment_kind_ kind = kind = "files" || kind = "camera" || kind = "photos" || kind = "audio" + || kind = "quick-photos" let indexed_outliner_autocomplete_candidates candidates = List.mapi diff --git a/shared/src/logseq/view.ml b/shared/src/logseq/view.ml index 434c24c5..10a4cd6b 100644 --- a/shared/src/logseq/view.ml +++ b/shared/src/logseq/view.ml @@ -470,12 +470,16 @@ let extension_registry () = let open Lui_extension in component "bottom-chrome-switch" [profile IOS SwiftUIHost] true [] [property "selection-active" BoolScalar true None] []); + Lui_extension.register_component registry (let open Lui_protocol in + let open Lui_extension in + component "composer-attachment-remove" [profile IOS SwiftUIHost] true [] + [property "label" StringScalar true None] [event "remove" []]); Lui_extension.register_component registry (let open Lui_protocol in let open Lui_extension in component "bottom-tab-strip" [profile IOS SwiftUIHost; profile AndroidOS KotlinHost] true [] [property "inset" IntScalar true None; property "selected-index" IntScalar true None; property "items" StringScalar true None; property "cell-width" IntScalar true None] - [event "select" [event_field "index" IntScalar true]; event "home-double-tap" []]); + [event "select" [event_field "index" IntScalar true]]); Lui_extension.register_component registry (Lui_extension.component "native-flashcards-toolbar" [Lui_protocol.profile Lui_protocol.IOS Lui_protocol.SwiftUIHost] diff --git a/shared/src/logseq/view_composer.ml b/shared/src/logseq/view_composer.ml index e940c83b..77e450a4 100644 --- a/shared/src/logseq/view_composer.ml +++ b/shared/src/logseq/view_composer.ml @@ -76,29 +76,36 @@ let composer_asset_preview (context : Lui_ui.ui_context) asset_source : t = text ~value:title ~style_class:"caption line-clamp-3" [] ] let composer_asset_view model_source (context : Lui_ui.ui_context) asset_source send : t = - let asset = Signal.sample asset_source in + let asset : Model.composer_asset = Signal.sample asset_source in + let label = View_base.tr (Signal.sample model_source) "Remove attachment" in + let remove () = + ignore (send (Model.RemoveComposerAsset (Signal.sample asset_source).uuid)) in + let preview = composer_asset_preview context asset_source in + let contents = + if uses_ios_composer_controls context then [ + custom (fun context parent -> + let node = Lui_ui.extension context "composer-attachment-remove" in + Lui_ui.extension_property context node "label" (StringValue label); + Lui_ui.on_event context node (function + | ExtensionEvent (_, _, "remove", _) -> remove () + | _ -> ()); + ignore (mount context ~parent:node preview); + attach context parent node; + node); + ] else [ + preview; + column ~width:128 ~height:128 ~padding:4 ~main:`start [ + row ~main:`end_ ~height:24 [ + icon_button ~icon:(`app "close") ~variant:`ghost ~size:`sm ~width:24 + ~height:24 ~corner_radius:12 ~background:"muted-foreground" ~foreground:"white" ~label + ~accessibility_identifier:"composer.asset.remove" ~on_press:remove []; + ]; + spacer ~grow:1.0 []; + ]; + ] in stack ~width:128 ~height:128 ~accessibility_identifier:(View_base.composer_asset_identifier asset) - [ - composer_asset_preview context asset_source; - column ~width:128 ~height:128 ~padding:4 ~main:`start - [ - row ~main:`end_ ~height:24 - [ - icon_button ~icon:(`app "close") ~variant:`ghost ~size:`sm ~width:24 - ~height:24 ~corner_radius:12 ~background:"muted-foreground" - ~foreground:"white" ~label:(View_base.tr (Signal.sample model_source) "Remove attachment") - ~accessibility_identifier:"composer.asset.remove" - ~on_press:(fun _ -> - ignore - (send - (Model.RemoveComposerAsset - (Signal.sample asset_source).uuid))) - []; - ]; - spacer ~grow:1.0 []; - ]; - ] + contents let task_status_row model_source status_source send = let status = Signal.sample status_source in diff --git a/shared/src/logseq/view_screens.ml b/shared/src/logseq/view_screens.ml index f79c0cde..7a08cac5 100644 --- a/shared/src/logseq/view_screens.ml +++ b/shared/src/logseq/view_screens.ml @@ -197,10 +197,11 @@ let bottom_tab_row ~android ~tab_width ~action_width model_source send : t = if name = "notifications" then View_collaboration.notification_label current else View_base.tr current title in let navigate destination action = let current : Model.logseq_model = Signal.sample model_source in - if android && destination = Model.JournalsDestination then + let home = destination = Model.JournalsDestination in + let at_root = current.destination = destination && current.app_navigation_path = [] in + if home && (android || (at_root && current.selected_page = None)) then ignore (send Model.ScrollHomeToTop) - else if current.destination <> destination || current.app_navigation_path <> [] - || (destination = Model.JournalsDestination && current.selected_page <> None) + else if not at_root || (home && current.selected_page <> None) then ignore (send action) in let tab (destination, title, name, image, selected_image, action) = let selected = Signal.map (fun (current : Model.logseq_model) -> current.destination = destination) model_source in @@ -224,11 +225,11 @@ let bottom_tab_row ~android ~tab_width ~action_width model_source send : t = ~label:(label current) ~accessibility_identifier:("tab.bottom." ^ name) ~on_press []) in - let action image title identifier event = + let action ?on_long_press image title identifier event = icon_button ~icon:(`app image) ~variant:`ghost ~size:`icon ~width:action_width ~height:cell ~foreground:"foreground" ~label:(View_base.tr current title) ~accessibility_identifier:identifier - ~on_press:(press send event) [] in + ~on_press:(press send event) ?on_long_press [] in let group name width children = row ~width:(List.length children * width + 2 * inset) ~padding:inset ~gap:0 ~cross:`center @@ -262,15 +263,14 @@ let bottom_tab_row ~android ~tab_width ~action_width model_source send : t = Option.iter (fun (destination, _, _, _, _, action) -> navigate destination action) (List.nth_opt destinations index) | _ -> ()) - | ExtensionEvent (_, _, "home-double-tap", _) -> - ignore (send Model.ScrollHomeToTop) | _ -> ()); ignore (mount context ~parent:node (group "tabs" tab_width (List.map tab destinations))); attach context parent node; node) in let actions = group "actions" action_width [ action "bottom-search" "Search" "button.search" Model.OpenSearch; - action "capture-circle" "Capture" "button.composer.expand" Model.ExpandComposer; + action "capture-circle" "Capture" "button.composer.expand" Model.ExpandComposer + ?on_long_press:(if android then None else Some (press send (Model.ChooseAttachment "quick-photos"))); ] in let actions = if android then box ~background:"glass" ~border_width:1 ~border_color:"border" ~corner_radius:29 [actions] diff --git a/shared/test/logseq/app_test.ml b/shared/test/logseq/app_test.ml index c2d0818c..41b2c93a 100644 --- a/shared/test/logseq/app_test.ml +++ b/shared/test/logseq/app_test.ml @@ -4930,7 +4930,7 @@ let ios_bottom_tabs_and_actions_use_separate_groups () = let strip = descendant_with_extension renderer application row "bottom-tab-strip" in let current_strip () = descendant_with_extension renderer application (native_bottom_chrome renderer application) "bottom-tab-strip" in - let swipe_to index = + let select_tab index = dispatch application (Lui_protocol.ExtensionEvent (current_strip (), "bottom-tab-strip", "select", Lui_protocol.String_map.singleton "index" (Lui_protocol.IntValue index))); flush application in @@ -4942,20 +4942,29 @@ let ios_bottom_tabs_and_actions_use_separate_groups () = (List.map (fun id -> id, 58) (children renderer tabs) @ List.map (fun id -> id, 50) (children renderer actions)); check_eq (property_string renderer capture Lui_protocol.InlineIconName) "app:capture-circle"; + let before_hold = App.model application in + dispatch application (Lui_protocol.LongPress capture); + flush application; + check_eq ~msg:"holding Capture requests the compact Photos picker" + (App.model application).pending_effects + (before_hold.pending_effects + @ [Model.PresentAttachmentEffect (before_hold.next_effect_id, "quick-photos")]); + check ~msg:"holding Capture leaves the text composer collapsed" + (not (App.model application).composer_expanded); check_eq (selected (tab "home")) true; - swipe_to 1; + select_tab 1; check_eq (selected (tab "tasks")) true; check_eq (extension_property application strip "selected-index") (Some (Lui_protocol.IntValue 1)); check_eq (selected (tab "home")) false; check (descendant_with_identifier renderer (Lui_app.root_node application) "tasks.empty" <> -1); - swipe_to 3; + select_tab 3; check_eq (App.model application).destination Model.TasksDestination; let root = Lui_app.root_node application in let inbox () = descendant_with_identifier renderer root "screen.notifications" in let retained_inbox = inbox () in check_eq (node renderer retained_inbox) (Some Lui_protocol.VirtualList); check (not (selected retained_inbox)); - swipe_to 2; + select_tab 2; check_eq (App.model application).destination Model.NotificationsDestination; check (selected (tab "notifications")); check_eq (inbox ()) retained_inbox; @@ -4981,21 +4990,22 @@ let ios_bottom_tabs_and_actions_use_separate_groups () = check_eq ~msg:"iOS keeps main's compact native-navigation inset" (property_int renderer top_inset Lui_protocol.HeightValue) 16; - let double_home () = - dispatch application (Lui_protocol.ExtensionEvent (current_strip (), "bottom-tab-strip", "home-double-tap", - Lui_protocol.String_map.empty)); - flush application in check_eq (App.model application).home_scroll_request 0; - double_home (); - swipe_to 1; + select_tab 0; + check_eq ~msg:"a single Home reselect requests a return to the top" + (App.model application).home_scroll_request 1; + select_tab 1; send application Model.ExpandComposer; flush application; check ~msg:"Capture defaults to a task on Tasks" ((App.model application).selected_task_status <> None); send application Model.DismissComposer; flush application; - double_home (); - check_eq (App.model application).home_scroll_request 2; + select_tab 0; + check_eq ~msg:"switching from Tasks to Home keeps the previous scroll position" + (App.model application).home_scroll_request 1; check_eq (App.model application).destination Model.JournalsDestination; + select_tab 0; + check_eq (App.model application).home_scroll_request 2; send application Model.ExpandComposer; flush application; check_eq ~msg:"Dismissing an empty task capture preserves normal capture on Home" @@ -11493,7 +11503,7 @@ let composer_attachment_previews_remove_only_the_selected_draft () = descendant_with_identifier renderer root "composer.asset.asset-a" in let remove = - descendant_with_identifier renderer preview "composer.asset.remove" + descendant_with_extension renderer application preview "composer-attachment-remove" in let attachment = descendant_with_identifier renderer root "button.attachment" @@ -11511,7 +11521,8 @@ let composer_attachment_previews_remove_only_the_selected_draft () = check_eq ~msg:"the add symbol keeps a regular stroke weight" (property renderer attachment Lui_protocol.StyleClass) None; - dispatch application (Lui_protocol.Press remove); + dispatch application (Lui_protocol.ExtensionEvent + (remove, "composer-attachment-remove", "remove", Lui_protocol.String_map.empty)); flush application; check_eq ~msg:"the close button removes only its own draft" (List.length (App.model application).composer_assets) 1; diff --git a/shared/test/logseq/drive/composer/composer-remove-asset.drive b/shared/test/logseq/drive/composer/composer-remove-asset.drive index d1e77363..7036cb9a 100644 --- a/shared/test/logseq/drive/composer/composer-remove-asset.drive +++ b/shared/test/logseq/drive/composer/composer-remove-asset.drive @@ -10,6 +10,6 @@ wait prop:accessibility-identifier=button.attachment press prop:accessibility-identifier=button.attachment press prop:accessibility-identifier=button.attachment.camera wait prop:accessibility-identifier=composer.asset.asset-1 -press prop:accessibility-identifier=composer.asset.remove +ext ext:composer-attachment-remove composer-attachment-remove remove '{}' expect-absent prop:accessibility-identifier=composer.asset.asset-1 expect-absent text:"Photo.jpg" diff --git a/tests/e2e/ios-composer-native-menus.yaml b/tests/e2e/ios-composer-native-menus.yaml index 8929b63c..aee59a7c 100644 --- a/tests/e2e/ios-composer-native-menus.yaml +++ b/tests/e2e/ios-composer-native-menus.yaml @@ -1,5 +1,11 @@ appId: com.logseq.logseq --- +- assertVisible: + id: button.composer.expand +- longPressOn: + id: button.composer.expand +- assertVisible: All Photos +- tapOn: Cancel - assertVisible: id: button.composer.expand - assertVisible: