diff --git a/macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptText.swift b/macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptText.swift new file mode 100644 index 00000000..97938514 --- /dev/null +++ b/macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptText.swift @@ -0,0 +1,49 @@ +import AppKit +import SwiftUI + +/// 只读提示词保留完整文本与选择复制;视口尺寸不依赖全文排版结果。 +struct ScenePromptText: NSViewRepresentable { + let text: String + let height: CGFloat + var fontSize: CGFloat = 12 + let label: String + + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView() + scroll.drawsBackground = false + scroll.hasVerticalScroller = true + scroll.autohidesScrollers = true + let textView = NSTextView(usingTextLayoutManager: true) + textView.isEditable = false + textView.isSelectable = true + textView.isRichText = false + textView.drawsBackground = false + textView.isVerticallyResizable = true + textView.isHorizontallyResizable = false + textView.autoresizingMask = [.width] + textView.minSize = NSSize(width: 0, height: height) + textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + textView.textContainer?.size = NSSize(width: 0, height: CGFloat.greatestFiniteMagnitude) + textView.textContainer?.widthTracksTextView = true + textView.textContainer?.lineFragmentPadding = 0 + textView.textContainerInset = NSSize(width: 10, height: 8) + scroll.documentView = textView + return scroll + } + + func updateNSView(_ scroll: NSScrollView, context: Context) { + guard let textView = scroll.documentView as? NSTextView else { return } + let font = NSFont.systemFont(ofSize: fontSize) + let color = NSColor(Theme.inkSecondary) + if textView.font != font { textView.font = font } + if textView.textColor != color { textView.textColor = color } + textView.setAccessibilityLabel(label) + // 焦点或悬停刷新不应重置选区,也不应重新设置整段长文本。 + if textView.string != text { textView.string = text } + } + + func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSScrollView, context: Context) -> CGSize? { + let width = proposal.width ?? 0 + return CGSize(width: width.isFinite ? width : 0, height: height) + } +} diff --git a/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift b/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift index 460452dc..8b91beed 100644 --- a/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift +++ b/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift @@ -574,7 +574,7 @@ private struct SceneListRow: View { } } -private struct SceneEditor: View { +struct SceneEditor: View { @Binding var scene: WeChatScene @Binding var enabled: Bool /// Whether this scene is the library's default — the menu offers 设为默认场景. @@ -594,6 +594,7 @@ private struct SceneEditor: View { /// first agent, mirroring the Windows preview; `.none` means clipboard / /// a custom app with no known agent. @State private var previewTarget: SkillPreviewTarget = .agent(AgentID.allCases[0]) + @FocusState private var promptFocused: Bool var body: some View { VStack(alignment: .leading, spacing: Space.l) { @@ -613,7 +614,12 @@ private struct SceneEditor: View { VStack(alignment: .leading, spacing: Space.l) { ReadOnlySceneField(title: L10n.text("名称"), text: scene.name) ReadOnlySceneField(title: L10n.text("说明"), text: scene.summary) - ReadOnlySceneField(title: L10n.text("提示词"), text: promptText) + VStack(alignment: .leading, spacing: 5) { + Text(L10n.text("提示词")).font(Typo.captionStrong).foregroundStyle(Theme.inkSecondary) + ScenePromptText(text: promptText.isEmpty ? L10n.text("无") : promptText, + height: 160, fontSize: 13.5, label: L10n.text("提示词")) + .background(Theme.sunken, in: RoundedRectangle(cornerRadius: Radius.row)) + } } } else { SceneField(title: L10n.text("名称"), text: $scene.name) @@ -628,9 +634,25 @@ private struct SceneEditor: View { Spacer(minLength: Space.s) insertSkillMenu } - TextField(L10n.text("提示词"), text: promptBinding, axis: .vertical) - .lineLimit(5...9) - .textFieldStyle(SettingsTextFieldStyle(multiline: true)) + // 自动增高的 TextField 会反复测量整段中文,阻塞设置窗口的布局。 + TextEditor(text: promptBinding) + .font(SettingsControlMetrics.font) + .foregroundStyle(Theme.ink) + .scrollContentBackground(.hidden) + .scrollIndicators(.visible) + .padding(6) + .frame(height: 160) + .background(Theme.sunken, in: RoundedRectangle(cornerRadius: SettingsControlMetrics.radius)) + .overlay { + RoundedRectangle(cornerRadius: SettingsControlMetrics.radius) + .strokeBorder(promptFocused ? Theme.ink : Theme.inputStroke, + lineWidth: promptFocused ? Stroke.focus : Stroke.hairline) + .allowsHitTesting(false) + } + .focused($promptFocused) + .focusEffectDisabled() + .accessibilityLabel(Text(L10n.text("提示词"))) + .accessibilityIdentifier("scene.promptEditor") } } @@ -713,12 +735,13 @@ private struct SceneEditor: View { } private var promptText: String { - [scene.instruction, scene.outputSpec.isEmpty ? "" : L10n.format("输出规范:\n%@", scene.outputSpec)] + guard !scene.outputSpec.isEmpty else { return scene.instruction } + return [scene.instruction, L10n.format("输出规范:\n%@", scene.outputSpec)] .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } .joined(separator: "\n\n") } - private var promptBinding: Binding { + var promptBinding: Binding { Binding( get: { promptText }, set: { applyPrompt($0) } @@ -728,11 +751,12 @@ private struct SceneEditor: View { /// User scenes declare skills by referencing them inline; the stored list /// follows the prompt so removing a `{{skill:id}}` drops the dependency. private func applyPrompt(_ text: String) { - scene.instruction = text - scene.outputSpec = "" - var seen = Set() - scene.requiredSkillIDs = SkillReference.parse(text) - .filter { seen.insert($0).inserted } + var updated = scene + updated.instruction = text + updated.outputSpec = "" + updated.requiredSkillIDs = SkillReference.parse(text) + // 一次输入只发布并保存一个完整场景,不对整库重复编码三次。 + scene = updated } // MARK: - Skill references & preview @@ -791,13 +815,7 @@ private struct SceneEditor: View { ) .frame(width: 190) } - Text(previewText(context: context)) - .font(Typo.paneCaption) - .foregroundStyle(Theme.inkSecondary) - .textSelection(.enabled) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.horizontal, 10) - .padding(.vertical, 8) + ScenePromptText(text: previewText(context: context), height: 200, label: L10n.text("转发提示词预览")) .background(Theme.sunken, in: RoundedRectangle(cornerRadius: Radius.row)) } } @@ -813,7 +831,7 @@ private struct SceneEditor: View { } ForEach(choices, id: \.id) { choice in Button("\(choice.name)(\(choice.id))\(librarySuffix(for: choice.id))") { - insertSkillToken(choice.id) + insertSkillToken(choice.id, firstResponder: NSApp.keyWindow?.firstResponder) } } } label: { @@ -843,9 +861,10 @@ private struct SceneEditor: View { /// Inserts the token at the live prompt field's caret when it owns the /// focus — the field editor is an NSTextView — otherwise appends it. - private func insertSkillToken(_ id: String) { + func insertSkillToken(_ id: String, firstResponder: NSResponder?) { let token = SkillReference.token(id) - if let textView = NSApp.keyWindow?.firstResponder as? NSTextView { + // 名称、说明和只读预览也可能成为 firstResponder,不能把技能写进它们。 + if promptFocused, let textView = firstResponder as? NSTextView, textView.isEditable { textView.insertText(token, replacementRange: textView.selectedRange()) return } diff --git a/macos/Tests/WeChatBridgeAppTests/SceneEditorTests.swift b/macos/Tests/WeChatBridgeAppTests/SceneEditorTests.swift new file mode 100644 index 00000000..14b96459 --- /dev/null +++ b/macos/Tests/WeChatBridgeAppTests/SceneEditorTests.swift @@ -0,0 +1,75 @@ +import AppKit +import SwiftUI +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeApp + +final class SceneEditorTests: XCTestCase { + @MainActor + func testPromptEditPublishesAndPersistsOneCompleteScene() throws { + let domain = "scene-save-tests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: domain)) + defer { defaults.removePersistentDomain(forName: domain) } + let preferences = Preferences(defaults: defaults) + let original = WeChatScene(id: "edited", name: "名称", instruction: "旧提示词", outputSpec: "旧规范", requiredSkillIDs: ["old-skill"]) + let untouched = WeChatScene(id: "untouched", name: "另一个场景", instruction: "保留内容", outputSpec: "保留规范") + preferences.scenes = SceneSettings(scenes: [original, untouched]) + var published: [WeChatScene] = [] + let scene = Binding(get: { preferences.scenes.scenes[0] }, set: { + published.append($0) + preferences.scenes.scenes[0] = $0 + }) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(domain) + let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) + let editor = SceneEditor(scene: scene, enabled: .constant(false), isDefault: false, toggleDefault: {}, skills: skills, + duplicate: {}, moveUp: {}, moveDown: {}, export: {}, remove: {}, save: {}) + let text = "新提示词 {{skill:new-skill}} {{skill:new-skill}}" + editor.promptBinding.wrappedValue = text + XCTAssertEqual(published.count, 1) + XCTAssertEqual(published.first?.instruction, text) + XCTAssertEqual(published.first?.outputSpec, "") + XCTAssertEqual(published.first?.requiredSkillIDs, ["new-skill"]) + XCTAssertEqual(preferences.scenes.scenes[1], untouched) + // 重载会补齐官方模板,只比较必须原样保留的用户场景。 + XCTAssertEqual(Preferences(defaults: defaults).scenes.scenes.filter { !$0.isOfficial }, preferences.scenes.scenes) + } + + @MainActor + func testPromptBindingPreservesWhitespaceAndExistingOutputSpec() { + var scene = WeChatScene(name: "名称", instruction: "原提示词", outputSpec: "原规范") + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) + let binding = Binding(get: { scene }, set: { scene = $0 }) + let editor = SceneEditor(scene: binding, enabled: .constant(false), isDefault: false, toggleDefault: {}, skills: skills, + duplicate: {}, moveUp: {}, moveDown: {}, export: {}, remove: {}, save: {}) + XCTAssertTrue(editor.promptBinding.wrappedValue.contains("原提示词")) + XCTAssertTrue(editor.promptBinding.wrappedValue.contains("原规范")) + XCTAssertEqual(scene.outputSpec, "原规范") + for text in ["\n", " \n\n", "", "新内容\n\n"] { + editor.promptBinding.wrappedValue = text + XCTAssertEqual(editor.promptBinding.wrappedValue, text) + XCTAssertEqual(scene.instruction, text) + XCTAssertEqual(scene.outputSpec, "") + } + } + + @MainActor + func testInsertingSkillDoesNotModifyAnotherTextResponder() { + _ = NSApplication.shared + var scene = WeChatScene(name: "名称", instruction: "提示词", outputSpec: "") + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) + let binding = Binding(get: { scene }, set: { scene = $0 }) + let editor = SceneEditor(scene: binding, enabled: .constant(false), isDefault: false, toggleDefault: {}, skills: skills, + duplicate: {}, moveUp: {}, moveDown: {}, export: {}, remove: {}, save: {}) + let otherText = NSTextView() + otherText.string = "场景名称或预览" + otherText.setSelectedRange(NSRange(location: 2, length: 0)) + // CI 不保证桌面激活,直接传入菜单读取的响应者,验证它不会被误写。 + editor.insertSkillToken("new-skill", firstResponder: otherText) + XCTAssertEqual(otherText.string, "场景名称或预览") + XCTAssertEqual(scene.instruction, "提示词 {{skill:new-skill}}") + XCTAssertEqual(scene.name, "名称") + XCTAssertEqual(scene.requiredSkillIDs, ["new-skill"]) + } +} diff --git a/macos/Tests/WeChatBridgeAppTests/ScenePromptTextTests.swift b/macos/Tests/WeChatBridgeAppTests/ScenePromptTextTests.swift new file mode 100644 index 00000000..f57ba2cf --- /dev/null +++ b/macos/Tests/WeChatBridgeAppTests/ScenePromptTextTests.swift @@ -0,0 +1,75 @@ +import AppKit +import SwiftUI +import XCTest +@testable import WeChatBridgeApp + +final class ScenePromptTextTests: XCTestCase { + @MainActor + func testLongChinesePreviewIsBoundedReadOnlyAndSelectable() async throws { + let text = String(repeating: "只保留已确认的事实、决定与待办。\n", count: 800) + let (_, textView) = try await showPreview(text) + let scroll = try XCTUnwrap(textView.enclosingScrollView) + XCTAssertEqual(textView.string, text) + XCTAssertFalse(textView.isEditable) + XCTAssertTrue(textView.isSelectable) + XCTAssertNotNil(textView.textLayoutManager) + XCTAssertEqual(scroll.frame.height, 200, accuracy: 1) + XCTAssertGreaterThan(textView.frame.width, 0) + XCTAssertTrue(textView.textContainer?.widthTracksTextView == true) + } + + @MainActor + func testResizingKeepsTheViewportBoundedAndTheFullText() async throws { + let text = String(repeating: "中文与 emoji 🧑🏽‍💻,保留末尾要求。\n", count: 800) + "这是最后一行。" + let (host, textView) = try await showPreview(text) + let scroll = try XCTUnwrap(textView.enclosingScrollView) + for width in [CGFloat(380), CGFloat(900)] { + host.setFrameSize(NSSize(width: width, height: 200)) + host.layoutSubtreeIfNeeded() + XCTAssertEqual(scroll.frame.height, 200, accuracy: 1) + XCTAssertEqual(textView.frame.width, scroll.contentSize.width, accuracy: 1) + XCTAssertEqual(textView.string, text) + XCTAssertFalse(scroll.hasHorizontalScroller) + } + } + + @MainActor + func testUnchangedRefreshPreservesSelectionAndNewTextReplacesPreview() async throws { + let text = String(repeating: "保留选区与完整预览。\n", count: 80) + let (host, textView) = try await showPreview(text) + let selection = NSRange(location: 1, length: 6) + textView.setSelectedRange(selection) + host.rootView = ScenePromptText(text: text, height: 200, label: "转发提示词预览") + try await Task.sleep(nanoseconds: 100_000_000) + host.layoutSubtreeIfNeeded() + XCTAssertEqual(textView.selectedRange(), selection) + host.rootView = ScenePromptText(text: "新场景的完整提示词", height: 200, label: "转发提示词预览") + try await Task.sleep(nanoseconds: 100_000_000) + host.layoutSubtreeIfNeeded() + XCTAssertEqual(textView.string, "新场景的完整提示词") + XCTAssertEqual(textView.enclosingScrollView?.frame.height, 200) + } + + @MainActor + private func showPreview(_ text: String) async throws -> (NSHostingView, NSTextView) { + _ = NSApplication.shared + let host = NSHostingView(rootView: ScenePromptText(text: text, height: 200, label: "转发提示词预览")) + // 与设置窗口一致,由外层窗口给定尺寸,而不是用内容的理想尺寸收窄窗口。 + host.sizingOptions = [] + host.setFrameSize(NSSize(width: 600, height: 200)) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 600, height: 200), styleMask: [.titled], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = host + addTeardownBlock { await MainActor.run { window.close() } } + window.orderFront(nil) + try await Task.sleep(nanoseconds: 100_000_000) + host.layoutSubtreeIfNeeded() + var pending = [host as NSView] + var textView: NSTextView? + while let view = pending.popLast() { + pending.append(contentsOf: view.subviews) + if let preview = view as? NSTextView { textView = preview } + } + return (host, try XCTUnwrap(textView)) + } +} diff --git a/macos/Tests/WeChatBridgeAppTests/SceneSettingsViewTests.swift b/macos/Tests/WeChatBridgeAppTests/SceneSettingsViewTests.swift new file mode 100644 index 00000000..787da2d4 --- /dev/null +++ b/macos/Tests/WeChatBridgeAppTests/SceneSettingsViewTests.swift @@ -0,0 +1,39 @@ +import AppKit +import SwiftUI +import WeChatBridgeCore +import XCTest +@testable import WeChatBridgeApp + +final class SceneSettingsViewTests: XCTestCase { + @MainActor + func testLongChinesePromptUsesABoundedScrollableEditor() async throws { + _ = NSApplication.shared + let domain = "scene-editor-tests-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: domain)) + defer { defaults.removePersistentDomain(forName: domain) } + let preferences = Preferences(defaults: defaults) + let prompt = String(repeating: "只整理已确认的事实、决定和待办;保留负责人及截止时间,未明确的信息标为待确认。\n", count: 80) + let root = FileManager.default.temporaryDirectory.appendingPathComponent(domain) + let skills = SkillLibrary(resourcesRoot: nil, store: SkillStore(root: root, configDirectory: root)) + preferences.scenes = SceneSettings(scenes: [WeChatScene(id: "long-prompt", name: "长提示词", instruction: prompt, outputSpec: "", enabled: true)]) + let host = NSHostingView(rootView: ScrollView { SceneSettingsView(preferences: preferences, skills: skills, router: SettingsRouter()) }.frame(width: 1100, height: 700)) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1100, height: 700), styleMask: [.titled], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = host + defer { window.close() } + window.orderFront(nil) + try await Task.sleep(nanoseconds: 100_000_000) + host.layoutSubtreeIfNeeded() + var pending = [host as NSView] + var textViews: [NSTextView] = [] + while let view = pending.popLast() { + pending.append(contentsOf: view.subviews) + if let textView = view as? NSTextView { textViews.append(textView) } + } + let editor = try XCTUnwrap(textViews.first { $0.isEditable && $0.string == prompt }) + let scroll = try XCTUnwrap(editor.enclosingScrollView) + XCTAssertGreaterThan(scroll.frame.height, 0) + XCTAssertLessThanOrEqual(scroll.frame.height, 160) + XCTAssertGreaterThan(editor.bounds.height, scroll.contentSize.height) + } +}