diff --git a/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift b/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift index 0d2a3e14..16258851 100644 --- a/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift +++ b/Application/Presentation/HomeTab/Sources/Record/Detail/RecordDetailView.swift @@ -12,7 +12,6 @@ import PresentationShared public struct RecordDetailView: View { @Environment(\.dismiss) private var dismiss @Environment(\.deviceType) private var deviceType - @Environment(\.isInDetailPanel) private var isInDetailPanel @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.readableContentWidth) private var readableContentWidth @Environment(\.usesDesktopLayout) private var usesDesktopLayout @@ -92,22 +91,18 @@ public struct RecordDetailView: View { } } - @ViewBuilder + // Duo는 뒤로 버튼을 오른쪽 세로 막대에 표시 + // 상세 판 안에서는 "개발 목표 / 기록" 경로의 판 막대로 표시 private var topBar: some View { - if isInDetailPanel { - // 상세 판 위쪽 막대에 "개발 목표 / 기록" 경로 표시 - DetailPanelBar(location: Text(store.goalTitle), title: Text(panelTitle)) - } else { - // Duo는 뒤로 버튼을 오른쪽 세로 막대에 표시 - RecordTopBar(RecordPresentation.text("development_record_detail_title")) { - if deviceType != .duo { - NavigationBackButton(action: { dismiss() }) - .disabled(store.isRestoring) - } - } trailing: { - EmptyView() + RecordTopBar(RecordPresentation.text("development_record_detail_title")) { + if deviceType != .duo { + NavigationBackButton(action: { dismiss() }) + .disabled(store.isRestoring) } + } trailing: { + EmptyView() } + .detailPanel(location: Text(store.goalTitle), title: Text(panelTitle)) } // 상세 판 경로에 표시하는 기록 제목, 작성 중인 기록은 작성 중인 제목 diff --git a/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionDetailView.swift b/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionDetailView.swift index 682cb104..06204825 100644 --- a/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionDetailView.swift +++ b/Application/Presentation/HomeTab/Sources/Record/History/RecordVersionDetailView.swift @@ -12,7 +12,6 @@ import PresentationShared struct RecordVersionDetailView: View { @Environment(\.dismiss) private var dismiss @Environment(\.deviceType) private var deviceType - @Environment(\.isInDetailPanel) private var isInDetailPanel @Environment(\.isiOSAppOnMac) private var isiOSAppOnMac @Environment(\.readableContentWidth) private var readableContentWidth @@ -50,25 +49,21 @@ struct RecordVersionDetailView: View { } } - @ViewBuilder + // Duo는 뒤로 버튼을 오른쪽 세로 막대에 표시 + // 상세 판 안에서는 "버전 이력 / 버전" 경로의 판 막대로 표시 private var topBar: some View { - if isInDetailPanel { - // 상세 판 위쪽 막대에 "버전 이력 / 버전" 경로 표시 - DetailPanelBar( - location: Text(RecordPresentation.text("development_record_history_title")), - title: Text(RecordPresentation.versionLabel(version.number)) - ) - } else { - // Duo는 뒤로 버튼을 오른쪽 세로 막대에 표시 - RecordTopBar(RecordPresentation.text("development_record_previous_version_title")) { - if deviceType != .duo { - NavigationBackButton(action: { dismiss() }) - .disabled(store.isRestoring) - } - } trailing: { - EmptyView() + RecordTopBar(RecordPresentation.text("development_record_previous_version_title")) { + if deviceType != .duo { + NavigationBackButton(action: { dismiss() }) + .disabled(store.isRestoring) } + } trailing: { + EmptyView() } + .detailPanel( + location: Text(RecordPresentation.text("development_record_history_title")), + title: Text(RecordPresentation.versionLabel(version.number)) + ) } // "이전 버전" 표시와 큰 제목, 버전·종류 배지, 날짜 diff --git a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings index 3efc27c3..7d4db98b 100644 --- a/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings +++ b/Application/Presentation/PresentationShared/Resources/Localizable.xcstrings @@ -511,6 +511,57 @@ } } }, + "detail_panel_text_copy" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Copy" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "복사하기" + } + } + } + }, + "detail_panel_text_look_up" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Look Up" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "찾아보기" + } + } + } + }, + "detail_panel_text_translate" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Translate" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "번역" + } + } + } + }, "detail_sidebar_empty" : { "extractionState" : "manual", "localizations" : { diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift index d471fc8e..e1992513 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/CompositionContainer.swift @@ -155,7 +155,13 @@ private struct CompositionDetailModifier some View { + modifier(DetailPanelModifier(location: location, title: title)) + } +} + +extension EnvironmentValues { // 사이드바까지 창 전체를 덮는 상세 판 안의 화면인지 여부 var isInDetailPanel: Bool { get { self[IsInDetailPanelKey.self] } @@ -19,24 +28,9 @@ public extension EnvironmentValues { } } -public extension View { - // 사이드바가 있는 창에서 항목을 열면 사이드바까지 창 전체를 덮는 상세 판 - // 위치와 크기는 고정하고 위쪽 막대는 내용이 DetailPanelBar로 그림 - func detailPanel( - item: Binding, - @ViewBuilder content: @escaping (Item) -> Content - ) -> some View { - modifier( - ProminentPresentation(item: item) { item, isShown, dismiss in - DetailPanelFrame(isShown: isShown, dismiss: dismiss) { - content(item) - } - } - ) - } -} - -private struct DetailPanelFrame: View { +// 사이드바가 있는 창에서 항목을 열면 사이드바까지 창 전체를 덮는 상세 판 +// 위치와 크기는 고정하고 위쪽 막대는 내용이 detailPanel이나 DetailPanelBar로 그림 +struct DetailPanelFrame: View { @Environment(\.colorScheme) private var colorScheme let isShown: Bool let dismiss: () -> Void @@ -80,29 +74,39 @@ private struct DetailPanelFrame: View { } } +private struct DetailPanelModifier: ViewModifier { + @Environment(\.isInDetailPanel) private var isInDetailPanel + let location: Text + let title: Text + + func body(content: Content) -> some View { + if isInDetailPanel { + DetailPanelBar(location: location, title: title) + } else { + content + } + } +} + // 상세 판 위쪽 막대, "위치 / 항목" 경로와 버튼, 닫기 버튼 표시 -// 막대를 우클릭하면 판 메뉴 표시 -public struct DetailPanelBar: View { +struct DetailPanelBar: View { @Environment(\.dismiss) private var dismiss private let location: Text private let title: Text private let actions: Actions - private let menu: Menu - public init( + init( location: Text, title: Text, - @ViewBuilder actions: () -> Actions, - @ViewBuilder menu: () -> Menu + @ViewBuilder actions: () -> Actions ) { self.location = location self.title = title self.actions = actions() - self.menu = menu() } - public var body: some View { - let bar = PaneTitleBar { + var body: some View { + PaneTitleBar { HStack(spacing: 8) { location .fontWeight(.medium) @@ -121,19 +125,246 @@ public struct DetailPanelBar: View { } .topBarButtonStyle() } + } +} - if Menu.self == EmptyView.self { - bar +extension DetailPanelBar where Actions == EmptyView { + init(location: Text, title: Text) { + self.init(location: location, title: title, actions: { EmptyView() }) + } +} + +extension View { + // 판 어디를 우클릭하거나 길게 눌러도 판을 제자리에 둔 채 누른 자리에 메뉴 표시 + // 본문 글자를 누르면 그 단어의 복사하기, 찾아보기, 번역을, 태그를 누르면 그 태그의 복사하기를 판 항목 위에 표시 + func detailPanelMenu( + text: DetailPanelTextReader? = nil, + _ menu: @escaping () -> UIMenu + ) -> some View { + modifier(DetailPanelMenuModifier(text: text, menu: menu)) + } +} + +// 판 메뉴가 누른 자리의 본문 단어를 읽는 방법 +// 누른 자리가 본문 안이면 그 자리 글자의 단어를 읽는 함수이고 본문 밖이면 nil, 읽은 단어는 글자 밖이면 nil +struct DetailPanelTextReader { + let word: @MainActor (CGPoint, UIView) -> (() async -> String?)? +} + +// 번역할 단어와 번역 창을 붙일 판 안의 자리 +private struct DetailPanelTranslation { + let text: String + let anchor: UnitPoint +} + +private struct DetailPanelMenuModifier: ViewModifier { + @State private var translation: DetailPanelTranslation? + let text: DetailPanelTextReader? + let menu: () -> UIMenu + + func body(content: Content) -> some View { + content + .background( + DetailPanelMenuAnchorView.composable { view in + view.menu = menu + view.text = text + view.translate = { translation = $0 } + } + ) + .translationPresentation( + isPresented: Binding( + get: { translation != nil }, + set: { isPresented in + if !isPresented { + translation = nil + } + } + ), + text: translation?.text ?? "", + attachmentAnchor: .point(translation?.anchor ?? .center) + ) + } +} + +// 판 크기를 재는 뒤쪽 뷰, 메뉴는 판을 띄운 화면의 뷰에 붙여 판 위 내용을 눌러도 열림 +@MainActor +private final class DetailPanelMenuAnchorView: UIView, UICoordinatedComposable { + var menu: () -> UIMenu = { UIMenu() } + var text: DetailPanelTextReader? + var translate: (DetailPanelTranslation) -> Void = { _ in } + private weak var coordinator: DetailPanelMenuCoordinator? + + override func didMoveToWindow() { + super.didMoveToWindow() + if window == nil { + coordinator?.uninstall() } else { - bar - .contentShape(.rect) - .contextMenu { menu } + coordinator?.install(anchor: self) } } + + func makeCoordinator() -> DetailPanelMenuCoordinator { + DetailPanelMenuCoordinator() + } + + func connect(coordinator: DetailPanelMenuCoordinator) { + self.coordinator = coordinator + } + + func update(coordinator: DetailPanelMenuCoordinator) { + coordinator.menu = menu + coordinator.text = text + coordinator.translate = translate + } + + func disconnect(coordinator: DetailPanelMenuCoordinator) { + coordinator.uninstall() + self.coordinator = nil + } } -public extension DetailPanelBar where Actions == EmptyView, Menu == EmptyView { - init(location: Text, title: Text) { - self.init(location: location, title: title, actions: { EmptyView() }, menu: { EmptyView() }) +private final class DetailPanelMenuCoordinator: NSObject, UIContextMenuInteractionDelegate { + var menu: (() -> UIMenu)? + var text: DetailPanelTextReader? + var translate: ((DetailPanelTranslation) -> Void)? + private weak var anchor: UIView? + private weak var host: UIViewController? + private var interaction: UIContextMenuInteraction? + private var location = CGPoint.zero + + func install(anchor: UIView) { + uninstall() + // 판을 띄운 화면, 판 위에 다시 띄운 시트는 이 화면의 뷰 밖이라 메뉴가 열리지 않음 + var responder = anchor.next + while let next = responder, !(next is UIViewController) { + responder = next.next + } + guard let host = responder as? UIViewController else { return } + + let interaction = UIContextMenuInteraction(delegate: self) + host.view.addInteraction(interaction) + self.anchor = anchor + self.host = host + self.interaction = interaction + } + + func uninstall() { + if let interaction { + interaction.view?.removeInteraction(interaction) + } + interaction = nil + } + + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configurationForMenuAtLocation location: CGPoint + ) -> UIContextMenuConfiguration? { + // 판 바깥 어두운 바탕에서는 열지 않음 + guard let anchor, let view = interaction.view, + anchor.bounds.contains(view.convert(location, to: anchor)), + let menu else { return nil } + + self.location = location + // 태그를 누르면 그 태그의 복사하기를 판 항목 위에 표시 + var hit = view.hitTest(location, with: nil) + while let next = hit, !(next is TagCopyView) { + hit = next.superview + } + if let tag = (hit as? TagCopyView)?.tagText { + let copy = UIAction( + title: String(localized: "detail_panel_text_copy", bundle: PresentationResources.bundle), + image: UIImage(systemName: "doc.on.doc") + ) { _ in + UIPasteboard.general.string = tag + } + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in + UIMenu(children: [UIMenu(options: .displayInline, children: [copy])] + menu().children) + } + } + + guard let readWord = text?.word(location, view) else { + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in menu() } + } + + // 본문 안을 누르면 단어를 읽은 뒤 판 항목 위에 단어 기능 묶음을 채움, 글자 밖이면 빈 묶음 + let words = UIDeferredMenuElement.uncached { [weak self] completion in + Task { @MainActor in + let word = await readWord() + completion(word.flatMap { self?.textMenu(for: $0, at: location, in: view) }.map { [$0] } ?? []) + } + } + return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in + UIMenu(children: [words] + menu().children) + } + } + + // 판을 띄워 올리지 않고 누른 자리에 메뉴를 붙이는 보이지 않는 미리보기 + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configuration: UIContextMenuConfiguration, + highlightPreviewForItemWithIdentifier identifier: any NSCopying + ) -> UITargetedPreview? { + targetedPreview(in: interaction.view) + } + + func contextMenuInteraction( + _ interaction: UIContextMenuInteraction, + configuration: UIContextMenuConfiguration, + dismissalPreviewForItemWithIdentifier identifier: any NSCopying + ) -> UITargetedPreview? { + targetedPreview(in: interaction.view) + } + + private func targetedPreview(in view: UIView?) -> UITargetedPreview? { + guard let view else { return nil } + + let parameters = UIPreviewParameters() + parameters.backgroundColor = .clear + parameters.shadowPath = UIBezierPath() + return UITargetedPreview( + view: UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)), + parameters: parameters, + target: UIPreviewTarget(container: view, center: location) + ) + } + + // 웹 뷰가 글자를 길게 누를 때 띄우던 기능 중 한 단어에 쓰는 묶음 + private func textMenu(for word: String, at location: CGPoint, in view: UIView) -> UIMenu { + let bundle = PresentationResources.bundle + + return UIMenu(options: .displayInline, children: [ + UIAction( + title: String(localized: "detail_panel_text_copy", bundle: bundle), + image: UIImage(systemName: "doc.on.doc") + ) { _ in + UIPasteboard.general.string = word + }, + UIAction( + title: String(localized: "detail_panel_text_look_up", bundle: bundle), + image: UIImage(systemName: "character.book.closed") + ) { [weak self] _ in + self?.present(UIReferenceLibraryViewController(term: word), at: location, in: view) + }, + UIAction( + title: String(localized: "detail_panel_text_translate", bundle: bundle), + image: UIImage(systemName: "translate") + ) { [weak self] _ in + guard let self, let anchor, !anchor.bounds.isEmpty else { return } + + let point = view.convert(location, to: anchor) + translate?(DetailPanelTranslation( + text: word, + anchor: UnitPoint(x: point.x / anchor.bounds.width, y: point.y / anchor.bounds.height) + )) + } + ]) + } + + // 누른 자리를 가리키는 팝오버로 시스템 화면 표시 + private func present(_ controller: UIViewController, at location: CGPoint, in view: UIView) { + controller.modalPresentationStyle = .popover + controller.popoverPresentationController?.sourceView = view + controller.popoverPresentationController?.sourceRect = CGRect(origin: location, size: .zero) + host?.present(controller, animated: true) } } diff --git a/Application/Presentation/PresentationShared/Sources/Common/Component/TagCopyMenuView.swift b/Application/Presentation/PresentationShared/Sources/Common/Component/TagCopyMenuView.swift index 28087f79..e2cdc1a1 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/Component/TagCopyMenuView.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/Component/TagCopyMenuView.swift @@ -15,20 +15,30 @@ struct TagCopyMenuView: UIViewRepresentable { TagCopyMenuCoordinator() } - func makeUIView(context: Context) -> UIView { - let view = UIView() + func makeUIView(context: Context) -> TagCopyView { + let view = TagCopyView() view.backgroundColor = .clear view.isAccessibilityElement = false - context.coordinator.install(on: view) + view.tagText = tagText + // 상세 판 안에서는 판 메뉴가 누른 태그의 복사하기를 표시 + if !context.environment.isInDetailPanel { + context.coordinator.install(on: view) + } context.coordinator.tagText = tagText return view } - func updateUIView(_ view: UIView, context: Context) { + func updateUIView(_ view: TagCopyView, context: Context) { + view.tagText = tagText context.coordinator.tagText = tagText } } +// 판 메뉴가 누른 자리의 태그를 찾을 수 있도록 구분한 뷰 +final class TagCopyView: UIView { + var tagText = "" +} + final class TagCopyMenuCoordinator: NSObject { var tagText = "" private weak var view: UIView? diff --git a/Application/Presentation/PresentationShared/Sources/Common/TodoMarkdownContentView.swift b/Application/Presentation/PresentationShared/Sources/Common/TodoMarkdownContentView.swift index 59ddb3d4..055fbec7 100644 --- a/Application/Presentation/PresentationShared/Sources/Common/TodoMarkdownContentView.swift +++ b/Application/Presentation/PresentationShared/Sources/Common/TodoMarkdownContentView.swift @@ -29,17 +29,23 @@ public struct MarkdownContentView: View { } struct TodoMarkdownContentView: View { + @Environment(\.isInDetailPanel) private var isInDetailPanel let content: String let referenceItems: [Int: TodoReferenceItem] var isScrollEnabled = true var onOpenTodoID: ((String) -> Void)? + // 판 메뉴가 누른 자리의 본문 단어를 읽는 방법 + static let panelTextReader = DetailPanelTextReader(word: MarkdownRendererTextLookup.wordReader) + var body: some View { + // 상세 판 본문은 판 메뉴가 단어를 읽음, 판 위에 띄운 참조 Todo 시트 본문은 isInDetailPanel이 false라 제외 MarkdownRendererView( markdown: content, references: rendererReferences, isScrollEnabled: isScrollEnabled, fontSize: AdaptiveSize.macFontSize(.body), + usesExternalMenu: isInDetailPanel, onOpenReferenceID: onOpenTodoID ) .frame(maxWidth: .infinity, maxHeight: isScrollEnabled ? .infinity : nil) diff --git a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift index dbf1c104..6e3eafaa 100644 --- a/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift +++ b/Application/Presentation/PresentationShared/Sources/Todo/Detail/TodoDetailPanel.swift @@ -47,8 +47,6 @@ public struct TodoDetailPanel: View { Image(systemName: "sidebar.right") } .topBarButtonStyle() - } menu: { - menu } HStack(spacing: 0) { @@ -73,64 +71,58 @@ public struct TodoDetailPanel: View { } } } + // 위쪽 막대, 본문, 세부 정보 열 어디를 우클릭하거나 길게 눌러도 판 메뉴 표시 + .detailPanelMenu(text: TodoMarkdownContentView.panelTextReader) { menu } // 세부 정보 열을 닫아 둔 동안에도 판 메뉴로 중요 표시와 완료를 바꾸도록 속성을 불러옴 .onAppear { store.send(.info(.onAppear)) } } - @ViewBuilder - private var menu: some View { + // 구분선으로 나눈 묶음마다 하나의 inline 메뉴 + private var menu: UIMenu { + let bundle = PresentationResources.bundle + var sections = [UIMenu]() if let onMoveToPane { - Button(action: onMoveToPane) { - Label { - Text("detail_panel_move_to_pane", bundle: PresentationResources.bundle) - } icon: { - Image(systemName: "sidebar.left") - } - } - Divider() + sections.append(UIMenu(options: .displayInline, children: [ + UIAction( + title: String(localized: "detail_panel_move_to_pane", bundle: bundle), + image: UIImage(systemName: "sidebar.left") + ) { _ in onMoveToPane() } + ])) } if store.info.isEditable, let editor = store.info.editor { - Button { - store.send(.info(.editor(.binding(.set(\.isPinned, !editor.isPinned))))) - } label: { - Label { - Text(editor.isPinned ? "todo_action_unpin" : "todo_action_pin", bundle: PresentationResources.bundle) - } icon: { - Image(systemName: editor.isPinned ? "star.slash" : "star") + sections.append(UIMenu(options: .displayInline, children: [ + UIAction( + title: String(localized: editor.isPinned ? "todo_action_unpin" : "todo_action_pin", bundle: bundle), + image: UIImage(systemName: editor.isPinned ? "star.slash" : "star") + ) { _ in + store.send(.info(.editor(.binding(.set(\.isPinned, !editor.isPinned))))) + }, + UIAction( + title: String( + localized: editor.isCompleted ? "todo_action_uncomplete" : "todo_action_complete", + bundle: bundle + ), + image: UIImage(systemName: editor.isCompleted ? "arrow.uturn.backward" : "checkmark") + ) { _ in + store.send(.info(.editor(.binding(.set(\.isCompleted, !editor.isCompleted))))) } - } - Button { - store.send(.info(.editor(.binding(.set(\.isCompleted, !editor.isCompleted))))) - } label: { - Label { - Text( - editor.isCompleted ? "todo_action_uncomplete" : "todo_action_complete", - bundle: PresentationResources.bundle - ) - } icon: { - Image(systemName: editor.isCompleted ? "arrow.uturn.backward" : "checkmark") - } - } - Divider() + ])) } if let onDelete { - Button(role: .destructive, action: onDelete) { - Label { - Text("common_delete", bundle: PresentationResources.bundle) - } icon: { - Image(systemName: "trash") - } - } - Divider() - } - Button { - dismiss() - } label: { - Label { - Text("common_close", bundle: PresentationResources.bundle) - } icon: { - Image(systemName: "xmark") - } + sections.append(UIMenu(options: .displayInline, children: [ + UIAction( + title: String(localized: "common_delete", bundle: bundle), + image: UIImage(systemName: "trash"), + attributes: .destructive + ) { _ in onDelete() } + ])) } + sections.append(UIMenu(options: .displayInline, children: [ + UIAction( + title: String(localized: "common_close", bundle: bundle), + image: UIImage(systemName: "xmark") + ) { _ in dismiss() } + ])) + return UIMenu(children: sections) } } diff --git a/Libraries/MarkdownRenderer/Sources/MarkdownRendererTextLookup.swift b/Libraries/MarkdownRenderer/Sources/MarkdownRendererTextLookup.swift new file mode 100644 index 00000000..e7e7a7f0 --- /dev/null +++ b/Libraries/MarkdownRenderer/Sources/MarkdownRendererTextLookup.swift @@ -0,0 +1,57 @@ +// +// MarkdownRendererTextLookup.swift +// MarkdownRenderer +// +// Created by opfic on 11/29/26. +// + +import UIKit +import WebKit + +// 바깥 메뉴가 누른 자리의 렌더러 본문 단어를 읽는 방법 +// 누른 자리의 뷰에서 위로 올라가며 바깥 메뉴를 쓰는 렌더러 웹 뷰를 찾음 +@MainActor +public enum MarkdownRendererTextLookup { + // 누른 자리가 바깥 메뉴를 쓰는 렌더러 본문 안이면 그 자리 글자의 단어를 읽는 함수, 본문 밖이면 nil + // 메뉴가 뜬 뒤에는 메뉴가 누른 자리를 덮으므로 웹 뷰는 누를 때 찾아 둠 + public static func wordReader(at point: CGPoint, in view: UIView) -> (() async -> String?)? { + guard let webView = webView(at: point, in: view) else { return nil } + + let location = view.convert(point, to: webView) + return { + let result = try? await webView.callAsyncJavaScript( + wordScript, + arguments: ["x": Double(location.x), "y": Double(location.y)], + contentWorld: .page + ) + return result as? String + } + } + + private static func webView(at point: CGPoint, in view: UIView) -> MarkdownRendererWebView? { + var current = view.hitTest(point, with: nil) + while let next = current, !(next is MarkdownRendererWebView) { + current = next.superview + } + guard let webView = current as? MarkdownRendererWebView, webView.usesExternalMenu else { return nil } + + return webView + } + + // 누른 자리의 글자 위치를 단어 범위로 넓히고, 단어 영역 밖이면 null + private static let wordScript = """ + const range = document.caretRangeFromPoint(x, y); + if (!range) { return null; } + range.expand("word"); + const rect = range.getBoundingClientRect(); + if (x < rect.left || rect.right < x || y < rect.top || rect.bottom < y) { return null; } + const text = range.toString().trim(); + return text.length === 0 ? null : text; + """ +} + +// 누른 자리에서 렌더러 본문을 찾을 수 있도록 구분한 웹 뷰 +final class MarkdownRendererWebView: WKWebView { + // 바깥 메뉴가 누른 자리의 단어를 읽는지 여부 + var usesExternalMenu = false +} diff --git a/Libraries/MarkdownRenderer/Sources/MarkdownRendererView.swift b/Libraries/MarkdownRenderer/Sources/MarkdownRendererView.swift index 77f4c27e..d4a847a7 100644 --- a/Libraries/MarkdownRenderer/Sources/MarkdownRendererView.swift +++ b/Libraries/MarkdownRenderer/Sources/MarkdownRendererView.swift @@ -19,12 +19,14 @@ public struct MarkdownRendererView: View { private let isScrollEnabled: Bool private let references: [Int: MarkdownRendererReference] private let onOpenReferenceID: ((String) -> Void)? + private let usesExternalMenu: Bool public init( markdown: String, references: [Int: MarkdownRendererReference] = [:], isScrollEnabled: Bool = true, fontSize: CGFloat? = nil, + usesExternalMenu: Bool = false, onOpenReferenceID: ((String) -> Void)? = nil ) { // 글자 크기를 받지 않으면 기본 본문 크기 @@ -34,6 +36,7 @@ public struct MarkdownRendererView: View { self.markdown = markdown self.isScrollEnabled = isScrollEnabled self.references = references + self.usesExternalMenu = usesExternalMenu self.onOpenReferenceID = onOpenReferenceID } @@ -45,6 +48,7 @@ public struct MarkdownRendererView: View { languageCode: locale.language.languageCode?.identifier ?? "und", fontSize: fontSize, isScrollEnabled: isScrollEnabled, + usesExternalMenu: usesExternalMenu, onContentHeightChange: { height in guard contentHeight != height else { return } contentHeight = height diff --git a/Libraries/MarkdownRenderer/Sources/MarkdownWebView.swift b/Libraries/MarkdownRenderer/Sources/MarkdownWebView.swift index 81b52b67..2922c70d 100644 --- a/Libraries/MarkdownRenderer/Sources/MarkdownWebView.swift +++ b/Libraries/MarkdownRenderer/Sources/MarkdownWebView.swift @@ -15,6 +15,7 @@ struct MarkdownWebView: UIViewRepresentable { let languageCode: String let fontSize: CGFloat let isScrollEnabled: Bool + var usesExternalMenu = false var onContentHeightChange: ((CGFloat) -> Void)? var onOpenReferenceID: ((String) -> Void)? var onOpenURL: ((URL) -> Void)? @@ -33,15 +34,25 @@ struct MarkdownWebView: UIViewRepresentable { ) } + // 바깥 메뉴가 누른 자리의 단어를 쓰는 동안 웹 뷰 자체 우클릭 메뉴 생략 + if usesExternalMenu { + contentController.addUserScript(WKUserScript( + source: "document.addEventListener('contextmenu', event => event.preventDefault());", + injectionTime: .atDocumentStart, + forMainFrameOnly: true + )) + } + let configuration = WKWebViewConfiguration() configuration.defaultWebpagePreferences.allowsContentJavaScript = true configuration.userContentController = contentController configuration.websiteDataStore = .nonPersistent() - let webView = WKWebView( + let webView = MarkdownRendererWebView( frame: .zero, configuration: configuration ) + webView.usesExternalMenu = usesExternalMenu webView.backgroundColor = .clear webView.isOpaque = false webView.navigationDelegate = context.coordinator