Commit 2197a7a1d9

2197a7a1d9d834d0ac0b029519ab79f4ada8cfe8

parent: f27a6bd93c

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 08:54 UTC

iOS: archive, publishing, agenda calendars, HTML and open, rich text copy, idle time, agenda folder import

Layout: unified · split

Sources/OrgApp/HTMLPreview.swift added +15
@@ -0,0 +1,15 @@
1import Foundation
2
3/// Export to HTML and Open where the page is shown from a temporary file (iOS, in Quick Look):
4/// the images go in the page, as nothing is beside it there.
5public enum HTMLPreview {
6 /// Writes `html` (an `HTMLExport.page`) as `name` in a new temporary folder. `directory` is
7 /// the Org file's folder, where relative image links are read from.
8 public static func write(_ html: String, directory: URL?, name: String) throws -> URL {
9 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-html-\(UUID().uuidString)")
10 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
11 let url = folder.appendingPathComponent(name)
12 try PDFExport.inliningImages(html, directory: directory).write(to: url, atomically: true, encoding: .utf8)
13 return url
14 }
15}
Sources/OrgstarMobile/ClockScreens.swift +9
@@ -76,6 +76,15 @@ enum MobileClock {
7676 }
7777 return true
7878 }
79
80 /// `org-resolve-clocks-if-idle` for the running clock, idle since `since`.
81 static func resolveIdle(since: Date, model: MobileModel, show: @escaping (String) -> Void) {
82 Task {
83 let outcome = await model.clock.resolveIdle(model.session, idleSince: since, ask: model.clockPrompts.ask)
84 if let jump = outcome.jump { model.openRequest = .offset(jump.path, jump.offset) }
85 if let message = outcome.messages.last(where: { !$0.isEmpty }) { show(message) }
86 }
87 }
7988}
8089
8190/// Recent entries to clock in to, and the commands that choose among them.
Sources/OrgstarMobile/EditorScreen.swift +123
@@ -69,6 +69,15 @@ struct EditorScreen: View {
6969 @State private var photos: [PhotosPickerItem] = []
7070 /// A file shown in Quick Look.
7171 @State private var previewed: URL?
72 /// The project whose publishing folder the folder picker is choosing.
73 @State private var publishFolder: PublishFolderRequest?
74 @State private var choosingPublishFolder = false
75
76 struct PublishFolderRequest {
77 let project: String
78 /// Publishes again, with the folder.
79 let then: () -> Void
80 }
7281
7382 enum Sheet: Identifiable {
7483 case palette, conflict, syncCopies, recovery
@@ -281,6 +290,18 @@ struct EditorScreen: View {
281290 }
282291 }
283292 }
293 .background {
294 Color.clear.fileImporter(isPresented: $choosingPublishFolder, allowedContentTypes: [.folder]) { result in
295 guard let request = publishFolder else { return }
296 publishFolder = nil
297 switch result {
298 case .success(let url):
299 if !PublishFolders.shared.set(url, for: request.project) { message = "orgstar can use \(url.lastPathComponent) only until it quits" }
300 request.then()
301 case .failure(let error): message = error.localizedDescription
302 }
303 }
304 }
284305 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
285306 .fullScreenCover(isPresented: $takingPhoto) {
286307 CameraPicker { data in
@@ -441,6 +462,18 @@ struct EditorScreen: View {
441462 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
442463 } else if id == "app.save" {
443464 _ = session.save(path)
465 } else if id == "app.archive" {
466 if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
467 } else if id == "app.copy-rich-text" {
468 if let text = session.document(of: path)?.text { message = ExportMenu.copy(path: path, text: text, theme: model.theme) }
469 } else if id == "app.export.html-open" {
470 exportHTMLAndOpen()
471 } else if id == "app.export.icalendar-agenda" || id == "app.export.icalendar-combined" {
472 agendaCalendars(combined: id == "app.export.icalendar-combined")
473 } else if id.hasPrefix("app.publish") {
474 publish(id)
475 } else if AppStoreCommands.unavailable(id) {
476 message = "Attachments can't be linked on iPhone and iPad; Attach File… copies the file."
444477 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
445478 sheet = .refile(id)
446479 } else if id == "app.table-import" {
@@ -576,6 +609,92 @@ extension EditorScreen {
576609 sheet = .exportSubtree(context.caret)
577610 }
578611
612 /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
613 private func exportHTMLAndOpen() {
614 guard let text = session.document(of: path)?.text else { return }
615 let html = OrgExport.html(text, path: path, theme: model.theme)
616 let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
617 .lastPathComponent
618 do {
619 previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
620 } catch {
621 message = "Can't export \(name): \(error.localizedDescription)"
622 }
623 }
624
625 /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
626 /// whose share button saves or sends it.
627 private func agendaCalendars(combined: Bool) {
628 guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
629 guard combined else { return message = calendars.exportEach() }
630 do {
631 previewed = try calendars.combined()
632 } catch {
633 message = "Can't export: \(error.localizedDescription)"
634 }
635 }
636
637 /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
638 private func publish(_ id: String) {
639 guard let all = publishProjects() else { return }
640 let current = Publish.projects(containing: path, in: all)
641 switch id {
642 case "app.publish.all":
643 publish(all.map(\.name))
644 case "app.publish.current-file":
645 guard let project = current.first else { return message = "File is not part of any known project" }
646 publish([project.name], only: path)
647 case "app.publish.current-project":
648 guard let project = current.first else { return message = "File is not part of any known project" }
649 publish([project.name])
650 default:
651 prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
652 if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
653 }
654 }
655 }
656
657 /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
658 /// message, when there are none.
659 private func publishProjects() -> [PublishProject]? {
660 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
661 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
662 if let problem = loaded.problems.first { message = problem }
663 guard !loaded.projects.isEmpty else {
664 message = "No [[publish]] projects in config.toml"
665 return nil
666 }
667 return PublishFolders.shared.applied(to: loaded.projects)
668 }
669
670 /// Publishes the projects named, `only` that file when given. A project that publishes
671 /// outside the folders added to orgstar asks for its folder first, once.
672 private func publish(_ names: [String], only: String? = nil) {
673 guard let all = publishProjects() else { return }
674 let chosen = all.filter { names.contains($0.name) }
675 do {
676 if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
677 message = "Choose the folder \(project.name) publishes to"
678 publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
679 choosingPublishFolder = true
680 return
681 }
682 if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
683 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
684 }
685 let read = { (file: String) -> String? in
686 session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8))
687 }
688 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
689 let report = try Publish.publish(chosen, all: all, only: only, read: read) { function, text, file, bodyOnly in
690 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle)
691 }
692 message = "Published \(report.published.count) files" + (report.skipped.isEmpty ? "" : ", \(report.skipped.count) up to date")
693 } catch {
694 message = "\(error)"
695 }
696 }
697
579698 /// Org-roam's commands, with Pro.
580699 private func roam(_ id: String) {
581700 if ProAccess.shared.allows(.roam) { roamActions.run(id) }
@@ -949,6 +1068,10 @@ struct CommandPalette: View {
9491068 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
9501069 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
9511070 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1071 ("app.archive", "Archive Subtree"), ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1072 ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1073 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1074 ("app.publish.current-project", "Publish Current Project"),
9521075 ("app.toggle-markup", "Show or Hide Markup"),
9531076 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
9541077 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
Sources/OrgstarMobile/EmacsImportScreen.swift +38 −6
@@ -5,8 +5,8 @@ import SwiftUI
55
66/// Import from Emacs: a configuration folder (a synced `~/.config/doom` or `~/.emacs.d`), read
77/// and picked from before anything changes. Settings go into the configuration
8/// folder's config.toml when there is one; agenda folders, which name the Mac's paths, are left
9/// out.
8/// folder's config.toml when there is one. Agenda folders name the Mac's paths, so each is
9/// added as the folder chosen for it on this device.
1010struct EmacsImportScreen: View {
1111 let model: MobileModel
1212 @State private var location: URL?
@@ -15,6 +15,11 @@ struct EmacsImportScreen: View {
1515 @State private var choosing = false
1616 @State private var summary: String?
1717 @State private var importing = false
18 /// The folders chosen on this device, by the Mac path they stand for.
19 @State private var folders: [String: URL] = [:]
20 /// The Mac path the folder picker is choosing for.
21 @State private var folderFor: String?
22 @State private var choosingFolder = false
1823
1924 var body: some View {
2025 List {
@@ -27,8 +32,25 @@ struct EmacsImportScreen: View {
2732 if let summary {
2833 Section { Text(summary) }
2934 } else if let result {
30 EmacsImportSections(result: result, groups: result.groups(folders: false), selected: $selected,
35 EmacsImportSections(result: result, groups: result.groups(folders: true), selected: $selected,
3136 font: .system(.callout, design: .monospaced))
37 let paths = EmacsImport.foldersToAdd(result.items.filter { selected.contains($0.id) }, workspace: model.workspace)
38 if !paths.isEmpty {
39 Section {
40 ForEach(paths, id: \.self) { path in
41 Button {
42 folderFor = path
43 choosingFolder = true
44 } label: {
45 LabeledContent(path, value: folders[path]?.lastPathComponent ?? "Choose…")
46 }
47 }
48 } header: {
49 Text("Folders on this device")
50 } footer: {
51 Text("Choose the folder on this device for each one. Folders not chosen aren't added.")
52 }
53 }
3254 }
3355 }
3456 .navigationTitle("Import from Emacs")
@@ -40,6 +62,15 @@ struct EmacsImportScreen: View {
4062 .fileImporter(isPresented: $choosing, allowedContentTypes: [.folder]) { chosen in
4163 if case .success(let url) = chosen { read(url) }
4264 }
65 .background {
66 // A second importer on the same view would replace the first.
67 Color.clear.fileImporter(isPresented: $choosingFolder, allowedContentTypes: [.folder]) { chosen in
68 guard let path = folderFor, case .success(let url) = chosen else { return }
69 // Kept for the bookmark the import makes; access stays on for the session.
70 _ = url.startAccessingSecurityScopedResource()
71 folders[path] = url
72 }
73 }
4374 }
4475
4576 private func read(_ url: URL) {
@@ -48,7 +79,8 @@ struct EmacsImportScreen: View {
4879 location = url
4980 let scanned = EmacsImport.scan(EmacsImport.files(in: url))
5081 result = scanned
51 selected = Set(scanned.groups(folders: false).flatMap(\.1).map(\.id))
82 selected = Set(scanned.groups(folders: true).flatMap(\.1).map(\.id))
83 folders = [:]
5284 summary = nil
5385 }
5486
@@ -57,8 +89,8 @@ struct EmacsImportScreen: View {
5789 importing = true
5890 let chosen = result.items.filter { selected.contains($0.id) }
5991 Task {
60 summary = await EmacsImport.apply(chosen, workspace: nil, directory: model.configFolder ?? UserConfig.directory,
61 writeConfig: model.configFolder != nil)
92 summary = await EmacsImport.apply(chosen, workspace: model.workspace, directory: model.configFolder ?? UserConfig.directory,
93 writeConfig: model.configFolder != nil, chosenFolders: folders)
6294 model.reloadConfig()
6395 importing = false
6496 }
Sources/OrgstarMobile/ExportMenu.swift +70 −9
@@ -91,6 +91,15 @@ struct OrgExport: Transferable {
9191 .exportingCondition { $0.format == .ascii }
9292 }
9393
94 /// The page HTML export makes of `text`, the file at `path`, with its setup files.
95 @MainActor
96 static func html(_ text: String, path: String, theme: ThemeSpec) -> String {
97 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
98 let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
99 return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
100 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: theme), language: OrgPreferences.exportLanguage())
101 }
102
94103 private func write() async throws -> SentTransferredFile {
95104 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
96105 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
@@ -172,26 +181,78 @@ struct ExportMenu: View {
172181 if let exportSubtree {
173182 Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
174183 }
184 if let calendars = AgendaCalendars(model: model) {
185 Divider()
186 if OrgExport.Format.icalendar.locked {
187 Button("Agenda Files to iCalendar (orgstar+)") { ProAccess.shared.allows(.export) }
188 } else {
189 Button("Export Agenda Files to iCalendar", systemImage: "calendar") { report(calendars.exportEach()) }
190 ShareLink(item: calendars, preview: SharePreview(calendars.fileName)) {
191 Label("Combine Agenda Files into iCalendar", systemImage: "calendar.badge.plus")
192 }
193 }
194 }
175195 Divider()
176 Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { copy() } }
196 Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { report(Self.copy(path: path, text: text, theme: model.theme)) } }
177197 }
178198 }
179199
180 /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
181 private func copy() {
182 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
183 let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
184 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
185 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), language: OrgPreferences.exportLanguage())
200 /// The file on the clipboard as HTML, RTF and plain text, to paste formatted. Returns a message.
201 @MainActor
202 static func copy(path: String, text: String, theme: ThemeSpec) -> String {
203 let html = OrgExport.html(text, path: path, theme: theme)
186204 do {
187205 try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
188 report("Copied as rich text")
206 return "Copied as rich text"
189207 } catch {
190 report("\(error)")
208 return "\(error)"
191209 }
192210 }
193211}
194212
213/// The agenda files as iCalendar: each to a calendar beside it
214/// (`org-icalendar-export-agenda-files`), or all in one calendar to share
215/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
216struct AgendaCalendars: Transferable {
217 let paths: [String]
218 /// The open files' text, which may not be saved yet.
219 let open: [String: String]
220
221 /// Nil without agenda files.
222 @MainActor init?(model: MobileModel) {
223 guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
224 self.paths = paths
225 open = Dictionary(model.session.openDocuments.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
226 }
227
228 var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
229
230 private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
231 guard let text = open[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
232 return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
233 }
234
235 /// Writes each agenda file's calendar beside it. Returns a message.
236 func exportEach() -> String {
237 do {
238 let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
239 return "Exported \(written.count) agenda files to iCalendar"
240 } catch {
241 return "Can't export: \(error.localizedDescription)"
242 }
243 }
244
245 /// The combined calendar, in a new temporary folder.
246 func combined() throws -> URL {
247 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
248 return try ICalendarFiles.combine(paths, to: folder.appendingPathComponent(fileName).path, options: OrgPreferences.icalendarOptions(), read: read)
249 }
250
251 static var transferRepresentation: some TransferRepresentation {
252 FileRepresentation(exportedContentType: .calendarEvent) { SentTransferredFile(try $0.combined()) }
253 }
254}
255
195256/// The subtree at `caret` shared alone, in each of the export formats.
196257struct SubtreeExportScreen: View {
197258 let path: String
Sources/OrgstarMobile/MobileEditor.swift +3 −1
@@ -425,7 +425,9 @@ final class MobileEditor: NSObject, DocumentBuffer {
425425 case "app.crypt.encrypt-entry": return onAppCommand != nil && OrgCrypt.heading(context.text, at: context.caret) != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) == nil
426426 case "app.crypt.open-entry", "app.crypt.decrypt-entry": return onAppCommand != nil && OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
427427 case "app.table-export", "app.plot": return onAppCommand != nil && ImportTable.exportText(context.text, at: context.caret, path: "") != nil
428 case "app.refile", "app.refile.copy": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
428 case "app.refile", "app.refile.copy", "app.archive": return onAppCommand != nil && Presentation.heading(containing: context.caret, in: context.tree) != nil
429 case "app.copy-rich-text", "app.export.html-open", "app.export.icalendar-agenda", "app.export.icalendar-combined": return onAppCommand != nil
430 case _ where id.hasPrefix("app.publish"): return onAppCommand != nil
429431 case _ where Self.linkCommands.contains(id): return onAppCommand != nil
430432 case "org.link.open": return OpenLinkAtPoint().applies(in: context)
431433 case "org.table.toggle-column-width", "org.table.shrink", "org.table.expand":
Sources/OrgstarMobile/OrgstarMobileApp.swift +9
@@ -119,6 +119,8 @@ struct RootView: View {
119119 @State private var hour = 0
120120 @State private var showingClockReport = false
121121 @State private var message: String?
122 /// When the app went to the background, for the clock's idle time.
123 @State private var backgrounded: Date?
122124 @Environment(\.scenePhase) private var scenePhase
123125 @AppStorage(OnboardingScreen.doneKey) private var onboarded = false
124126 @State private var onboarding = false
@@ -321,9 +323,16 @@ struct RootView: View {
321323 // Unsaved edits are written before the app may be stopped.
322324 if phase == .background {
323325 for path in session.dirtyPaths { _ = session.save(path) }
326 backgrounded = Date()
324327 }
325328 // Files and settings synced while away; not every sync tool tells file presenters.
326329 guard phase == .active else { return }
330 // iOS has no idle time: time away from the app while a clock ran stands in for it.
331 if let left = backgrounded, let since = ClockModel.idleSince(
332 backgrounded: left, now: Date(), running: model.clock.running, idleMinutes: OrgPreferences.clockIdleTime()) {
333 MobileClock.resolveIdle(since: since, model: model) { message = $0 }
334 }
335 backgrounded = nil
327336 takeShared()
328337 model.reloadConfig()
329338 Task { await workspace.refresh() }
Tests/OrgAppTests/PDFExportTests.swift +12
@@ -54,4 +54,16 @@ struct PDFExportTests {
5454 let html = #"<img src="img/a.png"> <img alt="c" src="/abs/c.svg"> <img src="https://x.org/r.png"> <img src="img/a.png">"#
5555 #expect(PDFExport.imageFiles(html, directory: URL(fileURLWithPath: "/notes")) == ["/notes/img/a.png", "/abs/c.svg"])
5656 }
57
58 /// Export to HTML and Open on iOS: a temporary page with its images in it.
59 @Test func previewHasItsImages() throws {
60 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)")
61 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
62 defer { try? FileManager.default.removeItem(at: folder) }
63 try Data([1, 2, 3]).write(to: folder.appendingPathComponent("a.png"))
64 let url = try HTMLPreview.write(#"<p><img src="a.png"></p>"#, directory: folder, name: "notes.html")
65 defer { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
66 #expect(url.lastPathComponent == "notes.html")
67 #expect(try String(contentsOf: url, encoding: .utf8) == #"<p><img src="data:image/png;base64,AQID"></p>"#)
68 }
5769}