Compare commits

..

28 Commits

Author SHA1 Message Date
fish 1a525c763e 归档笔记保留 Note 格式化操作
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-07-17 22:33:41 +08:00
fish a0dffdc715 增大收集箱列表文案与时间间距 2026-07-16 21:46:43 +08:00
fish 4765d48021 收集箱列表展示完整文案 2026-07-16 21:44:51 +08:00
fish f888e28d15 添加简体中文本地化支持 2026-07-16 21:38:07 +08:00
fish c934dbad84 调整完成按钮与键盘的间距 2026-07-16 21:35:40 +08:00
fish 4088db8ec0 编辑页完成按钮改为玻璃浮动效果 2026-07-16 21:26:36 +08:00
fish 255f171aa8 编辑页键盘增加完成按钮 2026-07-16 21:19:29 +08:00
fish 70870e1ec2 编辑页增加键盘遮挡处理 2026-07-16 21:13:52 +08:00
fish f1a380d105 保存失败时返回具体错误信息 2026-07-15 23:55:36 +08:00
fish 01ad237af3 修复 TextFormatter actor 隔离警告 2026-07-15 23:47:47 +08:00
fish 7d49f7d5a4 预置快捷指令自动读取剪贴板 2026-07-15 23:43:22 +08:00
fish 87eb958869 添加预置快捷指令 2026-07-15 23:39:15 +08:00
fish 4340fd3635 修复编译警告 2026-07-15 23:33:33 +08:00
fish ac2eac5fcd 修复收集箱后台返回不刷新 2026-07-15 23:22:37 +08:00
fish a386802a55 快捷指令预处理去掉标题前缀 2026-07-15 23:19:32 +08:00
fish 1f94b9884c 快捷指令保存文案前使用 iCloud 格式化预处理 2026-07-15 23:15:55 +08:00
fish 58a8d27315 归档增加标题并统一分隔符 2026-07-15 23:11:05 +08:00
fish 7f4fc34dbf 收集箱增加归档功能 2026-07-15 23:04:20 +08:00
fish 5af8038ec0 收集箱使用独立编辑页 2026-07-15 22:57:00 +08:00
fish 1ff250fa17 过滤剪贴板无效占位符 2026-07-15 22:51:42 +08:00
fish 42e647c932 修复后台返回首页收集箱数量不刷新 2026-07-15 22:49:26 +08:00
fish 080c7f00ce 首页菜单支持自定义排序 2026-07-15 22:46:56 +08:00
fish 545e023ffc 修复收集箱有内容时无法进入 2026-07-15 22:43:45 +08:00
fish 10ba84e349 修复快捷指令运行时崩溃 2026-07-15 22:40:19 +08:00
fish adf13ae47c 重置按钮增加确认弹窗 2026-07-15 22:31:16 +08:00
fish 6c62d4bce4 修复清空按钮在暗夜模式下显示为灰色 2026-07-15 22:26:20 +08:00
fish 000a56295f 添加项目说明与编译命令 2026-07-15 22:22:30 +08:00
fish bbd4f0e266 添加收集箱与快捷指令保存功能 2026-07-15 22:19:36 +08:00
12 changed files with 836 additions and 24 deletions
+16
View File
@@ -0,0 +1,16 @@
# 项目说明
## 构建与测试环境
- 开发设备:macOS
- Xcode 版本:26.3
- 主 App Deployment TargetiOS 26.0
- 可用的 iOS 模拟器:**iPhone 17 Pro**
## 常用命令
### 编译主 AppiPhone 17 Pro 模拟器)
```bash
xcodebuild -scheme Note -destination 'platform=iOS Simulator,name=iPhone 17 Pro' build
```
+1
View File
@@ -184,6 +184,7 @@
knownRegions = ( knownRegions = (
en, en,
Base, Base,
"zh-Hans",
); );
mainGroup = CFD40B073003C283009C9F2A; mainGroup = CFD40B073003C283009C9F2A;
minimizedProjectReferenceProxies = 1; minimizedProjectReferenceProxies = 1;
+167
View File
@@ -0,0 +1,167 @@
//
// ClipEditViewController.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import UIKit
class ClipEditViewController: UIViewController {
private var textView: UITextView!
private var floatingDoneButton: UIButton!
private var floatingDoneButtonBottomConstraint: NSLayoutConstraint!
private var clip: Clip
init(clip: Clip) {
self.clip = clip
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = "编辑文案"
navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground
setupNavigationBar()
setupTextView()
setupKeyboardObservers()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupKeyboardObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc private func keyboardWillShow(_ notification: Notification) {
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let keyboardFrameInView = view.convert(keyboardFrame, from: nil)
let intersection = keyboardFrameInView.intersection(view.bounds)
let keyboardHeight = intersection.height
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = keyboardHeight
self.textView.verticalScrollIndicatorInsets.bottom = keyboardHeight
self.floatingDoneButtonBottomConstraint.constant = -(keyboardHeight + 8)
self.floatingDoneButton.alpha = 1
self.view.layoutIfNeeded()
}
}
@objc private func keyboardWillHide(_ notification: Notification) {
let duration = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0.25
UIView.animate(withDuration: duration, delay: 0, options: .beginFromCurrentState) {
self.textView.contentInset.bottom = 0
self.textView.verticalScrollIndicatorInsets.bottom = 0
self.floatingDoneButtonBottomConstraint.constant = -16
self.floatingDoneButton.alpha = 0
self.view.layoutIfNeeded()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
textView.becomeFirstResponder()
}
private func setupNavigationBar() {
let saveButton = UIBarButtonItem(
title: "保存",
style: .prominent,
target: self,
action: #selector(didTapSaveButton)
)
navigationItem.rightBarButtonItem = saveButton
}
private func setupTextView() {
textView = UITextView()
textView.translatesAutoresizingMaskIntoConstraints = false
textView.backgroundColor = UIColor { traitCollection in
traitCollection.userInterfaceStyle == .dark ? .secondarySystemBackground : .white
}
textView.layer.cornerRadius = 12
textView.layer.borderWidth = 0.5
textView.layer.borderColor = UIColor.separator.cgColor
textView.layer.masksToBounds = true
textView.font = UIFont.preferredFont(forTextStyle: .body)
textView.textContainerInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
textView.text = clip.text
view.addSubview(textView)
var doneConfig = UIButton.Configuration.glass()
doneConfig.title = "完成"
doneConfig.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
var outgoing = incoming
outgoing.font = UIFont.systemFont(ofSize: 17, weight: .semibold)
return outgoing
}
doneConfig.baseForegroundColor = .label
doneConfig.cornerStyle = .capsule
doneConfig.contentInsets = NSDirectionalEdgeInsets(top: 15, leading: 22, bottom: 15, trailing: 22)
floatingDoneButton = UIButton(configuration: doneConfig)
floatingDoneButton.translatesAutoresizingMaskIntoConstraints = false
floatingDoneButton.alpha = 0
floatingDoneButton.addTarget(self, action: #selector(didTapFloatingDoneButton), for: .touchUpInside)
view.addSubview(floatingDoneButton)
let safeArea = view.safeAreaLayoutGuide
floatingDoneButtonBottomConstraint = floatingDoneButton.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -16)
NSLayoutConstraint.activate([
textView.topAnchor.constraint(equalTo: safeArea.topAnchor, constant: 16),
textView.leadingAnchor.constraint(equalTo: safeArea.leadingAnchor, constant: 16),
textView.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -16),
textView.bottomAnchor.constraint(equalTo: safeArea.bottomAnchor, constant: -16),
floatingDoneButton.trailingAnchor.constraint(equalTo: safeArea.trailingAnchor, constant: -16),
floatingDoneButtonBottomConstraint
])
}
@objc private func didTapFloatingDoneButton() {
textView.resignFirstResponder()
}
@objc private func didTapSaveButton() {
let updatedText = textView.text ?? ""
guard !updatedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
let alert = UIAlertController(title: "提示", message: "文案不能为空。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
return
}
var updatedClip = clip
updatedClip.text = updatedText
Task {
do {
try await ClipStore.shared.update(updatedClip)
_ = await MainActor.run {
self.navigationController?.popViewController(animated: true)
return ()
}
} catch {
await MainActor.run {
let alert = UIAlertController(title: "提示", message: "保存失败: \(error.localizedDescription)", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
self.present(alert, animated: true)
}
}
}
}
}
+290
View File
@@ -0,0 +1,290 @@
//
// ClipInboxViewController.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import UIKit
class ClipInboxViewController: UIViewController {
private var tableView: UITableView!
private var emptyLabel: UILabel!
private var archiveButton: UIButton!
private var clips: [Clip] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "收集箱"
navigationItem.largeTitleDisplayMode = .never
view.backgroundColor = .systemGroupedBackground
setupNavigationBar()
setupArchiveButton()
setupTableView()
setupEmptyLabel()
setupAppStateObserver()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadClips()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupAppStateObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(appDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
@objc private func appDidBecomeActive() {
loadClips()
}
private func setupNavigationBar() {
let clearButton = UIBarButtonItem(
title: "清空",
style: .plain,
target: self,
action: #selector(didTapClearButton)
)
clearButton.tintColor = .systemRed
navigationItem.rightBarButtonItem = clearButton
}
private func setupTableView() {
tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "clipCell")
tableView.backgroundColor = .systemGroupedBackground
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: archiveButton.topAnchor, constant: -16)
])
}
private func setupArchiveButton() {
var config = UIButton.Configuration.filled()
config.title = "归档"
config.baseBackgroundColor = .systemBlue
config.baseForegroundColor = .white
config.cornerStyle = .medium
config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 16, bottom: 0, trailing: 16)
archiveButton = UIButton(configuration: config)
archiveButton.translatesAutoresizingMaskIntoConstraints = false
archiveButton.addTarget(self, action: #selector(didTapArchiveButton), for: .touchUpInside)
view.addSubview(archiveButton)
NSLayoutConstraint.activate([
archiveButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
archiveButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -16),
archiveButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -16),
archiveButton.heightAnchor.constraint(equalToConstant: 52)
])
}
@objc private func didTapArchiveButton() {
guard clips.count >= 2 else {
let alert = UIAlertController(title: "提示", message: "至少需要两条文案才能归档。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
return
}
let title = self.archiveTitle()
let itemsText = clips.map { "\($0.text)\n\n---" }.joined(separator: "\n\n")
let archivedText = "\(title)\n\n\(itemsText)"
let viewController = FormatNoteViewController()
viewController.initialText = archivedText
navigationController?.pushViewController(viewController, animated: true)
}
private func archiveTitle() -> String {
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "zh_CN")
dateFormatter.dateFormat = "yyyy年MM月dd日"
let dateString = dateFormatter.string(from: Date())
let weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
let weekdayIndex = Calendar.current.component(.weekday, from: Date()) - 1
let weekday = (weekdayIndex >= 0 && weekdayIndex < weekdays.count) ? weekdays[weekdayIndex] : ""
return "【读书摘抄】\(dateString) \(weekday)"
}
private func setupEmptyLabel() {
emptyLabel = UILabel()
emptyLabel.translatesAutoresizingMaskIntoConstraints = false
emptyLabel.text = "还没有保存的文案\n复制内容后运行快捷指令即可收藏"
emptyLabel.numberOfLines = 0
emptyLabel.textAlignment = .center
emptyLabel.textColor = .secondaryLabel
emptyLabel.font = UIFont.preferredFont(forTextStyle: .body)
emptyLabel.isHidden = true
view.addSubview(emptyLabel)
NSLayoutConstraint.activate([
emptyLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
emptyLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
emptyLabel.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
emptyLabel.trailingAnchor.constraint(equalTo: view.readableContentGuide.trailingAnchor)
])
}
private func loadClips() {
Task {
do {
clips = try await ClipStore.shared.loadAll()
await MainActor.run {
tableView.reloadData()
updateEmptyState()
}
} catch {
await MainActor.run {
showError(message: "加载失败: \(error.localizedDescription)")
}
}
}
}
private func updateEmptyState() {
let isEmpty = clips.isEmpty
emptyLabel.isHidden = !isEmpty
tableView.isHidden = isEmpty
archiveButton.isHidden = isEmpty
}
@objc private func didTapClearButton() {
guard !clips.isEmpty else {
let alert = UIAlertController(title: "提示", message: "收集箱为空,没有可清空的内容。", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
return
}
let alert = UIAlertController(
title: "清空收集箱",
message: "确定要删除所有保存的文案吗?此操作不可撤销。",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "清空", style: .destructive) { [weak self] _ in
self?.clearAllClips()
})
present(alert, animated: true)
}
private func clearAllClips() {
Task {
do {
try await ClipStore.shared.clearAll()
clips = []
await MainActor.run {
tableView.reloadData()
updateEmptyState()
}
} catch {
await MainActor.run {
showError(message: "清空失败: \(error.localizedDescription)")
}
}
}
}
private func deleteClip(at indexPath: IndexPath) {
let clip = clips[indexPath.row]
Task {
do {
try await ClipStore.shared.delete(id: clip.id)
clips.remove(at: indexPath.row)
await MainActor.run {
tableView.deleteRows(at: [indexPath], with: .automatic)
updateEmptyState()
}
} catch {
await MainActor.run {
showError(message: "删除失败: \(error.localizedDescription)")
}
}
}
}
private func openClip(_ clip: Clip) {
let viewController = ClipEditViewController(clip: clip)
navigationController?.pushViewController(viewController, animated: true)
}
private func showError(message: String) {
let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "确定", style: .default))
present(alert, animated: true)
}
}
extension ClipInboxViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return clips.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "clipCell", for: indexPath)
let clip = clips[indexPath.row]
var config = cell.defaultContentConfiguration()
config.text = previewText(for: clip.text)
config.textProperties.numberOfLines = 0
config.secondaryText = formattedDate(clip.createdAt)
config.secondaryTextProperties.color = .secondaryLabel
config.textToSecondaryTextVerticalPadding = 12
cell.contentConfiguration = config
cell.accessoryType = .disclosureIndicator
return cell
}
private func previewText(for text: String) -> String {
let preview = text.trimmingCharacters(in: .whitespacesAndNewlines)
if preview.isEmpty {
return "(无内容)"
}
return preview
}
private func formattedDate(_ date: Date) -> String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .short
return formatter.localizedString(for: date, relativeTo: Date())
}
}
extension ClipInboxViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let clip = clips[indexPath.row]
openClip(clip)
}
func tableView(_ tableView: UITableView,
trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "删除") { [weak self] _, _, completion in
self?.deleteClip(at: indexPath)
completion(true)
}
return UISwipeActionsConfiguration(actions: [deleteAction])
}
}
+112
View File
@@ -0,0 +1,112 @@
//
// ClipStore.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import Foundation
struct Clip: Codable, Identifiable, Equatable, Sendable {
let id: UUID
var text: String
let createdAt: Date
var source: String?
nonisolated init(id: UUID = UUID(), text: String, createdAt: Date = Date(), source: String? = nil) {
self.id = id
self.text = text
self.createdAt = createdAt
self.source = source
}
}
enum ClipStoreError: Error, LocalizedError {
case appGroupUnavailable
var errorDescription: String? {
switch self {
case .appGroupUnavailable:
return "无法访问 App Group 容器,请检查签名和 entitlements 配置。"
}
}
}
actor ClipStore {
static let shared = ClipStore()
private let appGroupIdentifier = "group.com.fishestlife.note"
private let fileName = "clips.json"
private let subdirectory = "SharedFiles/Clips"
private var cachedClips: [Clip]?
private func fileURL() throws -> URL {
let fileManager = FileManager.default
guard let containerURL = fileManager.containerURL(forSecurityApplicationGroupIdentifier: appGroupIdentifier) else {
throw ClipStoreError.appGroupUnavailable
}
let directoryURL = containerURL.appendingPathComponent(subdirectory, isDirectory: true)
try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true)
return directoryURL.appendingPathComponent(fileName)
}
private init() {}
func save(text: String, source: String? = nil) async throws {
var clips = try await loadAll()
let clip = Clip(text: text, source: source)
clips.insert(clip, at: 0)
try await persist(clips)
}
func loadAll() async throws -> [Clip] {
if let cached = cachedClips {
return cached
}
let url = try fileURL()
let fileManager = FileManager.default
guard fileManager.fileExists(atPath: url.path) else {
cachedClips = []
return []
}
let data = try Data(contentsOf: url)
let clips = try JSONDecoder().decode([Clip].self, from: data)
cachedClips = clips
return clips
}
func update(_ clip: Clip) async throws {
var clips = try await loadAll()
guard let index = clips.firstIndex(where: { $0.id == clip.id }) else {
return
}
clips[index] = clip
try await persist(clips)
}
func delete(id: UUID) async throws {
var clips = try await loadAll()
clips.removeAll { $0.id == id }
try await persist(clips)
}
func clearAll() async throws {
try await persist([])
}
func count() async throws -> Int {
let clips = try await loadAll()
return clips.count
}
private func persist(_ clips: [Clip]) async throws {
let url = try fileURL()
let data = try JSONEncoder().encode(clips)
try data.write(to: url, options: .atomic)
cachedClips = clips
}
}
+13
View File
@@ -184,6 +184,19 @@ class FormatLogViewController: UIViewController {
} }
@objc private func didTapResetButton() { @objc private func didTapResetButton() {
let alert = UIAlertController(
title: "确认重置",
message: "确定要清空当前内容吗?",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "重置", style: .destructive) { [weak self] _ in
self?.performReset()
})
present(alert, animated: true)
}
private func performReset() {
textView.text = "" textView.text = ""
isFormatted = false isFormatted = false
formatButton.setTitle("格式化", for: .normal) formatButton.setTitle("格式化", for: .normal)
+13 -4
View File
@@ -35,10 +35,6 @@ class FormatNoteViewController: UIViewController {
setupUI() setupUI()
if let initialText = initialText { if let initialText = initialText {
textView.text = initialText textView.text = initialText
isNoteFormatted = true
noteButton.setTitle("复制并打开备忘录", for: .normal)
rightBarButtonMode = .reset
updateRightBarButtonItem()
} }
setupKeyboardObservers() setupKeyboardObservers()
} }
@@ -192,6 +188,19 @@ class FormatNoteViewController: UIViewController {
} }
@objc private func didTapResetButton() { @objc private func didTapResetButton() {
let alert = UIAlertController(
title: "确认重置",
message: "确定要清空当前内容吗?",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
alert.addAction(UIAlertAction(title: "重置", style: .destructive) { [weak self] _ in
self?.performReset()
})
present(alert, animated: true)
}
private func performReset() {
textView.text = "" textView.text = ""
rightBarButtonMode = .paste rightBarButtonMode = .paste
isCloudFormatted = false isCloudFormatted = false
+20
View File
@@ -0,0 +1,20 @@
//
// NoteAppShortcuts.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import AppIntents
struct NoteAppShortcuts: AppShortcutsProvider {
static var appShortcuts: [AppShortcut] {
AppShortcut(
intent: SaveClipIntent(),
phrases: ["保存剪贴板到 ${applicationName}"],
shortTitle: "保存剪贴板",
systemImageName: "doc.text"
)
}
}
+61
View File
@@ -0,0 +1,61 @@
//
// SaveClipIntent.swift
// Note
//
// Created by Kimi Code CLI on 2026/7/15.
//
import AppIntents
import UIKit
struct SaveClipIntent: AppIntent {
static var title: LocalizedStringResource = "保存剪贴板到 Note"
static var description: IntentDescription? = "将一段文本保存到 Note App 的收集箱,稍后统一处理。"
@Parameter(title: "文案", description: "要保存的文本内容", default: "")
var text: String
@Parameter(title: "来源", description: "文案来源,例如应用名称", default: "快捷指令")
var source: String?
init() {}
init(text: String, source: String? = nil) {
self.text = text
self.source = source
}
func perform() async throws -> some IntentResult & ReturnsValue<String> {
var inputText = text
if inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
inputText = await MainActor.run {
UIPasteboard.general.string ?? ""
}
}
let trimmed = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else {
return .result(value: "文案为空,未保存。")
}
guard !isSystemClipboardPlaceholder(trimmed) else {
return .result(value: "剪贴板没有有效文本,未保存。")
}
let formattedText = TextFormatter.formatForShortcut(trimmed)
try await ClipStore.shared.save(text: formattedText, source: source)
return .result(value: "已保存到收集箱。")
}
private func isSystemClipboardPlaceholder(_ text: String) -> Bool {
let lowercased = text.lowercased()
if lowercased.hasPrefix("clipboard ") && lowercased.contains(" at ") {
return true
}
if text == "获取剪贴板" {
return true
}
return false
}
}
+12 -7
View File
@@ -9,7 +9,7 @@ import Foundation
enum TextFormatter { enum TextFormatter {
static func formatLog(_ text: String) -> String { static nonisolated func formatLog(_ text: String) -> String {
var content = text var content = text
content = content.replacingOccurrences(of: "# ", with: "") content = content.replacingOccurrences(of: "# ", with: "")
@@ -31,7 +31,14 @@ enum TextFormatter {
return content return content
} }
static func formatForCloud(_ text: String) -> String { static nonisolated func formatForCloud(_ text: String) -> String {
var content = formatForShortcut(text)
content = "# " + content
content = insertEmptyLineAfterFirstLine(content)
return content
}
static nonisolated func formatForShortcut(_ text: String) -> String {
var content = text var content = text
content = content.replacingOccurrences(of: " ", with: "") content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: " ", with: "") content = content.replacingOccurrences(of: " ", with: "")
@@ -71,12 +78,10 @@ enum TextFormatter {
content = content.replacingOccurrences(of: " ", with: "") content = content.replacingOccurrences(of: " ", with: "")
content = content.replacingOccurrences(of: "---", with: "---\n") content = content.replacingOccurrences(of: "---", with: "---\n")
content = content.replacingOccurrences(of: "日星期", with: "日 星期") content = content.replacingOccurrences(of: "日星期", with: "日 星期")
content = "# " + content
content = insertEmptyLineAfterFirstLine(content)
return content return content
} }
static func formatForNote(_ text: String) -> String { static nonisolated func formatForNote(_ text: String) -> String {
var content = text var content = text
content = content.replacingOccurrences(of: "# ", with: "") content = content.replacingOccurrences(of: "# ", with: "")
content = content.replacingOccurrences(of: "#", with: "") content = content.replacingOccurrences(of: "#", with: "")
@@ -111,13 +116,13 @@ enum TextFormatter {
return result.trimmingCharacters(in: .whitespacesAndNewlines) return result.trimmingCharacters(in: .whitespacesAndNewlines)
} }
static func removeEmptyLines(_ text: String) -> String { static nonisolated func removeEmptyLines(_ text: String) -> String {
let lines = text.components(separatedBy: .newlines) let lines = text.components(separatedBy: .newlines)
let nonEmptyLines = lines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty } let nonEmptyLines = lines.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }
return nonEmptyLines.joined(separator: "\n") return nonEmptyLines.joined(separator: "\n")
} }
static func insertEmptyLineAfterFirstLine(_ text: String) -> String { static nonisolated func insertEmptyLineAfterFirstLine(_ text: String) -> String {
var lines = text.components(separatedBy: .newlines) var lines = text.components(separatedBy: .newlines)
if !lines.isEmpty { if !lines.isEmpty {
lines.insert("", at: 1) lines.insert("", at: 1)
+130 -13
View File
@@ -10,25 +10,54 @@ import UIKit
class ViewController: UIViewController { class ViewController: UIViewController {
private var tableView: UITableView! private var tableView: UITableView!
private var editButton: UIBarButtonItem!
private let menuOrderKey = "homeMenuOrder"
private struct MenuItem { private struct MenuItem {
let icon: String let icon: String
let iconColor: UIColor let iconColor: UIColor
let title: String let title: String
let identifier: String
} }
private let menuItems: [[MenuItem]] = [ private let defaultMenuItems: [MenuItem] = [
[ MenuItem(icon: "tray.full", iconColor: .systemIndigo, title: "收集箱", identifier: "inbox"),
MenuItem(icon: "note.text", iconColor: .systemYellow, title: "打开备忘录"), MenuItem(icon: "note.text", iconColor: .systemYellow, title: "打开备忘录", identifier: "notes"),
MenuItem(icon: "doc.text", iconColor: .systemBlue, title: "格式化日志"), MenuItem(icon: "doc.text", iconColor: .systemBlue, title: "格式化日志", identifier: "formatLog"),
MenuItem(icon: "text.alignleft", iconColor: .systemGreen, title: "格式化笔记"), MenuItem(icon: "text.alignleft", iconColor: .systemGreen, title: "格式化笔记", identifier: "formatNote"),
MenuItem(icon: "folder", iconColor: .systemOrange, title: "打开文件") MenuItem(icon: "folder", iconColor: .systemOrange, title: "打开文件", identifier: "files")
]
] ]
private var menuItems: [[MenuItem]] = []
override func viewDidLoad() { override func viewDidLoad() {
super.viewDidLoad() super.viewDidLoad()
menuItems = [loadMenuOrder()]
setupUI() setupUI()
setupAppStateObserver()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateInboxBadge()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func setupAppStateObserver() {
NotificationCenter.default.addObserver(
self,
selector: #selector(appDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
@objc private func appDidBecomeActive() {
updateInboxBadge()
} }
private func setupUI() { private func setupUI() {
@@ -37,6 +66,9 @@ class ViewController: UIViewController {
navigationItem.largeTitleDisplayMode = .always navigationItem.largeTitleDisplayMode = .always
view.backgroundColor = .systemGroupedBackground view.backgroundColor = .systemGroupedBackground
editButton = UIBarButtonItem(title: "编辑", style: .plain, target: self, action: #selector(didTapEditButton))
navigationItem.rightBarButtonItem = editButton
tableView = UITableView(frame: .zero, style: .insetGrouped) tableView = UITableView(frame: .zero, style: .insetGrouped)
tableView.translatesAutoresizingMaskIntoConstraints = false tableView.translatesAutoresizingMaskIntoConstraints = false
tableView.delegate = self tableView.delegate = self
@@ -52,6 +84,34 @@ class ViewController: UIViewController {
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
]) ])
} }
@objc private func didTapEditButton() {
tableView.setEditing(!tableView.isEditing, animated: true)
editButton.title = tableView.isEditing ? "完成" : "编辑"
}
private func loadMenuOrder() -> [MenuItem] {
guard let savedOrder = UserDefaults.standard.array(forKey: menuOrderKey) as? [String] else {
return defaultMenuItems
}
var orderedItems: [MenuItem] = []
for identifier in savedOrder {
if let item = defaultMenuItems.first(where: { $0.identifier == identifier }) {
orderedItems.append(item)
}
}
let remaining = defaultMenuItems.filter { item in
!orderedItems.contains { $0.identifier == item.identifier }
}
return orderedItems + remaining
}
private func saveMenuOrder() {
let identifiers = menuItems.flatMap { $0.map(\.identifier) }
UserDefaults.standard.set(identifiers, forKey: menuOrderKey)
}
} }
extension ViewController: UITableViewDataSource { extension ViewController: UITableViewDataSource {
@@ -74,34 +134,91 @@ extension ViewController: UITableViewDataSource {
config.imageProperties.tintColor = item.iconColor config.imageProperties.tintColor = item.iconColor
config.imageToTextPadding = 12 config.imageToTextPadding = 12
cell.contentConfiguration = config cell.contentConfiguration = config
cell.accessoryType = .disclosureIndicator cell.accessoryType = tableView.isEditing ? .none : .disclosureIndicator
cell.selectionStyle = tableView.isEditing ? .none : .default
return cell return cell
} }
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard sourceIndexPath != destinationIndexPath else { return }
let item = menuItems[sourceIndexPath.section].remove(at: sourceIndexPath.row)
menuItems[destinationIndexPath.section].insert(item, at: destinationIndexPath.row)
saveMenuOrder()
}
} }
extension ViewController: UITableViewDelegate { extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true) tableView.deselectRow(at: indexPath, animated: true)
guard !tableView.isEditing else { return }
let item = menuItems[indexPath.section][indexPath.row] let item = menuItems[indexPath.section][indexPath.row]
switch item.title { switch item.identifier {
case "打开备忘录": case "inbox":
let viewController = ClipInboxViewController()
navigationController?.pushViewController(viewController, animated: true)
case "notes":
openSystemNotesApp() openSystemNotesApp()
case "格式化日志": case "formatLog":
let viewController = FormatLogViewController() let viewController = FormatLogViewController()
navigationController?.pushViewController(viewController, animated: true) navigationController?.pushViewController(viewController, animated: true)
case "格式化笔记": case "formatNote":
let viewController = FormatNoteViewController() let viewController = FormatNoteViewController()
navigationController?.pushViewController(viewController, animated: true) navigationController?.pushViewController(viewController, animated: true)
case "打开文件": case "files":
openFilesApp() openFilesApp()
default: default:
break break
} }
} }
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
private func updateInboxBadge() {
Task {
guard let count = try? await ClipStore.shared.count(), count > 0 else {
await MainActor.run {
self.updateInboxTitle("收集箱")
}
return
}
await MainActor.run {
self.updateInboxTitle("收集箱(\(count)")
}
}
}
private func updateInboxTitle(_ title: String) {
for (sectionIndex, section) in menuItems.enumerated() {
for (rowIndex, item) in section.enumerated() {
if item.identifier == "inbox" {
menuItems[sectionIndex][rowIndex] = MenuItem(
icon: item.icon,
iconColor: item.iconColor,
title: title,
identifier: item.identifier
)
let indexPath = IndexPath(row: rowIndex, section: sectionIndex)
tableView.reloadRows(at: [indexPath], with: .none)
return
}
}
}
}
private func openSystemNotesApp() { private func openSystemNotesApp() {
openURLIfPossible("mobilenotes://") openURLIfPossible("mobilenotes://")
} }
+1
View File
@@ -0,0 +1 @@
/* Simplified Chinese localization */