From bacedf4c652c1314ac5cadc2706457058cb0cab0 Mon Sep 17 00:00:00 2001 From: lixianglei <1315035686@qq.com> Date: Wed, 21 Oct 2026 10:55:02 +0800 Subject: [PATCH] =?UTF-8?q?fix(macos):=20=E4=B8=BA=E5=9C=BA=E6=99=AF?= =?UTF-8?q?=E9=95=BF=E6=8F=90=E7=A4=BA=E8=AF=8D=E7=BC=96=E8=BE=91=E5=92=8C?= =?UTF-8?q?=E9=A2=84=E8=A7=88=E9=99=90=E5=88=B6=E5=B8=83=E5=B1=80=E9=AB=98?= =?UTF-8?q?=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Views/Settings/ScenePromptTextView.swift | 103 +++++++++++++++ .../Views/Settings/SceneSettingsView.swift | 50 +++++--- .../ScenePromptTextViewTests.swift | 120 ++++++++++++++++++ 3 files changed, 253 insertions(+), 20 deletions(-) create mode 100644 macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptTextView.swift create mode 100644 macos/Tests/WeChatBridgeAppTests/ScenePromptTextViewTests.swift diff --git a/macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptTextView.swift b/macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptTextView.swift new file mode 100644 index 0000000..8aa03f5 --- /dev/null +++ b/macos/Sources/WeChatBridgeApp/Views/Settings/ScenePromptTextView.swift @@ -0,0 +1,103 @@ +import AppKit +import SwiftUI +import WeChatBridgeCore + +/// 将文本布局留在原生滚动视图内,避免长提示词参与整个设置页的高度计算。 +struct ScenePromptTextView: NSViewRepresentable { + @Binding var text: String + var isEditable = true + + static let editorIdentifier = "scene.promptEditor" + + func makeCoordinator() -> Coordinator { + Coordinator(text: $text) + } + + func makeNSView(context: Context) -> ScenePromptScrollView { + let view = ScenePromptScrollView(frame: NSRect(x: 0, y: 0, width: 320, height: 160)) + view.textView.delegate = context.coordinator + configure(view) + return view + } + + func updateNSView(_ view: ScenePromptScrollView, context: Context) { + context.coordinator.text = $text + configure(view) + } + + private func configure(_ view: ScenePromptScrollView) { + view.update(text: text, isEditable: isEditable) + view.textView.identifier = NSUserInterfaceItemIdentifier( + isEditable ? Self.editorIdentifier : "scene.promptPreview" + ) + view.textView.setAccessibilityLabel( + L10n.text(isEditable ? "提示词" : "转发提示词预览") + ) + } + + final class Coordinator: NSObject, NSTextViewDelegate { + var text: Binding + + init(text: Binding) { + self.text = text + } + + func textDidChange(_ notification: Notification) { + guard let view = notification.object as? NSTextView, + !view.hasMarkedText(), + text.wrappedValue != view.string + else { return } + text.wrappedValue = view.string + } + } +} + +final class ScenePromptScrollView: NSScrollView { + let textView = NSTextView(frame: .zero) + + override init(frame: NSRect) { + super.init(frame: frame) + borderType = .noBorder + drawsBackground = false + hasVerticalScroller = true + hasHorizontalScroller = false + autohidesScrollers = true + + textView.drawsBackground = false + textView.isRichText = false + textView.importsGraphics = false + textView.allowsUndo = true + textView.isSelectable = true + textView.isVerticallyResizable = true + textView.isHorizontallyResizable = false + textView.autoresizingMask = [.width] + textView.minSize = .zero + textView.maxSize = NSSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude) + textView.textContainerInset = NSSize(width: 5, height: 8) + textView.textContainer?.containerSize = NSSize( + width: contentSize.width, + height: CGFloat.greatestFiniteMagnitude + ) + textView.textContainer?.widthTracksTextView = true + textView.frame = NSRect(origin: .zero, size: contentSize) + documentView = textView + } + + required init?(coder: NSCoder) { + fatalError("不支持从归档创建场景文本视图") + } + + func update(text: String, isEditable: Bool) { + if textView.isEditable != isEditable { + textView.isEditable = isEditable + } + let font = NSFont.systemFont(ofSize: isEditable ? 12.5 : 12, weight: isEditable ? .medium : .regular) + if textView.font != font { textView.font = font } + let color = NSColor(isEditable ? Theme.ink : Theme.inkSecondary) + if textView.textColor != color { textView.textColor = color } + + // 相同内容不重设文本,保留光标、撤销记录、滚动位置和输入法组合状态。 + guard textView.string != text, !textView.hasMarkedText() else { return } + textView.string = text + } +} diff --git a/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift b/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift index 460452d..c601f27 100644 --- a/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift +++ b/macos/Sources/WeChatBridgeApp/Views/Settings/SceneSettingsView.swift @@ -613,7 +613,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) + promptView(text: .constant(promptText), isEditable: false) + } } } else { SceneField(title: L10n.text("名称"), text: $scene.name) @@ -628,9 +633,7 @@ private struct SceneEditor: View { Spacer(minLength: Space.s) insertSkillMenu } - TextField(L10n.text("提示词"), text: promptBinding, axis: .vertical) - .lineLimit(5...9) - .textFieldStyle(SettingsTextFieldStyle(multiline: true)) + promptView(text: promptBinding, isEditable: true) } } @@ -725,14 +728,28 @@ private struct SceneEditor: View { ) } + private func promptView(text: Binding, isEditable: Bool) -> some View { + ScenePromptTextView(text: text, isEditable: isEditable) + .frame(height: 160) + .frame(maxWidth: .infinity) + .background(Theme.sunken, in: RoundedRectangle(cornerRadius: SettingsControlMetrics.radius)) + .clipShape(RoundedRectangle(cornerRadius: SettingsControlMetrics.radius)) + .overlay { + RoundedRectangle(cornerRadius: SettingsControlMetrics.radius) + .strokeBorder(Theme.inputStroke, lineWidth: Stroke.hairline) + } + } + /// 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 updated = scene + updated.instruction = text + updated.outputSpec = "" var seen = Set() - scene.requiredSkillIDs = SkillReference.parse(text) + updated.requiredSkillIDs = SkillReference.parse(text) .filter { seen.insert($0).inserted } + scene = updated } // MARK: - Skill references & preview @@ -778,11 +795,10 @@ private struct SceneEditor: View { } VStack(alignment: .leading, spacing: 5) { - HStack(spacing: Space.s) { + VStack(alignment: .leading, spacing: Space.s) { Text(L10n.text("转发提示词预览")) .font(Typo.captionStrong) .foregroundStyle(Theme.inkSecondary) - Spacer(minLength: Space.s) SettingsSelect( title: L10n.text("预览目标"), selection: $previewTarget, @@ -791,14 +807,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) - .background(Theme.sunken, in: RoundedRectangle(cornerRadius: Radius.row)) + promptView(text: .constant(previewText(context: context)), isEditable: false) } } } @@ -841,11 +850,12 @@ 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) { let token = SkillReference.token(id) - if let textView = NSApp.keyWindow?.firstResponder as? NSTextView { + if let textView = NSApp.keyWindow?.firstResponder as? NSTextView, + textView.identifier?.rawValue == ScenePromptTextView.editorIdentifier, + textView.isEditable { textView.insertText(token, replacementRange: textView.selectedRange()) return } diff --git a/macos/Tests/WeChatBridgeAppTests/ScenePromptTextViewTests.swift b/macos/Tests/WeChatBridgeAppTests/ScenePromptTextViewTests.swift new file mode 100644 index 0000000..d4daa45 --- /dev/null +++ b/macos/Tests/WeChatBridgeAppTests/ScenePromptTextViewTests.swift @@ -0,0 +1,120 @@ +import AppKit +import SwiftUI +import XCTest +@testable import WeChatBridgeApp + +final class ScenePromptTextViewTests: XCTestCase { + @MainActor + func testSwiftUIEditorAndPreviewStayBoundedInsideAnOuterScrollView() { + _ = NSApplication.shared + let prompt = String(repeating: "用于布局回归的长提示词。\n", count: 2_000) + let host = NSHostingView(rootView: ScrollView { + VStack { + ScenePromptTextView(text: .constant(prompt)).frame(height: 160) + ScenePromptTextView(text: .constant(prompt), isEditable: false).frame(height: 160) + } + }) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 320, height: 400), + styleMask: [.titled], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + window.contentView = host + defer { window.close() } + host.layoutSubtreeIfNeeded() + + let views = promptViews(in: host) + XCTAssertEqual(views.count, 2) + for view in views { + XCTAssertEqual(view.frame.height, 160, accuracy: 1) + XCTAssertGreaterThan(view.frame.width, 0) + XCTAssertEqual(view.textView.string, prompt) + } + } + + @MainActor + func testLongPromptScrollsWithoutGrowingTheViewportOrLosingText() throws { + let prompt = String(repeating: "测试段落:保留中文、emoji 🧪 和全部换行。\n", count: 2_000) + let view = ScenePromptScrollView(frame: NSRect(x: 0, y: 0, width: 320, height: 160)) + view.update(text: prompt, isEditable: true) + view.layoutSubtreeIfNeeded() + let container = try XCTUnwrap(view.textView.textContainer) + let layout = try XCTUnwrap(view.textView.layoutManager) + layout.ensureLayout(for: container) + + XCTAssertEqual(view.textView.string, prompt) + XCTAssertEqual(view.frame.height, 160) + XCTAssertGreaterThan(layout.usedRect(for: container).height, view.contentSize.height) + XCTAssertTrue(view.hasVerticalScroller) + XCTAssertFalse(view.hasHorizontalScroller) + XCTAssertTrue(container.widthTracksTextView) + + view.textView.scrollRangeToVisible(NSRange(location: (prompt as NSString).length, length: 0)) + XCTAssertGreaterThan(view.contentView.bounds.origin.y, 0) + XCTAssertEqual(view.frame.height, 160) + } + + @MainActor + func testPreviewKeepsFullTextSelectableAndReadOnly() { + let prompt = String(repeating: "预览内容\n", count: 2_000) + let view = ScenePromptScrollView(frame: NSRect(x: 0, y: 0, width: 320, height: 160)) + view.update(text: prompt, isEditable: false) + + XCTAssertEqual(view.textView.string, prompt) + XCTAssertFalse(view.textView.isEditable) + XCTAssertTrue(view.textView.isSelectable) + XCTAssertFalse(view.textView.isRichText) + } + + @MainActor + func testUnchangedUpdatePreservesSelectionAndScrollPosition() { + let prompt = String(repeating: "测试段落\n", count: 2_000) + let view = ScenePromptScrollView(frame: NSRect(x: 0, y: 0, width: 320, height: 160)) + view.update(text: prompt, isEditable: true) + let selection = NSRange(location: (prompt as NSString).length - 5, length: 2) + view.textView.setSelectedRange(selection) + view.textView.scrollRangeToVisible(selection) + let scrollPosition = view.contentView.bounds.origin + + view.update(text: prompt, isEditable: true) + + XCTAssertEqual(view.textView.selectedRange(), selection) + XCTAssertEqual(view.contentView.bounds.origin, scrollPosition) + } + + @MainActor + func testEditingAndSkillInsertionUpdateTheBindingOncePerChange() { + var prompt = "测试🧪内容" + var changes = 0 + let binding = Binding(get: { prompt }, set: { prompt = $0; changes += 1 }) + let coordinator = ScenePromptTextView.Coordinator(text: binding) + let view = ScenePromptScrollView(frame: NSRect(x: 0, y: 0, width: 320, height: 160)) + view.update(text: prompt, isEditable: true) + view.textView.delegate = coordinator + + view.textView.insertText("{{skill:test-skill}}", replacementRange: NSRange(location: 2, length: 0)) + + XCTAssertEqual(prompt, "测试{{skill:test-skill}}🧪内容") + XCTAssertEqual(changes, 1) + view.update(text: prompt, isEditable: true) + XCTAssertEqual(changes, 1) + } + + @MainActor + func testExternalUpdateDoesNotReplaceInputMethodComposition() { + let view = ScenePromptScrollView(frame: NSRect(x: 0, y: 0, width: 320, height: 160)) + view.update(text: "原文", isEditable: true) + view.textView.setMarkedText("拼音", selectedRange: NSRange(location: 2, length: 0), + replacementRange: NSRange(location: 2, length: 0)) + XCTAssertTrue(view.textView.hasMarkedText()) + + view.update(text: "原文", isEditable: true) + + XCTAssertTrue(view.textView.hasMarkedText()) + XCTAssertEqual(view.textView.string, "原文拼音") + } + + @MainActor + private func promptViews(in view: NSView) -> [ScenePromptScrollView] { + if let prompt = view as? ScenePromptScrollView { return [prompt] } + return view.subviews.flatMap { promptViews(in: $0) } + } +}