mirror of
https://github.com/shadowsocks/ShadowsocksX-NG.git
synced 2026-11-29 01:46:31 +00:00
feat(servers): add ordered favorites
This commit is contained in:
@@ -15,6 +15,12 @@
|
||||
**配置组(Configuration group)**:
|
||||
具有名称和子节点顺序的容器,可包含服务器配置和嵌套配置组;每个节点最多属于一个父节点,组之间不形成环。
|
||||
|
||||
**收藏(Favorite)**:
|
||||
用户对一个服务器配置或配置组的独立标记,不改变节点的来源或目录位置,也不包含对其后代的标记。
|
||||
|
||||
**收藏列表(Favorites list)**:
|
||||
用户排列的收藏节点序列,每个节点最多出现一次,配置组与服务器配置均作为单独一项,不展开后代。
|
||||
|
||||
**节点时间戳(Node timestamps)**:
|
||||
配置目录中每个节点(服务器配置或配置组)的创建时间与修改时间事实。创建时间是节点进入目录的时刻;修改时间是节点自身资料、或分组的直接子节点集合与顺序最后一次变化的时刻,移动节点本身不算修改。历史文档未记录的时间是未知事实,不做回填。
|
||||
|
||||
|
||||
@@ -38,12 +38,14 @@ struct CatalogCommitBootstrap {
|
||||
let catalogSnapshotReader: RuntimeCatalogSnapshotReading
|
||||
fileprivate let committedCatalogState: CommittedCatalogState
|
||||
fileprivate let subscriptions: [SubscriptionRecord]
|
||||
fileprivate let favoriteIDs: [NodeID]
|
||||
|
||||
fileprivate init(document: CatalogDocument) {
|
||||
let state = CommittedCatalogState(catalog: document.catalog)
|
||||
catalogSnapshotReader = state
|
||||
committedCatalogState = state
|
||||
subscriptions = document.subscriptions
|
||||
favoriteIDs = document.favoriteIDs
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +108,7 @@ final class CatalogCommitCoordinator {
|
||||
/// 目录在共享来源中只有一份;订阅状态仍由协调器持有。
|
||||
var committedCatalog: ConfigurationCatalog { catalogState.catalogSnapshot }
|
||||
private(set) var committedSubscriptions: [SubscriptionRecord]
|
||||
private(set) var committedFavoriteIDs: [NodeID]
|
||||
|
||||
init(
|
||||
fileStore: CatalogFileStore,
|
||||
@@ -116,6 +119,7 @@ final class CatalogCommitCoordinator {
|
||||
self.runtime = runtime
|
||||
catalogState = bootstrap.committedCatalogState
|
||||
committedSubscriptions = bootstrap.subscriptions
|
||||
committedFavoriteIDs = bootstrap.favoriteIDs
|
||||
}
|
||||
|
||||
/// Test and isolated-module convenience: still performs exactly one document
|
||||
@@ -140,21 +144,36 @@ final class CatalogCommitCoordinator {
|
||||
var workingCatalog = committedCatalog
|
||||
var workingSubscriptions = committedSubscriptions
|
||||
let result = try mutate(&workingCatalog, &workingSubscriptions)
|
||||
let workingFavorites = committedFavoriteIDs.filter { workingCatalog.entry(for: $0) != nil }
|
||||
try fileStore.save(
|
||||
CatalogDocument(catalog: workingCatalog, subscriptions: workingSubscriptions))
|
||||
CatalogDocument(
|
||||
catalog: workingCatalog, subscriptions: workingSubscriptions,
|
||||
favoriteIDs: workingFavorites))
|
||||
catalogState.publish(workingCatalog)
|
||||
committedSubscriptions = workingSubscriptions
|
||||
committedFavoriteIDs = workingFavorites
|
||||
scheduleRuntimeSync(
|
||||
CommittedCatalogSnapshot(catalog: workingCatalog, subscriptions: workingSubscriptions))
|
||||
return result
|
||||
}
|
||||
|
||||
/// 收藏只改变用户选择,不调度运行时收敛,也不修改目录节点时间戳。
|
||||
func commitFavorites(_ favoriteIDs: [NodeID]) throws {
|
||||
guard favoriteIDs != committedFavoriteIDs else { return }
|
||||
try fileStore.save(
|
||||
CatalogDocument(
|
||||
catalog: committedCatalog, subscriptions: committedSubscriptions,
|
||||
favoriteIDs: favoriteIDs))
|
||||
committedFavoriteIDs = favoriteIDs
|
||||
}
|
||||
|
||||
/// Legacy 导入等独立路径直接落盘后对齐已提交状态;不触发运行时收敛
|
||||
/// (导入的运行时边界由独立路径自行驱动,不经普通提交管线)。
|
||||
func reloadCommittedStateFromStore() {
|
||||
let document = Self.loadCommitted(from: fileStore)
|
||||
catalogState.publish(document.catalog)
|
||||
committedSubscriptions = document.subscriptions
|
||||
committedFavoriteIDs = document.favoriteIDs
|
||||
}
|
||||
|
||||
/// 异步收敛调度:无活动目标不调用运行时;同步开始前与结束后都以代次
|
||||
|
||||
@@ -14,7 +14,9 @@ extension CatalogWorkflow {
|
||||
-> ImportRunOutcome
|
||||
{
|
||||
var outcomes: [ImportSourceOutcome] = []
|
||||
var newSelection: NodeID?
|
||||
for source in sources {
|
||||
let previousIDs = Set(importChildren(of: parent).map(\.id))
|
||||
let result: ImportSourceResult
|
||||
switch source {
|
||||
case .clipboardText(let text):
|
||||
@@ -25,8 +27,16 @@ extension CatalogWorkflow {
|
||||
name: name, data: data, into: parent, credentials: dependencies.credentials)
|
||||
}
|
||||
outcomes.append(ImportSourceOutcome(source: source, result: result))
|
||||
if let created = importChildren(of: parent).last(where: { !previousIDs.contains($0.id) }) {
|
||||
newSelection = created.id
|
||||
}
|
||||
}
|
||||
return ImportRunOutcome(sources: outcomes)
|
||||
return ImportRunOutcome(sources: outcomes, newNodeSelectionCandidate: newSelection)
|
||||
}
|
||||
|
||||
private func importChildren(of parent: NodeID?) -> [CatalogTreeNode] {
|
||||
if let parent { return tree.node(withID: parent)?.childNodes ?? [] }
|
||||
return tree.roots
|
||||
}
|
||||
|
||||
/// 单文件分派:内容优先嗅探。可解码位图(ImageIO 事实)走二维码;内容为
|
||||
|
||||
@@ -19,6 +19,7 @@ import Foundation
|
||||
final class CatalogWorkflow: ObservableObject {
|
||||
/// 目录树 projection(侧栏、级联、移动目的地、删除确认共用)。
|
||||
@Published private(set) var tree: CatalogTreeSnapshot
|
||||
@Published private(set) var favoriteIDs: [NodeID]
|
||||
/// 订阅卡片 projection(非敏感)。
|
||||
@Published private(set) var subscriptions: [SubscriptionSummary] = []
|
||||
/// 正在刷新的订阅身份(并发守卫的只读观察面)。
|
||||
@@ -53,6 +54,7 @@ final class CatalogWorkflow: ObservableObject {
|
||||
init(dependencies: CatalogWorkflowDependencies) {
|
||||
self.dependencies = dependencies
|
||||
let coordinator = dependencies.coordinator
|
||||
favoriteIDs = coordinator.committedFavoriteIDs
|
||||
tree = .build(
|
||||
from: coordinator.committedCatalog,
|
||||
credentials: dependencies.credentials, plugins: dependencies.plugins)
|
||||
@@ -90,6 +92,37 @@ final class CatalogWorkflow: ObservableObject {
|
||||
dependencies.coordinator.committedCatalog.entry(for: id)?.displayName ?? ""
|
||||
}
|
||||
|
||||
/// 有序平面收藏;配置组只返回自身,详情仍使用同一个节点身份。
|
||||
var favorites: [CatalogTreeNode] {
|
||||
favoriteIDs.compactMap { tree.node(withID: $0) }
|
||||
}
|
||||
|
||||
func isFavorite(_ id: NodeID) -> Bool { favoriteIDs.contains(id) }
|
||||
|
||||
func setFavorite(_ id: NodeID, isFavorite: Bool) throws {
|
||||
guard tree.containsNode(id) else { throw CatalogError.nodeNotFound(id) }
|
||||
var updated = favoriteIDs
|
||||
if isFavorite {
|
||||
if !updated.contains(id) { updated.append(id) }
|
||||
} else {
|
||||
updated.removeAll { $0 == id }
|
||||
}
|
||||
try dependencies.coordinator.commitFavorites(updated)
|
||||
favoriteIDs = dependencies.coordinator.committedFavoriteIDs
|
||||
}
|
||||
|
||||
/// 将收藏移至指定收藏前;nil 表示末尾,不接受未收藏的节点。
|
||||
func moveFavorite(_ id: NodeID, before target: NodeID?) throws {
|
||||
guard favoriteIDs.contains(id) else { throw CatalogError.nodeNotFound(id) }
|
||||
if let target, !favoriteIDs.contains(target) { throw CatalogError.nodeNotFound(target) }
|
||||
guard id != target else { return }
|
||||
var updated = favoriteIDs.filter { $0 != id }
|
||||
let index = target.flatMap { updated.firstIndex(of: $0) } ?? updated.endIndex
|
||||
updated.insert(id, at: index)
|
||||
try dependencies.coordinator.commitFavorites(updated)
|
||||
favoriteIDs = dependencies.coordinator.committedFavoriteIDs
|
||||
}
|
||||
|
||||
/// 服务器叶子的已知阻塞原因(typed;编辑面「激活状态」区)。
|
||||
func serverInvalidReasons(for id: NodeID) -> [LeafInvalidationReason] {
|
||||
tree.node(withID: id)?.invalidReasons ?? []
|
||||
@@ -361,6 +394,7 @@ final class CatalogWorkflow: ObservableObject {
|
||||
/// 提交成功后的 projection 重建(树 + 订阅卡片)。
|
||||
func republishCommittedState() {
|
||||
let coordinator = dependencies.coordinator
|
||||
favoriteIDs = coordinator.committedFavoriteIDs
|
||||
tree = .build(
|
||||
from: coordinator.committedCatalog,
|
||||
credentials: dependencies.credentials, plugins: dependencies.plugins)
|
||||
|
||||
@@ -18,6 +18,8 @@ enum ImportSource: Equatable, Sendable {
|
||||
/// 主 actor,无跨域传递)。
|
||||
struct ImportRunOutcome {
|
||||
let sources: [ImportSourceOutcome]
|
||||
/// 最后一个成功来源创建的节点;供收藏页导入后进入本地列表。
|
||||
var newNodeSelectionCandidate: NodeID?
|
||||
|
||||
/// 成功来源中的落点/新建分组(最后一个),供导入后选中;nil 表示无可
|
||||
/// 选中目标(全部失败,或只导入了目录根层的文本来源)。
|
||||
|
||||
@@ -98,13 +98,18 @@ struct CatalogTreeSnapshot: Equatable {
|
||||
/// 活动目标的显示名路径(根 → 节点," / " 连接);目标不在树中为 nil。
|
||||
/// 代理控制窄缝经此取安全路径摘要(issue #47),树结构不出目录 module。
|
||||
func pathSummary(for id: NodeID) -> String? {
|
||||
pathComponents(for: id)?.joined(separator: " / ")
|
||||
}
|
||||
|
||||
/// 节点的名称路径;分隔符与来源标签由呈现层决定。
|
||||
func pathComponents(for id: NodeID) -> [String]? {
|
||||
guard var node = self.node(withID: id) else { return nil }
|
||||
var names = [node.name]
|
||||
while let parentID = node.parentID, let parent = self.node(withID: parentID) {
|
||||
names.insert(parent.name, at: 0)
|
||||
node = parent
|
||||
}
|
||||
return names.joined(separator: " / ")
|
||||
return names
|
||||
}
|
||||
|
||||
/// 全树已知无效服务器总数(诊断计数)。
|
||||
|
||||
@@ -1188,6 +1188,28 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"收藏": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Favorites"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"路径": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Path"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "1.0"
|
||||
|
||||
@@ -319,6 +319,28 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"收藏": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Favorite"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"取消收藏": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Unfavorite"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"version": "1.0"
|
||||
|
||||
@@ -15,6 +15,17 @@ struct CatalogNodeDetailView: View {
|
||||
var body: some View {
|
||||
if let node {
|
||||
NodeDetailView(detail: presentation(for: node)) {
|
||||
Button(
|
||||
workflow.isFavorite(nodeID)
|
||||
? String(localized: "取消收藏", table: "ServerDetails")
|
||||
: String(localized: "收藏", table: "ServerDetails")
|
||||
) {
|
||||
do {
|
||||
try workflow.setFavorite(nodeID, isFavorite: !workflow.isFavorite(nodeID))
|
||||
} catch {
|
||||
errors.present(error)
|
||||
}
|
||||
}
|
||||
Button(
|
||||
activation.pendingTargetID == nodeID
|
||||
? String(localized: "激活中…", table: "ServerDetails")
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
/// 浏览位置与节点来源分别表达;收藏可以同时包含两种来源。
|
||||
enum ServerListSection: Hashable {
|
||||
case favorites
|
||||
case manual
|
||||
case subscription
|
||||
|
||||
init(source: NodeSource) {
|
||||
self = source == .manual ? .manual : .subscription
|
||||
}
|
||||
|
||||
var source: NodeSource? {
|
||||
switch self {
|
||||
case .favorites: nil
|
||||
case .manual: .manual
|
||||
case .subscription: .subscription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 平面收藏表只重排收藏;详情及节点命令仍使用原目录身份。
|
||||
struct FavoriteServersTable<MenuContent: View>: View {
|
||||
@ObservedObject var workflow: CatalogWorkflow
|
||||
let activeTargetID: NodeID?
|
||||
@Binding var selection: NodeID?
|
||||
let errors: ErrorAlertPresenter
|
||||
@ViewBuilder let contextMenu: (Set<NodeID>) -> MenuContent
|
||||
@State private var dropState = ServerTableDropState()
|
||||
@FocusState private var isTableFocused: Bool
|
||||
|
||||
var body: some View {
|
||||
let rows = workflow.favorites
|
||||
Table(of: CatalogTreeNode.self, selection: $selection) {
|
||||
TableColumn("名称") { node in
|
||||
ServerTableNameCell(node: node, activeTargetID: activeTargetID)
|
||||
}
|
||||
.width(min: 140, ideal: 200)
|
||||
TableColumn("路径") { node in
|
||||
let path = path(for: node)
|
||||
Text(path)
|
||||
.lineLimit(1)
|
||||
.truncationMode(.tail)
|
||||
.help(path)
|
||||
}
|
||||
.width(min: 160, ideal: 300)
|
||||
} rows: {
|
||||
ForEach(rows) { node in
|
||||
TableRow(node)
|
||||
.itemProvider {
|
||||
dropState.provider(for: node.id, payload: node.id.rawValue, type: .plainText)
|
||||
}
|
||||
}
|
||||
.onInsert(of: [.plainText]) { index, providers in
|
||||
insert(providers, at: index, in: rows.map(\.id))
|
||||
}
|
||||
}
|
||||
.focused($isTableFocused)
|
||||
.simultaneousGesture(TapGesture().onEnded { isTableFocused = true })
|
||||
.contextMenu(forSelectionType: NodeID.self, menu: contextMenu)
|
||||
.onKeyPress(.escape) {
|
||||
guard selection != nil else { return .ignored }
|
||||
selection = nil
|
||||
return .handled
|
||||
}
|
||||
.overlay {
|
||||
if rows.isEmpty {
|
||||
ContentUnavailableView("收藏", systemImage: "star")
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private func path(for node: CatalogTreeNode) -> String {
|
||||
let source = node.source == .manual ? String(localized: "本地") : String(localized: "订阅")
|
||||
return ([source] + (workflow.tree.pathComponents(for: node.id) ?? [node.name]))
|
||||
.joined(separator: "/")
|
||||
}
|
||||
|
||||
/// 原生 Table 的行间插入回调;仅接受本表发起的单节点拖动。
|
||||
private func insert(_ providers: [NSItemProvider], at index: Int, in ids: [NodeID]) {
|
||||
guard providers.count == 1, let provider = providers.first,
|
||||
let id = dropState.draggedID, ids.contains(id), (0...ids.count).contains(index)
|
||||
else { return }
|
||||
let target = ids.indices.contains(index) ? ids[index] : nil
|
||||
dropState.finishDrop()
|
||||
let typeIdentifier = UTType.plainText.identifier
|
||||
provider.loadDataRepresentation(forTypeIdentifier: typeIdentifier) { data, _ in
|
||||
guard let data, String(data: data, encoding: .utf8) == id.rawValue else { return }
|
||||
Task { @MainActor in
|
||||
do {
|
||||
try workflow.moveFavorite(id, before: target)
|
||||
} catch {
|
||||
errors.present(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ struct ImportServersSheet: View {
|
||||
let workflow: CatalogWorkflow
|
||||
let clipboard: any TextClipboard
|
||||
@Binding var selection: NodeID?
|
||||
var selectNewNodes = false
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
@State private var resultRows: [ImportResultRow] = []
|
||||
@@ -159,7 +160,9 @@ struct ImportServersSheet: View {
|
||||
ImportOutcomePresentation.row(
|
||||
for: sourceOutcome, targetName: targetDisplayName(for: sourceOutcome.result))
|
||||
})
|
||||
if let candidate = outcome.selectionCandidate {
|
||||
if let candidate = selectNewNodes
|
||||
? outcome.newNodeSelectionCandidate : outcome.selectionCandidate
|
||||
{
|
||||
selection = candidate
|
||||
}
|
||||
isImporting = false
|
||||
|
||||
@@ -12,18 +12,24 @@ final class ServerTableDropState {
|
||||
weak var reader: ServerTableDropReaderView?
|
||||
private(set) var draggedID: NodeID?
|
||||
|
||||
func provider(for id: NodeID, payload: String) -> NSItemProvider {
|
||||
func provider(for id: NodeID, payload: String, type: UTType = .serverCatalogNode)
|
||||
-> NSItemProvider
|
||||
{
|
||||
draggedID = id
|
||||
// 原生 Table 行间插入使用系统字符串表示;接收方仍校验本表拖动的节点身份。
|
||||
if type == .plainText { return NSItemProvider(object: payload as NSString) }
|
||||
let provider = NSItemProvider()
|
||||
let data = Data(payload.utf8)
|
||||
provider.registerDataRepresentation(
|
||||
forTypeIdentifier: UTType.serverCatalogNode.identifier, visibility: .ownProcess
|
||||
forTypeIdentifier: type.identifier, visibility: .ownProcess
|
||||
) { completion in
|
||||
completion(data, nil)
|
||||
return nil
|
||||
}
|
||||
return provider
|
||||
}
|
||||
|
||||
func finishDrop() { draggedID = nil }
|
||||
}
|
||||
|
||||
/// SwiftUI TableRowContent 的 dropDestination 不能返回拒绝结果。
|
||||
|
||||
@@ -12,7 +12,7 @@ struct ServersView: View {
|
||||
/// ServerTableNameCell/ServerDetailView 的传参先例同法)。
|
||||
let activeTargetID: NodeID?
|
||||
@Binding var selection: NodeID?
|
||||
@Binding var source: NodeSource
|
||||
@Binding var section: ServerListSection
|
||||
@Binding var sortOrder: [ServerTableSort]
|
||||
/// 服务器管理的展开状态跨工作区页面切换保留,不落盘。
|
||||
@ObservedObject var expansion: CatalogExpansionState
|
||||
@@ -40,8 +40,17 @@ struct ServersView: View {
|
||||
HSplitView {
|
||||
sourceSidebar
|
||||
.frame(minWidth: 120, idealWidth: 150, maxWidth: 200)
|
||||
serverTable
|
||||
.frame(minWidth: 380, idealWidth: 520, maxWidth: .infinity)
|
||||
Group {
|
||||
if section == .favorites {
|
||||
FavoriteServersTable(
|
||||
workflow: workflow, activeTargetID: activeTargetID,
|
||||
selection: $selection, errors: errors, contextMenu: nodeContextMenu)
|
||||
} else {
|
||||
serverTable
|
||||
}
|
||||
}
|
||||
.toolbar { toolbarContent }
|
||||
.frame(minWidth: 380, idealWidth: 520, maxWidth: .infinity)
|
||||
// 分栏身份必须稳定;节点身份只重建内部详情会话,保留用户拖动后的宽度。
|
||||
ZStack(alignment: .topLeading) {
|
||||
serverDetailPane
|
||||
@@ -83,27 +92,39 @@ struct ServersView: View {
|
||||
.onChange(of: selection) {
|
||||
shareContext = nil
|
||||
}
|
||||
.onChange(of: workflow.favoriteIDs) {
|
||||
if section == .favorites, let selection, !workflow.isFavorite(selection) {
|
||||
self.selection = nil
|
||||
}
|
||||
}
|
||||
.onChange(of: workflow.tree) {
|
||||
if let selection, !workflow.tree.containsNode(selection) {
|
||||
self.selection = nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var sourceSidebar: some View {
|
||||
List(
|
||||
selection: Binding<NodeSource?>(
|
||||
get: { source },
|
||||
selection: Binding<ServerListSection?>(
|
||||
get: { section },
|
||||
set: { value in
|
||||
guard let value, value != source else { return }
|
||||
guard let value, value != section else { return }
|
||||
selection = nil
|
||||
source = value
|
||||
section = value
|
||||
})
|
||||
) {
|
||||
Label("本地", systemImage: "internaldrive").tag(NodeSource.manual)
|
||||
Label("订阅", systemImage: "arrow.triangle.2.circlepath").tag(NodeSource.subscription)
|
||||
Label("收藏", systemImage: "star").tag(ServerListSection.favorites)
|
||||
Label("本地", systemImage: "internaldrive").tag(ServerListSection.manual)
|
||||
Label("订阅", systemImage: "arrow.triangle.2.circlepath").tag(ServerListSection.subscription)
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
}
|
||||
|
||||
private var serverTable: some View {
|
||||
let rows = workflow.tree.visibleRows(
|
||||
source: source, sortedBy: sortOrder, collapsed: expansion.collapsedGroupIDs)
|
||||
source: section.source ?? .manual, sortedBy: sortOrder, collapsed: expansion.collapsedGroupIDs
|
||||
)
|
||||
let depths = Dictionary(uniqueKeysWithValues: rows.map { ($0.id, $0.depth) })
|
||||
return Table(
|
||||
of: CatalogTreeNode.self, selection: $selection,
|
||||
@@ -132,6 +153,12 @@ struct ServersView: View {
|
||||
.padding(.leading, CGFloat(depths[node.id] ?? 0) * 14)
|
||||
}
|
||||
.width(min: 160, ideal: 240)
|
||||
TableColumn("收藏") { node in
|
||||
Image(systemName: workflow.isFavorite(node.id) ? "star.fill" : "star")
|
||||
.accessibilityLabel(Text("收藏"))
|
||||
.accessibilityValue(Text(workflow.isFavorite(node.id) ? "收藏" : "—"))
|
||||
}
|
||||
.width(44)
|
||||
TableColumn("创建时间", sortUsing: ServerTableSort(.createdAt)) { node in
|
||||
timestampCell(node.createdAt)
|
||||
}
|
||||
@@ -155,15 +182,7 @@ struct ServersView: View {
|
||||
if !isServerTableFocused { isServerTableFocused = true }
|
||||
}
|
||||
)
|
||||
.contextMenu(forSelectionType: NodeID.self) { ids in
|
||||
if let id = ids.first, let node = workflow.tree.node(withID: id) {
|
||||
ServerNodeContextMenu(
|
||||
node: node, workflow: workflow, activation: activation, errors: errors,
|
||||
onEdit: presentEditServer, onRename: { renameTarget = $0 },
|
||||
onNewGroup: presentNewGroup, onDuplicate: duplicateNode,
|
||||
onDelete: { deleteTarget = $0 }, onExport: exportConfigurationGroup)
|
||||
}
|
||||
}
|
||||
.contextMenu(forSelectionType: NodeID.self, menu: nodeContextMenu)
|
||||
.onKeyPress(.escape) {
|
||||
guard selection != nil else { return .ignored }
|
||||
selection = nil
|
||||
@@ -182,9 +201,20 @@ struct ServersView: View {
|
||||
.onDrop(
|
||||
of: [.serverCatalogNode],
|
||||
delegate: ServerTableDropDelegate(
|
||||
state: dropState, rows: rows, source: source, workflow: workflow, onDrop: handleDrop)
|
||||
state: dropState, rows: rows, source: section.source ?? .manual, workflow: workflow,
|
||||
onDrop: handleDrop)
|
||||
)
|
||||
.toolbar { toolbarContent }
|
||||
}
|
||||
|
||||
@ViewBuilder
|
||||
private func nodeContextMenu(_ ids: Set<NodeID>) -> some View {
|
||||
if let id = ids.first, let node = workflow.tree.node(withID: id) {
|
||||
ServerNodeContextMenu(
|
||||
node: node, workflow: workflow, activation: activation, errors: errors,
|
||||
onEdit: presentEditServer, onRename: { renameTarget = $0 },
|
||||
onNewGroup: presentNewGroup, onDuplicate: duplicateNode,
|
||||
onDelete: { deleteTarget = $0 }, onExport: exportConfigurationGroup)
|
||||
}
|
||||
}
|
||||
|
||||
private func timestampCell(_ date: Date?) -> some View {
|
||||
@@ -267,41 +297,43 @@ extension ServersView {
|
||||
|
||||
@ToolbarContentBuilder
|
||||
private var toolbarContent: some ToolbarContent {
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Menu {
|
||||
Picker(
|
||||
"排序",
|
||||
selection: Binding<ServerTableSort.Field?>(
|
||||
get: { sortOrder.first?.field },
|
||||
set: { field in sortOrder = field.map { [ServerTableSort($0)] } ?? [] })
|
||||
) {
|
||||
Text("无").tag(nil as ServerTableSort.Field?)
|
||||
Text("名称").tag(ServerTableSort.Field.name as ServerTableSort.Field?)
|
||||
Text("创建时间").tag(ServerTableSort.Field.createdAt as ServerTableSort.Field?)
|
||||
Text("修改时间").tag(ServerTableSort.Field.updatedAt as ServerTableSort.Field?)
|
||||
if section != .favorites {
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Menu {
|
||||
Picker(
|
||||
"排序",
|
||||
selection: Binding<ServerTableSort.Field?>(
|
||||
get: { sortOrder.first?.field },
|
||||
set: { field in sortOrder = field.map { [ServerTableSort($0)] } ?? [] })
|
||||
) {
|
||||
Text("无").tag(nil as ServerTableSort.Field?)
|
||||
Text("名称").tag(ServerTableSort.Field.name as ServerTableSort.Field?)
|
||||
Text("创建时间").tag(ServerTableSort.Field.createdAt as ServerTableSort.Field?)
|
||||
Text("修改时间").tag(ServerTableSort.Field.updatedAt as ServerTableSort.Field?)
|
||||
}
|
||||
.pickerStyle(.inline)
|
||||
} label: {
|
||||
Label("排序", systemImage: "arrow.up.arrow.down")
|
||||
}
|
||||
.pickerStyle(.inline)
|
||||
} label: {
|
||||
Label("排序", systemImage: "arrow.up.arrow.down")
|
||||
.labelStyle(.iconOnly)
|
||||
.help("排序")
|
||||
}
|
||||
.labelStyle(.iconOnly)
|
||||
.help("排序")
|
||||
}
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button {
|
||||
presentNewServer(in: workflow.importTargetParent(for: selection))
|
||||
} label: {
|
||||
Label("新建服务器", systemImage: "plus")
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button {
|
||||
presentNewServer(in: workflow.importTargetParent(for: selection))
|
||||
} label: {
|
||||
Label("新建服务器", systemImage: "plus")
|
||||
}
|
||||
.help("新建服务器")
|
||||
}
|
||||
.help("新建服务器")
|
||||
}
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button {
|
||||
presentNewGroup(in: workflow.importTargetParent(for: selection))
|
||||
} label: {
|
||||
Label("新建分组", systemImage: "folder.badge.plus")
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button {
|
||||
presentNewGroup(in: workflow.importTargetParent(for: selection))
|
||||
} label: {
|
||||
Label("新建分组", systemImage: "folder.badge.plus")
|
||||
}
|
||||
.help("新建分组")
|
||||
}
|
||||
.help("新建分组")
|
||||
}
|
||||
ToolbarItem(placement: .primaryAction) {
|
||||
Button {
|
||||
@@ -385,7 +417,7 @@ extension ServersView {
|
||||
}
|
||||
|
||||
private func selectCreatedNode(_ id: NodeID) {
|
||||
source = .manual
|
||||
section = .manual
|
||||
expansion.reveal(id, in: workflow.tree)
|
||||
selection = id
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ struct MainWindowView: View {
|
||||
/// 更新期间发布;外部导航反向同步,route 仍是导航位置的唯一来源。
|
||||
@State private var tabSelection: WorkspaceDestination = WorkspaceRoute.initialDestination
|
||||
@State private var selection: NodeID?
|
||||
@State private var serverSource: NodeSource = .manual
|
||||
@State private var serverSection: ServerListSection = .manual
|
||||
@State private var serverSortOrder: [ServerTableSort] = []
|
||||
/// 全局导入面板由窗口壳持有。
|
||||
@State private var presentedWorkspaceSheet: WorkspaceSheet?
|
||||
@@ -67,7 +67,8 @@ struct MainWindowView: View {
|
||||
}
|
||||
.onChange(of: selection) {
|
||||
guard let selection, let node = workflow.tree.node(withID: selection) else { return }
|
||||
serverSource = node.source
|
||||
guard serverSection != .favorites else { return }
|
||||
serverSection = ServerListSection(source: node.source)
|
||||
expansion.reveal(selection, in: workflow.tree)
|
||||
}
|
||||
.navigationTitle(route.destination.label)
|
||||
@@ -76,7 +77,14 @@ struct MainWindowView: View {
|
||||
switch sheet {
|
||||
case .importServers:
|
||||
ImportServersSheet(
|
||||
workflow: workflow, clipboard: clipboard, selection: $selection)
|
||||
workflow: workflow, clipboard: clipboard,
|
||||
selection: Binding(
|
||||
get: { selection },
|
||||
set: { id in
|
||||
if id != nil { serverSection = .manual }
|
||||
selection = id
|
||||
}),
|
||||
selectNewNodes: serverSection == .favorites)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,7 +121,7 @@ struct MainWindowView: View {
|
||||
activation: activationFeedback,
|
||||
activeTargetID: control.snapshot.activeTarget?.id,
|
||||
selection: $selection,
|
||||
source: $serverSource,
|
||||
section: $serverSection,
|
||||
sortOrder: $serverSortOrder,
|
||||
expansion: expansion,
|
||||
clipboard: clipboard,
|
||||
|
||||
@@ -14,9 +14,9 @@ struct CatalogFileStore {
|
||||
|
||||
/// v2 起携带订阅记录;v1(无订阅字段)仍可读取。v3 移除节点级 enabled
|
||||
/// 语义;v4 把订阅失败字符串替换为 typed facts;v5 增加节点创建/修改时间
|
||||
/// (v1–v4 读取为 nil 未知,不回填)。读取兼容 v1–v5,写入始终使用 v5。
|
||||
private static let supportedVersions: Set<Int> = [1, 2, 3, 4, 5]
|
||||
private static let currentVersion = 5
|
||||
/// (v1–v4 读取为 nil 未知,不回填);v6 增加有序收藏。读取兼容 v1–v6。
|
||||
private static let supportedVersions: Set<Int> = [1, 2, 3, 4, 5, 6]
|
||||
private static let currentVersion = 6
|
||||
private static let jsonEncoder: JSONEncoder = {
|
||||
let encoder = JSONEncoder()
|
||||
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
|
||||
@@ -46,11 +46,12 @@ struct CatalogFileStore {
|
||||
|
||||
/// 整体重写并原子替换;失败时保留原文件。目录按 D5 基线强制 0700(含自愈)。
|
||||
func save(_ document: CatalogDocument) throws {
|
||||
try validateFavorites(document.favoriteIDs, in: document.catalog)
|
||||
let payload = CatalogFilePayload(
|
||||
version: Self.currentVersion,
|
||||
rootChildren: document.catalog.rootChildren,
|
||||
entries: document.catalog.entries.values.sorted { $0.id.rawValue < $1.id.rawValue },
|
||||
subscriptions: document.subscriptions)
|
||||
subscriptions: document.subscriptions, favoriteIDs: document.favoriteIDs)
|
||||
let data: Data
|
||||
do {
|
||||
data = try Self.jsonEncoder.encode(payload)
|
||||
@@ -105,17 +106,31 @@ struct CatalogFileStore {
|
||||
detail: "subscription group missing \(record.groupID.rawValue)")
|
||||
}
|
||||
}
|
||||
return CatalogDocument(catalog: catalog, subscriptions: subscriptions)
|
||||
let favoriteIDs = payload.favoriteIDs ?? []
|
||||
try validateFavorites(favoriteIDs, in: catalog)
|
||||
return CatalogDocument(
|
||||
catalog: catalog, subscriptions: subscriptions, favoriteIDs: favoriteIDs)
|
||||
}
|
||||
|
||||
private func validateFavorites(_ ids: [NodeID], in catalog: ConfigurationCatalog) throws {
|
||||
var seen = Set<NodeID>()
|
||||
for id in ids {
|
||||
guard seen.insert(id).inserted, catalog.entry(for: id) != nil else {
|
||||
throw PersistenceError.corrupt(detail: "duplicate or missing favorite node \(id.rawValue)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// 落盘文档形态:版本号 + 根子序 + 全量节点表(顺序语义在根序与分组显子序中)
|
||||
/// + 订阅记录(v2 起携带;v1 缺省为空)。v3 节点条目不再写出 `enabled`;
|
||||
/// v4 的失败状态只写 typed facts,不再写旧 `reason` 字段;v5 节点条目携带
|
||||
/// 创建/修改时间,未知(历史文档迁移节点)省略键。
|
||||
/// 创建/修改时间,未知(历史文档迁移节点)省略键;v6 保存独立的收藏序列。
|
||||
private struct CatalogFilePayload: Codable {
|
||||
var version: Int
|
||||
var rootChildren: [NodeID]
|
||||
var entries: [CatalogEntry]
|
||||
var subscriptions: [SubscriptionRecord]?
|
||||
var favoriteIDs: [NodeID]?
|
||||
}
|
||||
|
||||
@@ -198,7 +198,9 @@ struct LegacyImportPlanner {
|
||||
regeneratedIdentityCount: serverImport.regeneratedIdentityCount)
|
||||
return LegacyImportPlan(
|
||||
groupID: groupID,
|
||||
document: CatalogDocument(catalog: catalog, subscriptions: existingDocument.subscriptions),
|
||||
document: CatalogDocument(
|
||||
catalog: catalog, subscriptions: existingDocument.subscriptions,
|
||||
favoriteIDs: existingDocument.favoriteIDs),
|
||||
credentials: serverImport.credentials,
|
||||
report: report)
|
||||
}
|
||||
|
||||
@@ -76,18 +76,21 @@ enum SubscriptionRefreshStatus: Codable, Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
/// 配置目录持久化文档的完整形态:结构树 + 订阅源记录。两者一次原子落盘,
|
||||
/// 配置目录持久化文档:结构树、订阅源记录与有序收藏一次原子落盘,
|
||||
/// 保证「订阅记录 ↔ 固定分组子树」跨文档一致。
|
||||
struct CatalogDocument: Equatable, Sendable {
|
||||
var catalog: ConfigurationCatalog
|
||||
var subscriptions: [SubscriptionRecord]
|
||||
var favoriteIDs: [NodeID]
|
||||
|
||||
init(
|
||||
catalog: ConfigurationCatalog = ConfigurationCatalog(),
|
||||
subscriptions: [SubscriptionRecord] = []
|
||||
subscriptions: [SubscriptionRecord] = [],
|
||||
favoriteIDs: [NodeID] = []
|
||||
) {
|
||||
self.catalog = catalog
|
||||
self.subscriptions = subscriptions
|
||||
self.favoriteIDs = favoriteIDs
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -173,7 +173,7 @@ final class CatalogFileStoreTests: XCTestCase {
|
||||
|
||||
try store.save(loaded)
|
||||
let raw = try String(contentsOf: store.fileURL, encoding: .utf8)
|
||||
XCTAssertTrue(raw.contains("\"version\" : 5"))
|
||||
XCTAssertTrue(raw.contains("\"version\" : 6"))
|
||||
XCTAssertFalse(raw.contains("\"reason\""))
|
||||
XCTAssertFalse(raw.contains("provider.example"))
|
||||
}
|
||||
@@ -203,7 +203,7 @@ final class CatalogFileStoreTests: XCTestCase {
|
||||
try store.save(loaded)
|
||||
|
||||
let raw = try String(contentsOf: store.fileURL, encoding: .utf8)
|
||||
XCTAssertTrue(raw.contains("\"version\" : 5"))
|
||||
XCTAssertTrue(raw.contains("\"version\" : 6"))
|
||||
XCTAssertFalse(raw.contains("\"enabled\""), "v3 起不再写出节点级 enabled")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
|
||||
@testable import ShadowsocksX_NG2
|
||||
|
||||
@MainActor
|
||||
struct CatalogWorkflowFavoritesTests {
|
||||
@Test(arguments: [false, true], [false, true])
|
||||
func textImportSelectsNewNodeIncludingPartialSuccess(partial: Bool, intoGroup: Bool) async throws
|
||||
{
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let parent =
|
||||
intoGroup ? try await fixture.workflow.createGroup(named: "Existing", into: nil) : nil
|
||||
let uri = "ss://YWVzLTI1Ni1nY206cHc@203.0.113.7:8388#New"
|
||||
let outcome = await fixture.workflow.importServers(
|
||||
from: [.clipboardText(partial ? uri + "\ninvalid" : uri)], into: parent)
|
||||
let children =
|
||||
parent.flatMap { fixture.workflow.tree.node(withID: $0)?.childNodes }
|
||||
?? fixture.workflow.tree.roots
|
||||
let added = try #require(children.first)
|
||||
#expect(outcome.newNodeSelectionCandidate == added.id)
|
||||
#expect(fixture.workflow.favoriteIDs.isEmpty)
|
||||
}
|
||||
|
||||
@Test func legacyImportPreservesExistingFavorites() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let group = try await fixture.workflow.createGroup(named: "Existing", into: nil)
|
||||
try fixture.workflow.setFavorite(group, isFavorite: true)
|
||||
let snapshot = try LegacySnapshot(propertyList: [
|
||||
"ServerProfiles": [
|
||||
[
|
||||
"ServerHost": "203.0.113.8", "ServerPort": 8388,
|
||||
"Method": "aes-256-gcm", "Password": "fixture", "Remark": "Imported",
|
||||
]
|
||||
]
|
||||
])
|
||||
let workflow = makeCatalogWorkflow(
|
||||
coordinator: CatalogCommitCoordinator(fileStore: fixture.store, runtime: fixture.runtime),
|
||||
credentials: fixture.credentials,
|
||||
legacyImportService: LegacyImportService(
|
||||
source: FixedLegacySnapshotProvider(snapshot: snapshot), catalogStore: fixture.store,
|
||||
credentials: fixture.credentials, marker: InMemoryLegacyImportMarker()))
|
||||
let outcome = try await workflow.importLegacy()
|
||||
#expect(outcome.report.importedServerCount == 1)
|
||||
#expect(workflow.favoriteIDs == [group])
|
||||
#expect(fixture.reloaded().favoriteIDs == [group])
|
||||
}
|
||||
|
||||
@Test(arguments: [1, 2, 3, 4, 5])
|
||||
func oldDocumentsStartWithoutFavorites(version: Int) throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let json = "{\"version\":\(version),\"rootChildren\":[],\"entries\":[]}"
|
||||
try Data(json.utf8).write(to: fixture.store.fileURL)
|
||||
#expect(try fixture.store.load().favoriteIDs.isEmpty)
|
||||
#expect(fixture.reloaded().favorites.isEmpty)
|
||||
}
|
||||
|
||||
@Test func failedSavesKeepTheCommittedOrder() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let first = try await fixture.workflow.createGroup(named: "First", into: nil)
|
||||
let second = try await fixture.workflow.createGroup(named: "Second", into: nil)
|
||||
try fixture.workflow.setFavorite(first, isFavorite: true)
|
||||
try fixture.workflow.setFavorite(second, isFavorite: true)
|
||||
let originalData = try Data(contentsOf: fixture.store.fileURL)
|
||||
let gate = fixture.store.fileURL.deletingLastPathComponent()
|
||||
let backup = fixture.directory.appendingPathComponent("backup")
|
||||
try FileManager.default.moveItem(at: gate, to: backup)
|
||||
try Data().write(to: gate)
|
||||
|
||||
#expect(throws: (any Error).self) {
|
||||
try fixture.workflow.moveFavorite(second, before: first)
|
||||
}
|
||||
#expect(throws: (any Error).self) {
|
||||
try fixture.workflow.setFavorite(first, isFavorite: false)
|
||||
}
|
||||
#expect(fixture.workflow.favoriteIDs == [first, second])
|
||||
try FileManager.default.removeItem(at: gate)
|
||||
try FileManager.default.moveItem(at: backup, to: gate)
|
||||
#expect(try Data(contentsOf: fixture.store.fileURL) == originalData)
|
||||
#expect(fixture.reloaded().favoriteIDs == [first, second])
|
||||
}
|
||||
|
||||
@Test func invalidReorderTargetsLeaveFavoritesUnchanged() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let group = try await fixture.workflow.createGroup(named: "Group", into: nil)
|
||||
try fixture.workflow.setFavorite(group, isFavorite: true)
|
||||
let missing = NodeID(rawValue: "missing")
|
||||
#expect(throws: CatalogError.nodeNotFound(missing)) {
|
||||
try fixture.workflow.moveFavorite(group, before: missing)
|
||||
}
|
||||
#expect(throws: CatalogError.nodeNotFound(missing)) {
|
||||
try fixture.workflow.setFavorite(missing, isFavorite: true)
|
||||
}
|
||||
try fixture.workflow.moveFavorite(group, before: group)
|
||||
#expect(fixture.reloaded().favoriteIDs == [group])
|
||||
}
|
||||
|
||||
@Test func subscriptionRefreshPreservesSurvivorsAndNeverRestoresRemovedFavorites() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let summary = try await fixture.workflow.createSubscription(
|
||||
urlString: "https://example.com/sub.json")
|
||||
let group = try #require(fixture.workflow.tree.node(withID: summary.groupID))
|
||||
let nestedNode = group.childNodes.first { $0.isGroup }
|
||||
let nested = try #require(nestedNode)
|
||||
let server = try #require(nested.childNodes.first)
|
||||
for id in [server.id, summary.groupID, nested.id] {
|
||||
try fixture.workflow.setFavorite(id, isFavorite: true)
|
||||
}
|
||||
|
||||
fixture.fetcher.setBehavior(.success(SubscriptionDocs.treeRenamedAndReordered()))
|
||||
await fixture.workflow.refreshSubscription(summary.id)
|
||||
#expect(fixture.workflow.favoriteIDs == [server.id, summary.groupID, nested.id])
|
||||
|
||||
fixture.fetcher.setBehavior(.success(Data("invalid".utf8)))
|
||||
await fixture.workflow.refreshSubscription(summary.id)
|
||||
#expect(fixture.reloaded().favoriteIDs == [server.id, summary.groupID, nested.id])
|
||||
|
||||
fixture.fetcher.setBehavior(.success(SubscriptionDocs.flat(serverCount: 0)))
|
||||
await fixture.workflow.refreshSubscription(summary.id)
|
||||
#expect(fixture.reloaded().favoriteIDs == [summary.groupID])
|
||||
fixture.fetcher.setBehavior(.success(SubscriptionDocs.tree()))
|
||||
await fixture.workflow.refreshSubscription(summary.id)
|
||||
#expect(fixture.workflow.tree.containsNode(server.id))
|
||||
#expect(fixture.workflow.favoriteIDs == [summary.groupID])
|
||||
|
||||
try fixture.workflow.setFavorite(server.id, isFavorite: true)
|
||||
_ = try await fixture.workflow.removeSubscription(summary.id)
|
||||
#expect(fixture.reloaded().favorites.isEmpty)
|
||||
}
|
||||
|
||||
@Test func importingNewNodesDoesNotInheritFavorites() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let uri = "ss://YWVzLTI1Ni1nY206cHc@203.0.113.7:8388#Same"
|
||||
_ = await fixture.workflow.importServers(from: [.clipboardText(uri)], into: nil)
|
||||
let first = try #require(fixture.workflow.tree.roots.first)
|
||||
try fixture.workflow.setFavorite(first.id, isFavorite: true)
|
||||
_ = await fixture.workflow.importServers(from: [.clipboardText(uri)], into: nil)
|
||||
#expect(fixture.workflow.tree.roots.count == 2)
|
||||
#expect(fixture.workflow.favoriteIDs == [first.id])
|
||||
}
|
||||
|
||||
@Test(arguments: [["group", "group"], ["missing"]])
|
||||
func inconsistentFavoritesCannotBeLoaded(ids: [String]) throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
var catalog = ConfigurationCatalog()
|
||||
try catalog.addGroup("Group", id: NodeID(rawValue: "group"))
|
||||
try fixture.store.save(CatalogDocument(catalog: catalog))
|
||||
let raw = try JSONSerialization.jsonObject(with: Data(contentsOf: fixture.store.fileURL))
|
||||
var payload = try #require(raw as? [String: Any])
|
||||
payload["favoriteIDs"] = ids
|
||||
try JSONSerialization.data(withJSONObject: payload).write(to: fixture.store.fileURL)
|
||||
|
||||
#expect(throws: CatalogFileStore.PersistenceError.self) { try fixture.store.load() }
|
||||
}
|
||||
|
||||
@Test func directoryEditsPreserveFavoritesAndRemovalCleansDescendants() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let parent = try await fixture.workflow.createGroup(named: "Parent", into: nil)
|
||||
let child = try await fixture.workflow.createGroup(named: "Child", into: parent)
|
||||
let other = try await fixture.workflow.createGroup(named: "Other", into: nil)
|
||||
for id in [child, parent, other] {
|
||||
try fixture.workflow.setFavorite(id, isFavorite: true)
|
||||
}
|
||||
try await fixture.workflow.renameGroup(child, to: "Renamed")
|
||||
try await fixture.workflow.move(parent, to: other)
|
||||
let copy = try await fixture.workflow.duplicate(parent, nameSuffix: "Copy")
|
||||
#expect(fixture.workflow.favorites.map(\.id) == [child, parent, other])
|
||||
#expect(fixture.workflow.favorites.first?.name == "Renamed")
|
||||
#expect(!fixture.workflow.isFavorite(copy))
|
||||
|
||||
_ = try await fixture.workflow.remove(parent)
|
||||
#expect(fixture.workflow.favoriteIDs == [other])
|
||||
#expect(fixture.reloaded().favoriteIDs == [other])
|
||||
}
|
||||
|
||||
@Test func reorderingAndRefavoritingChangeOnlyFavorites() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let first = try await fixture.workflow.createGroup(named: "First", into: nil)
|
||||
let second = try await fixture.workflow.createGroup(named: "Second", into: nil)
|
||||
let third = try await fixture.workflow.createGroup(named: "Third", into: nil)
|
||||
let originalTree = fixture.workflow.tree
|
||||
fixture.runtime.hasActiveTarget = true
|
||||
for id in [first, second, third] {
|
||||
try fixture.workflow.setFavorite(id, isFavorite: true)
|
||||
}
|
||||
|
||||
try fixture.workflow.moveFavorite(third, before: first)
|
||||
#expect(fixture.workflow.favorites.map(\.id) == [third, first, second])
|
||||
try fixture.workflow.moveFavorite(third, before: nil)
|
||||
#expect(fixture.workflow.favorites.map(\.id) == [first, second, third])
|
||||
try fixture.workflow.setFavorite(second, isFavorite: false)
|
||||
try fixture.workflow.setFavorite(second, isFavorite: true)
|
||||
#expect(fixture.reloaded().favorites.map(\.id) == [first, third, second])
|
||||
#expect(fixture.workflow.tree == originalTree)
|
||||
#expect(fixture.workflow.runtimeSync == .idle)
|
||||
await Task.yield()
|
||||
#expect(fixture.runtime.convergeCount == 0)
|
||||
}
|
||||
|
||||
@Test func favoritesAreUniqueOrderedAndRestored() async throws {
|
||||
let fixture = try FavoritesFixture()
|
||||
defer { fixture.cleanUp() }
|
||||
let first = try await fixture.workflow.createGroup(named: "First", into: nil)
|
||||
let second = try await fixture.workflow.createGroup(named: "Second", into: first)
|
||||
|
||||
try fixture.workflow.setFavorite(first, isFavorite: true)
|
||||
try fixture.workflow.setFavorite(second, isFavorite: true)
|
||||
try fixture.workflow.setFavorite(first, isFavorite: true)
|
||||
|
||||
#expect(fixture.workflow.favorites.map(\.id) == [first, second])
|
||||
#expect(fixture.reloaded().favorites.map(\.id) == [first, second])
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private struct FavoritesFixture {
|
||||
let directory: URL
|
||||
let store: CatalogFileStore
|
||||
let runtime = FakeCatalogRuntime()
|
||||
let credentials = InMemoryCredentialStore()
|
||||
let fetcher = FakeSubscriptionFetcher(behavior: .success(SubscriptionDocs.tree()))
|
||||
let workflow: CatalogWorkflow
|
||||
|
||||
init() throws {
|
||||
directory = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("favorites-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
let gate = directory.appendingPathComponent("gate", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: gate, withIntermediateDirectories: true)
|
||||
store = CatalogFileStore(fileURL: gate.appendingPathComponent("catalog.json"))
|
||||
workflow = makeCatalogWorkflow(
|
||||
coordinator: CatalogCommitCoordinator(fileStore: store, runtime: runtime),
|
||||
credentials: credentials, plugins: NoManagedPluginProvider(), subscriptionFetcher: fetcher)
|
||||
}
|
||||
|
||||
func reloaded() -> CatalogWorkflow {
|
||||
makeCatalogWorkflow(
|
||||
coordinator: CatalogCommitCoordinator(fileStore: store, runtime: runtime),
|
||||
credentials: credentials, plugins: NoManagedPluginProvider(), subscriptionFetcher: fetcher)
|
||||
}
|
||||
|
||||
func cleanUp() { try? FileManager.default.removeItem(at: directory) }
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
# 收藏按节点身份保存独立顺序
|
||||
|
||||
Status: Accepted (2026-10-09)
|
||||
|
||||
收藏是用户对配置目录节点的独立选择,支持手动与订阅来源的服务器配置和配置组。收藏以节点身份组成的去重有序序列保存,不复制节点资料、不展开组的后代、不改变目录位置。收藏顺序独立于目录顺序;新收藏以及取消后重新添加的收藏追加到末尾。改名和移动保留收藏,复制和导入产生的新节点不继承收藏。
|
||||
|
||||
收藏序列与目录、订阅记录保存于同一目录文档,节点删除和失效收藏清理作为一次原子保存。订阅刷新后仍存在的节点保留收藏;消失节点的收藏立即清除,同身份再次出现不恢复收藏。相比单独保存偏好或保留失效引用,该选择省去跨文件一致性和墓碑状态,但不提供远端节点短暂消失后的自动恢复。
|
||||
|
||||
收藏命令集中在现有 `CatalogWorkflow`,持久化成功后发布新状态;失败保持原状态并显示错误。仅改变收藏或收藏顺序不得触发运行状态收敛,也不得更新节点时间戳。目录内容变化仍遵循现有提交与运行状态收敛规则。收藏不是配置组成员变更,不能借用目录移动或目录排序命令表达。
|
||||
@@ -0,0 +1,35 @@
|
||||
# 服务器收藏
|
||||
|
||||
日期:2026-10-09。状态:设计与实施范围已确认,实现与验证见本次提交。
|
||||
|
||||
本文记录本次任务的需求与验收条件,不代表代码当前具备这些能力。领域术语见根目录 `GLOSSARY.md`;持久化决定见 ADR-0032。
|
||||
|
||||
## 列表与入口
|
||||
|
||||
- 入口位于服务器页面内部边栏首位,顺序为「收藏/本地/订阅」。现有初始「本地」选择保持不变。
|
||||
- 收藏列表使用平面 Table,仅有「名称」「路径」两列,无层级展开、列排序或排序工具栏入口。
|
||||
- 名称显示当前节点自身名称;配置组显示组名。名称列沿用节点类型、有效性与活动目标的现有呈现。
|
||||
- 路径使用 `/` 分隔,包含「本地/订阅」来源名称、全部祖先和节点自身名称,例如 `订阅/机场/香港/HK01`。
|
||||
- 名称中的 `/` 原样显示,不转义。改名或移动后路径随目录更新;截断时悬停显示完整路径。
|
||||
- 每个节点最多出现一次;收藏配置组仅增加该组一行,不自动收藏或展示后代。父组与后代可以分别收藏。
|
||||
- 新收藏追加至末尾;取消后重新收藏也追加至末尾。收藏与顺序跨应用重启保留。
|
||||
- 列表拖动只改变收藏顺序,不改变配置目录的位置或顺序。拒绝目录移动语义和外部拖入。
|
||||
|
||||
## 选择与命令
|
||||
|
||||
- 选择收藏行留在收藏列表,右侧复用原节点详情。配置组通过现有「激活」按钮激活。
|
||||
- 详情增加「收藏/取消收藏」按钮;英文为 `Favorite / Unfavorite`。
|
||||
- 「本地/订阅」列表在「名称」与「创建时间」之间增加「收藏」列;该列无排序,使用 `star.fill` 与 `star` 显示状态,仅展示、不响应点击。
|
||||
- 当前收藏取消后,清除选择与详情,不自动选择相邻行;删除或订阅刷新导致选中节点消失时同样清除选择。
|
||||
- 收藏行保留原节点右键菜单与资格限制。收藏列表隐藏「排序」「新建服务器」「新建分组」工具栏项,其余已有节点命令保持现有行为。
|
||||
- 「分享」按当前节点提供;全局「导入」入口保留。导入成功产生节点后切换到「本地」并选中新节点,新节点不自动收藏。现有复制或新建回调同样切换至「本地」并选择新节点。
|
||||
- 失效服务器与空组可以收藏;收藏不改变激活资格。侧栏切换继续清除节点选择。
|
||||
|
||||
## 保存与验收
|
||||
|
||||
- 用节点身份保存收藏顺序,不持久化派生名称、路径或凭据。
|
||||
- 目录文档升级到 v6,兼容读取 v1–v5,历史文档默认为空收藏;写入使用 v6。
|
||||
- 删除节点、移除订阅及订阅刷新消失节点时,同次保存清除失效收藏。刷新失败保留原目录及收藏。
|
||||
- 收藏变化不触发代理运行状态收敛,不改变节点创建或修改时间。保存失败保持此前列表和顺序,并显示错误。
|
||||
- 通过公共命令验证收藏唯一性、追加与重排、保存失败、重启恢复、旧文档兼容、订阅身份延续及消失、递归清理、不继承收藏、无运行状态收敛与时间戳变化。
|
||||
- 用原生应用验证平面 Table、列位置、详情按钮、选择清理、拖动落点、路径悬停和工具栏。自动测试与原生界面证据分别汇报。
|
||||
Reference in New Issue
Block a user