iOS: fold an open drawer by tapping; delete an empty added folder !219

merged merged by cmc on 2026-10-10 20:47 UTC · krz/orgstar:drawer-refold into main

6 files changed, +81 −31

Layout: unified · split

Sources/OrgPresentation/ReadingText.swift +18 −10
@@ -14,8 +14,9 @@ public enum ReadingText {
1414 public var offset: Int
1515 /// A pretty sub/superscript's body: true raised, false lowered.
1616 public var superscript: Bool?
17 /// A fold's `…`: where the hidden range it stands for starts.
18 public var unfolds: Int?
17 /// A drawer's opening line, and a folded one's `…`: where the hidden range they fold
18 /// and unfold starts.
19 public var toggles: Int?
1920 }
2021
2122 /// How the text shows, as the editor's display settings make it.
@@ -34,8 +35,11 @@ public enum ReadingText {
3435 }
3536 }
3637
37 /// `folded` are drawers' and blocks' hidden ranges (`Wrapper.hidden`).
38 public static func segments(_ tree: OrgTree, in range: Range<Int>, folded: [Range<Int>] = [], display: Display = Display()) -> [Segment] {
38 /// `folded` are drawers' and blocks' hidden ranges (`Wrapper.hidden`); `open` are those of
39 /// unfolded ones whose opening line folds them.
40 public static func segments(
41 _ tree: OrgTree, in range: Range<Int>, folded: [Range<Int>] = [], open: [Range<Int>] = [], display: Display = Display()
42 ) -> [Segment] {
3943 let text = tree.text as NSString
4044 // A fold hides from the end of the opening line through the closing line, so the
4145 // marker sits on the opening line.
@@ -78,7 +82,13 @@ public enum ReadingText {
7882 }
7983 }
8084 }
85 // Opening lines that fold or unfold, a wider target than a `…`.
86 let lineStart = { (end: Int) in text.lineRange(for: NSRange(location: end, length: 0)).location }
87 let openings = folds.map { (line: lineStart($0.lowerBound)..<$0.lowerBound, start: $0.lowerBound + 1) }
88 + open.filter { $0.lowerBound > range.lowerBound && $0.lowerBound <= range.upperBound }
89 .map { (line: lineStart($0.lowerBound - 1)..<($0.lowerBound - 1), start: $0.lowerBound) }
8190 var bounds: Set<Int> = [range.lowerBound, range.upperBound]
91 for opening in openings { bounds.formUnion([max(range.lowerBound, opening.line.lowerBound), opening.line.upperBound]) }
8292 let replacedRanges = replaced.keys.map { $0..<($0 + 1) }
8393 for r in runs.map(\.range) + hidden + replacedRanges + scripts.map(\.range) {
8494 bounds.insert(max(range.lowerBound, min(range.upperBound, r.lowerBound)))
@@ -87,7 +97,7 @@ public enum ReadingText {
8797 let points = bounds.sorted()
8898 var segments: [Segment] = []
8999 func append(_ segment: Segment) {
90 if var last = segments.last, last.roles == segment.roles, last.link == segment.link, last.superscript == segment.superscript, last.unfolds == segment.unfolds,
100 if var last = segments.last, last.roles == segment.roles, last.link == segment.link, last.superscript == segment.superscript, last.toggles == segment.toggles,
91101 last.offset + (last.text as NSString).length == segment.offset {
92102 last.text += segment.text
93103 segments[segments.count - 1] = last
@@ -112,19 +122,17 @@ public enum ReadingText {
112122 var scriptAt = [Bool?](repeating: nil, count: intervals)
113123 for script in scripts { for k in covered(script.range) where scriptAt[k] == nil { scriptAt[k] = script.superscript } }
114124 let foldStarts = Set(folds.map(\.lowerBound))
115 // A fold's opening line opens it too, a wider target than its `…`.
116 let openings = folds.map { (line: text.lineRange(for: NSRange(location: $0.lowerBound, length: 0)).location..<$0.lowerBound, start: $0.lowerBound + 1) }
117125 for (k, (a, b)) in zip(points, points.dropFirst()).enumerated() {
118126 if foldStarts.contains(a) {
119 segments.append(Segment(text: "…", roles: [.metadata], link: nil, offset: a, unfolds: a + 1))
127 segments.append(Segment(text: "…", roles: [.metadata], link: nil, offset: a, toggles: a + 1))
120128 }
121129 if hiddenAt[k] { continue }
122130 let roles = rolesAt[k]
123131 let link = roles.contains(.link) ? Links.link(at: a, text: tree.text, tree: tree)?.link : nil
124132 let superscript = scriptAt[k]
125133 let shown = replaced[a] ?? text.substring(with: NSRange(location: a, length: b - a))
126 let unfolds = openings.first { $0.line.contains(a) }?.start
127 let segment = Segment(text: shown, roles: roles, link: link, offset: a, superscript: superscript, unfolds: unfolds)
134 let toggles = openings.first { $0.line.contains(a) }?.start
135 let segment = Segment(text: shown, roles: roles, link: link, offset: a, superscript: superscript, toggles: toggles)
128136 if replaced[a] != nil { segments.append(segment) } else { append(segment) }
129137 }
130138 return segments
Sources/OrgstarMobile/FoldersScreen.swift +30 −3
@@ -13,6 +13,8 @@ struct FoldersScreen: View {
1313 /// Counts deletions and new folders, so the list reads the empty folders on disk again.
1414 @State private var changes = 0
1515 @State private var creating: NewItem?
16 /// The added folder whose deletion from disk is being confirmed.
17 @State private var deletingRoot: String?
1618
1719 var body: some View {
1820 List {
@@ -20,6 +22,9 @@ struct FoldersScreen: View {
2022 Section((root as NSString).lastPathComponent) {
2123 FolderContents(workspace: workspace, root: root, folder: "", deleting: $deleting, changes: changes)
2224 Button("Remove Folder", role: .destructive) { try? workspace.removeRoot(path: root) }
25 if isEmptyFolder(root) {
26 Button("Delete Folder…", role: .destructive) { deletingRoot = root }
27 }
2328 }
2429 }
2530 if let error = workspace.lastError {
@@ -27,6 +32,23 @@ struct FoldersScreen: View {
2732 }
2833 }
2934 .navigationTitle("Folders")
35 .confirmationDialog("Delete “\(deletingRoot.map { ($0 as NSString).lastPathComponent } ?? "")”?",
36 isPresented: Binding { deletingRoot != nil } set: { if !$0 { deletingRoot = nil } }, titleVisibility: .visible) {
37 Button("Delete", role: .destructive) {
38 guard let root = deletingRoot else { return }
39 deletingRoot = nil
40 Task {
41 do {
42 try await workspace.trash(root)
43 try workspace.removeRoot(path: root)
44 } catch {
45 workspace.lastError = "Can't delete \((root as NSString).lastPathComponent): \(error.localizedDescription)"
46 }
47 }
48 }
49 } message: {
50 Text("The empty folder is removed from disk and from orgstar.")
51 }
3052 .navigationDestination(for: FolderRoute.self) { route in
3153 FolderPage(workspace: workspace, session: session, route: route)
3254 }
@@ -186,6 +208,12 @@ extension FoldersScreen {
186208 }
187209}
188210
211/// A folder with nothing in it but dotfiles.
212private func isEmptyFolder(_ path: String) -> Bool {
213 guard let inside = try? FileManager.default.contentsOfDirectory(atPath: path) else { return false }
214 return inside.allSatisfy { $0.hasPrefix(".") }
215}
216
189217/// A subfolder to show, relative to its root.
190218struct FolderRoute: Hashable {
191219 let root: String
@@ -212,9 +240,8 @@ private struct FolderContents: View {
212240 guard let names = try? fm.contentsOfDirectory(atPath: url.path) else { return [] }
213241 return names.filter { name in
214242 var isFolder: ObjCBool = false
215 guard !name.hasPrefix("."), fm.fileExists(atPath: url.appendingPathComponent(name).path, isDirectory: &isFolder), isFolder.boolValue,
216 let inside = try? fm.contentsOfDirectory(atPath: url.appendingPathComponent(name).path) else { return false }
217 return inside.allSatisfy { $0.hasPrefix(".") }
243 let path = url.appendingPathComponent(name).path
244 return !name.hasPrefix(".") && fm.fileExists(atPath: path, isDirectory: &isFolder) && isFolder.boolValue && isEmptyFolder(path)
218245 }
219246 }
220247
Sources/OrgstarMobile/MobileEditor.swift +12 −9
@@ -917,27 +917,30 @@ extension MobileEditor: UITextViewDelegate {
917917}
918918
919919extension MobileEditor: UIGestureRecognizerDelegate {
920 /// The start of the folded line whose `…` is at `point`: the space after its text.
921 private func foldedLine(at point: CGPoint) -> Int? {
920 /// The drawer or block a tap at `point` folds or unfolds: a folded one's `…`, the space after
921 /// its first line, or anywhere on an open drawer's first line.
922 private func foldToggle(at point: CGPoint) -> Int? {
922923 guard let manager = textView.textLayoutManager, let content = manager.textContentManager else { return nil }
923924 let inContainer = CGPoint(x: point.x - textView.textContainerInset.left, y: point.y - textView.textContainerInset.top)
924925 guard let fragment = manager.textLayoutFragment(for: inContainer), let range = fragment.textElement?.elementRange else { return nil }
925926 let start = content.offset(from: content.documentRange.location, to: range.location)
926 guard hidden.isFolded(start),
927 let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first
928 else { return nil }
929 return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil
927 guard let line = fragment.textLineFragments.first(where: { $0.characterRange.length > 0 }) ?? fragment.textLineFragments.first else { return nil }
928 if hidden.isFolded(start) { return inContainer.x - fragment.layoutFragmentFrame.minX >= line.typographicBounds.maxX ? start : nil }
929 guard Wrappers.starting(at: start, in: document.tree)?.kind == .drawer,
930 inContainer.y - fragment.layoutFragmentFrame.minY < line.typographicBounds.maxY else { return nil }
931 return start
930932 }
931933
932 /// A tap on a fold's `…` opens it, as TAB on its line does.
934 /// A tap on a fold's `…` opens it, and one on an open drawer's first line folds it, as TAB
935 /// on the line does.
933936 @objc fileprivate func tappedFold(_ tap: UITapGestureRecognizer) {
934 guard let start = foldedLine(at: tap.location(in: textView)),
937 guard let start = foldToggle(at: tap.location(in: textView)),
935938 let next = Presentation.cycle(at: start, in: document.tree, fold) else { return }
936939 setFolds(next)
937940 }
938941
939942 func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
940 foldedLine(at: gestureRecognizer.location(in: textView)) != nil
943 foldToggle(at: gestureRecognizer.location(in: textView)) != nil
941944 }
942945
943946 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool {
Sources/OrgstarMobile/ReaderScreen.swift +11 −4
@@ -28,6 +28,8 @@ struct ReaderScreen: View {
2828 let session: DocumentSession
2929 @State private var fold = FoldState()
3030 @State private var folded: [Range<Int>] = []
31 /// Drawers and blocks the file opens with folded, which fold and unfold from their first line.
32 @State private var foldable: [Range<Int>] = []
3133 @State private var loadedPath: String?
3234 /// The file's display: indentation, leading stars, inline images, truncation.
3335 @State private var startup: StartupDisplay?
@@ -186,7 +188,7 @@ struct ReaderScreen: View {
186188 .frame(maxWidth: image.width.map { CGFloat($0) } ?? image.picture.size.width, alignment: .leading)
187189 .accessibilityLabel((image.path as NSString).lastPathComponent)
188190 } else {
189 lineText(attributed(ReadingText.segments(tree, in: part.range, folded: folded, display: display), heading: nil, theme).trimmingTrailingNewlines(), theme)
191 lineText(attributed(ReadingText.segments(tree, in: part.range, folded: folded, open: foldable.filter { !folded.contains($0) }, display: display), heading: nil, theme).trimmingTrailingNewlines(), theme)
190192 .textSelection(.enabled)
191193 }
192194 }
@@ -273,7 +275,7 @@ struct ReaderScreen: View {
273275 // Found again by position when followed.
274276 part.link = URL(string: "orgstar-link:\(segment.offset)")
275277 }
276 if let start = segment.unfolds { part.link = URL(string: "orgstar-unfold:\(start)") }
278 if let start = segment.toggles { part.link = URL(string: "orgstar-fold:\(start)") }
277279 if let superscript = segment.superscript {
278280 // Raised or lowered as the editor draws `org-pretty-entities` scripts.
279281 part.baselineOffset = (superscript ? 0.3 : -0.3) * font.pointSize
@@ -316,6 +318,7 @@ struct ReaderScreen: View {
316318 let display = Presentation.startupDisplay(tree, options: session.options)
317319 startup = display
318320 folded = display.wrappers.map(\.hidden)
321 foldable = folded
319322 guard loadedPath != session.path else { return }
320323 loadedPath = session.path
321324 fold = display.folds
@@ -334,8 +337,12 @@ struct ReaderScreen: View {
334337 }
335338
336339 private func follow(_ url: URL) -> OpenURLAction.Result {
337 if url.scheme == "orgstar-unfold", let start = Int(url.absoluteString.dropFirst("orgstar-unfold:".count)) {
338 folded.removeAll { $0.lowerBound == start }
340 if url.scheme == "orgstar-fold", let start = Int(url.absoluteString.dropFirst("orgstar-fold:".count)) {
341 if folded.contains(where: { $0.lowerBound == start }) {
342 folded.removeAll { $0.lowerBound == start }
343 } else if let range = foldable.first(where: { $0.lowerBound == start }) {
344 folded.append(range)
345 }
339346 return .handled
340347 }
341348 guard url.scheme == "orgstar-link", let offset = Int(url.absoluteString.dropFirst("orgstar-link:".count)),
Tests/OrgPresentationTests/ReadingTextTests.swift +7 −2
@@ -11,8 +11,13 @@ struct ReadingTextTests {
1111 let segments = ReadingText.segments(tree, in: 0..<(text as NSString).length, folded: folded)
1212 #expect(segments.map(\.text).joined() == "* TODO H :t:\n:PROPERTIES:…\nSee the site and *b* c.org.\n")
1313 // The drawer's first line and its `…` name the hidden range they open.
14 #expect(segments.filter { $0.unfolds != nil }.map(\.text).joined() == ":PROPERTIES:…")
15 #expect(segments.first { $0.text == "…" }?.unfolds == folded.first?.lowerBound)
14 #expect(segments.filter { $0.toggles != nil }.map(\.text).joined() == ":PROPERTIES:…")
15 #expect(segments.first { $0.text == "…" }?.toggles == folded.first?.lowerBound)
16 // Opened, its first line folds it again.
17 let opened = ReadingText.segments(tree, in: 0..<(text as NSString).length, open: folded)
18 #expect(opened.filter { $0.toggles != nil }.map(\.text).joined() == ":PROPERTIES:")
19 #expect(opened.first { $0.toggles != nil }?.toggles == folded.first?.lowerBound)
20 #expect(!opened.contains { $0.text.contains("…") })
1621 let site = segments.first { $0.text == "the site" }
1722 #expect(site?.link?.raw == "https://a.org" && site?.roles.contains(.link) == true)
1823 #expect(segments.first { $0.text == "TODO" }?.roles.contains(.todo) == true)
docs/manual/guide/14-ios.org +3 −3
@@ -21,7 +21,7 @@ orgstar on iOS works on folders you choose, in iCloud Drive or in another app's
21211. Open the Folders tab and tap Add Folder (the folder icon with a plus).
22222. Choose a folder in the picker.
2323
24orgstar keeps access to the folder across launches. Each folder appears as a section listing its =.org= files by their path inside the folder. Remove Folder at the end of a section removes it from orgstar; the files stay where they are.
24orgstar keeps access to the folder across launches. Each folder appears as a section listing its =.org= files by their path inside the folder. Remove Folder at the end of a section removes it from orgstar; the files stay where they are. An added folder that is empty also has Delete Folder…, which deletes it from disk too.
2525
2626Swipe left on a file, or touch and hold it, to delete it. orgstar asks first. A file in iCloud Drive goes to Recently Deleted in the Files app; elsewhere it is removed. New File… and New Folder… under + at the top right make one in the folder shown, or with several added folders, in the one you pick; a file name without an extension gets =.org=. Empty folders are listed too and delete the same way; a folder with anything in it other than hidden files can't be deleted from orgstar.
2727
@@ -36,7 +36,7 @@ There is no way to open a single file from the Files app. Add the folder that co
3636Tap a file in Folders, Search or the agenda to read it.
3737
3838- Tap a heading to fold or unfold it, as =TAB= cycles it on the Mac. A chevron marks headings with content.
39- The file opens with the visibility its =#+STARTUP= line asks for, then each heading's =VISIBILITY= property when =#+STARTUP= sets a visibility. Drawers and blocks are folded as =org-cycle-hide-drawer-startup= and =org-cycle-hide-block-startup= say, or as the file's =#+STARTUP= says (=hidedrawers=, =nohideblocks= and the like).
39- The file opens with the visibility its =#+STARTUP= line asks for, then each heading's =VISIBILITY= property when =#+STARTUP= sets a visibility. Drawers and blocks are folded as =org-cycle-hide-drawer-startup= and =org-cycle-hide-block-startup= say, or as the file's =#+STARTUP= says (=hidedrawers=, =nohideblocks= and the like). Tap a folded drawer's first line or its =…= to open it, and the first line again to fold it.
4040- Text is styled as in the editor, in the theme's colours, font, size, line spacing and heading sizes, on the theme's background: TODO keywords, priorities, tags, emphasis, code, timestamps, links, and the code in src blocks. Text can be selected and copied.
4141- The reader follows the editor's display settings (see Themes and display below): Show Markup, hidden emphasis markers, pretty entities, indentation, leading stars, inline images and truncated lines. Tables show at full width, without narrowed columns.
4242- Tap a link to follow it. Links to headings and files in your folders open in the reader; web links open in the browser.
@@ -46,7 +46,7 @@ Tap a file in Folders, Search or the agenda to read it.
4646
4747Tap Edit in the reader. The title shows the buffer name, with =•= while there are unsaved changes. The tab bar is hidden while you edit.
4848
49The editor folds headings, drawers and blocks, styles text with the theme from the configuration folder (see Themes and display below), and runs the same Org commands as the Mac. Autocorrection, smart quotes and smart dashes are off; spell checking follows =spell-check= in =config.toml= and is off by default.
49The editor folds headings, drawers and blocks (tap a fold's =…= to open it, and an open drawer's first line to fold it), styles text with the theme from the configuration folder (see Themes and display below), and runs the same Org commands as the Mac. Autocorrection, smart quotes and smart dashes are off; spell checking follows =spell-check= in =config.toml= and is off by default.
5050
5151The toolbar has:
5252