Repository Public
1// ORIX Docs2// File: App/Sources/Sidebar/OutlinePanel.swift3// Description: The outline panel: the document's headings with their numbers, navigation, and section reordering and4// promotion/demotion through the editing engine.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import SwiftUI9import DocModel1011/// The outline with, for every heading, where its section can move and whether its level can change.12struct OutlineModel {13 struct Item: Identifiable {14 let entry: OutlineEntry15 /// Block index to pass to `moveSection(startingAt:before:)` to move the section above its previous sibling.16 var moveUpDestination: Int?17 /// Same, to move it below its next sibling.18 var moveDownDestination: Int?19 /// Level of the built-in heading style applied to the paragraph (nil when the outline level comes from elsewhere).20 var styleLevel: Int?21 var canPromote = false22 var canDemote = false23 var id: String { entry.id }24 }2526 var items: [Item] = []27 /// Id of the heading whose section holds the caret.28 var currentID: String?2930 init(doc: DocumentModel, outline: [OutlineEntry], caretBlock: Int?) {31 let body = doc.body32 // Outline level of every block: 0 for body text, -1 for a section break (sections never move across one).33 var styleLevels: [String: Int] = [:]34 var levels = [Int](repeating: 0, count: body.count)35 for (i, block) in body.enumerated() {36 switch block {37 case .paragraph(let p):38 if let direct = p.props.outlineLevel { levels[i] = direct; continue }39 if let cached = styleLevels[p.style] { levels[i] = cached; continue }40 let l = doc.styles.styleProps(p.style).para.outlineLevel ?? 041 styleLevels[p.style] = l42 levels[i] = l43 case .sectionBreak: levels[i] = -144 default: break45 }46 }47 func sectionEnd(_ start: Int) -> Int {48 let lvl = levels[start]49 var end = start + 150 while end < body.count, levels[end] != -1, !(levels[end] > 0 && levels[end] <= lvl) { end += 1 }51 return end52 }53 let headingStyles = Dictionary(uniqueKeysWithValues: (1...9).map { (StyleID.heading($0), $0) })54 func hasStyle(_ level: Int) -> Bool { doc.styles.style(StyleID.heading(level))?.kind == .paragraph }5556 for entry in outline where body.indices.contains(entry.blockIndex) && levels[entry.blockIndex] > 0 {57 let i = entry.blockIndex, lvl = levels[i]58 var item = Item(entry: entry)59 // Previous sibling: the nearest heading above at the same level, with no shallower heading or section break in between.60 var j = i - 161 while j >= 0, levels[j] != -1, !(levels[j] > 0 && levels[j] <= lvl) { j -= 1 }62 if j >= 0, levels[j] == lvl { item.moveUpDestination = j }63 let end = sectionEnd(i)64 if end < body.count, levels[end] == lvl { item.moveDownDestination = sectionEnd(end) }65 if let style = body[i].paragraph?.style, let n = headingStyles[style] {66 item.styleLevel = n67 item.canPromote = n > 1 && hasStyle(n - 1)68 item.canDemote = n < 9 && hasStyle(n + 1)69 }70 items.append(item)71 }72 if let caretBlock { currentID = items.last { $0.entry.blockIndex <= caretBlock }?.id }73 }74}7576struct OutlinePanel: View {77 @Bindable var session: DocumentSession7879 var body: some View {80 let _ = session.revision81 let _ = session.selectionRevision82 let model = OutlineModel(doc: session.doc, outline: session.numbering.outline,83 caretBlock: session.selection.story == .body ? session.selection.head.path.block : nil)84 let current = model.items.first { $0.id == model.currentID }85 VStack(spacing: 0) {86 SidebarSectionHeader(title: "Outline") {87 if !model.items.isEmpty { Text("\(model.items.count) headings").accessibilityIdentifier("outline-count") }88 }89 .padding(.horizontal, ORIX.Space.m).frame(height: 30)90 if model.items.isEmpty {91 EmptyState(symbol: "list.bullet.indent", title: "No headings yet",92 message: "Give a paragraph a heading style (⌥⌘1, ⌥⌘2 or ⌥⌘3) and it appears here, ready to navigate and reorder.")93 } else {94 ScrollViewReader { proxy in95 ScrollView {96 LazyVStack(alignment: .leading, spacing: 1) {97 ForEach(model.items) { item in98 OutlineRow(item: item, isCurrent: item.id == model.currentID, minLevel: model.items.map(\.entry.level).min() ?? 1,99 select: { session.revealBlock(id: item.id) }, perform: { run($0, on: item) })100 .id(item.id)101 }102 }103 .padding(.horizontal, ORIX.Space.s).padding(.bottom, ORIX.Space.s)104 }105 .onChange(of: model.currentID) { _, id in if let id { withAnimation(ORIX.Motion.quick) { proxy.scrollTo(id) } } }106 }107 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)108 HStack(spacing: 2) {109 ForEach(OutlineAction.allCases) { action in110 BarButton(symbol: action.symbol, help: action.help, isEnabled: current.map { action.isEnabled($0) } ?? false) {111 if let current { run(action, on: current) }112 }113 .accessibilityIdentifier("outline-\(action.rawValue)")114 if action == .moveDown { BarDivider() }115 }116 Spacer(minLength: ORIX.Space.s)117 if let current {118 Text(current.entry.text).font(ORIX.Font.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1).truncationMode(.tail)119 .accessibilityLabel(Text("Current section: \(current.entry.text)"))120 }121 }122 .padding(.horizontal, ORIX.Space.s).frame(height: 32)123 }124 }125 .accessibilityIdentifier("outline-panel")126 }127128 private func run(_ action: OutlineAction, on item: OutlineModel.Item) {129 guard action.isEnabled(item) else { return }130 let block = item.entry.blockIndex131 switch action {132 case .moveUp:133 guard let destination = item.moveUpDestination else { return }134 session.perform(String(localized: "Move Section Up")) { $0.moveSection(startingAt: block, before: destination) }135 case .moveDown:136 guard let destination = item.moveDownDestination else { return }137 session.perform(String(localized: "Move Section Down")) { $0.moveSection(startingAt: block, before: destination) }138 case .promote, .demote:139 guard let level = item.styleLevel else { return }140 let target = StyleID.heading(action == .promote ? level - 1 : level + 1)141 session.perform(action == .promote ? String(localized: "Promote Heading") : String(localized: "Demote Heading")) { e in142 e.selection = Selection(caret: Position(block: block, offset: 0))143 e.setParagraphStyle(target)144 }145 }146 session.canvas?.scrollToCaret(center: true)147 }148}149150enum OutlineAction: String, CaseIterable, Identifiable {151 case moveUp, moveDown, promote, demote152 var id: String { rawValue }153 var symbol: String {154 switch self { case .moveUp: return "arrow.up"; case .moveDown: return "arrow.down"; case .promote: return "decrease.indent"; case .demote: return "increase.indent" }155 }156 var help: LocalizedStringKey {157 switch self {158 case .moveUp: return "Move Section Up"159 case .moveDown: return "Move Section Down"160 case .promote: return "Promote Heading"161 case .demote: return "Demote Heading"162 }163 }164 func isEnabled(_ item: OutlineModel.Item) -> Bool {165 switch self {166 case .moveUp: return item.moveUpDestination != nil167 case .moveDown: return item.moveDownDestination != nil168 case .promote: return item.canPromote169 case .demote: return item.canDemote170 }171 }172}173174private struct OutlineRow: View {175 let item: OutlineModel.Item176 let isCurrent: Bool177 let minLevel: Int178 let select: () -> Void179 let perform: (OutlineAction) -> Void180 @State private var hover = false181182 var body: some View {183 let level = item.entry.level184 let depth = min(5, max(0, level - minLevel))185 Button(action: select) {186 HStack(alignment: .firstTextBaseline, spacing: 6) {187 if let number = item.entry.number {188 Text(number).font(.system(size: 11).monospacedDigit()).foregroundStyle(isCurrent ? ORIX.Palette.accent : ORIX.Palette.textTertiary)189 }190 Text(item.entry.text)191 .font(.system(size: depth == 0 ? 12 : 11.5, weight: depth == 0 ? .semibold : .regular))192 .foregroundStyle(depth <= 1 ? ORIX.Palette.text : ORIX.Palette.textSecondary)193 .lineLimit(2).multilineTextAlignment(.leading)194 Spacer(minLength: 0)195 }196 .padding(.leading, 8 + CGFloat(depth) * 12).padding(.trailing, 6).padding(.vertical, 4)197 .frame(maxWidth: .infinity, alignment: .leading)198 .background(RoundedRectangle(cornerRadius: ORIX.Radius.s).fill(isCurrent ? ORIX.Palette.accent.opacity(0.13) : (hover ? ORIX.Palette.text.opacity(0.06) : .clear)))199 .overlay(alignment: .leading) {200 if isCurrent { RoundedRectangle(cornerRadius: 1).fill(ORIX.Palette.accent).frame(width: 2.5).padding(.vertical, 4) }201 }202 .contentShape(Rectangle())203 }204 .buttonStyle(.plain)205 .onHover { hover = $0 }206 .contextMenu {207 ForEach(OutlineAction.allCases) { action in208 Button { perform(action) } label: { Label(action.help, systemImage: action.symbol) }.disabled(!action.isEnabled(item))209 if action == .moveDown { Divider() }210 }211 }212 .accessibilityLabel(Text(item.entry.number.map { "\($0) \(item.entry.text)" } ?? item.entry.text))213 .accessibilityValue(Text("Level \(level)"))214 .accessibilityAddTraits(isCurrent ? .isSelected : [])215 .accessibilityIdentifier("outline-row-\(item.entry.blockIndex)")216 }217}218