Repository Public
1// ORIX Docs2// File: App/Sources/Workspace/WorkspaceView.swift3// Description: The document window's content: mode bar, format bar, sidebar, ruler, canvas, inspector and status bar.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI8import AppKit9import DocModel1011struct WorkspaceView: View {12 @Bindable var session: DocumentSession1314 var body: some View {15 VStack(spacing: 0) {16 if session.mode != .focus {17 ModeBar(session: session)18 FormatBar(session: session)19 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)20 }21 HStack(spacing: 0) {22 if session.showSidebar && session.mode != .focus {23 SidebarView(session: session)24 .frame(width: 252)25 .transition(.move(edge: .leading))26 Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)27 }28 VStack(spacing: 0) {29 if session.showRuler && session.mode != .focus {30 RulerView(session: session).frame(height: 22)31 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)32 }33 CanvasHost(session: session)34 }35 .frame(minWidth: 320)36 if session.showInspector && session.mode != .focus {37 Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)38 InspectorView(session: session)39 .frame(width: 284)40 .transition(.move(edge: .trailing))41 }42 }43 if session.mode != .focus {44 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)45 StatusBar(session: session)46 }47 }48 .background(ORIX.Palette.chrome)49 .ignoresSafeArea(.container, edges: session.mode == .focus ? .top : [])50 .animation(ORIX.Motion.standard, value: session.showSidebar)51 .animation(ORIX.Motion.standard, value: session.showInspector)52 .sheet(item: $session.activeSheet) { kind in SheetHost(kind: kind, session: session) }53 .overlay(alignment: .topTrailing) {54 if session.mode == .focus {55 Button { session.mode = .writing } label: { Label("Exit Focus", systemImage: "xmark.circle.fill").labelStyle(.iconOnly).font(.system(size: 16)) }56 .buttonStyle(.plain).foregroundStyle(ORIX.Palette.textTertiary).padding(14)57 .help("Exit Focus mode (Esc)")58 }59 }60 }61}6263/// Title-bar row: workspace modes and panel toggles.64struct ModeBar: View {65 @Bindable var session: DocumentSession66 var body: some View {67 HStack(spacing: ORIX.Space.s) {68 Spacer().frame(width: 72) // traffic lights69 BarButton(symbol: "sidebar.left", help: "Sidebar", isOn: session.showSidebar) { session.run(.toggleSidebar) }70 Spacer()71 HStack(spacing: 2) {72 ForEach(WorkspaceMode.allCases) { mode in73 Button { session.mode = mode } label: {74 HStack(spacing: 5) {75 Image(systemName: mode.symbol).font(.system(size: 11, weight: .medium))76 Text(mode.title).font(.system(size: 11.5, weight: session.mode == mode ? .semibold : .regular))77 }78 .padding(.horizontal, 10).padding(.vertical, 4)79 .foregroundStyle(session.mode == mode ? Color.white : ORIX.Palette.textSecondary)80 .background(Capsule().fill(session.mode == mode ? AnyShapeStyle(ORIX.Palette.accentGradient) : AnyShapeStyle(Color.clear)))81 .contentShape(Capsule())82 }83 .buttonStyle(.plain)84 .accessibilityIdentifier("mode-\(mode.rawValue)")85 .accessibilityAddTraits(session.mode == mode ? .isSelected : [])86 }87 }88 .padding(3)89 .background(Capsule().fill(ORIX.Palette.text.opacity(0.06)))90 Spacer()91 if session.doc.settings.trackChanges { Pill(text: String(localized: "Tracking Changes"), color: ORIX.Palette.warning) }92 BarButton(symbol: "sidebar.right", help: "Inspector", isOn: session.showInspector) { session.run(.toggleInspector) }93 }94 .padding(.horizontal, ORIX.Space.m)95 .frame(height: 38)96 .background(WindowDragArea())97 }98}99100/// Lets the user drag the window by the mode bar, as with a regular title bar.101struct WindowDragArea: NSViewRepresentable {102 final class DragView: NSView {103 override var mouseDownCanMoveWindow: Bool { true }104 override func mouseUp(with event: NSEvent) { if event.clickCount == 2 { window?.performZoom(nil) } }105 }106 func makeNSView(context: Context) -> NSView { DragView() }107 func updateNSView(_ nsView: NSView, context: Context) {}108}109110/// Hosts the canvas in a scroll view.111struct CanvasHost: NSViewRepresentable {112 let session: DocumentSession113114 func makeNSView(context: Context) -> NSScrollView {115 let scroll = NSScrollView()116 scroll.hasVerticalScroller = true117 scroll.hasHorizontalScroller = true118 scroll.autohidesScrollers = true119 scroll.drawsBackground = true120 scroll.backgroundColor = ORIX.Palette.canvasNS121 scroll.scrollerStyle = .overlay122 let canvas = EditorCanvasView(session: session)123 scroll.documentView = canvas124 session.canvas = canvas125 scroll.contentView.postsFrameChangedNotifications = true126 context.coordinator.observe(scroll, canvas: canvas)127 DispatchQueue.main.async {128 canvas.recomputeFrames()129 canvas.window?.makeFirstResponder(canvas)130 // A window too narrow for the page at 100 % starts fitted to its width.131 let fit = canvas.zoomToFitWidth()132 if fit < 1, UserDefaults.standard.object(forKey: "ORIXZoom") == nil { session.zoom = max(0.5, (fit * 20).rounded(.down) / 20) }133 }134 return scroll135 }136137 func updateNSView(_ scroll: NSScrollView, context: Context) {}138139 func makeCoordinator() -> Coordinator { Coordinator() }140141 final class Coordinator {142 nonisolated(unsafe) private var token: NSObjectProtocol?143 func observe(_ scroll: NSScrollView, canvas: EditorCanvasView) {144 token = NotificationCenter.default.addObserver(forName: NSView.frameDidChangeNotification, object: scroll.contentView, queue: .main) { [weak canvas] _ in145 MainActor.assumeIsolated { canvas?.recomputeFrames(); canvas?.needsDisplay = true }146 }147 }148 deinit { if let token { NotificationCenter.default.removeObserver(token) } }149 }150}151152struct StatusBar: View {153 @Bindable var session: DocumentSession154 var body: some View {155 let _ = session.selectionRevision156 HStack(spacing: ORIX.Space.m) {157 Text("Page \(session.currentPage + 1) of \(session.layout.pageCount)").accessibilityIdentifier("status-pages")158 Divider().frame(height: 11)159 Text("\(session.statistics.words) words").accessibilityIdentifier("status-words")160 Text("\(session.statistics.characters) characters").foregroundStyle(ORIX.Palette.textTertiary)161 if !session.selection.isCaret {162 let st = DocumentStatistics(text: session.editor.selectedText)163 Text("\(st.words) selected").foregroundStyle(ORIX.Palette.accent)164 }165 if let msg = session.statusMessage {166 Divider().frame(height: 11)167 Text(msg).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1)168 .onAppear { let m = msg; DispatchQueue.main.asyncAfter(deadline: .now() + 6) { if session.statusMessage == m { session.statusMessage = nil } } }169 }170 Spacer()171 if session.document?.isDocumentEdited == true { Text("Edited").foregroundStyle(ORIX.Palette.textTertiary) }172 if !session.importWarnings.isEmpty {173 Button { session.activeSheet = .importWarnings } label: { Label("\(session.importWarnings.count) import notes", systemImage: "exclamationmark.triangle") }174 .buttonStyle(.plain).foregroundStyle(ORIX.Palette.warning)175 }176 Text(session.doc.meta.language.uppercased()).foregroundStyle(ORIX.Palette.textTertiary)177 HStack(spacing: 2) {178 BarButton(symbol: "minus", help: "Zoom Out") { session.run(.zoomOut) }179 Menu {180 ForEach([0.5, 0.75, 1, 1.25, 1.5, 2, 3], id: \.self) { z in Button("\(Int(z * 100)) %") { session.zoom = z } }181 Divider()182 Button("Fit Width") { session.run(.zoomFitWidth) }183 } label: { Text("\(Int((session.zoom * 100).rounded())) %").monospacedDigit().frame(width: 44) }184 .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize()185 BarButton(symbol: "plus", help: "Zoom In") { session.run(.zoomIn) }186 }187 }188 .font(.system(size: 11))189 .foregroundStyle(ORIX.Palette.textSecondary)190 .padding(.horizontal, ORIX.Space.m)191 .frame(height: 26)192 .background(ORIX.Palette.chrome)193 }194}195196/// Horizontal ruler aligned with the page under the caret: margins, column edges, indents and tab stops of the current paragraph.197struct RulerView: View {198 @Bindable var session: DocumentSession199 var body: some View {200 let _ = session.selectionRevision201 let setup = session.doc.setup(ofSection: session.currentSectionIndex)202 let para = session.editor.currentParagraphFormat()203 let cText = ORIX.Palette.text, cSecondary = ORIX.Palette.textSecondary, cTertiary = ORIX.Palette.textTertiary204 let cSurface = ORIX.Palette.surface, cAccent = ORIX.Palette.accent205 let zoomValue = session.zoom206 GeometryReader { geo in207 Canvas { ctx, size in208 let z = zoomValue209 let pageW = setup.pageWidth * z210 let x0 = max(26, (size.width - pageW) / 2)211 let page = CGRect(x: x0, y: 3, width: pageW, height: size.height - 6)212 ctx.fill(Path(roundedRect: page, cornerRadius: 2), with: .color(cText.opacity(0.07)))213 let content = CGRect(x: x0 + setup.margins.left * z, y: 3, width: setup.contentWidth * z, height: size.height - 6)214 ctx.fill(Path(roundedRect: content, cornerRadius: 2), with: .color(cSurface))215 // Ticks every eighth of an inch (or every 5 mm for metric paper), labels on whole units.216 let metric = setup.paper.name.hasPrefix("A") || setup.paper.name.hasPrefix("B")217 let unit: CGFloat = metric ? 72 / 2.54 : 72218 let divisions = metric ? 2 : 8219 var i = 0220 while CGFloat(i) * unit / CGFloat(divisions) * z <= content.width {221 let x = content.minX + CGFloat(i) * unit / CGFloat(divisions) * z222 let major = i % divisions == 0223 let h: CGFloat = major ? 0 : (i % (divisions / 2) == 0 ? 5 : 3)224 if major, i > 0 {225 ctx.draw(Text("\(i / divisions)").font(.system(size: 8)).foregroundStyle(cTertiary), at: CGPoint(x: x, y: size.height / 2))226 } else if !major {227 ctx.fill(Path(CGRect(x: x, y: (size.height - h) / 2, width: 0.5, height: h)), with: .color(cTertiary.opacity(0.7)))228 }229 i += 1230 }231 // Column edges.232 if setup.columns > 1 {233 for c in 1..<setup.columns {234 let gx = content.minX + (CGFloat(c) * (setup.columnWidth + setup.columnGap) - setup.columnGap) * z235 ctx.fill(Path(CGRect(x: gx, y: 3, width: setup.columnGap * z, height: size.height - 6)), with: .color(cText.opacity(0.07)))236 }237 }238 // Indents of the current paragraph.239 func marker(_ x: CGFloat, up: Bool) {240 var p = Path()241 let y: CGFloat = up ? size.height - 3 : 3242 p.move(to: CGPoint(x: x, y: y)); p.addLine(to: CGPoint(x: x - 4, y: y + (up ? -6 : 6))); p.addLine(to: CGPoint(x: x + 4, y: y + (up ? -6 : 6))); p.closeSubpath()243 ctx.fill(p, with: .color(cAccent))244 }245 marker(content.minX + (para.indentLeft + para.firstLineIndent) * z, up: false)246 marker(content.minX + para.indentLeft * z, up: true)247 marker(content.minX + (setup.columnWidth - para.indentRight) * z, up: true)248 for t in para.tabs {249 let x = content.minX + t.position * z250 ctx.draw(Text(t.kind == .right ? "⌟" : (t.kind == .center ? "⊥" : "⌞")).font(.system(size: 9, weight: .bold)).foregroundStyle(cSecondary), at: CGPoint(x: x, y: size.height - 7))251 }252 }253 .frame(width: geo.size.width, height: geo.size.height)254 }255 .background(ORIX.Palette.chrome)256 .accessibilityHidden(true)257 }258}259