diff --git a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidOutlinerSpacingTest.kt b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidOutlinerSpacingTest.kt index e865bbd3..dfe825df 100644 --- a/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidOutlinerSpacingTest.kt +++ b/android/app/src/androidTest/kotlin/com/logseq/logseq/AndroidOutlinerSpacingTest.kt @@ -1,6 +1,10 @@ package com.logseq.logseq import android.accessibilityservice.AccessibilityService +import android.view.View +import android.view.ViewGroup +import android.view.inspector.WindowInspector +import android.webkit.WebView import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialExpressiveTheme @@ -373,6 +377,58 @@ class AndroidOutlinerSpacingTest { assertEquals("A disclosure must not change document row spacing", after.value, before.value, 0.5f) } + @Test fun deeplyNestedEmbedsKeepTheDisclosureInTheTrailingGutter() { + fun embedSnapshot(type: String, collapsed: Boolean = false): String { + val response = JSONObject(snapshot()) + val rows = response.getJSONObject("result").getJSONArray("outlinerRows") + val embed = rows.getJSONObject(0).put("depth", 24).put("isCollapsed", collapsed) + embed.getJSONObject("block").put("markup", JSONArray().put(JSONObject() + .put("type", type).put("embedURL", "https://127.0.0.1:1"))) + if (collapsed) rows.remove(1) else rows.getJSONObject(1).put("depth", 25) + return response.toString() + } + fun findWebView(view: View): WebView? = when (view) { + is WebView -> view + is ViewGroup -> (0 until view.childCount).firstNotNullOfOrNull { findWebView(view.getChildAt(it)) } + else -> null + } + render() + val disclosure = ui.onNodeWithTag("button.outliner.collapse.parent") + val rowEnd = disclosure.getUnclippedBoundsInRoot().right + for (type in listOf("iframe", "video")) { + ui.runOnIdle { + filter.applyJson(requireNotNull(bridge).applySnapshot(embedSnapshot(type))) + } + val media = ui.onNodeWithTag("media.webview.loaded", useUnmergedTree = true) + media.assertIsDisplayed() + disclosure.assertIsDisplayed() + val buttonBounds = disclosure.getUnclippedBoundsInRoot() + assertTrue("The $type disclosure ends at the row edge", + buttonBounds.right in (rowEnd - 1.dp)..(rowEnd + 1.dp)) + val webView = ui.runOnIdle { + requireNotNull(WindowInspector.getGlobalWindowViews().firstNotNullOfOrNull(::findWebView)) + .also { it.loadDataWithBaseURL(null, """ + + Wide $type fixture + + + + """.trimIndent(), "text/html", "UTF-8", null) } + } + ui.waitUntil(5_000) { ui.runOnIdle { webView.title == "Wide $type fixture" } } + assertTrue("The $type leaves room for the disclosure", + media.getUnclippedBoundsInRoot().right <= buttonBounds.left + 1.dp) + disclosure.performTouchInput { click(center) } + ui.runOnIdle { + assertTrue(events.filterIsInstance().any { it.name == "collapse" }) + events.clear() + filter.applyJson(requireNotNull(bridge).applySnapshot(embedSnapshot(type, collapsed = true))) + } + ui.onNodeWithText("Child note").assertDoesNotExist() + disclosure.assertIsDisplayed() + } + } + @Test fun taskDatePropertiesAlignWithBlockText() { render() for (variant in 0..3) { @@ -398,8 +454,19 @@ class AndroidOutlinerSpacingTest { render() val zoom = ui.onNodeWithTag("button.outliner.zoom.parent.Parent note") zoom.assertIsDisplayed().assertTouchWidthIsEqualTo(48.dp).assertTouchHeightIsEqualTo(48.dp) + val bullet = zoom.getUnclippedBoundsInRoot() + val journal = ui.onNodeWithTag("list.outliner") + val viewport = journal.getUnclippedBoundsInRoot() ui.runOnIdle { events.clear() } - zoom.performTouchInput { click(center) } - ui.runOnIdle { assertEquals(1, events.filterIsInstance().size) } + journal.performTouchInput { + click(Offset( + (bullet.left - viewport.left - 4.dp).toPx(), + ((bullet.top + bullet.bottom) / 2 - viewport.top).toPx(), + )) + } + ui.runOnIdle { + assertEquals(listOf("parent"), events.filterIsInstance() + .filter { it.name == "open-node" }.map { it.values["uuid"] }) + } } } diff --git a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/OutlinerBlockRow.kt b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/OutlinerBlockRow.kt index d7f40f3d..48824e4d 100644 --- a/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/OutlinerBlockRow.kt +++ b/android/app/src/main/kotlin/com/logseq/logseq/ui/extensions/OutlinerBlockRow.kt @@ -44,7 +44,9 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.layout import androidx.compose.ui.layout.onPlaced import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.LocalDensity @@ -322,6 +324,7 @@ private fun OutlinerBlockRow( val stroke = 1.dp.toPx() for (level in 0 until guideCount) { val x = (12 + level * 22).dp.toPx() + if (x >= size.width) break val top = if (level == bulletDepth) 17.5.dp.toPx() else 0f if (size.height > top) { drawLine(guideColor, Offset(x, top), Offset(x, size.height), strokeWidth = stroke) @@ -337,165 +340,173 @@ private fun OutlinerBlockRow( markerInsetDp = markerInset, onToggleSelection = { currentContext.emit("toggle-selection", "uuid" to row.uuid) }, ) { - Row( + Box( modifier = Modifier.fillMaxWidth() .then( if (highlight == Color.Transparent) Modifier else Modifier.background(highlight, RoundedCornerShape(8.dp)), ) .padding(vertical = 2.dp), - verticalAlignment = Alignment.Top, ) { - if (row.depth > 0) { - Spacer(Modifier.width((row.depth * 22).dp)) - } - val zoomTarget = row.embedSourceUuid ?: row.uuid - Box( - modifier = Modifier - .size(24.dp) - .semantics { - testTag = "button.outliner.zoom.${row.uuid}.${row.title}" - testTagsAsResourceId = true - if (row.openLabel.isNotEmpty()) contentDescription = row.openLabel - } - .combinedClickable( - role = Role.Button, - onClick = { - if (row.selectionMode) currentContext.emit("toggle-selection", "uuid" to row.uuid) - else currentContext.emit("open-node", "uuid" to zoomTarget) - }, - onLongClick = if (row.hasCustomContent) null else ({ menuOpen = true }), - ), - contentAlignment = Alignment.Center, + Row( + modifier = Modifier.fillMaxWidth() + .padding(end = if (row.hasChildren) 24.dp else 0.dp), + verticalAlignment = Alignment.Top, ) { - when { - row.listNumber != null -> Text( - text = "${row.listNumber}.", - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - row.nodeIconJson != null -> NodeIcon(row.nodeIconJson, size = 18, muted = false) - else -> Icon( - imageVector = masterIcons.getValue( - if (row.collapsed && row.hasChildren) "outliner-bullet-closed" else "outliner-bullet", - ), - contentDescription = null, - tint = bulletColor, - modifier = Modifier - .size(24.dp) - .semantics { - testTag = "outliner.bullet-glyph.${row.uuid}" - testTagsAsResourceId = true + if (row.depth > 0) { + Spacer(Modifier.layout { _, constraints -> + val indent = minOf((row.depth * 22).dp.roundToPx(), constraints.maxWidth / 2) + layout(indent, 0) {} + }) + } + val zoomTarget = row.embedSourceUuid ?: row.uuid + Box( + modifier = Modifier + .size(24.dp) + .semantics { + testTag = "button.outliner.zoom.${row.uuid}.${row.title}" + testTagsAsResourceId = true + if (row.openLabel.isNotEmpty()) contentDescription = row.openLabel + } + .combinedClickable( + role = Role.Button, + onClick = { + if (row.selectionMode) currentContext.emit("toggle-selection", "uuid" to row.uuid) + else currentContext.emit("open-node", "uuid" to zoomTarget) }, - ) + onLongClick = if (row.hasCustomContent) null else ({ menuOpen = true }), + ), + contentAlignment = Alignment.Center, + ) { + when { + row.listNumber != null -> Text( + text = "${row.listNumber}.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + row.nodeIconJson != null -> NodeIcon(row.nodeIconJson, size = 18, muted = false) + else -> Icon( + imageVector = masterIcons.getValue( + if (row.collapsed && row.hasChildren) "outliner-bullet-closed" else "outliner-bullet", + ), + contentDescription = null, + tint = bulletColor, + modifier = Modifier + .size(24.dp) + .semantics { + testTag = "outliner.bullet-glyph.${row.uuid}" + testTagsAsResourceId = true + }, + ) + } } - } - Spacer(Modifier.width(2.dp)) - row.status?.let { status -> - OutlinerRowPicker( - id = "button.block-task-status", - title = status.title, - icon = status.icon, - tint = luiThemeColor(status.foreground, foreground = true), - glyphTag = "outliner.task-status-icon.${row.uuid}", - iconAlignment = Alignment.CenterStart, - ) { dismiss -> - row.statuses.forEachIndexed { index, choice -> - OutlinerMenuChoice( - title = choice.title, - icon = choice.icon, - selected = choice.optionId == status.optionId, - index = index, - itemCount = row.statuses.size, - tint = luiThemeColor(choice.foreground, foreground = true), - modifier = outlinerControlTag(choice.optionId), - ) { - dismiss() - currentContext.emit("set-status", "uuid" to row.uuid, "count" to index) + Spacer(Modifier.width(2.dp)) + row.status?.let { status -> + OutlinerRowPicker( + id = "button.block-task-status", + title = status.title, + icon = status.icon, + tint = luiThemeColor(status.foreground, foreground = true), + glyphTag = "outliner.task-status-icon.${row.uuid}", + iconAlignment = Alignment.CenterStart, + ) { dismiss -> + row.statuses.forEachIndexed { index, choice -> + OutlinerMenuChoice( + title = choice.title, + icon = choice.icon, + selected = choice.optionId == status.optionId, + index = index, + itemCount = row.statuses.size, + tint = luiThemeColor(choice.foreground, foreground = true), + modifier = outlinerControlTag(choice.optionId), + ) { + dismiss() + currentContext.emit("set-status", "uuid" to row.uuid, "count" to index) + } } } } - } - row.priority?.let { priority -> - OutlinerRowPicker("button.block-task-priority", priority.title, priority.icon) { dismiss -> - val choices = row.raw.optJSONArray("priorities") - val count = choices?.length() ?: 0 - for (index in 0 until count) { - val choice = choices?.optJSONObject(index) ?: continue - val uuid = choice.optString("uuid") - OutlinerMenuChoice( - title = choice.optString("title"), - icon = choice.optString("icon"), - selected = uuid == priority.uuid, - index = index, + row.priority?.let { priority -> + OutlinerRowPicker("button.block-task-priority", priority.title, priority.icon) { dismiss -> + val choices = row.raw.optJSONArray("priorities") + val count = choices?.length() ?: 0 + for (index in 0 until count) { + val choice = choices?.optJSONObject(index) ?: continue + val uuid = choice.optString("uuid") + OutlinerMenuChoice( + title = choice.optString("title"), + icon = choice.optString("icon"), + selected = uuid == priority.uuid, + index = index, + itemCount = count + 1, + modifier = outlinerControlTag("button.block-task-priority-option.$uuid"), + ) { + dismiss() + currentContext.emit("set-priority", "priority" to uuid) + } + } + BlockActionItem( + title = row.raw.optString("clearPriorityTitle", "Clear priority"), + icon = "", + index = count, itemCount = count + 1, - modifier = outlinerControlTag("button.block-task-priority-option.$uuid"), + modifier = outlinerControlTag("button.block-task-priority-clear"), ) { dismiss() - currentContext.emit("set-priority", "priority" to uuid) + currentContext.emit("set-priority", "priority" to "") } } - BlockActionItem( - title = row.raw.optString("clearPriorityTitle", "Clear priority"), - icon = "", - index = count, - itemCount = count + 1, - modifier = outlinerControlTag("button.block-task-priority-clear"), - ) { - dismiss() - currentContext.emit("set-priority", "priority" to "") - } } - } - row.pdfPage?.let { page -> - Text( - text = "📌 P$page", - style = MaterialTheme.typography.labelMedium, - color = luiThemeColor("link", foreground = true) ?: MaterialTheme.colorScheme.primary, - modifier = outlinerControlTag("pdf.annotation-page.${row.uuid}") - .clickable { currentContext.emit("menu-action", "payload" to "open-annotation") } - .padding(horizontal = 4.dp, vertical = 6.dp), - ) - } - if (!row.hasCustomContent && row.tags.isEmpty()) { - OutlinerRowRichBody( - modifier = Modifier.weight(1f), - context = context, - row = row, - resolveAssetPath = resolveAssetPath, - youtubeStarts = youtubeStarts, - onOpenImage = onOpenImage, - loadImage = loadImage, - menuOpen = menuOpen, - onMenuOpen = { menuOpen = it }, - onMenuHold = { menuHeld = it }, - ) - } else { - Column(Modifier.weight(1f)) { - if (row.hasCustomContent) { - context.Children() - } else { - OutlinerRowRichBody( - modifier = Modifier.fillMaxWidth(), - context = context, - row = row, - resolveAssetPath = resolveAssetPath, - youtubeStarts = youtubeStarts, - onOpenImage = onOpenImage, - loadImage = loadImage, - menuOpen = menuOpen, - onMenuOpen = { menuOpen = it }, - onMenuHold = { menuHeld = it }, - ) - } - if (row.tags.isNotEmpty()) { - FlowRow( - modifier = Modifier.padding(top = 2.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - verticalArrangement = Arrangement.spacedBy(2.dp), - ) { - row.tags.forEach { tag -> - OutlinerRowTagChip(row, tag, currentContext) + row.pdfPage?.let { page -> + Text( + text = "📌 P$page", + style = MaterialTheme.typography.labelMedium, + color = luiThemeColor("link", foreground = true) ?: MaterialTheme.colorScheme.primary, + modifier = outlinerControlTag("pdf.annotation-page.${row.uuid}") + .clickable { currentContext.emit("menu-action", "payload" to "open-annotation") } + .padding(horizontal = 4.dp, vertical = 6.dp), + ) + } + if (!row.hasCustomContent && row.tags.isEmpty()) { + OutlinerRowRichBody( + modifier = Modifier.weight(1f).clipToBounds(), + context = context, + row = row, + resolveAssetPath = resolveAssetPath, + youtubeStarts = youtubeStarts, + onOpenImage = onOpenImage, + loadImage = loadImage, + menuOpen = menuOpen, + onMenuOpen = { menuOpen = it }, + onMenuHold = { menuHeld = it }, + ) + } else { + Column(Modifier.weight(1f).clipToBounds()) { + if (row.hasCustomContent) { + context.Children() + } else { + OutlinerRowRichBody( + modifier = Modifier.fillMaxWidth(), + context = context, + row = row, + resolveAssetPath = resolveAssetPath, + youtubeStarts = youtubeStarts, + onOpenImage = onOpenImage, + loadImage = loadImage, + menuOpen = menuOpen, + onMenuOpen = { menuOpen = it }, + onMenuHold = { menuHeld = it }, + ) + } + if (row.tags.isNotEmpty()) { + FlowRow( + modifier = Modifier.padding(top = 2.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalArrangement = Arrangement.spacedBy(2.dp), + ) { + row.tags.forEach { tag -> + OutlinerRowTagChip(row, tag, currentContext) + } } } } @@ -505,6 +516,7 @@ private fun OutlinerBlockRow( val chevron = logseqIconResolver.icon(if (row.collapsed) "chevron-right" else "chevron-down") Box( modifier = Modifier + .align(Alignment.TopEnd) .size(24.dp) .semantics { testTag = "button.outliner.collapse.${row.uuid}" diff --git a/apple/Sources/Logseq/LGInlineImage.swift b/apple/Sources/Logseq/LGInlineImage.swift index ed5600cf..17aabb1e 100644 --- a/apple/Sources/Logseq/LGInlineImage.swift +++ b/apple/Sources/Logseq/LGInlineImage.swift @@ -125,6 +125,26 @@ private final class LGInlineImageThumbnailCache: @unchecked Sendable { } struct LGInlineImage: View { + private struct PreviewLayout: Layout { + let size: CGSize + var fitsContent = false + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + // The outliner proposes the width left after indentation and row controls. + let width = min(proposal.width ?? size.width, size.width) + let previewHeight = size.height * (width / size.width) + let contentHeight = fitsContent + ? subviews.first?.sizeThatFits(ProposedViewSize(width: width, height: nil)).height ?? 0 + : 0 + return CGSize(width: width, height: max(previewHeight, contentHeight)) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + subviews.first?.place(at: CGPoint(x: bounds.midX, y: bounds.midY), + anchor: .center, proposal: ProposedViewSize(bounds.size)) + } + } + let url: URL let dimensions: LGImageDimensions? @State private var thumbnail: CGImage? @@ -140,14 +160,15 @@ struct LGInlineImage: View { var body: some View { let size = dimensions?.previewSize ?? LGInlineImageThumbnailCache.shared.previewSize(for: url) Group { - if let thumbnail { - let displaySize = size ?? LGImageDimensions(width: thumbnail.width, height: thumbnail.height).previewSize - Image(decorative: thumbnail, scale: 1) - .resizable() - .scaledToFit() - .frame(width: displaySize?.width, height: displaySize?.height) - .clipShape(.rect(cornerRadius: 8)) - .frame(maxWidth: .infinity, alignment: .leading) + if let thumbnail, + let displaySize = size ?? LGImageDimensions(width: thumbnail.width, height: thumbnail.height).previewSize { + PreviewLayout(size: displaySize) { + Image(decorative: thumbnail, scale: 1) + .resizable() + .scaledToFit() + .clipShape(.rect(cornerRadius: 8)) + } + .frame(maxWidth: .infinity, alignment: .leading) } else { Self.placeholder(size: size) { ProgressView() } } @@ -177,15 +198,19 @@ struct LGInlineImage: View { } } - static func placeholder(size: CGSize?, @ViewBuilder content: () -> Content) -> some View { - content() - .frame(width: size?.width, height: size?.height ?? 120) - .background { - if size != nil { - RoundedRectangle(cornerRadius: 8).fill(.secondary.opacity(0.08)) + static func placeholder(size: CGSize?, fitsContent: Bool = false, + @ViewBuilder content: () -> Content) -> some View { + Group { + if let size { + PreviewLayout(size: size, fitsContent: fitsContent) { + content().frame(minHeight: fitsContent ? 44 : nil) } + .background { RoundedRectangle(cornerRadius: 8).fill(.secondary.opacity(0.08)) } + } else { + content().frame(minHeight: 120) } - .frame(maxWidth: .infinity, alignment: .leading) + } + .frame(maxWidth: .infinity, alignment: .leading) } } #endif diff --git a/apple/Sources/Logseq/LGRichBlockExtension.swift b/apple/Sources/Logseq/LGRichBlockExtension.swift index fc295cff..c30cf603 100644 --- a/apple/Sources/Logseq/LGRichBlockExtension.swift +++ b/apple/Sources/Logseq/LGRichBlockExtension.swift @@ -43,15 +43,15 @@ final class LGYouTubePlaybackState { } struct OutlinerDropIndicator: View { - let placement: OutlinerDropPlacement? - let depth: Int + let destination: OutlinerDropDestination? var body: some View { Canvas { context, size in - guard let placement else { return } - let parentX = min(size.width, CGFloat(max(0, depth)) * 22 + 12) + guard let destination else { return } + let placement = destination.placement + let parentX = min(size.width, destination.leadingInset + OutlinerLayoutMetrics.rootBulletCenterX) let y: CGFloat = placement == .before ? 1 : max(1, size.height - 1) - let x = placement == .inside ? min(size.width, parentX + 22) : parentX + let x = placement == .inside ? min(size.width, parentX + OutlinerLayoutMetrics.indentation) : parentX var line = Path() if placement == .inside { line.move(to: CGPoint(x: parentX, y: max(1, y - 12))) @@ -291,12 +291,13 @@ struct LGAssetPreview: View { .accessibilityLabel(selectionLabel.map(Text.init(verbatim:)) ?? Text("Preview image")) .accessibilityIdentifier("image.open." + uuid) } else if let downloadError { - LGInlineImage.placeholder(size: imageDimensions?.previewSize) { + LGInlineImage.placeholder(size: imageDimensions?.previewSize, fitsContent: true) { Button { guard allowsInteraction() else { return } if let selectBlock { selectBlock() } else { retry += 1 } } label: { SwiftUI.Label("Retry image", systemImage: "arrow.clockwise") + .multilineTextAlignment(.center) } .accessibilityLabel(selectionLabel.map(Text.init(verbatim:)) ?? Text("Retry image")) .accessibilityHint(downloadError) diff --git a/apple/Sources/Logseq/OutlinerDropZone.swift b/apple/Sources/Logseq/OutlinerDropZone.swift index 1de9d456..c362d645 100644 --- a/apple/Sources/Logseq/OutlinerDropZone.swift +++ b/apple/Sources/Logseq/OutlinerDropZone.swift @@ -14,6 +14,11 @@ enum OutlinerDropPlacement: Equatable { } } +struct OutlinerDropDestination: Equatable { + let placement: OutlinerDropPlacement + let leadingInset: CGFloat +} + enum OutlinerDropZone { static func placement( startX: CGFloat, @@ -21,12 +26,12 @@ enum OutlinerDropZone { rowX: CGFloat, rowY: CGFloat, rowHeight: CGFloat, - depth: Int = 0 + leadingInset: CGFloat = 0 ) -> OutlinerDropPlacement { let topZone = min(16, max(rowHeight, 1) * 0.25) if rowY < topZone { return .before } let indent: CGFloat = 22 - let childX = CGFloat(max(0, depth) + 1) * indent + let childX = leadingInset + indent if dropX - startX >= indent && rowX >= childX { return .inside } return .after } diff --git a/apple/Sources/Logseq/OutlinerIndentGuides.swift b/apple/Sources/Logseq/OutlinerIndentGuides.swift index e5b5e916..9bd15f30 100644 --- a/apple/Sources/Logseq/OutlinerIndentGuides.swift +++ b/apple/Sources/Logseq/OutlinerIndentGuides.swift @@ -6,15 +6,16 @@ enum OutlinerGuideGeometry { let path = CGMutablePath() for level in 0.. guideStart { - let x = OutlinerLayoutMetrics.bulletCenterX(depth: max(0, depth)) - path.move(to: CGPoint(x: x, y: guideStart)) - path.addLine(to: CGPoint(x: x, y: size.height)) + let bulletX = OutlinerLayoutMetrics.bulletCenterX(depth: max(0, depth)) + if expanded, bulletX < size.width, size.height > guideStart { + path.move(to: CGPoint(x: bulletX, y: guideStart)) + path.addLine(to: CGPoint(x: bulletX, y: size.height)) } return path } diff --git a/apple/Sources/Logseq/OutlinerRowExtension.swift b/apple/Sources/Logseq/OutlinerRowExtension.swift index 4d5c254a..f9b4a213 100644 --- a/apple/Sources/Logseq/OutlinerRowExtension.swift +++ b/apple/Sources/Logseq/OutlinerRowExtension.swift @@ -109,8 +109,8 @@ struct OutlinerRowPayload: Decodable, Equatable { @MainActor final class OutlinerBlockInteractions: NSObject, UIContextMenuInteractionDelegate, UIDragInteractionDelegate, UIDropInteractionDelegate { struct DropTarget { let id: String - let depth: Int - let showPlacement: (OutlinerDropPlacement?) -> Void + let richRowInset: CGFloat + let showPlacement: (OutlinerDropDestination?) -> Void let drop: (OutlinerDropPlacement) -> Void } @@ -190,23 +190,25 @@ struct OutlinerRowPayload: Decodable, Equatable { origin(for: session) != nil } - private func placement(for interaction: UIDropInteraction, session: any UIDropSession) -> OutlinerDropPlacement? { + private func destination(for interaction: UIDropInteraction, session: any UIDropSession) -> OutlinerDropDestination? { guard let origin = origin(for: session), let target = configuration?.dropTarget, let view = interaction.view, let window = view.window else { return nil } let point = session.location(in: view) - return OutlinerDropZone.placement(startX: origin.x, dropX: session.location(in: window).x, - rowX: point.x, rowY: point.y, rowHeight: view.bounds.height, depth: target.depth) + let inset = (view as? OutlinerTextRowView)?.leadingInset ?? target.richRowInset + let placement = OutlinerDropZone.placement(startX: origin.x, dropX: session.location(in: window).x, + rowX: point.x, rowY: point.y, rowHeight: view.bounds.height, leadingInset: inset) + return OutlinerDropDestination(placement: placement, leadingInset: inset) } func dropInteraction(_ interaction: UIDropInteraction, sessionDidUpdate session: any UIDropSession) -> UIDropProposal { - let placement = placement(for: interaction, session: session) - configuration?.dropTarget?.showPlacement(placement) - return UIDropProposal(operation: placement == nil ? .cancel : .move) + let destination = destination(for: interaction, session: session) + configuration?.dropTarget?.showPlacement(destination) + return UIDropProposal(operation: destination == nil ? .cancel : .move) } func dropInteraction(_ interaction: UIDropInteraction, performDrop session: any UIDropSession) { - guard let placement = placement(for: interaction, session: session) else { return } - configuration?.dropTarget?.drop(placement) + guard let destination = destination(for: interaction, session: session) else { return } + configuration?.dropTarget?.drop(destination.placement) configuration?.dropTarget?.showPlacement(nil) } @@ -244,7 +246,8 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta func sizeThatFits(_ proposal: ProposedViewSize, uiViewController: UIHostingController, context: Context) -> CGSize? { guard let width = proposal.width else { return nil } - return uiViewController.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)) + let measured = uiViewController.sizeThatFits(in: CGSize(width: width, height: .greatestFiniteMagnitude)) + return CGSize(width: width, height: measured.height) } private var hostedContent: AnyView { @@ -312,8 +315,11 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta let context: LUIAppleExtensionViewContext let row: OutlinerRowPayload let playback: LGYouTubePlaybackState - @State private var dropPlacement: OutlinerDropPlacement? @State private var titleWidth: CGFloat = 0 + #if os(iOS) + @State private var dropDestination: OutlinerDropDestination? + @State private var cappedRichRowInset: CGFloat? + #endif @Environment(\.luiSemanticColors) private var semanticColors @Environment(\.colorScheme) private var colorScheme @Environment(\.logseqDarkTheme) private var darkTheme @@ -366,7 +372,7 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta } if row.allowsDrag != false { selectable - .overlay { OutlinerDropIndicator(placement: dropPlacement, depth: row.depth) } + .overlay { OutlinerDropIndicator(destination: dropDestination) } } else { selectable } @@ -409,8 +415,8 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta #if os(iOS) private var blockInteractions: OutlinerBlockInteractions.Configuration { let dropTarget: OutlinerBlockInteractions.DropTarget? = context.isUserInteractionEnabled && row.allowsDrag != false - ? .init(id: row.uuid, depth: row.depth, - showPlacement: { dropPlacement = $0 }, + ? .init(id: row.uuid, richRowInset: cappedRichRowInset ?? preferredIndent, + showPlacement: { dropDestination = $0 }, drop: { emit("drop", extra: ["placement": .string($0.eventValue)]) }) : nil return .init( @@ -522,9 +528,21 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta } #endif + private var preferredIndent: CGFloat { + CGFloat(max(0, row.depth)) * OutlinerLayoutMetrics.indentation + } + private var swiftUIContent: some View { HStack(alignment: .top, spacing: 0) { - Color.clear.frame(width: CGFloat(max(0, row.depth)) * 22, height: 1) + Color.clear + .frame(minWidth: 0, maxWidth: preferredIndent) + .frame(height: 1) + #if os(iOS) + .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { width in + let capped = width < preferredIndent ? width : nil + if cappedRichRowInset != capped { cappedRichRowInset = capped } + } + #endif let bullet = Group { if row.journalBullet { IconImage(name: row.collapsed && row.hasChildren ? "outliner_bullet_closed" : "outliner_bullet", size: 24).frame(height: 24) @@ -658,7 +676,8 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta .accessibilityIdentifier("outliner.sync-failed." + row.uuid) } } - .frame(maxWidth: .infinity, alignment: .leading) + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .clipped() #if os(iOS) .background(OutlinerScrollAnchorMarker(blockID: row.uuid, anchorID: row.scrollAnchorID ?? row.uuid)) #endif @@ -666,6 +685,7 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta let hitSize = OutlinerLayoutMetrics.disclosureHitSize let hitWidth = hitSize + row.disclosureGutter Color.clear.frame(width: hitWidth, height: OutlinerLayoutMetrics.titleLineHeight) + .layoutPriority(1) .overlay(alignment: .topTrailing) { Button { emit("collapse") } label: { HStack(spacing: 0) { @@ -684,6 +704,7 @@ private struct OutlinerHostedBlockRow: UIViewControllerRepresenta } } } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) .font(.body) .padding(.vertical, OutlinerLayoutMetrics.rowVerticalPadding) .background { OutlinerIndentGuides(row: row) } diff --git a/apple/Sources/Logseq/OutlinerTextRow.swift b/apple/Sources/Logseq/OutlinerTextRow.swift index d1f1dd53..ba345105 100644 --- a/apple/Sources/Logseq/OutlinerTextRow.swift +++ b/apple/Sources/Logseq/OutlinerTextRow.swift @@ -147,6 +147,8 @@ struct OutlinerTextRow: UIViewRepresentable { blockInteractions?.configuration = configuration } + var leadingInset: CGFloat { bullet.frame.minX } + private var resolvedLinkColor: UIColor? func update(_ row: OutlinerRowPayload, semanticColors: [String: Color] = [:], linkColor: Color? = nil, @@ -292,13 +294,14 @@ struct OutlinerTextRow: UIViewRepresentable { private func layout(width: CGFloat, apply: Bool) -> CGFloat { guard let row else { return 0 } - let inset = CGFloat(max(0, row.depth)) * 22 let statusWidth: CGFloat = row.status == nil ? 0 : OutlinerLayoutMetrics.statusIconSize + OutlinerLayoutMetrics.statusContentSpacing let disclosureSize = OutlinerLayoutMetrics.disclosureHitSize let trailing = row.hasChildren ? disclosureSize + row.disclosureGutter : 0 let priorityWidth: CGFloat = row.priority == nil ? 0 : 25 let iconLeading: CGFloat = row.status != nil ? OutlinerLayoutMetrics.statusLeading : (row.priority != nil ? 20 : 26) - let leading = inset + iconLeading + statusWidth + priorityWidth + let controlsWidth = iconLeading + statusWidth + priorityWidth + let inset = min(CGFloat(max(0, row.depth)) * 22, max(0, width - trailing - controlsWidth - 44)) + let leading = inset + controlsWidth let bodyWidth = max(1, width - leading - trailing) let titleHeight = OutlinerNativeTextMeasurement.size(text: title.attributedText?.string ?? "", font: title.font, width: bodyWidth, verticalInset: title.verticalInset, @@ -317,9 +320,13 @@ struct OutlinerTextRow: UIViewRepresentable { height += 2 var x = leading for button in tags { - let size = button.sizeThatFits(CGSize(width: bodyWidth, height: 22)) - if apply { button.frame = CGRect(x: x, y: height, width: size.width, height: 22) } - x += size.width + 6 + let tagWidth = min(bodyWidth, button.sizeThatFits(CGSize(width: bodyWidth, height: 22)).width) + if x > leading && x + tagWidth > leading + bodyWidth { + x = leading + height += 24 + } + if apply { button.frame = CGRect(x: x, y: height, width: tagWidth, height: 22) } + x += tagWidth + 6 } height += 22 } diff --git a/apple/Tests/Policies/OutlinerDropZone/main.swift b/apple/Tests/Policies/OutlinerDropZone/main.swift index 52179019..ee569d52 100644 --- a/apple/Tests/Policies/OutlinerDropZone/main.swift +++ b/apple/Tests/Policies/OutlinerDropZone/main.swift @@ -1,14 +1,16 @@ import Foundation -func placement(from start: CGFloat, to drop: CGFloat, rowX: CGFloat, rowY: CGFloat = 14, depth: Int = 0) -> OutlinerDropPlacement { - OutlinerDropZone.placement(startX: start, dropX: drop, rowX: rowX, rowY: rowY, rowHeight: 28, depth: depth) +func placement(from start: CGFloat, to drop: CGFloat, rowX: CGFloat, rowY: CGFloat = 14, leadingInset: CGFloat = 0) -> OutlinerDropPlacement { + OutlinerDropZone.placement(startX: start, dropX: drop, rowX: rowX, rowY: rowY, rowHeight: 28, leadingInset: leadingInset) } precondition(placement(from: 150, to: 150, rowX: 140) == .after, "A vertical drag must remain a sibling") precondition(placement(from: 150, to: 125, rowX: 115) == .after, "Dragging left must allow outdenting") precondition(placement(from: 100, to: 121, rowX: 111) == .after) precondition(placement(from: 100, to: 122, rowX: 112) == .inside) -precondition(placement(from: 45, to: 75, rowX: 65, depth: 2) == .after) -precondition(placement(from: 45, to: 76, rowX: 66, depth: 2) == .inside) +precondition(placement(from: 45, to: 75, rowX: 65, leadingInset: 44) == .after) +precondition(placement(from: 45, to: 76, rowX: 66, leadingInset: 44) == .inside) +precondition(placement(from: 310, to: 342, rowX: 342, leadingInset: 304) == .inside, + "Dropping rightward at the visible title of a capped row must nest the block") precondition(placement(from: 100, to: 150, rowX: 140, rowY: 1) == .before) print("Outliner drop policy checks passed") diff --git a/apple/Tests/UI/block-disclosure-edge.swift b/apple/Tests/UI/block-disclosure-edge.swift index 4cb5b3f3..265e998b 100644 --- a/apple/Tests/UI/block-disclosure-edge.swift +++ b/apple/Tests/UI/block-disclosure-edge.swift @@ -1,30 +1,94 @@ import SwiftUI import UIKit +import WebKit @testable import Logseq +@MainActor private final class TestDragSession: NSObject, UIDragSession, UIDropSession { + var localContext: Any? + var localDragSession: (any UIDragSession)? { self } + var items: [UIDragItem] = [] + let allowsMoveOperation = true + let isRestrictedToDraggingApplication = true + let progress = Progress() + var progressIndicatorStyle: UIDropSessionProgressIndicatorStyle = .none + var windowPoint = CGPoint.zero + + func location(in view: UIView) -> CGPoint { view.convert(windowPoint, from: view.window) } + func hasItemsConforming(toTypeIdentifiers typeIdentifiers: [String]) -> Bool { false } + func canLoadObjects(ofClass aClass: any NSItemProviderReading.Type) -> Bool { false } + func loadObjects(ofClass aClass: any NSItemProviderReading.Type, + completion: @escaping ([any NSItemProviderReading]) -> Void) -> Progress { progress } +} + @main struct CheckBlockDisclosureEdge { @MainActor static func main() async throws { - func snapshot(collapsed: Bool) throws -> String { + let fixture = URL.temporaryDirectory.appendingPathComponent("journal-diagram.png") + let imageSize = CGSize(width: 900, height: 480) + let format = UIGraphicsImageRendererFormat() + format.scale = 1 + let image = UIGraphicsImageRenderer(size: imageSize, format: format).image { context in + UIColor.systemTeal.setFill() + context.fill(CGRect(origin: .zero, size: imageSize)) + } + guard let png = image.pngData() else { throw failure("Could not create the journal image") } + try png.write(to: fixture) + defer { try? FileManager.default.removeItem(at: fixture) } + + func snapshot(collapsed: Bool, media: String? = nil, cappedDrop: Bool = false) throws -> String { func block(_ uuid: String, _ title: String) -> [String: Any] { ["uuid": uuid, "title": title, "pageId": "today", "journalTitle": "Nov 24th, 2026", "journalDay": 20261124] } + func imageBlock(_ uuid: String, localPath: String? = nil) -> [String: Any] { + var asset = block(uuid, "journal-diagram.png") + asset["isAsset"] = true + asset["assetType"] = "image/png" + asset["imageDimensions"] = ["width": Int(imageSize.width), "height": Int(imageSize.height)] + asset["localPath"] = localPath + return ["block": asset, "depth": 3] + } var rows: [[String: Any]] = [ ["block": block("parent", "Tabs"), "depth": 0, "hasChildren": true, "isCollapsed": collapsed] ] - if !collapsed { rows.append(["block": block("child", "Journals"), "depth": 1]) } + if cappedDrop { + rows.append(["block": block("destination", "Capped destination"), "depth": 24]) + } else if let media { + let html = """ + +
+
+ """ + var embed = block("media", "Wide embedded \(media)") + let source = "data:text/html;base64," + Data(html.utf8).base64EncodedString() + embed["markup"] = [["type": media, "embedURL": source]] + rows.append(["block": embed, "depth": 24, "hasChildren": true]) + } else if !collapsed { + rows += [ + ["block": block("child", "Journals"), "depth": 1], + ["block": block("branch", "Journal notes"), "depth": 1, "hasChildren": true], + ["block": block("nested", "Implementation details"), "depth": 2, "hasChildren": true], + imageBlock("unavailable-image"), + imageBlock("local-image", localPath: fixture.path) + ] + } let result: [String: Any] = ["graphName": "Work", "selectedGraphId": "work", "outlinerRows": rows] return String(decoding: try JSONSerialization.data(withJSONObject: ["ok": true, "result": result]), as: UTF8.self) } let collapsedSnapshot = try snapshot(collapsed: true) let expandedSnapshot = try snapshot(collapsed: false) + let dropSnapshot = try snapshot(collapsed: true, cappedDrop: true) var collapsed = true + var observedDrop: String? let runtime = LGRuntime(native: LGCoreNativeCaller(), effectExecutor: LGCoreEffectExecutor(callCore: { request in if let data = request.params.payload?.data(using: .utf8), - let effect = try? JSONSerialization.jsonObject(with: data) as? [String: Any], - effect["kind"] as? String == "toggle-outliner-collapsed", effect["text"] as? String == "parent" { - collapsed.toggle() + let effect = try? JSONSerialization.jsonObject(with: data) as? [String: Any] { + if effect["kind"] as? String == "toggle-outliner-collapsed", effect["text"] as? String == "parent" { + collapsed.toggle() + } else if effect["kind"] as? String == "drop-outliner-blocks", effect["text"] as? String == "destination" { + observedDrop = effect["metadata"] as? String + return dropSnapshot + } } return collapsed ? collapsedSnapshot : expandedSnapshot })) @@ -42,15 +106,13 @@ import UIKit views(window).first { $0.accessibilityIdentifier == identifier && !$0.isHidden } } - try await Task.sleep(for: .milliseconds(700)) - for initiallyCollapsed in [true, false] { - guard collapsed == initiallyCollapsed, - let disclosure = control("button.outliner.collapse.parent") as? UIButton, - let arrow = disclosure.imageView else { throw failure("Missing disclosure control") } + func checkedDisclosure(_ id: String) throws -> UIButton { + guard let disclosure = control("button.outliner.collapse." + id) as? UIButton, + let arrow = disclosure.imageView else { throw failure("Missing disclosure control for \(id)") } let arrowFrame = arrow.convert(arrow.bounds, to: window) // On a compact viewport, the existing row margin and glyph inset leave 14 points. let gap = window.bounds.maxX - arrowFrame.maxX - guard abs(gap - 14) <= 1 else { throw failure("Unexpected arrow inset: \(gap)") } + guard abs(gap - 14) <= 1 else { throw failure("Unexpected arrow inset for \(id): \(gap)") } for distance: CGFloat in [12, 6, 2] { for offset: CGFloat in [-6, 0, 6] { let point = CGPoint(x: window.bounds.maxX - distance, y: arrowFrame.midY + offset) @@ -59,7 +121,26 @@ import UIKit } } } + return disclosure + } + try await Task.sleep(for: .milliseconds(700)) + for initiallyCollapsed in [true, false] { + guard collapsed == initiallyCollapsed else { throw failure("Unexpected collapse state") } + let screenshot = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try FileManager.default.createDirectory(at: .documentsDirectory, withIntermediateDirectories: true) + let phase = initiallyCollapsed ? "collapsed" : "expanded" + try screenshot.pngData()?.write(to: URL.documentsDirectory.appendingPathComponent("journal-\(phase).png")) + let disclosure = try checkedDisclosure("parent") + if !initiallyCollapsed { + _ = try checkedDisclosure("branch") + _ = try checkedDisclosure("nested") + guard let child = control("outliner.block-action.child") else { throw failure("Missing expanded child") } + let trailingGap = window.bounds.maxX - child.convert(child.bounds, to: window).maxX + guard abs(trailingGap - 8) <= 1 else { throw failure("Unexpected leaf content inset: \(trailingGap)") } + } disclosure.sendActions(for: .touchUpInside) await runtime.drainEffectsForTesting() try await Task.sleep(for: .milliseconds(350)) @@ -68,12 +149,72 @@ import UIKit (child != nil) == initiallyCollapsed else { throw failure("The edge target must toggle the block's child visibility") } - if let child { - let trailingGap = window.bounds.maxX - child.convert(child.bounds, to: window).maxX - guard abs(trailingGap - 8) <= 1 else { throw failure("Unexpected leaf content inset: \(trailingGap)") } + } + for media in ["iframe", "video"] { + try runtime.applyCoreResponse(snapshot(collapsed: false, media: media)) + try await Task.sleep(for: .milliseconds(700)) + let webViews = views(window).compactMap { $0 as? WKWebView } + guard let embed = webViews.first(where: { $0.bounds.width > 0 && !$0.isHidden }) else { + throw failure("Missing \(media) preview") + } + let frame = embed.convert(embed.bounds, to: window) + let screenWidth = window.bounds.width + guard frame.minX >= 0, frame.maxX <= screenWidth - 44 else { + throw failure("\(media) exceeded the row content area: \(frame)") + } + var wideContentLoaded = false + for _ in 0..<30 { + if (try? await embed.evaluateJavaScript("document.getElementById('wide')?.offsetWidth ?? 0")) as? Int == 1600 { + wideContentLoaded = true + break + } + try await Task.sleep(for: .milliseconds(100)) } + guard wideContentLoaded else { + throw failure("The oversized \(media) fixture did not load") + } + _ = try checkedDisclosure("parent") + let screenshot = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try screenshot.pngData()?.write(to: URL.documentsDirectory.appendingPathComponent("journal-\(media).png")) + } + try runtime.applyCoreResponse(dropSnapshot) + try await Task.sleep(for: .milliseconds(350)) + guard let source = control("outliner.block-action.parent")?.superview as? OutlinerTextRowView, + let target = control("outliner.block-action.destination")?.superview as? OutlinerTextRowView, + let drag = source.interactions.compactMap({ $0 as? UIDragInteraction }).first, + let drop = target.interactions.compactMap({ $0 as? UIDropInteraction }).first, + let sourceDelegate = drag.delegate as? OutlinerBlockInteractions, + let targetDelegate = drop.delegate as? OutlinerBlockInteractions else { + throw failure("Missing drag interactions on the journal rows") + } + let session = TestDragSession() + let targetPoint = target.convert(CGPoint(x: target.leadingInset + 38, y: target.bounds.midY), to: window) + session.windowPoint = CGPoint(x: targetPoint.x - 32, y: targetPoint.y) + session.items = sourceDelegate.dragInteraction(drag, itemsForBeginning: session) + session.windowPoint = targetPoint + guard target.leadingInset < 24 * 22, + targetDelegate.dropInteraction(drop, sessionDidUpdate: session).operation == .move else { + throw failure("The fixture must produce a rightward drag onto a capped row") } - print("PASS: the Journal disclosure hits the trailing gutter and toggles in both directions") + targetDelegate.dropInteraction(drop, performDrop: session) + await runtime.drainEffectsForTesting() + guard observedDrop == "inside" else { throw failure("The capped row must receive a child drop") } + + let retryLabel = Button("Retry image") {} + .frame(minHeight: 44) + .environment(\.dynamicTypeSize, .accessibility3) + let retryHeight = UIHostingController(rootView: retryLabel) + .sizeThatFits(in: CGSize(width: 100, height: 1_000)).height + let preview = LGInlineImage.placeholder(size: CGSize(width: 326, height: 37), fitsContent: true) { + retryLabel + } + let previewHeight = UIHostingController(rootView: preview) + .sizeThatFits(in: CGSize(width: 100, height: 1_000)).height + guard previewHeight >= retryHeight else { throw failure("The wide image preview clipped the retry action") } + + print("PASS: nested images, video and iframe previews leave room for Journal disclosure controls") } static func failure(_ message: String) -> NSError {