Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions Commandoak/Model/Command.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
20 changes: 16 additions & 4 deletions Commandoak/View/CommandsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -21,6 +21,7 @@ struct CommandsView: View {
Text(cmd.name)
}
}
.onMove(perform: moveItems)
.onDelete(perform: deleteItems)
}
.navigationSplitViewColumnWidth(min: 180, ideal: 200)
Expand All @@ -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])
Expand Down
2 changes: 1 addition & 1 deletion Commandoak/View/Menu/CommandsMenuBarView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down