Files
museion/Museion/WorkspaceView.swift
T
AlexKucera de1154dacd
CI / ci (push) Canceled after 0s
feat(editor): drop an image into the prose (#141)
Dragging an image onto a saved post's prose editor copies it (never
moves) into the piece's assets/ under a parser-clean slugged name
(collision -2 via the shared uniqueFile helper) and inserts
![alt](assets/<slug>.<ext>) at the drop point with alt selected for
type-over — one edit step, one undo.

Routing rides the window-level SwiftUI drop destination, field-verified
to starve every deeper drag destination (nested SwiftUI targets never
fire; AppKit NSDraggingDestination overrides never fire). Pure-markdown
sets keep the open-as-guest behavior; mixed md+image sets refuse loudly
instead of silently dropping the images behind the opened markdown.

The drop point comes from NSEvent.mouseLocation mapped through the one
geometry source that answers under SwiftUI hosting —
firstRect(forCharacterRange:), bottom-up screen coords. Non-contiguous
layout returns zero/stale rects for off-screen characters, so the solve
(a pure static function, pinned by windowless tests) samples the
document, keeps only viewport-band rects, brackets the drop between two
in-band samples, binary-searches the bracket, and slides to the next
whitespace gap — a landing never splices inside a word or an existing
ref. The typewriter inset re-syncs after the edit so scrolling never
freezes. The source gate refuses folders and symlinks alike: copyItem
would land the LINK itself, and the #34 publish rail would then refuse
the whole send. Type gate = the rail's exact set (PNG/JPEG/GIF/WebP/
SVG) — nothing enters assets/ that can't ship. Drafts, outlines, and
guest surfaces refuse loudly.

Finish-audit (three fresh-context reviewers) drove the mixed-set
routing, the symlink refusal, and the pure-function extraction; every
pin flip-verified in one batched cycle. Eleven ingest tests; suite 557.

Closes #141
2026-11-02 17:47:35 +01:00

