Consolidate images and files

This commit is contained in:
Christoph Hagen
2024-12-09 12:18:55 +01:00
parent 394cf7a2e4
commit 4f08526978
77 changed files with 1970 additions and 1619 deletions

View File

@ -0,0 +1,109 @@
import SwiftUI
struct AddFileView: View {
@Environment(\.dismiss)
private var dismiss: DismissAction
@EnvironmentObject
private var content: Content
@Binding
var selectedFile: FileResource?
@Binding
var selectedImage: ImageResource?
@State
private var filesToAdd: [FileToAdd] = []
init(selectedImage: Binding<ImageResource?>, selectedFile: Binding<FileResource?>) {
_selectedFile = selectedFile
_selectedImage = selectedImage
}
var body: some View {
ScrollView {
Text("Select files to add")
.foregroundStyle(.secondary)
List {
ForEach(filesToAdd) { file in
FileToAddView(file: file, delete: delete)
}
}.frame(minHeight: 300)
HStack {
Button("Cancel", role: .cancel) { dismiss() }
Button("Select more files", action: openFilePanel)
Button("Add selected", action: importSelectedFiles)
.disabled(filesToAdd.isEmpty)
}
}
.padding()
}
private func openFilePanel() {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = true
panel.showsHiddenFiles = false
panel.title = "Select files to add"
panel.prompt = ""
let response = panel.runModal()
guard response == .OK else {
print("Failed to select files to import")
return
}
for url in panel.urls {
guard !filesToAdd.contains(where: { $0.url == url }) else {
print("Skipping already selected file \(url.path())")
continue
}
print("Selected file \(url.path())")
let newFile = FileToAdd(content: content, url: url)
filesToAdd.append(newFile)
}
}
private func delete(file: FileToAdd) {
guard let index = filesToAdd.firstIndex(of: file) else {
return
}
filesToAdd.remove(at: index)
}
private func importSelectedFiles() {
for file in filesToAdd {
guard file.isSelected else {
print("Skipping unselected file \(file.uniqueId)")
continue
}
guard !file.idAlreadyExists else {
print("Skipping existing file \(file.uniqueId)")
continue
}
guard content.storage.copyFile(at: file.url, fileId: file.uniqueId) else {
print("Failed to import file '\(file.uniqueId)' at \(file.url.path())")
return
}
let resource = FileResource(
content: content,
id: file.uniqueId,
en: "", de: "")
// TODO: Insert at correct index?
content.files.insert(resource, at: 0)
selectedFile = resource
}
dismiss()
}
}
#Preview {
AddFileView(selectedImage: .constant(nil),
selectedFile: .constant(nil))
}

View File

