adds first version of the app

This commit is contained in:
2026-10-17 14:33:43 +02:00
parent ab1abadcd1
commit 7b891819b0
3066 changed files with 29585 additions and 0 deletions
+96
View File
@@ -0,0 +1,96 @@
import Foundation
import ImageIO
import UniformTypeIdentifiers
public enum ImageStoreError: Error, Equatable {
case unsupportedType(String)
/// The data is no image that ImageIO can read, so it cannot become a PNG.
case unreadableImage
case noFreeName
}
/// Puts pasted and dropped images in the image folder and gives back the path of their image line.
public struct ImageStore: Sendable {
public static let fileExtensions: Set<String> = ["png", "jpg", "jpeg", "gif", "heic", "webp"]
public static let folderName = "images"
/// The folder of the page file; image links are relative to it.
public let base: URL
private let now: @Sendable () -> Date
private let random: @Sendable () -> UInt16
private let timeZone: TimeZone
public init(
base: URL = PageStore.defaultURL.deletingLastPathComponent(),
now: @escaping @Sendable () -> Date = Date.init,
random: @escaping @Sendable () -> UInt16 = { UInt16.random(in: .min ... .max) },
timeZone: TimeZone = .current
) {
self.base = base
self.now = now
self.random = random
self.timeZone = timeZone
}
public var folder: URL {
base.appendingPathComponent(Self.folderName, isDirectory: true)
}
public static func isImageFile(_ url: URL) -> Bool {
url.isFileURL && fileExtensions.contains(url.pathExtension.lowercased())
}
/// Copies an image file into the image folder with its own extension.
/// - Returns: the path relative to `base`, as `images/<name>`.
public func copy(file: URL) throws -> String {
let ext = file.pathExtension.lowercased()
guard Self.fileExtensions.contains(ext) else { throw ImageStoreError.unsupportedType(ext) }
let target = try freeURL(ext: ext)
try FileManager.default.copyItem(at: file, to: target)
return relativePath(target)
}
/// Writes raw image data, as from the pasteboard, as a PNG file.
/// - Returns: the path relative to `base`, as `images/<name>`.
public func write(imageData data: Data) throws -> String {
let png = data.starts(with: [0x89, 0x50, 0x4E, 0x47]) ? data : try Self.pngData(data)
let target = try freeURL(ext: "png")
try png.write(to: target, options: .withoutOverwriting)
return relativePath(target)
}
/// The name for an image made now: `2026-10-16-085512-a3f0`.
public func name(ext: String) -> String {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone
let c = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now())
let stamp = String(format: "%04d-%02d-%02d-%02d%02d%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
return "\(stamp)-\(String(format: "%04x", random())).\(ext)"
}
private func freeURL(ext: String) throws -> URL {
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
for _ in 0..<32 {
let url = folder.appendingPathComponent(name(ext: ext))
if !FileManager.default.fileExists(atPath: url.path) { return url }
}
throw ImageStoreError.noFreeName
}
private func relativePath(_ url: URL) -> String {
"\(Self.folderName)/\(url.lastPathComponent)"
}
private static func pngData(_ data: Data) throws -> Data {
guard let source = CGImageSourceCreateWithData(data as CFData, nil),
let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw ImageStoreError.unreadableImage }
let out = NSMutableData()
guard let destination = CGImageDestinationCreateWithData(out, UTType.png.identifier as CFString, 1, nil) else {
throw ImageStoreError.unreadableImage
}
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil)
CGImageDestinationAddImage(destination, image, properties)
guard CGImageDestinationFinalize(destination) else { throw ImageStoreError.unreadableImage }
return out as Data
}
}
+89
View File
@@ -0,0 +1,89 @@
import Foundation
import Observation
import PlakCore
public enum PageStoreError: Error, Equatable {
/// The page file exists but cannot be read as UTF-8; saving over it would lose the page.
case unreadable(path: String)
}
/// Reads the page file at launch and keeps it in step with the page.
///
/// Every `changed()` schedules one save after the debounce; a failed save keeps the page in
/// memory, sets `saveError`, and is tried again on the next change or `flush()`.
@MainActor
@Observable
public final class PageStore {
public nonisolated static var defaultURL: URL {
FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
.appendingPathComponent("plak", isDirectory: true)
.appendingPathComponent("page.md")
}
/// The page file as read at launch; an empty page when there was no file.
public let loaded: PageFile
/// Makes the page file text when a save runs, so a keystroke costs no conversion; nil writes nothing.
@ObservationIgnored public var contents: () -> String? = { nil }
/// The message of the last failed save; nil once a save succeeds.
public private(set) var saveError: String?
public let url: URL
private let debounce: Duration
private let write: @Sendable (Data, URL) throws -> Void
@ObservationIgnored private var pending: Task<Void, Never>?
@ObservationIgnored private var isDirty = false
/// Reads the page file; a missing file gives an empty page.
/// - Throws: `PageStoreError.unreadable` when the file exists but cannot be read.
public init(
url: URL = PageStore.defaultURL,
debounce: Duration = .milliseconds(500),
write: @escaping @Sendable (Data, URL) throws -> Void = PageStore.writeAtomically
) throws {
self.url = url
self.debounce = debounce
self.write = write
if FileManager.default.fileExists(atPath: url.path) {
guard let data = try? Data(contentsOf: url), let text = String(data: data, encoding: .utf8) else {
throw PageStoreError.unreadable(path: url.path)
}
loaded = PageFile(text: text)
} else {
loaded = PageFile()
}
}
/// Marks the page as changed; the save follows after the debounce.
public func changed() {
isDirty = true
pending?.cancel()
let delay = debounce
pending = Task { [weak self] in
try? await Task.sleep(for: delay)
guard !Task.isCancelled else { return }
self?.flush()
}
}
/// Writes a pending change now, as on quit.
public func flush() {
pending?.cancel()
pending = nil
guard isDirty, let text = contents() else { return }
do {
try write(Data(text.utf8), url)
isDirty = false
saveError = nil
} catch {
saveError = error.localizedDescription
}
}
/// Creates the folder when needed and replaces the file in one step.
public nonisolated static func writeAtomically(_ data: Data, to url: URL) throws {
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
try data.write(to: url, options: .atomic)
}
}