657 lines
22 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// WorkspaceView.swift
// Museion
//
// #17 (S1.1): the workspace shell — nav rail + panes, built from the design
// contract's grid geometry (ref/Web-Prototype/museion-workspace.html):
// rail 56 | library 232 | editor min 420 | mentor 356.
// #108: the Archive rail destination (box icon, above Settings) + the
// New Project ask both live here.
//
import SwiftUI
/// The post-gate main surface. Posts shows the full four-column workspace;
/// Sessions/Learnings/Settings fill the space after the rail until their
/// tickets land (#28/#26; Settings is real here).
struct WorkspaceView: View {
@Environment(AppGateState.self) private var gate
@State private var selection: Pane = .posts
enum Pane: Hashable {
case posts
case sessions
case learnings
/// #32 (S5.2): the trend view — the writer's arc across unaided
/// first-draft captures, sibling of Learnings (measurement beside
/// memory).
case trends
/// #108: the archive rail destination — archive/ as a first-class
/// pane (prototype variant B/C verdict: a destination, not a
/// library disclosure).
case archive
case settings
}
var body: some View {
GeometryReader { geo in
Group {
if gate.isFocused {
// #21: the rail recedes; the pane takes the full width. The
// measure stays centered — revealed panes float, never push.
paneContent(geo)
} else {
HStack(spacing: 0) {
navRail
paneBorder
paneContent(geo)
}
}
}
// #91: drag a markdown file onto the window — same guest slot as
// File ▸ Open… Non-markdown drops are refused.
.dropDestination(for: URL.self) { urls, _ in
// #141: the window destination is the only one that ever
// fires (field-verified 2026-11-02 — nested editor-level
// SwiftUI targets are never consulted, and AppKit views
// registered for file drags are starved by it).
// PURE-markdown sets keep #91's open-as-guest; a mixed
// md+image set falls through and ingestDrop refuses it
// loudly (images must not vanish silently behind the md).
// Nil text view: bounce.
if urls.allSatisfy(PostStore.isMarkdown), let url = urls.first {
gate.posts.openExternal(url)
selection = .posts
return true
}
guard let textView = gate.proseDrop.textView else { return false }
return textView.ingestDrop(urls)
}
// #21: left-edge hover slides rail+library back in as an overlay.
// Library only while the window width allows it (#17 verdict stands:
// a collapsed pane is not summoned by focus).
.overlay {
if gate.isFocused {
// #17 verdict: the library reveal honors the width collapse.
let showsLibrary = geo.size.width >= 1100
FocusOverlayPanel(edge: .leading, panelWidth: leftRevealWidth(showsLibrary)) {
HStack(spacing: 0) {
navRail
paneBorder
if showsLibrary {
PostsLibraryColumn(home: gate.museionHome, model: gate.posts)
}
}
}
}
}
.background(DesignTokens.background)
// #94: the ONE Origin ask per import batch. Dismissal without an
// answer (Esc/Cancel) drops the batch.
.sheet(isPresented: originAskBinding) {
OriginAskSheet(count: gate.posts.pendingImportURLs?.count ?? 0) { origin in
gate.posts.importFiles(origin: origin, home: gate.museionHome)
}
}
// #108: File ▸ New Project… ask — commands can't present sheets, so
// the model stages and this window presents (OriginAsk pattern).
.sheet(isPresented: newProjectAskBinding) {
NewProjectSheet { name in
if let reason = gate.posts.createProject(named: name, home: gate.museionHome) {
return reason
}
gate.posts.newProjectPending(named: name)
return nil
}
}
// #111 (S7): the mixed-content outline guard ask — presents over an
// empty editor (select held the open; nothing can edit while it's
// up). Prose = safe open; Outline = explicit consent to the save
// drop; Esc/Cancel backs out with nothing opened.
.sheet(isPresented: outlineGuardBinding) {
OutlineGuardSheet {
gate.posts.openGuardedOutlineInProse(home: gate.museionHome)
} openAsOutline: {
gate.posts.openGuardedOutlineAsOutline(home: gate.museionHome)
}
}
// #114 (S4): the Convert to Post ask — which body the outline
// piece becomes (verbatim bullets vs headings ladder). Verbatim
// is the default: lossless. Esc/Cancel converts nothing.
.sheet(isPresented: convertAskBinding) {
ConvertSheet(lossy: gate.posts.pendingConversion?.lossy ?? false) { headingsLadder in
gate.posts.convertToPost(headingsLadder: headingsLadder, home: gate.museionHome)
}
}
}
// Collapsed floor: rail 56 + editor placeholder (export ≤920 layout).
.frame(minWidth: 480, minHeight: 320)
// #92/#94: the editor column lives in Posts — a guest buffer or an
// import's opened post surfaces there, whatever pane was showing.
.onChange(of: gate.posts.externalSession != nil) { _, isUp in
if isUp {
selection = .posts
}
}
// #108 audit: ⌘N/New Project open a DRAFT — session is nil, so the
// selectedPostID onChange below can't hop. Hop on the draft itself.
.onChange(of: gate.posts.draft != nil) { _, isDraft in
if isDraft {
selection = .posts
}
}
.onChange(of: gate.posts.selectedPostID) { _, _ in
if gate.posts.session != nil {
selection = .posts
}
}
}
/// #94: the ask presents while a batch is staged.
private var originAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.pendingImportURLs != nil },
set: {
if !$0 {
gate.posts.cancelImport()
}
},
)
}
/// #108: the New Project ask presents while staged.
private var newProjectAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.askNewProject },
set: {
if !$0 {
gate.posts.cancelNewProject()
}
},
)
}
/// #111 (S7): the outline guard ask presents while an open is held.
private var outlineGuardBinding: Binding<Bool> {
Binding(
get: { gate.posts.outlineGuardPieceID != nil },
set: {
if !$0 {
gate.posts.cancelOutlineGuard()
}
},
)
}
/// #114 (S4): the Convert to Post ask — dismissal is the cancel.
private var convertAskBinding: Binding<Bool> {
Binding(
get: { gate.posts.pendingConversion != nil },
set: {
if !$0 {
gate.posts.cancelConversion()
}
},
)
}
@ViewBuilder
private func paneContent(_ geo: GeometryProxy) -> some View {
@Bindable var gate = gate
switch selection {
case .posts:
// #14: mentor column hands in the app-scoped model + gate's winner.
// Column collapse mirrors the export's media queries (library ≤1100,
// mentor ≤920) as macOS pane collapse per the PRD.
PostsPaneView(
home: gate.museionHome,
mentor: gate.mentor,
mentorBinaryPath: gate.gateModel.currentBinaryPath,
model: gate.posts,
availableWidth: geo.size.width - DesignTokens.railWidth,
// #137: the pass bar's missing-key way out (ArchivePaneView
// closure precedent).
onOpenSettings: { selection = .settings },
)
case .sessions:
// #28: the Sessions pane — roster + active transcript over the
// app-scoped mentor model, the same reach as Learnings' home.
SessionsPaneView(
model: gate.mentor,
posts: gate.posts,
binaryPath: gate.gateModel.currentBinaryPath,
home: gate.museionHome,
)
case .learnings:
// #26: list-only pane over <home>/learnings/ — read side;
// promoting a fix card (the fix-card rail) writes the files.
LearningsPaneView(home: gate.museionHome)
case .trends:
// #32 (S5.2): the arc — rides PostsModel's watched scan, so
// the pane refreshes with the library, no scan of its own.
TrendsPaneView(model: gate.posts)
case .archive:
// #108: list-only pane — clicking a row selects the piece and
// hops to Posts where its editor lives.
ArchivePaneView(home: gate.museionHome, model: gate.posts) {
selection = .posts
}
case .settings:
// #137 (S4): a committed Chat model change restarts the resident
// chat engine in place (slice A's engine-side API; deferred to
// turn end while streaming).
SettingsPaneView(
home: $gate.museionHome,
binaryPath: gate.gateModel.currentBinaryPath,
onChatSurfaceWrite: { gate.mentor.requestRestart() },
)
}
}
/// The left reveal panel's width: rail + border (+ library when the
/// unfocused width verdict grants it).
private func leftRevealWidth(_ showsLibrary: Bool) -> CGFloat {
DesignTokens.railWidth + 1 + (showsLibrary ? DesignTokens.libraryWidth : 0)
}
/// 1px contract border between rail and pane (`.rail { border-right }`).
private var paneBorder: some View {
Rectangle()
.fill(DesignTokens.border)
.frame(width: 1)
}
// MARK: Nav rail
private var navRail: some View {
VStack(spacing: 8) {
RailButton(pane: .posts, selection: $selection, label: "Posts", systemImage: "doc.text")
RailButton(pane: .sessions, selection: $selection, label: "Sessions", systemImage: "bubble.left")
RailButton(pane: .learnings, selection: $selection, label: "Learnings", systemImage: "cube")
// #32: Trends after Learnings — measurement beside memory.
RailButton(pane: .trends, selection: $selection, label: "Trends", systemImage: "chart.xyaxis.line")
Spacer()
// #108: Archive at the rail bottom, above Settings (prototype's
// box icon).
RailButton(pane: .archive, selection: $selection, label: "Archive", systemImage: "archivebox")
RailButton(pane: .settings, selection: $selection, label: "Settings", systemImage: "gearshape")
}
.padding(.horizontal, 4)
.padding(.vertical, 8)
.frame(width: DesignTokens.railWidth)
.frame(maxHeight: .infinity)
}
}
/// #108: the Archive pane — archive/ as a rail destination (prototype
/// verdict: a destination, not a library disclosure). List-only: clicking a
/// piece selects it and hops to Posts, where the editor column lives.
private struct ArchivePaneView: View {
let home: URL
var model: PostsModel
/// Fired after a row select — the pane can't reach WorkspaceView's
/// selection itself.
let onOpenPiece: () -> Void
@State private var renamingPost: Post?
/// #108: collapsed project sections — per-view state, not persisted
/// (mirrors the library column).
@State private var collapsed: Set<String> = []
private var archivedByProject: [String: [Post]] {
Dictionary(grouping: model.posts.filter(\.isArchived), by: \.project)
}
/// #108: the prototype's toggle — click the project name (or chevron).
private func toggle(_ project: String) {
if collapsed.contains(project) {
collapsed.remove(project)
} else {
collapsed.insert(project)
}
}
var body: some View {
VStack(spacing: 0) {
// No New button — things arrive here by being moved, not created.
PaneHeader(title: "Archive")
if archivedByProject.isEmpty {
emptyState
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
// #108 audit: Finder order, matching the library's sort.
ForEach(archivedByProject.keys.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, id: \.self) { project in
let pieces = archivedByProject[project] ?? []
// Same section-head shape as the library (#108
// variant B), plus the project-level way out.
HStack(alignment: .firstTextBaseline, spacing: 8) {
Image(systemName: "chevron.down")
.font(.system(size: 9, weight: .semibold))
.rotationEffect(.degrees(collapsed.contains(project) ? -90 : 0))
.foregroundStyle(DesignTokens.muted)
.onTapGesture {
withAnimation { toggle(project) }
}
.accessibilityLabel("Toggle \(project)")
.accessibilityHint(collapsed.contains(project) ? "Collapsed" : "Expanded")
Text(project)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
.textCase(.lowercase) // #108: display-only — the folder name keeps its case
.lineLimit(1)
.truncationMode(.tail)
.onTapGesture {
withAnimation { toggle(project) }
}
Text("· \(pieces.count)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0)
Button("Unarchive") {
model.unarchiveProject(project, home: home)
}
.buttonStyle(.plain)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.help("Move the whole project back to projects/")
.accessibilityLabel("Unarchive \(project)")
}
.padding(.top, 16)
.padding(.horizontal, 14)
.padding(.bottom, 6)
if !collapsed.contains(project) {
ForEach(pieces) { post in
LibraryPostRow(post: post, selected: post.id == model.selectedPostID) {
model.select(post.id, home: home)
onOpenPiece()
}
.contextMenu {
Button("Move Back to \(post.project)") {
model.restorePost(post, home: home)
}
Button("Rename…") { renamingPost = post }
// #114 (S4): works archived too — the piece
// stays where it is, only type + body flip.
if post.type == .outline {
Button("Convert to Post…") {
model.stageConversion(post, home: home)
}
}
}
}
}
}
}
.padding(.bottom, 12)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(DesignTokens.background)
.sheet(item: $renamingPost) { post in
RenamePostSheet(post: post) { title in
model.rename(post, to: title, home: home)
}
}
}
private var emptyState: some View {
VStack(spacing: 8) {
Text("Nothing archived")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Finished projects and pieces fold away here. Move things here from their context menu; they stay openable and editable.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #94: the ONE Origin ask per import batch — writer (default) / ai, with the
/// immutability line (CONTEXT.md: Origin). Answering runs the batch.
private struct OriginAskSheet: View {
let count: Int
let answer: (Post.Origin) -> Void
@Environment(\.dismiss) private var dismiss
@State private var origin: Post.Origin = .writer
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Who wrote this?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text(count == 1
? "Importing 1 file as a Post — the original is untouched."
: "Importing \(count) files as Posts — the originals are untouched.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Picker("Origin", selection: $origin) {
Text("I wrote it (writer)").tag(Post.Origin.writer)
Text("AI-assisted (ai)").tag(Post.Origin.ai)
}
.pickerStyle(.radioGroup)
Text("Origin is stamped once and never asked again — it decides whether the draft's stats can measure you.")
.font(.caption)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Import") {
answer(origin)
dismiss()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 380)
}
}
/// #111 (S7): the mixed-content outline guard ask. The piece has prose
/// lines the outliner can't show — opening it as an outline would drop
/// them on the next save. Prose = nothing drops; Outline = the explicit
/// choice the ruling requires.
private struct OutlineGuardSheet: View {
let openInProse: () -> Void
let openAsOutline: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Open as outline or prose?")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("This outline has paragraph lines between its bullets. The outliner can't show them — opening as an outline drops them on the next save. Prose mode shows everything.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Text("Outline mode keeps its bullets, indentation, and folding. You can convert or clean up later.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelOutlineGuard) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Open as Outline") {
openAsOutline()
}
Button("Open in Prose") {
openInProse()
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 420)
}
}
/// #114 (S4): the Convert to Post ask — which body the piece becomes.
/// Verbatim (default) keeps every line; the ladder re-maps outline levels
/// to headings. On mixed content the ladder would drop prose lines —
/// the sheet says so.
private struct ConvertSheet: View {
let lossy: Bool
/// false = verbatim bullets, true = headings ladder — one decision,
/// one model call.
let convert: (Bool) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Convert to Post")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("The piece keeps its name, project, and Pass State — it becomes a prose post. How should the outline body read?")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
if lossy {
Text("This outline has paragraph lines between its bullets. The headings ladder drops them; verbatim keeps every line.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
Text("Verbatim keeps the bullets as they are; Headings turns top-level blocks into section headings, deeper levels step down.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
HStack {
Spacer()
// Dismissal itself is the cancel (binding set(false) →
// cancelConversion) — Esc and ⌘. land here too.
Button("Cancel", role: .cancel) {}
.keyboardShortcut(.cancelAction)
Button("Headings") {
convert(true)
}
Button("Verbatim Bullets") {
convert(false)
}
.keyboardShortcut(.defaultAction)
}
}
.padding(20)
.frame(width: 440)
}
}
/// #108: New Project ask — the sheet behind File ▸ New Project… (and any
/// future materialize path). Create runs through the model's raw op; the
/// thrown reason is shown inline and the sheet stays up.
private struct NewProjectSheet: View {
/// Create + open a draft in it; nil = success, a string = the failure
/// reason to show inline (keeps the sheet up).
let create: (String) -> String?
@Environment(\.dismiss) private var dismiss
@State private var name = ""
@State private var failure: String?
var body: some View {
VStack(alignment: .leading, spacing: 12) {
Text("New Project")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Pieces land here when it's selected.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
TextField("Name", text: $name)
.textFieldStyle(.roundedBorder)
.onSubmit { confirm() }
if let failure {
Text(failure)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
}
HStack {
Spacer()
Button("Cancel", role: .cancel) { dismiss() }
.keyboardShortcut(.cancelAction)
Button("Create", action: confirm)
.keyboardShortcut(.defaultAction)
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
}
}
.padding(20)
.frame(width: 360)
}
private func confirm() {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
if let reason = create(trimmed) {
failure = reason
} else {
dismiss()
}
}
}
/// Rail button per the export: 44×44 muted icon, hover wash, and the current
/// pane raised as a surface card with a 2px selection bar on the rail's edge.
private struct RailButton: View {
let pane: WorkspaceView.Pane
@Binding var selection: WorkspaceView.Pane
let label: String
let systemImage: String
@State private var hover = false
var body: some View {
let selected = selection == pane
Button {
selection = pane
} label: {
Image(systemName: systemImage)
.frame(width: 44, height: 44)
}
.buttonStyle(.plain)
.foregroundStyle(selected ? DesignTokens.foreground : DesignTokens.muted)
.background {
if selected || hover {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(selected ? DesignTokens.border : .clear),
)
}
}
.overlay(alignment: .leading) {
// Selection bar (`.rail-btn[aria-current]::before`); offset to sit
// on the rail's leading edge like the export's negative inset.
if selected {
Rectangle()
.fill(DesignTokens.foreground)
.frame(width: 2, height: 22)
.offset(x: -6)
}
}
.onHover { hover = $0 }
.help(label)
.accessibilityLabel(label)
}
}
/// Pane-head row per the export (52pt, serif 15 semibold title, bottom border).
/// Trailing slot carries #18's New Post button (export `.pane-head .icon-btn`).
struct PaneHeader<Trailing: View>: View {
let title: String
@ViewBuilder var trailing: () -> Trailing
init(title: String, @ViewBuilder trailing: @escaping () -> Trailing = { EmptyView() }) {
self.title = title
self.trailing = trailing
}
var body: some View {
VStack(spacing: 0) {
HStack {
Text(title)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer()
trailing()
}
.padding(.horizontal, 14)
.frame(minHeight: 52)
Rectangle()
.fill(DesignTokens.border)
.frame(height: 1)
}
}
}