@ -1,37 +1,68 @@
import SwiftUI
import SFSafeSymbols
struct FileContentView: View {
private let iconSize: CGFloat = 150
@ObservedObject
var file: FileResource
@EnvironmentObject
private var content: Content
@State
private var fileContent: String = ""
var body: some View {
VStack {
if fileContent != "" {
TextEditor(text: $fileContent)
.font(.body.monospaced())
.textEditorStyle(.plain)
} else {
Text("The file is not a text file")
.onAppear(perform: loadFileContent)
switch file.type {
case .image:
file.imageToDisplay
.resizable()
.aspectRatio(contentMode: .fit)
case .model:
VStack {
Image(systemSymbol: .cubeTransparent)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: iconSize)
Text("No preview available")
.font(.title)
}
.foregroundStyle(.secondary)
case .text, .code:
TextFileContentView(file: file)
.id(file.id)
case .video:
VStack {
Image(systemSymbol: .film)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: iconSize)
Text("No preview available")
.font(.title)
}
.foregroundStyle(.secondary)
case .other:
VStack {
Image(systemSymbol: .docQuestionmark)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: iconSize)
Text("No preview available")
.font(.title)
}
.foregroundStyle(.secondary)
}
}.padding()
}
}
private func loadFileContent() {
do {
fileContent = try content.storage.fileContent(for: file.uniqueId)
} catch {
print(error)
fileContent = ""
}
extension FileContentView: MainContentView {
init(item: FileResource) {
self.file = item
}
static let itemDescription = "a file"
}
#Preview {

View File

@ -5,22 +5,75 @@ struct FileDetailView: View {
@ObservedObject
var file: FileResource
@State
private var newId: String
init(file: FileResource) {
self.file = file
self.newId = file.id
}
private let allowedCharactersInPostId = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-.")).inverted
private var idExists: Bool {
file.content.files.contains { $0.id == newId }
}
private var containsInvalidCharacters: Bool {
newId.rangeOfCharacter(from: allowedCharactersInPostId) != nil
}
var body: some View {
VStack(alignment: .leading) {
Text("File Name")
.font(.headline)
TextField("", text: $file.uniqueId)
.textFieldStyle(.roundedBorder)
.padding(.bottom)
.disabled(true)
Text("Description")
HStack {
TextField("", text: $newId)
.textFieldStyle(.roundedBorder)
Button(action: setNewId) {
Text("Update")
}
.disabled(newId.isEmpty || containsInvalidCharacters || idExists)
}
Text("German Description")
.font(.headline)
TextField("", text: $file.description)
TextField("", text: $file.germanDescription)
.textFieldStyle(.roundedBorder)
Text("English Description")
.font(.headline)
TextField("", text: $file.englishDescription)
.textFieldStyle(.roundedBorder)
if file.type.isImage {
Text("Image size")
.font(.headline)
Text("\(Int(file.size.width)) x \(Int(file.size.height)) (\(file.aspectRatio))")
.foregroundStyle(.secondary)
#warning("Add button to show image versions")
}
Spacer()
}.padding()
}
private func setNewId() {
guard file.content.storage.move(file: file.id, to: newId) else {
print("Failed to move file \(file.id)")
newId = file.id
return
}
file.id = newId
}
}
extension FileDetailView: MainContentView {
init(item: FileResource) {
self.init(file: item)
}
static let itemDescription = "a file"
}
#Preview {
FileDetailView(file: .mock)
}

View File

@ -0,0 +1,100 @@
import SwiftUI
private enum FileFilterType: String, Hashable, CaseIterable, Identifiable {
case images
case text
case videos
case other
var text: String {
switch self {
case .images: return "Image"
case .text: return "Text"
case .videos: return "Video"
case .other: return "Other"
}
}
var id: String {
rawValue
}
func matches(_ type: FileType) -> Bool {
switch self {
case .images: return type.isImage
case .text: return type.isTextFile
case .videos: return type.isVideo
case .other: return type.isOtherFile
}
}
}
struct FileListView: View {
@EnvironmentObject
private var content: Content
@Binding
var selectedFile: FileResource?
@State
private var selectedFileType: FileFilterType = .images
@State
private var searchString = ""
var filesBySelectedType: [FileResource] {
content.files.filter { selectedFileType.matches($0.type) }
}
var filteredFiles: [FileResource] {
guard !searchString.isEmpty else {
return filesBySelectedType
}
return filesBySelectedType.filter { $0.id.contains(searchString) }
}
var body: some View {
VStack(alignment: .center) {
Picker("", selection: $selectedFileType) {
ForEach(FileFilterType.allCases) { type in
Text(type.text).tag(type)
}
}
.pickerStyle(.segmented)
.padding(.trailing, 7)
TextField("", text: $searchString, prompt: Text("Search"))
.textFieldStyle(.roundedBorder)
.padding(.horizontal, 8)
List(filteredFiles, selection: $selectedFile) { file in
Text(file.id).tag(file)
}
.onChange(of: selectedFileType) { oldValue, newValue in
guard oldValue != newValue else {
return
}
if let selectedFile,
newValue.matches(selectedFile.type) {
return
}
selectedFile = filteredFiles.first
}
}
.onAppear {
if selectedFile == nil {
selectedFile = content.files.first
}
}
}
}
#Preview {
NavigationSplitView {
FileListView(selectedFile: .constant(nil))
.environmentObject(Content.mock)
.navigationSplitViewColumnWidth(250)
} detail: {
Text("")
.frame(width: 50)
}
}

View File

