This commit is contained in:
zeus
2025-01-22 16:22:33 +08:00
parent 09b9cec8ec
commit 738c373a77
2534 changed files with 0 additions and 486292 deletions
@@ -1,154 +0,0 @@
#if os(iOS) || os(macOS)
import Foundation
import Library
import SwiftUI
@MainActor
public struct EditProfileContentView: View {
public struct Context: Codable, Hashable {
public let profileID: Int64
public let readOnly: Bool
}
private let profileID: Int64?
private let readOnly: Bool
public init(_ context: Context?) {
profileID = context?.profileID
readOnly = context?.readOnly == true
}
@Environment(\.dismiss) private var dismiss
@State private var isLoading = true
@State private var profile: Profile!
@State private var profileContent = ""
@State private var isChanged = false
@State private var alert: Alert?
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task {
await loadContent()
}
}
} else {
viewBuilder {
if readOnly {
TextEditor(text: .constant(profileContent))
} else {
TextEditor(text: $profileContent)
}
}
.font(Font.system(.caption2, design: .monospaced))
.autocorrectionDisabled(true)
// https://stackoverflow.com/questions/66721935/swiftui-how-to-disable-the-smart-quotes-in-texteditor
// https://stackoverflow.com/questions/74034171/textfield-with-autocorrectiondisabled-still-shows-predictive-text-bar
.textContentType(.init(rawValue: ""))
#if os(iOS)
.keyboardType(.asciiCapable)
.textInputAutocapitalization(.none)
.background(Color(UIColor.secondarySystemGroupedBackground))
#elseif os(macOS)
.padding()
#endif
.onChangeCompat(of: profileContent) {
isChanged = true
}
}
}
.alertBinding($alert)
.navigationTitle(navigationTitle)
#if os(macOS)
.toolbar {
ToolbarItemGroup(placement: .navigation) {
if !readOnly {
Button {
Task {
await saveContent()
}
} label: {
Label("Save", image: "save")
}
.disabled(!isChanged)
} else {
Button {
NSPasteboard.general.setString(profileContent, forType: .fileContents)
} label: {
Label("Copy", systemImage: "clipboard.fill")
}
}
}
}
#elseif os(iOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
if !readOnly {
Button("Save") {
Task {
await saveContent()
}
}.disabled(!isChanged)
} else {
Button("Copy") {
UIPasteboard.general.string = profileContent
}
}
}
}
.navigationBarTitleDisplayMode(.inline)
#endif
}
private var navigationTitle: String {
if readOnly {
return "View Content"
} else {
return "Edit Content"
}
}
private func loadContent() async {
do {
try await loadContentBackground()
} catch {
alert = Alert(error)
}
isLoading = false
}
private nonisolated func loadContentBackground() async throws {
guard let profileID else {
throw NSError(domain: "Context destroyed", code: 0)
}
guard let profile = try await ProfileManager.get(profileID) else {
throw NSError(domain: "Profile missing", code: 0)
}
let profileContent = try profile.read()
await MainActor.run {
self.profile = profile
self.profileContent = profileContent
}
}
private func saveContent() async {
guard let profile else {
return
}
do {
try await saveContentBackground(profile)
} catch {
alert = Alert(error)
return
}
isChanged = false
}
private nonisolated func saveContentBackground(_ profile: Profile) async throws {
try await profile.write(profileContent)
}
}
#endif
@@ -1,177 +0,0 @@
import Libbox
import Library
import SwiftUI
@MainActor
public struct EditProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.dismiss) private var dismiss
@EnvironmentObject private var profile: Profile
@State private var isLoading = false
@State private var isChanged = false
@State private var alert: Alert?
@State private var shareLinkPresented = false
@State private var shareLinkText: String?
public init() {}
public var body: some View {
FormView {
FormItem("Name") {
TextField("Name", text: $profile.name, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
Picker(selection: $profile.type) {
Text("Local").tag(ProfileType.local)
Text("iCloud").tag(ProfileType.icloud)
Text("Remote").tag(ProfileType.remote)
} label: {
Text("Type")
}
.disabled(true)
if profile.type == .icloud {
FormItem("Path") {
TextField("Path", text: $profile.path, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
} else if profile.type == .remote {
FormItem("URL") {
TextField("URL", text: $profile.remoteURL.unwrapped(""), prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
Toggle("Auto Update", isOn: $profile.autoUpdate)
FormItem("Auto Update Interval") {
TextField("Auto Update Interval", text: $profile.autoUpdateInterval.stringBinding(defaultValue: 60), prompt: Text("In Minutes"))
.multilineTextAlignment(.trailing)
#if os(iOS)
.keyboardType(.numberPad)
#endif
}
}
if profile.type == .remote {
Section("Status") {
FormTextItem("Last Updated", profile.lastUpdatedString)
}
}
Section("Action") {
if profile.type != .remote {
#if os(iOS) || os(macOS)
FormNavigationLink {
EditProfileContentView(EditProfileContentView.Context(profileID: profile.id!, readOnly: false))
} label: {
Label("Edit Content", systemImage: "pencil")
.foregroundColor(.accentColor)
}
#endif
} else {
#if os(iOS) || os(macOS)
FormNavigationLink {
EditProfileContentView(EditProfileContentView.Context(profileID: profile.id!, readOnly: true))
} label: {
Label("View Content", systemImage: "doc.fill")
.foregroundColor(.accentColor)
}
#endif
FormButton {
isLoading = true
Task {
await updateProfile()
}
} label: {
Label("Update", systemImage: "arrow.clockwise")
}
.foregroundColor(.accentColor)
.disabled(isLoading)
}
FormButton(role: .destructive) {
Task {
await deleteProfile()
}
} label: {
Label("Delete", systemImage: "trash.fill")
}
.foregroundColor(.red)
}
}
.onChangeCompat(of: profile.name) {
isChanged = true
}
.onChangeCompat(of: profile.remoteURL) {
isChanged = true
}
.onChangeCompat(of: profile.autoUpdate) {
isChanged = true
}
.disabled(isLoading)
#if os(macOS)
.toolbar {
ToolbarItemGroup(placement: .navigation) {
Button {
isLoading = true
Task {
await saveProfile()
}
} label: {
Image("save", bundle: ApplicationLibrary.bundle, label: Text("Save"))
}
.disabled(isLoading || !isChanged)
}
}
#elseif os(iOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
isLoading = true
Task {
await saveProfile()
}
}.disabled(!isChanged)
}
}
#endif
.alertBinding($alert)
.navigationTitle("Edit Profile")
}
private func updateProfile() async {
defer {
isLoading = false
}
do {
try await Task.sleep(nanoseconds: UInt64(100 * Double(NSEC_PER_MSEC)))
try await profile.updateRemoteProfile()
environments.profileUpdate.send()
} catch {
alert = Alert(error)
}
}
private func deleteProfile() async {
do {
try await ProfileManager.delete(profile)
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
dismiss()
}
private func saveProfile() async {
do {
_ = try await ProfileManager.update(profile)
#if os(iOS) || os(tvOS)
try await UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
} catch {
alert = Alert(error)
return
}
isChanged = false
isLoading = false
environments.profileUpdate.send()
}
}
@@ -1,210 +0,0 @@
#if os(tvOS)
import DeviceDiscoveryUI
import Libbox
import Library
import SwiftUI
@MainActor
public struct ImportProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.dismiss) private var dismiss
@State private var isLoading = false
@State private var selected = false
@State private var alert: Alert?
@State private var connection: NWConnection?
@State private var socket: NWSocket?
@State private var profiles: [LibboxProfilePreview]?
@State private var isImporting = false
public init() {}
public var body: some View {
VStack(alignment: .center) {
if !selected {
Form {
Section {
EmptyView()
} footer: {
Text("To import configurations from your iPhone or iPad, make sure sing-box is the **same version** on both devices and **VPN is disabled**.")
}
DevicePicker(
.applicationService(name: "sing-box:profile"))
{ endpoint in
selected = true
Task {
await handleEndpoint(endpoint)
}
} label: {
Text("Select Device")
} fallback: {
EmptyView()
} parameters: {
.applicationService
}
}
} else if let profiles {
Form {
Section {
EmptyView()
} footer: {
Text("\(profiles.count) Profiles")
}
ForEach(profiles, id: \.profileID) { profile in
Button(profile.name) {
isLoading = true
Task {
selectProfile(profileID: profile.profileID)
isLoading = false
}
}.disabled(isLoading || isImporting)
}
}
} else {
Text("Connecting...")
}
}
.focusSection()
.alertBinding($alert)
.navigationTitle("Import Profile")
}
private func reset() {
if let connection {
connection.stateUpdateHandler = nil
connection.cancel()
self.connection = nil
}
if let socket {
socket.cancel()
self.socket = nil
}
selected = false
profiles = nil
}
private func handleEndpoint(_ endpoint: NWEndpoint) async {
let connection = NWConnection(to: endpoint, using: NWParameters.applicationService)
self.connection = connection
socket = NWSocket(connection)
connection.stateUpdateHandler = { state in
switch state {
case let .failed(error):
DispatchQueue.main.async { [self] in
reset()
alert = Alert(error)
}
default: break
}
}
connection.start(queue: .global())
do {
try await loopMessages()
} catch {
alert = Alert(error)
reset()
}
}
private nonisolated func loopMessages() async throws {
guard let socket = await socket else {
return
}
var message: Data
while true {
do {
message = try socket.read()
} catch {
throw NSError(domain: "read from connection: \(error.localizedDescription)", code: 0)
}
var error: NSError?
switch Int64(message[0]) {
case LibboxMessageTypeError:
let message = LibboxDecodeErrorMessage(message, &error)
if let error {
throw error
}
if let message {
throw NSError(domain: "remote error: \(message.message)", code: 0)
}
case LibboxMessageTypeProfileList:
let decoder = LibboxProfileDecoder()
try decoder.decode(message)
let iterator = decoder.iterator()!
var profiles = [LibboxProfilePreview]()
while iterator.hasNext() {
let profile = iterator.next()!
if profile.type == LibboxProfileTypeiCloud {
// not supported on tvOS
continue
}
profiles.append(profile)
}
await MainActor.run { [self, profiles] in
self.profiles = profiles
isImporting = false
}
case LibboxMessageTypeProfileContent:
let content = LibboxDecodeProfileContent(message, &error)
if let error {
throw error
}
try await importProfile(content!)
return
default:
throw NSError(domain: "unknown message type \(message[0])", code: 0)
}
}
}
private func selectProfile(profileID: Int64) {
guard let connection else {
return
}
guard let socket else {
return
}
connection.stateUpdateHandler = nil
let request = LibboxProfileContentRequest()
request.profileID = profileID
do {
try socket.write(request.encode())
isImporting = true
} catch {
alert = Alert(error)
reset()
}
}
private nonisolated func importProfile(_ content: LibboxProfileContent) async throws {
var type: ProfileType = .local
switch content.type {
case LibboxProfileTypeLocal:
type = .local
case LibboxProfileTypeiCloud:
type = .icloud
case LibboxProfileTypeRemote:
type = .remote
default:
break
}
let nextProfileID = try await ProfileManager.nextID()
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
try content.config.write(to: profileConfig, atomically: true, encoding: .utf8)
var lastUpdated: Date?
if content.lastUpdated > 0 {
lastUpdated = Date(timeIntervalSince1970: Double(content.lastUpdated))
}
try await ProfileManager.create(Profile(name: content.name, type: type, path: profileConfig.relativePath, remoteURL: content.remotePath, autoUpdate: content.autoUpdate, lastUpdated: lastUpdated))
await reset()
await MainActor.run {
environments.profileUpdate.send()
dismiss()
}
}
}
#endif
@@ -1,253 +0,0 @@
import Foundation
import Libbox
import Library
import SwiftUI
@MainActor
public struct NewProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.dismiss) private var dismiss
@State private var isSaving = false
@State private var profileName = "Sub"
@State private var profileType = ProfileType.remote
@State private var fileImport = false
@State private var fileURL: URL!
@State private var remotePath = ""
@State private var autoUpdate = true
@State private var autoUpdateInterval: Int32 = 60
@State private var pickerPresented = false
@State private var alert: Alert?
public struct ImportRequest: Codable, Hashable {
public let name: String
public let url: String
}
public init(_ importRequest: ImportRequest? = nil) {
if let importRequest {
_profileName = .init(initialValue: importRequest.name)
_profileType = .init(initialValue: .remote)
_remotePath = .init(initialValue: importRequest.url)
}
}
public var body: some View {
FormView {
FormItem("Name") {
TextField("Name", text: $profileName, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
Picker(selection: $profileType) {
#if !os(tvOS)
Text("Local").tag(ProfileType.local)
Text("iCloud").tag(ProfileType.icloud)
#endif
Text("Remote").tag(ProfileType.remote)
} label: {
Text("Type")
}
if profileType == .local {
Picker(selection: $fileImport) {
Text("Create New").tag(false)
Text("Import").tag(true)
} label: {
Text("File")
}
#if os(tvOS)
.disabled(true)
#endif
viewBuilder {
if fileImport {
HStack {
Text("File Path")
Spacer()
Spacer()
if let fileURL {
Button(fileURL.fileName) {
pickerPresented = true
}
} else {
Button("Choose") {
pickerPresented = true
}
}
}
}
}
} else if profileType == .icloud {
FormItem("Path") {
TextField("Path", text: $remotePath, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
} else if profileType == .remote {
FormItem("URL") {
TextField("URL", text: $remotePath, prompt: Text("Required"))
.multilineTextAlignment(.trailing)
}
Toggle("Auto Update", isOn: $autoUpdate)
FormItem("Auto Update Interval") {
TextField("Auto Update Interval", text: $autoUpdateInterval.stringBinding(defaultValue: 60), prompt: Text("In Minutes"))
.multilineTextAlignment(.trailing)
#if os(iOS)
.keyboardType(.numberPad)
#endif
}
}
Section {
if !isSaving {
FormButton {
isSaving = true
Task {
await createProfile()
}
} label: {
Label("Create", systemImage: "doc.fill.badge.plus")
}
} else {
ProgressView()
}
}
}
.navigationTitle("New Profile")
.alertBinding($alert)
#if os(iOS) || os(macOS)
.fileImporter(
isPresented: $pickerPresented,
allowedContentTypes: [.json],
allowsMultipleSelection: false
) { result in
do {
let urls = try result.get()
if !urls.isEmpty {
fileURL = urls[0]
}
} catch {
alert = Alert(error)
return
}
}
#endif
}
private func createProfile() async {
defer {
isSaving = false
}
if profileName.isEmpty {
alert = Alert(errorMessage: "Missing profile name")
return
}
if remotePath.isEmpty {
if profileType == .icloud {
alert = Alert(errorMessage: "Missing path")
return
} else if profileType == .remote {
alert = Alert(errorMessage: "Missing URL")
return
}
}
do {
try await createProfileBackground()
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
dismiss()
#if os(macOS)
resetFields()
#endif
}
private func resetFields() {
profileName = ""
profileType = .local
fileImport = false
fileURL = nil
remotePath = ""
}
private nonisolated func createProfileBackground() async throws {
let nextProfileID = try await ProfileManager.nextID()
var savePath = ""
var remoteURL: String? = nil
var lastUpdated: Date? = nil
let profileName = await profileName
let profileType = await profileType
let fileImport = await fileImport
let fileURL = await fileURL
let remotePath = await remotePath
let autoUpdate = await autoUpdate
let autoUpdateInterval = await autoUpdateInterval
if profileType == .local {
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
if fileImport {
guard let fileURL else {
throw NSError(domain: "Missing file", code: 0)
}
if !fileURL.startAccessingSecurityScopedResource() {
throw NSError(domain: "Missing access to selected file", code: 0)
}
defer {
fileURL.stopAccessingSecurityScopedResource()
}
try String(contentsOf: fileURL).write(to: profileConfig, atomically: true, encoding: .utf8)
} else {
try "{}".write(to: profileConfig, atomically: true, encoding: .utf8)
}
savePath = profileConfig.relativePath
} else if profileType == .icloud {
if !FileManager.default.fileExists(atPath: FilePath.iCloudDirectory.path) {
try FileManager.default.createDirectory(at: FilePath.iCloudDirectory, withIntermediateDirectories: true)
}
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(remotePath, isDirectory: false)
_ = saveURL.startAccessingSecurityScopedResource()
defer {
saveURL.stopAccessingSecurityScopedResource()
}
do {
_ = try String(contentsOf: saveURL)
} catch {
try "{}".write(to: saveURL, atomically: true, encoding: .utf8)
}
savePath = remotePath
} else if profileType == .remote {
let remoteContent = try HTTPClient().getString(remotePath)
print(remoteContent)
var error: NSError?
LibboxCheckConfig(remoteContent, &error)
if let error {
throw error
}
let profileConfigDirectory = FilePath.sharedDirectory.appendingPathComponent("configs", isDirectory: true)
try FileManager.default.createDirectory(at: profileConfigDirectory, withIntermediateDirectories: true)
let profileConfig = profileConfigDirectory.appendingPathComponent("config_\(nextProfileID).json")
try remoteContent.write(to: profileConfig, atomically: true, encoding: .utf8)
savePath = profileConfig.relativePath
remoteURL = remotePath
lastUpdated = .now
}
try await ProfileManager.create(Profile(
name: profileName,
type: profileType,
path: savePath,
remoteURL: remoteURL,
autoUpdate: autoUpdate,
autoUpdateInterval: autoUpdateInterval,
lastUpdated: lastUpdated
))
if profileType == .remote {
#if os(iOS) || os(tvOS)
try await UIProfileUpdateTask.configure()
#else
try await ProfileUpdateTask.configure()
#endif
}
}
}
@@ -1,423 +0,0 @@
import Foundation
import Libbox
import Library
import Network
import QRCode
import SwiftUI
@MainActor
public struct ProfileView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@Environment(\.importProfile) private var importProfile
@Environment(\.importRemoteProfile) private var importRemoteProfile
@State private var importRemoteProfileRequest: NewProfileView.ImportRequest?
@State private var importRemoteProfilePresented = false
@State private var isLoading = true
@State private var isUpdating = false
@State private var alert: Alert?
@State private var profileList: [ProfilePreview] = []
#if os(iOS) || os(tvOS)
@State private var editMode = EditMode.inactive
#endif
#if os(tvOS)
@Environment(\.devicePickerSupports) private var devicePickerSupports
#endif
public init() {}
public var body: some View {
VStack {
if isLoading {
ProgressView().onAppear {
Task {
await doReload()
}
}
} else {
ZStack {
if let importRemoteProfileRequest {
NavigationDestinationCompat(isPresented: $importRemoteProfilePresented) {
NewProfileView(importRemoteProfileRequest)
}
}
FormView {
#if os(iOS)
FormNavigationLink {
NewProfileView()
} label: {
Text("New Profile").foregroundColor(.accentColor)
}
.disabled(editMode.isEditing)
#elseif os(macOS)
FormNavigationLink {
NewProfileView()
} label: {
Text("New Profile")
}
#elseif os(tvOS)
Section {
FormNavigationLink {
NewProfileView()
} label: {
Text("New Profile").foregroundColor(.accentColor)
}
if ApplicationLibrary.inPreview || devicePickerSupports(.applicationService(name: "sing-box"), parameters: { .applicationService }) {
FormNavigationLink {
ImportProfileView()
} label: {
Text("Import Profile").foregroundColor(.accentColor)
}
}
}
#endif
if profileList.isEmpty {
Text("Empty profiles")
} else {
List {
ForEach(profileList, id: \.id) { profile in
viewBuilder {
#if os(iOS) || os(tvOS)
if editMode.isEditing == true {
Text(profile.name)
} else {
ProfileItem(self, profile)
}
#else
ProfileItem(self, profile)
#endif
}
}
.onMove(perform: moveProfile)
.onDelete(perform: deleteProfile)
}
}
}
}
}
}
.disabled(isUpdating)
.alertBinding($alert, $isLoading)
.onAppear {
if let profile = importProfile.wrappedValue {
importProfile.wrappedValue = nil
createImportProfileDialog(profile)
}
if let remoteProfile = importRemoteProfile.wrappedValue {
importRemoteProfile.wrappedValue = nil
createImportRemoteProfileDialog(remoteProfile)
}
}
.onChangeCompat(of: importProfile.wrappedValue) { newValue in
if let newValue {
importProfile.wrappedValue = nil
createImportProfileDialog(newValue)
}
}
.onChangeCompat(of: importRemoteProfile.wrappedValue) { newValue in
if let newValue {
importRemoteProfile.wrappedValue = nil
createImportRemoteProfileDialog(newValue)
}
}
.onReceive(environments.profileUpdate) { _ in
Task {
await doReload()
}
}
#if os(iOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton().disabled(profileList.isEmpty)
}
}
#elseif os(tvOS)
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
if editMode == .inactive {
Button("Edit") {
editMode = .active
}
.disabled(profileList.isEmpty)
} else {
Button("Done") {
editMode = .inactive
}
}
}
}
#endif
#if os(iOS) || os(tvOS)
.environment(\.editMode, $editMode)
#endif
}
private func createImportProfileDialog(_ profile: LibboxProfileContent) {
alert = Alert(
title: Text("Import Profile"),
message: Text("Are you sure to import profile \(profile.name)?"),
primaryButton: .default(Text("Import")) {
Task {
do {
try await profile.importProfile()
} catch {
alert = Alert(error)
return
}
await doReload()
}
},
secondaryButton: .cancel()
)
}
private func createImportRemoteProfileDialog(_ newValue: LibboxImportRemoteProfile) {
importRemoteProfileRequest = .init(name: newValue.name, url: newValue.url)
alert = Alert(
title: Text("Import Remote Profile"),
message: Text("Are you sure to import remote profile \(newValue.name)? You will connect to \(newValue.host) to download the configuration."),
primaryButton: .default(Text("Import")) {
importRemoteProfilePresented = true
},
secondaryButton: .cancel()
)
}
private func doReload() async {
defer {
isLoading = false
}
if ApplicationLibrary.inPreview {
profileList = [
ProfilePreview(Profile(id: 0, name: "profile local", type: .local, path: "")),
ProfilePreview(Profile(id: 1, name: "profile remote", type: .remote, path: "", lastUpdated: Date(timeIntervalSince1970: 0))),
]
} else {
do {
profileList = try await ProfileManager.list().map { ProfilePreview($0) }
} catch {
alert = Alert(error)
return
}
}
environments.emptyProfiles = profileList.isEmpty
}
private func updateProfile(_ profile: Profile) async {
await updateProfileBackground(profile)
isUpdating = false
}
private nonisolated func updateProfileBackground(_ profile: Profile) async {
do {
_ = try await profile.updateRemoteProfile()
} catch {
await MainActor.run {
alert = Alert(error)
}
}
}
private func deleteProfile(_ profile: Profile) async {
do {
_ = try await ProfileManager.delete(profile)
} catch {
alert = Alert(error)
return
}
environments.profileUpdate.send()
}
private func moveProfile(from source: IndexSet, to destination: Int) {
profileList.move(fromOffsets: source, toOffset: destination)
for (index, profile) in profileList.enumerated() {
profileList[index].order = UInt32(index)
profile.origin.order = UInt32(index)
}
Task {
do {
try await ProfileManager.update(profileList.map(\.origin))
} catch {
alert = Alert(error)
}
environments.profileUpdate.send()
}
}
private func deleteProfile(where profileIndex: IndexSet) {
let profileToDelete = profileIndex.map { index in
profileList[index].origin
}
profileList.remove(atOffsets: profileIndex)
environments.emptyProfiles = profileList.isEmpty
Task {
do {
_ = try await ProfileManager.delete(profileToDelete)
} catch {
alert = Alert(error)
}
environments.profileUpdate.send()
}
}
@MainActor
public struct ProfileItem: View {
private let parent: ProfileView
@State private var profile: ProfilePreview
@State private var shareLinkPresented = false
public init(_ parent: ProfileView, _ profile: ProfilePreview) {
self.parent = parent
_profile = State(initialValue: profile)
}
public var body: some View {
#if os(iOS) || os(macOS)
if #available(iOS 16.0, macOS 13.0,*) {
body0.draggable(profile.origin)
} else {
body0
}
#else
body0
#endif
}
private var body0: some View {
viewBuilder {
#if !os(macOS)
FormNavigationLink {
EditProfileView().environmentObject(profile.origin)
} label: {
Text(profile.name)
}
.sheet(isPresented: $shareLinkPresented) {
shareLinkView.padding()
}
.contextMenu {
ProfileShareButton(parent.$alert, profile.origin) {
Label("Share", systemImage: "square.and.arrow.up.fill")
}
if profile.type == .remote {
Button {
shareLinkPresented = true
} label: {
Label("Share URL as QR Code", systemImage: "qrcode")
}
Button {
parent.isUpdating = true
Task {
await parent.updateProfile(profile.origin)
profile = ProfilePreview(profile.origin)
}
} label: {
Label("Update", systemImage: "arrow.clockwise")
}
}
Button(role: .destructive) {
Task {
await parent.deleteProfile(profile.origin)
}
} label: {
Label("Delete", systemImage: "trash.fill")
}
}
#else
FormNavigationLink {
EditProfileView().environmentObject(profile.origin)
} label: {
HStack {
VStack(alignment: .leading) {
Text(profile.name)
if profile.type == .remote {
Spacer(minLength: 4)
Text("Last Updated: \(profile.origin.lastUpdatedString)").font(.caption)
}
}
HStack {
if profile.type == .remote {
Button {
parent.isUpdating = true
Task {
await parent.updateProfile(profile.origin)
profile = ProfilePreview(profile.origin)
}
} label: {
Image(systemName: "arrow.clockwise")
}
.padding(.leading, 4)
Button {
shareLinkPresented = true
} label: {
Image(systemName: "qrcode")
}
.padding(.leading, 4)
.popover(isPresented: $shareLinkPresented, arrowEdge: .bottom) {
shareLinkView
}
}
ProfileShareButton(parent.$alert, profile.origin) {
Image(systemName: "square.and.arrow.up.fill")
}
.padding(.leading, 4)
Button {
Task {
await parent.deleteProfile(profile.origin)
}
} label: {
Image(systemName: "trash.fill")
}
.padding([.leading, .trailing], 4)
}
.buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .trailing)
}
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
}
#endif
}
}
private var shareLinkView: some View {
#if os(iOS)
viewBuilder {
if #available(iOS 16.0, *) {
shareLinkView0
.presentationDetents([.medium])
.presentationDragIndicator(.visible)
} else {
shareLinkView0
}
}
#elseif os(macOS)
shareLinkView0
.frame(minWidth: 300, minHeight: 300)
#else
shareLinkView0
#endif
}
private var foregroundColor: CGColor {
#if canImport(UIKit)
return UIColor.label.cgColor
#elseif canImport(AppKit)
return NSColor.labelColor.cgColor
#endif
}
private var shareLinkView0: some View {
QRCodeViewUI(
content: LibboxGenerateRemoteProfileImportLink(profile.name, profile.remoteURL!),
errorCorrection: .low,
foregroundColor: foregroundColor,
backgroundColor: CGColor(gray: 1.0, alpha: 0.0)
)
}
}
}