Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions apple/Schrodinger/Store/Markdown.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
import Foundation

/// One block of a Markdown text, in reading order. Inline marks (bold, links, code spans…) stay in the text and
/// are read by `Markdown.inline` when the block is drawn.
enum MarkdownBlock: Equatable, Sendable {
enum Marker: Equatable, Sendable { case bullet, number(String), task(done: Bool) }
case heading(level: Int, text: String)
case paragraph(String)
case listItem(depth: Int, marker: Marker, text: String)
case quote(String)
case code(String)
case rule
case table(header: [String], rows: [[String]])
}

/// Reads the Markdown the AI writes its results in: headings, paragraphs, lists (nested, numbered, check boxes),
/// quotes, fenced code, rules and tables. Anything it does not know is kept as a paragraph, so no text is lost.
enum Markdown {
static func blocks(_ source: String) -> [MarkdownBlock] {
let lines = source.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
.components(separatedBy: "\n")
var out: [MarkdownBlock] = []
var para: [String] = []
var indents: [Int] = [] // the indents of the list levels open now
var open = false // the last block can still take another line
var i = 0

func flush() {
if !para.isEmpty { out.append(.paragraph(para.joined(separator: "\n"))); para = [] }
}

while i < lines.count {
let raw = lines[i]
i += 1
let line = raw.trimmingCharacters(in: .whitespaces)
let indent = Self.indent(of: raw)

if let fence = Self.fence(line) {
flush()
var body: [String] = []
while i < lines.count, !lines[i].trimmingCharacters(in: .whitespaces).hasPrefix(fence) { body.append(lines[i]); i += 1 }
i += 1 // the closing fence
out.append(.code(body.joined(separator: "\n")))
indents = []; open = false
continue
}
if line.isEmpty { flush(); open = false; continue }
if let h = Self.heading(line) {
flush(); out.append(h); indents = []; open = false
continue
}
if line.contains("|"), i < lines.count, Self.isTableRule(lines[i]) {
flush()
let header = Self.cells(line)
i += 1
var rows: [[String]] = []
while i < lines.count {
let r = lines[i].trimmingCharacters(in: .whitespaces)
if r.isEmpty || !r.contains("|") { break }
rows.append(Self.cells(r)); i += 1
}
out.append(.table(header: header, rows: rows))
indents = []; open = false
continue
}
// A line of = under a paragraph makes that paragraph a heading.
if !para.isEmpty, line.count >= 2, line.allSatisfy({ $0 == "=" }) {
let text = para.joined(separator: " ")
para = []
out.append(.heading(level: 1, text: text)); indents = []; open = false
continue
}
if Self.isRule(line) {
flush(); out.append(.rule); indents = []; open = false
continue
}
if line.hasPrefix(">") {
flush()
var text = String(line.dropFirst())
if text.hasPrefix(" ") { text.removeFirst() }
if open, case .quote(let before)? = out.last { out[out.count - 1] = .quote(before + "\n" + text) } else { out.append(.quote(text)) }
indents = []; open = true
continue
}
if let item = Self.listItem(line) {
flush()
while let last = indents.last, last > indent { indents.removeLast() }
if indents.last != indent { indents.append(indent) }
out.append(.listItem(depth: indents.count - 1, marker: item.marker, text: item.text))
open = true
continue
}
// An indented line right under a list item goes on with that item.
if open, indent > 0, para.isEmpty, case .listItem(let depth, let marker, let text)? = out.last {
out[out.count - 1] = .listItem(depth: depth, marker: marker, text: text + " " + line)
continue
}
para.append(line); indents = []; open = false
}
flush()
return out
}

/// Bold, italics, code spans, strikethrough and links in one block's text. Line breaks are kept.
static func inline(_ text: String) -> AttributedString {
let options = AttributedString.MarkdownParsingOptions(interpretedSyntax: .inlineOnlyPreservingWhitespace)
return (try? AttributedString(markdown: text, options: options)) ?? AttributedString(text)
}

private static func indent(of raw: String) -> Int {
var n = 0
for c in raw {
if c == " " { n += 1 } else if c == "\t" { n += 4 } else { break }
}
return n
}

private static func fence(_ line: String) -> String? {
if line.hasPrefix("```") { return "```" }
if line.hasPrefix("~~~") { return "~~~" }
return nil
}

private static func heading(_ line: String) -> MarkdownBlock? {
let level = line.prefix(while: { $0 == "#" }).count
guard (1...6).contains(level) else { return nil }
let rest = line.dropFirst(level)
guard rest.isEmpty || rest.first == " " else { return nil }
var text = rest.trimmingCharacters(in: .whitespaces)
if let closing = text.range(of: " #+$", options: .regularExpression) { text.removeSubrange(closing) }
return .heading(level: level, text: text.trimmingCharacters(in: .whitespaces))
}

private static func isRule(_ line: String) -> Bool {
let s = line.filter { $0 != " " }
guard s.count >= 3, let c = s.first, c == "-" || c == "*" || c == "_" else { return false }
return s.allSatisfy { $0 == c }
}

private static func listItem(_ line: String) -> (marker: MarkdownBlock.Marker, text: String)? {
if let first = line.first, first == "-" || first == "*" || first == "+", line.dropFirst().first == " " {
let text = line.dropFirst(2).trimmingCharacters(in: .whitespaces)
if text.hasPrefix("[ ] ") { return (.task(done: false), String(text.dropFirst(4))) }
if text.hasPrefix("[x] ") || text.hasPrefix("[X] ") { return (.task(done: true), String(text.dropFirst(4))) }
return (.bullet, text)
}
let digits = line.prefix(while: { $0 >= "0" && $0 <= "9" })
guard (1...9).contains(digits.count) else { return nil }
let rest = line.dropFirst(digits.count)
guard let mark = rest.first, mark == "." || mark == ")", rest.dropFirst().first == " " else { return nil }
return (.number(String(digits)), rest.dropFirst(2).trimmingCharacters(in: .whitespaces))
}

private static func isTableRule(_ raw: String) -> Bool {
let s = raw.trimmingCharacters(in: .whitespaces)
return s.contains("-") && s.contains("|") && s.allSatisfy { $0 == "-" || $0 == ":" || $0 == "|" || $0 == " " }
}

private static func cells(_ line: String) -> [String] {
var s = line.trimmingCharacters(in: .whitespaces)
if s.hasPrefix("|") { s.removeFirst() }
if s.hasSuffix("|") { s.removeLast() }
return s.components(separatedBy: "|").map { $0.trimmingCharacters(in: .whitespaces) }
}
}
8 changes: 8 additions & 0 deletions apple/Schrodinger/Views/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ final class Selection {
var revealID: UUID? = nil
/// An item with children whose Delete was tapped: the outline asks whether its children go too.
var deleteAskID: UUID? = nil
/// Item whose AI result is shown over the whole window (see ResultViewer).
var resultID: UUID? = nil
/// Show an item from anywhere in the app: switch to the outline and open its info.
func open(_ id: UUID) { panel = .outline; nodeID = id; infoID = id; revealID = id }
}
Expand All @@ -42,6 +44,12 @@ struct ContentView: View {
#if os(iOS)
.shakeToUndo()
#endif
// An AI result, read full-window. The outline underneath takes no keys or taps meanwhile.
.disabled(sel.resultID != nil)
.overlay {
if let id = sel.resultID { ResultViewer(nodeID: id, sel: sel).transition(.opacity) }
}
.animation(.snappy(duration: 0.2), value: sel.resultID)
.sheet(item: Binding(get: { sel.panel == .outline ? nil : sel.panel }, set: { sel.panel = $0 ?? .outline })) { p in
NavigationStack {
panelView(p)
Expand Down
3 changes: 3 additions & 0 deletions apple/Schrodinger/Views/ItemInfo.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ struct ItemSheetBody: View {
}

@State private var copied = false
@Environment(Selection.self) private var sel: Selection?

@ViewBuilder private var content: some View {
if let a = node.artifact, !a.isEmpty {
Expand All @@ -197,6 +198,8 @@ struct ItemSheetBody: View {
.font(PanelPalette.label(.caption2)).foregroundStyle(Color.ink.opacity(0.55))
Spacer(minLength: 8)
// The result, out of the app: copied, opened in the Mac's Markdown app, or sent to any app that takes a file or text.
FieldIcon(systemImage: "arrow.up.left.and.arrow.down.right", width: 34) { sel?.resultID = node.id }
.help("Read full screen").accessibilityLabel("Read result full screen")
FieldIcon(systemImage: copied ? "checkmark" : "doc.on.doc", on: copied, width: 34) { copy(a) }
.help("Copy").accessibilityLabel("Copy result")
#if os(macOS)
Expand Down
1 change: 1 addition & 0 deletions apple/Schrodinger/Views/OutlineView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2022,6 +2022,7 @@ struct NodeRow: View {
ShareLink(item: OutlineText(rootID: node.id), preview: SharePreview(node.title.isEmpty ? "Item" : node.title)) { Label("Share…", systemImage: "square.and.arrow.up") }
// The AI's result on its own, as a Markdown file or text, for any other app.
if let a = node.artifact, !a.isEmpty {
Button { sel.resultID = node.id } label: { Label("Read result", systemImage: "arrow.up.left.and.arrow.down.right") }
ShareLink(item: ResultFile(title: node.title, markdown: a), preview: SharePreview(ResultFile.filename(for: node.title))) { Label("Share result…", systemImage: "doc.text") }
}
Divider()
Expand Down
172 changes: 172 additions & 0 deletions apple/Schrodinger/Views/ResultViewer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import SwiftUI
import SwiftData
#if os(macOS)
import AppKit
#else
import UIKit
#endif

/// An item's AI result, filling the window: the Markdown drawn as a document, under a bar of breadcrumbs that lead
/// back to the outline (the item's parents, then the item, each by name). Opened from the result block in an item's field.
struct ResultViewer: View {
let nodeID: UUID
var sel: Selection
@Environment(\.modelContext) private var ctx
private var store: Store { Store(ctx) }

var body: some View {
let node = store.node(nodeID)
let text = node?.artifact ?? ""
VStack(spacing: 0) {
bar(node, text: text)
Divider()
ScrollView {
MarkdownView(blocks: Markdown.blocks(text))
.frame(maxWidth: 720, alignment: .leading)
.padding(.horizontal, 20).padding(.vertical, 18)
.frame(maxWidth: .infinity)
}
}
.background(Color.canvas.ignoresSafeArea())
.accessibilityAddTraits(.isModal)
.onAppear { Self.endEditing(); if text.isEmpty { close() } }
}

private func close() { sel.resultID = nil }
/// Back to the outline, at one item: the outline shows it and opens its field.
private func go(to id: UUID) { sel.resultID = nil; sel.open(id) }

/// The item's parents, outermost first, then the item.
private func path(_ node: Node?) -> [Node] {
var path: [Node] = []
var p = node
while let x = p, path.count < 64 { path.insert(x, at: 0); p = x.parentID.flatMap { store.node($0) } }
return path
}

private func bar(_ node: Node?, text: String) -> some View {
let crumbs = path(node)
return HStack(spacing: 8) {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 3) {
// The path to the item, by name; the last block is the item itself. Each leads to its place in the outline.
ForEach(Array(crumbs.enumerated()), id: \.element.id) { i, n in
let name = n.title.isEmpty ? "Untitled" : n.title
crumb(name.uppercased(), systemImage: i == 0 ? "chevron.left" : nil, fill: [PanelPalette.lavender, PanelPalette.periwinkle, PanelPalette.rose][i % 3]) { go(to: n.id) }
.accessibilityLabel("Back to \(name)")
}
// Where you are: not a button.
crumbLabel("RESULT", systemImage: nil, fill: PanelPalette.peach).accessibilityAddTraits(.isHeader)
}
}
.defaultScrollAnchor(.trailing)
if !text.isEmpty {
ShareLink(item: ResultFile(title: node?.title ?? "", markdown: text), preview: SharePreview(ResultFile.filename(for: node?.title ?? ""))) {
Image(systemName: "square.and.arrow.up").font(.system(size: 15, weight: .medium)).foregroundStyle(Color.ink.opacity(0.6))
.frame(width: 34, height: 34).contentShape(Rectangle())
}
.help("Share or open in another app").accessibilityLabel("Share result")
}
Button { if let node { go(to: node.id) } else { close() } } label: {
Image(systemName: "xmark").font(.system(size: 15, weight: .medium)).foregroundStyle(Color.ink.opacity(0.6))
.frame(width: 34, height: 34).contentShape(Rectangle())
}
.keyboardShortcut(.cancelAction)
.help("Close (Esc)").accessibilityLabel("Close result")
}
.buttonStyle(.plain)
.padding(.leading, StatusBar.margin).padding(.trailing, 8).padding(.vertical, 6)
.background(Color.canvas)
}

private func crumb(_ title: String, systemImage: String? = nil, fill: Color, action: @escaping () -> Void) -> some View {
Button(action: action) { crumbLabel(title, systemImage: systemImage, fill: fill) }
}

private func crumbLabel(_ title: String, systemImage: String?, fill: Color) -> some View {
HStack(spacing: 4) {
if let systemImage { Image(systemName: systemImage).font(.system(size: 10, weight: .heavy)) }
Text(title).font(PanelPalette.label(.caption)).lineLimit(1).truncationMode(.tail)
}
.foregroundStyle(PanelPalette.text(on: fill))
.padding(.horizontal, 8).frame(maxWidth: 180).frame(height: 28)
.background(fill)
.contentShape(Rectangle())
}

/// Ends any typing in the outline underneath (and puts the keyboard away).
private static func endEditing() {
#if os(iOS)
UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
#else
NSApp.keyWindow?.makeFirstResponder(nil)
#endif
}
}

/// Markdown blocks drawn as a document, in the app's font.
struct MarkdownView: View {
let blocks: [MarkdownBlock]

var body: some View {
VStack(alignment: .leading, spacing: 9) {
ForEach(Array(blocks.enumerated()), id: \.offset) { _, block in row(block) }
}
.foregroundStyle(Color.ink)
.textSelection(.enabled)
}

private func face(_ style: Font.TextStyle, weight: Font.Weight = .regular) -> Font { Appearance.shared.font.font(style, weight: weight) }

@ViewBuilder private func row(_ block: MarkdownBlock) -> some View {
switch block {
case .heading(let level, let text):
Text(Markdown.inline(text))
.font(face(level == 1 ? .title : level == 2 ? .title2 : level == 3 ? .title3 : .headline, weight: .bold))
.padding(.top, level <= 2 ? 8 : 3)
.accessibilityAddTraits(.isHeader)
case .paragraph(let text):
Text(Markdown.inline(text))
case .listItem(let depth, let marker, let text):
HStack(alignment: .firstTextBaseline, spacing: 8) {
mark(marker).frame(minWidth: 18, alignment: .trailing)
Text(Markdown.inline(text))
}
.padding(.leading, CGFloat(depth) * 20)
case .quote(let text):
Text(Markdown.inline(text)).foregroundStyle(Color.ink.opacity(0.7))
.padding(.leading, 12)
.overlay(alignment: .leading) { Rectangle().fill(Color.ink.opacity(0.25)).frame(width: 3) }
case .code(let text):
ScrollView(.horizontal, showsIndicators: false) {
Text(text).font(.system(.callout, design: .monospaced)).padding(10)
}
.frame(maxWidth: .infinity, alignment: .leading)
.background(PanelPalette.field, in: RoundedRectangle(cornerRadius: 6))
case .rule:
Divider().padding(.vertical, 4)
case .table(let header, let rows):
ScrollView(.horizontal, showsIndicators: false) {
Grid(alignment: .leading, horizontalSpacing: 18, verticalSpacing: 7) {
GridRow {
ForEach(Array(header.enumerated()), id: \.offset) { _, cell in Text(Markdown.inline(cell)).fontWeight(.semibold) }
}
Divider()
ForEach(Array(rows.enumerated()), id: \.offset) { _, cells in
GridRow {
ForEach(Array(cells.enumerated()), id: \.offset) { _, cell in Text(Markdown.inline(cell)) }
}
}
}
}
}
}

@ViewBuilder private func mark(_ marker: MarkdownBlock.Marker) -> some View {
switch marker {
case .bullet: Text("\u{2022}")
case .number(let n): Text(n + ".").monospacedDigit()
case .task(let done): Image(systemName: done ? "checkmark.square" : "square").accessibilityLabel(done ? "Done" : "Not done")
}
}
}
Loading