@ -0,0 +1,46 @@
import Foundation
final class FileToAdd: ObservableObject {
unowned let content: Content
let url: URL
@Published
var uniqueId: String
@Published
var isSelected: Bool = true
init(content: Content, url: URL) {
self.content = content
self.url = url
self.uniqueId = url.lastPathComponent
}
var idAlreadyExists: Bool {
content.files.contains { $0.id == uniqueId }
}
}
extension FileToAdd: Identifiable {
var id: URL {
url
}
}
extension FileToAdd: Equatable {
static func == (lhs: FileToAdd, rhs: FileToAdd) -> Bool {
lhs.url == rhs.url
}
}
extension FileToAdd: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(url)
}
}

View File

@ -0,0 +1,45 @@
import SwiftUI
import SFSafeSymbols
struct FileToAddView: View {
@ObservedObject
var file: FileToAdd
let delete: (FileToAdd) -> Void
var body: some View {
VStack(alignment: .leading) {
HStack {
Image(systemSymbol: file.isSelected ? .checkmarkCircleFill : .circle)
.resizable()
.frame(width: 20, height: 20)
.foregroundStyle(.blue)
.onTapGesture {
file.isSelected.toggle()
}
Image(systemSymbol: .trashCircleFill)
.resizable()
.frame(width: 20, height: 20)
.foregroundStyle(.red)
.onTapGesture {
delete(file)
}
TextField("", text: $file.uniqueId)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: 200)
}
Text(file.url.path())
.foregroundStyle(.secondary)
}
}
}
#Preview {
List {
FileToAddView(file: .init(content: .mock, url: URL(fileURLWithPath: "/path/to/file.swift")), delete: { _ in })
FileToAddView(file: .init(content: .mock, url: URL(fileURLWithPath: "/path/to/file2.swift")), delete: { _ in })
}
}

View File

@ -1,79 +0,0 @@
import SwiftUI
struct FilesView: View {
@EnvironmentObject
private var content: Content
@State
private var selected: FileResource? = nil
var body: some View {
NavigationSplitView {
List(content.files, selection: $selected) { file in
Text(file.uniqueId)
.tag(file)
}
.toolbar {
ToolbarItem(placement: .primaryAction) {
Button(action: openFilePanel) {
Label("Add file", systemSymbol: .plus)
}
}
}
.navigationSplitViewColumnWidth(min: 250, ideal: 250, max: 250)
} content: {
if let selected {
FileContentView(file: selected)
.id(selected.uniqueId)
} else {
Text("Select a file")
}
} detail: {
if let selected {
FileDetailView(file: selected)
} else {
EmptyView()
}
}
}
private func openFilePanel() {
let panel = NSOpenPanel()
// Sets up so user can only select a single directory
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = true
panel.showsHiddenFiles = false
panel.title = "Select files to add"
panel.prompt = ""
let response = panel.runModal()
guard response == .OK else {
print("Failed to select files to import")
return
}
for url in panel.urls {
let fileId = url.lastPathComponent
guard !content.files.contains(where: { $0.uniqueId == fileId }) else {
print("A file '\(fileId)' already exists")
continue
}
let type = FileType(fileExtension: fileId.fileExtension)
let file = FileResource(type: type, uniqueId: fileId, description: "")
guard content.storage.copyFile(at: url, fileId: fileId) else {
print("Failed to import file '\(fileId)'")
continue
}
content.files.insert(file, at: 0)
}
}
}
#Preview {
FilesView()
.environmentObject(Content.mock)
}

View File

@ -0,0 +1,38 @@
import SwiftUI
struct TextFileContentView: View {
@ObservedObject
var file: FileResource
@State
private var fileContent: String = ""
var body: some View {
if fileContent != "" {
TextEditor(text: $fileContent)
.font(.body.monospaced())
.textEditorStyle(.plain)
//.background(.clear)
} else {
VStack {
Image(systemSymbol: .docText)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 150)
Text("No preview available")
.font(.title)
}
.foregroundStyle(.secondary)
.onAppear(perform: loadFileContent)
}
}
private func loadFileContent() {
guard fileContent == "" else {
return
}
fileContent = file.textContent()
print("Loaded content of file \(file.id)")
}
}