Files
note/Note/ClipInboxViewController.swift
T

291 lines
11 KiB
Swift

//
// 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])
}
}