diff --git a/Commandoak/Model/Command.swift b/Commandoak/Model/Command.swift index e6d58ef..f1f947a 100644 --- a/Commandoak/Model/Command.swift +++ b/Commandoak/Model/Command.swift @@ -8,13 +8,25 @@ import SwiftData @Model final class Command { - var name: String - var icon: String - var execute: String + static let defaultName = "New command" + static let defaultIcon = "🕹️" + static let defaultExecute = "" + static let defaultPosition = 0 - init(name: String = "New command", icon: String = "🕹️", execute: String = "") { + var name: String = defaultName + var icon: String = defaultIcon + var execute: String = defaultExecute + var position: Int = defaultPosition + + init( + name: String = defaultName, + icon: String = defaultIcon, + execute: String = defaultExecute, + position: Int = defaultPosition + ) { self.name = name self.icon = icon self.execute = execute + self.position = position } } diff --git a/Commandoak/View/CommandsView.swift b/Commandoak/View/CommandsView.swift index b366231..0f175d4 100644 --- a/Commandoak/View/CommandsView.swift +++ b/Commandoak/View/CommandsView.swift @@ -8,7 +8,7 @@ import SwiftData struct CommandsView: View { @Environment(\.modelContext) private var modelContext - @Query private var commands: [Command] + @Query(sort: \Command.position) private var commands: [Command] var body: some View { NavigationSplitView { @@ -21,6 +21,7 @@ struct CommandsView: View { Text(cmd.name) } } + .onMove(perform: moveItems) .onDelete(perform: deleteItems) } .navigationSplitViewColumnWidth(min: 180, ideal: 200) @@ -38,12 +39,23 @@ struct CommandsView: View { private func addItem() { withAnimation { - let newItem = Command() - modelContext.insert(newItem) + let newCmd = Command(position: commands.count) + modelContext.insert(newCmd) } } - private func deleteItems(offsets: IndexSet) { + private func moveItems(from source: IndexSet, to destination: Int) { + withAnimation { + var sortedCommands = commands + sortedCommands.move(fromOffsets: source, toOffset: destination) + + for (index, cmd) in sortedCommands.enumerated() { + cmd.position = index + } + } + } + + private func deleteItems(at offsets: IndexSet) { withAnimation { for index in offsets { modelContext.delete(commands[index]) diff --git a/Commandoak/View/Menu/CommandsMenuBarView.swift b/Commandoak/View/Menu/CommandsMenuBarView.swift index f72a6fc..01c6aff 100644 --- a/Commandoak/View/Menu/CommandsMenuBarView.swift +++ b/Commandoak/View/Menu/CommandsMenuBarView.swift @@ -9,7 +9,7 @@ import SwiftData struct CommandsMenuBarView: View { @Environment(\.openWindow) private var openWindow - @Query private var commands: [Command] + @Query(sort: \Command.position) private var commands: [Command] var body: some View { ForEach(Array(commands.enumerated()), id: \.offset) { index, cmd in