Cotton code
126 lines · 4.6 KB · SwiftRaw
// Every file column, inline: local bytes first, a PDF's first page or a// bounded image, a tap that opens the file in the one viewer, and an OS// share/save handoff.import CottonKitimport CottonValuesimport PDFKitimport SwiftUIstruct FileColumnContent: View {  let value: RecordValue  let seed: String  @Environment(\.cottonCore) private var core  @Environment(\.attachmentStore) private var store  @Environment(\.theme) private var theme  @Environment(\.viewerPresenter) private var viewer  @Environment(\.tableDefinitions) private var definitions  @State private var url: URL?  @State private var shared: URL?  @State private var shareDirectory: URL?  @State private var kind: FilePreview.Kind?  @State private var fetching = false  var body: some View {    VStack(alignment: .leading, spacing: FileColumnContentKnobs.faceFileColumnGap) {      if let kind {        Button {          open()        } label: {          switch kind {          case .pdf(let pdf): FilePagesSheet(pdf: pdf, seed: seed)          case .image(let image):            Image(uiImage: image).resizable().scaledToFit().blendMode(.multiply)          }        }        .buttonStyle(.plain)        .accessibilityLabel(AttachmentValue.read(value)?.name ?? "")        .viewerSource(itemID)      } else if url == nil {        // Not on this phone: the slip with the file's name and Fetch.        AbsentSlip(          kind: AbsentKind.of(name: AttachmentValue.read(value)?.name), name: AttachmentValue.read(value)?.name, words: words,          fetching: fetching, onFetch: source == nil ? nil : { Task { await fetch() } },          compact: true)      }      if let shared {        ShareLink(item: shared) { Text(words?.share ?? "").paperHand(theme.scale.handSize + 1) }      }    }    .task(id: value) {      discardCopy()      url = nil      kind = nil      guard let reference = AttachmentValue.read(value)?.ref, let store = source else { return }      let local = await store.localURL(for: reference)      guard !Task.isCancelled else { return }      url = local      kind = url.flatMap { FilePreview.Kind(path: $0.path) }      prepareCopy()    }    .onDisappear { discardCopy() }  }  private var itemID: String { "file/\(seed)/\(AttachmentValue.read(value)?.ref ?? "")" }  /// The file, whole, in the viewer: a PDF read through PDFKit, a picture  /// zoomed, anything else through Quick Look.  private func open() {    guard let file = AttachmentValue.read(value) else { return }    var picture = false    if case .image = kind { picture = true }    let item = ViewerItem(id: itemID, kind: picture ? .photo : .document, key: file.ref, title: file.name)    viewer?.open(ViewerSet(items: [item], start: 0))  }  private var words: ViewerWords? { ViewerWords.reading(definitions) }  /// The file fetched, because the person asked on the slip.  private func fetch() async {    guard !fetching, let ref = AttachmentValue.read(value)?.ref, let source else { return }    fetching = true    defer { fetching = false }    // A fetch that fails leaves the slip as it was, with Fetch.    url = try? await source.ensure(for: ref)    kind = url.flatMap { FilePreview.Kind(path: $0.path) }    prepareCopy()  }  private var source: (any AttachmentStore)? {    store ?? core.map { CoreAttachmentStore(core: $0) }  }  static func copyName(_ name: String?, fallback: String) -> String {    let leaf = name.map { ($0 as NSString).lastPathComponent } ?? ""    return leaf.isEmpty || leaf == "." || leaf == ".." ? fallback : leaf  }  private func prepareCopy() {    discardCopy()      if let url {        let directory = FileManager.default.temporaryDirectory.appendingPathComponent(          UUID().uuidString)        let copy = directory.appendingPathComponent(          Self.copyName(AttachmentValue.read(value)?.name, fallback: url.lastPathComponent))        do {          try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)          try FileManager.default.copyItem(at: url, to: copy)          shareDirectory = directory          shared = copy        } catch {          try? FileManager.default.removeItem(at: directory)          shared = nil        }      }  }  private func discardCopy() {    if let shareDirectory { try? FileManager.default.removeItem(at: shareDirectory) }    shareDirectory = nil    shared = nil  }}/// The sizes, counts and timings FileColumnContent draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum FileColumnContentKnobs {    static let faceFileColumnGap: CGFloat = 10}