Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Browser9// File : SPBrowser/Shared/Aura/Features/CanvasBoardView.swift10// Module : SPBrowser11// Repository : https://git.spboucher.ai/sp-browser12// Created : 2026-11-1913// Last Modified : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : None specified (no license file in this repository)80// Maintainer : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import SwiftUI88import UniformTypeIdentifiers8990/// State of the canvas being shown: the board, the viewport and the selection. Edits are saved (debounced) to the store.91@MainActor92@Observable93final class CanvasController {94 @ObservationIgnored let store: CanvasStore95 @ObservationIgnored var onChange: (() -> Void)?96 private(set) var board: CanvasBoard97 private(set) var boards: [CanvasBoard] = []98 var viewport = AuraViewport()99 var selection = Set<UUID>()100 var editing: UUID?101 /// When set, the next card tapped is connected to this one.102 var connectingFrom: UUID?103 var guides = CanvasBoard.Snap(origin: .zero)104 var query = ""105 @ObservationIgnored private var saveTask: Task<Void, Never>?106107 init(store: CanvasStore) {108 self.store = store109 let all = store.boards110 board = all.first ?? store.create(name: L("My canvas"))111 boards = store.boards112 }113114 func reload() {115 boards = store.boards116 if let fresh = store.board(board.id) { board = fresh } else if let first = boards.first { board = first } else { board = store.create(name: L("My canvas")); boards = store.boards }117 }118119 func open(_ id: UUID) {120 flush()121 guard let next = store.board(id) else { return }122 board = next123 selection = []; editing = nil; connectingFrom = nil124 viewport = AuraViewport()125 }126127 func newBoard(name: String = "") { flush(); board = store.create(name: name); boards = store.boards; selection = []; viewport = AuraViewport() }128129 func rename(_ name: String) { mutate { $0.name = name.trimmingCharacters(in: .whitespaces).isEmpty ? $0.name : name } }130131 func deleteCurrentBoard() {132 saveTask?.cancel()133 store.delete(board.id)134 boards = store.boards135 board = boards.first ?? store.create(name: L("My canvas"))136 boards = store.boards137 selection = []138 onChange?()139 }140141 func setSynced(_ value: Bool) { mutate { $0.isSynced = value }; flush() }142143 /// Applies an edit and schedules a save.144 func mutate(_ body: (inout CanvasBoard) -> Void) {145 body(&board)146 board.modifiedAt = Date()147 saveTask?.cancel()148 saveTask = Task { [weak self] in149 try? await Task.sleep(for: .milliseconds(450))150 guard !Task.isCancelled else { return }151 self?.flush()152 }153 }154155 func flush() {156 saveTask?.cancel()157 store.save(board)158 boards = store.boards159 onChange?()160 }161162 @discardableResult163 func add(_ kind: CanvasCard.Kind, title: String = "", text: String = "", url: String? = nil, asset: String? = nil, at point: CGPoint? = nil) -> CanvasCard? {164 var created: CanvasCard?165 mutate { created = $0.add(kind, title: title, text: text, url: url, asset: asset, at: point) }166 if let created { selection = [created.id] }167 return created168 }169170 /// Text that was dropped or pasted: an address becomes a link card, anything else an excerpt.171 func addDropped(_ text: String, at point: CGPoint? = nil) {172 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)173 guard !trimmed.isEmpty else { return }174 if let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https", !trimmed.contains(" ") {175 add(url.pathExtension.lowercased() == "pdf" ? .pdf : .link, title: url.host ?? trimmed, url: trimmed, at: point)176 } else {177 add(.text, text: trimmed, at: point)178 }179 }180181 func addImage(_ data: Data, title: String = "", kind: CanvasCard.Kind = .image, url: String? = nil, at point: CGPoint? = nil) {182 guard let asset = store.storeAsset(data, board: board.id) else { return }183 add(kind, title: title, url: url, asset: asset, at: point)184 }185186 func removeSelection() {187 let ids = selection188 guard !ids.isEmpty else { return }189 mutate { $0.remove(ids) }190 selection = []191 }192193 func tapCard(_ id: UUID, extend: Bool) {194 if let from = connectingFrom {195 if from != id { mutate { $0.toggleConnection(from, id) }; AuraHaptics.play(.snap) }196 connectingFrom = nil197 return198 }199 if extend { if selection.contains(id) { selection.remove(id) } else { selection.insert(id) } } else { selection = [id] }200 }201202 /// World point shown at the centre of the view.203 func worldCenter() -> CGPoint { CGPoint(x: -viewport.offset.width / viewport.scale, y: -viewport.offset.height / viewport.scale) }204205 func fit(in size: CGSize) {206 guard let box = board.contentBounds, box.width > 0 else { viewport = AuraViewport(); return }207 let scale = CGFloat(CanvasBoard.clampZoom(Double(min((size.width - 120) / box.width, (size.height - 160) / box.height, 1.2))))208 viewport = AuraViewport(scale: scale, offset: CGSize(width: -box.midX * scale, height: -box.midY * scale))209 }210}211212/// What the browser offers the canvas: the page in front, a way to open links, an optional capture, and export.213struct CanvasHost {214 var currentPage: () -> (title: String, url: String)?215 var open: (URL) -> Void216 /// PNG of the visible page; only called from the explicit "Capture" action.217 var capture: (() async -> Data?)?218 var export: (_ markdown: String, _ name: String) -> Void219 var canSync: Bool220 var dismiss: () -> Void221}222223/// AURA Canvas: an endless board of cards. Full canvas on Mac and iPad; on iPhone a vertical list of cards with the map one tap away.224struct CanvasBoardView: View {225 @Bindable var controller: CanvasController226 let host: CanvasHost227 @Environment(\.horizontalSizeClass) private var sizeClass228 @Environment(\.auraPolicy) private var policy229 @State private var showsMapOnPhone = false230 @State private var renaming = false231 @State private var nameDraft = ""232 @State private var confirmingDelete = false233234 private var compact: Bool { sizeClass == .compact }235 private static let zoomRange: ClosedRange<CGFloat> = CGFloat(CanvasBoard.zoomRange.lowerBound)...CGFloat(CanvasBoard.zoomRange.upperBound)236237 var body: some View {238 VStack(spacing: 0) {239 header240 Rectangle().fill(Aura.Palette.hairline).frame(height: 1)241 if compact && !showsMapOnPhone { CanvasCardList(controller: controller, host: host) } else { surface }242 }243 .background(Aura.Palette.surface)244 .alert(L("Rename canvas"), isPresented: $renaming) {245 TextField(L("Name"), text: $nameDraft)246 Button(L("Rename")) { controller.rename(nameDraft); controller.flush() }247 Button(L("Cancel"), role: .cancel) {}248 }249 .confirmationDialog(L("Delete “%@”?", controller.board.name), isPresented: $confirmingDelete, titleVisibility: .visible) {250 Button(L("Delete Canvas"), role: .destructive) { controller.deleteCurrentBoard() }251 Button(L("Cancel"), role: .cancel) {}252 } message: { Text(L("Its %d cards and their images will be removed from this device.", controller.board.cards.count)) }253 .onDisappear { controller.flush() }254 .accessibilityIdentifier("canvas")255 }256257 // MARK: Header258259 private var header: some View {260 HStack(spacing: 8) {261 Menu {262 ForEach(controller.boards) { board in263 Button { controller.open(board.id) } label: { Label(board.name, systemImage: board.id == controller.board.id ? "checkmark" : "rectangle.3.group") }264 }265 Divider()266 Button { controller.newBoard() } label: { Label(L("New Canvas"), systemImage: "plus") }267 Button { nameDraft = controller.board.name; renaming = true } label: { Label(L("Rename…"), systemImage: "pencil") }268 if host.canSync {269 Button { controller.setSynced(!controller.board.isSynced) } label: {270 Label(controller.board.isSynced ? L("Stop Synchronizing This Canvas") : L("Synchronize This Canvas"), systemImage: "arrow.triangle.2.circlepath")271 }272 }273 Button { host.export(controller.board.markdown(), controller.board.name) } label: { Label(L("Export as Markdown…"), systemImage: "square.and.arrow.up") }274 Divider()275 Button(role: .destructive) { confirmingDelete = true } label: { Label(L("Delete Canvas…"), systemImage: "trash") }276 } label: {277 HStack(spacing: 6) {278 Image(systemName: "rectangle.3.group").foregroundStyle(Aura.gradient)279 Text(controller.board.name).font(.headline).lineLimit(1)280 if controller.board.isSynced { Image(systemName: "arrow.triangle.2.circlepath").font(.caption).foregroundStyle(.secondary).accessibilityLabel(L("Synchronized")) }281 Image(systemName: "chevron.down").font(.caption2.weight(.bold)).foregroundStyle(.secondary)282 }283 .contentShape(Rectangle())284 }285 .menuStyle(.borderlessButton).fixedSize()286 .accessibilityIdentifier("canvas-board-menu")287 Spacer(minLength: 4)288 if !compact {289 AuraSearchField(text: $controller.query, placeholder: L("Search cards"), height: 30, fontSize: 13, identifier: "canvas-search").frame(width: 190)290 } else {291 AuraIconButton(symbol: showsMapOnPhone ? "list.bullet" : "map", label: showsMapOnPhone ? L("Show as List") : L("Show as Canvas"), isActive: showsMapOnPhone) {292 AuraMotion.perform(.expressive) { showsMapOnPhone.toggle() }293 }294 }295 addMenu296 Button(L("Done")) { controller.flush(); host.dismiss() }.keyboardShortcut(.cancelAction).accessibilityIdentifier("canvas-done")297 }298 .padding(.horizontal, 14).padding(.vertical, 9)299 }300301 private var addMenu: some View {302 Menu {303 Button { controller.add(.note, at: compact ? nil : controller.worldCenter()); if let id = controller.selection.first { controller.editing = id } } label: { Label(L("Note"), systemImage: "note.text") }304 if let page = host.currentPage() {305 Button { controller.add(page.url.lowercased().hasSuffix(".pdf") ? .pdf : .tab, title: page.title, url: page.url, at: compact ? nil : controller.worldCenter()) } label: { Label(L("Current Page"), systemImage: "globe") }306 if let capture = host.capture {307 Button {308 Task { if let data = await capture() { controller.addImage(data, title: page.title, kind: .capture, url: page.url, at: compact ? nil : controller.worldCenter()) } }309 } label: { Label(L("Capture of Current Page"), systemImage: "camera.viewfinder") }310 }311 }312 Button { if let text = PlatformActions.pasteboardString() { controller.addDropped(text, at: compact ? nil : controller.worldCenter()) } } label: { Label(L("Paste Link or Text"), systemImage: "doc.on.clipboard") }313 } label: {314 Label(L("Add"), systemImage: "plus").labelStyle(.titleAndIcon)315 }316 .menuStyle(.borderlessButton).fixedSize()317 .accessibilityIdentifier("canvas-add")318 }319320 // MARK: Surface321322 private func screen(_ point: CGPoint, _ size: CGSize) -> CGPoint {323 CGPoint(x: size.width / 2 + point.x * controller.viewport.scale + controller.viewport.offset.width,324 y: size.height / 2 + point.y * controller.viewport.scale + controller.viewport.offset.height)325 }326327 private func world(_ point: CGPoint, _ size: CGSize) -> CGPoint {328 CGPoint(x: (point.x - size.width / 2 - controller.viewport.offset.width) / controller.viewport.scale,329 y: (point.y - size.height / 2 - controller.viewport.offset.height) / controller.viewport.scale)330 }331332 private var surface: some View {333 GeometryReader { proxy in334 let size = proxy.size335 let found = Set(controller.board.search(controller.query).map(\.id))336 ZStack {337 AuraGrid(viewport: controller.viewport)338 Color.clear.contentShape(Rectangle())339 .gesture(SpatialTapGesture(count: 2).onEnded { value in340 controller.add(.note, at: world(value.location, size))341 controller.editing = controller.selection.first342 })343 .simultaneousGesture(TapGesture().onEnded { controller.selection = []; controller.editing = nil; controller.connectingFrom = nil })344 .gesture(DragGesture(minimumDistance: 4).onChanged { controller.viewport.pan(by: $0.translation) }.onEnded { _ in controller.viewport.endPan() })345 links(size)346 ForEach(controller.board.groups) { group in347 if let frame = controller.board.bounds(ofGroup: group.id) { groupFrame(group, frame, size) }348 }349 ForEach(controller.board.cards) { card in350 CanvasCardView(card: card, controller: controller, host: host, scale: controller.viewport.scale,351 isDimmed: !controller.query.isEmpty && !found.contains(card.id),352 image: controller.store.assetURL(card.asset, board: controller.board.id))353 .frame(width: card.width, height: card.height)354 .scaleEffect(controller.viewport.scale)355 .position(screen(card.center, size))356 .zIndex(controller.selection.contains(card.id) ? 5 : 1)357 }358 guideLines(size)359 VStack { Spacer(); bottomBar(size) }.padding(12)360 if controller.board.cards.isEmpty {361 AuraEmptyState(symbol: "rectangle.3.group", title: L("An empty canvas"),362 message: L("Drop links, text and images here, add the current page, or double-click anywhere to write a note."))363 .allowsHitTesting(false)364 }365 }366 .clipped()367 .simultaneousGesture(MagnifyGesture().onChanged { controller.viewport.zoom(by: $0.magnification, range: Self.zoomRange) }.onEnded { _ in controller.viewport.endZoom() })368 .onScrollWheel { delta, zooming in369 if zooming { controller.viewport.step(delta.height > 0 ? 1.05 : 0.95, range: Self.zoomRange) }370 else { controller.viewport.offset.width += delta.width; controller.viewport.offset.height += delta.height }371 }372 .dropDestination(for: URL.self) { urls, location in373 for (index, url) in urls.enumerated() {374 let point = world(CGPoint(x: location.x + CGFloat(index) * 24, y: location.y + CGFloat(index) * 24), size)375 if url.isFileURL, let data = try? Data(contentsOf: url), PlatformImage(data: data) != nil { controller.addImage(data, title: url.lastPathComponent, at: point) }376 else if !url.isFileURL { controller.addDropped(url.absoluteString, at: point) }377 }378 return !urls.isEmpty379 }380 .dropDestination(for: String.self) { items, location in381 for item in items { controller.addDropped(item, at: world(location, size)) }382 return !items.isEmpty383 }384 .dropDestination(for: Data.self) { items, location in385 for data in items where PlatformImage(data: data) != nil { controller.addImage(data, at: world(location, size)) }386 return !items.isEmpty387 }388 .onAppear { if controller.viewport == AuraViewport(), !controller.board.cards.isEmpty { controller.fit(in: size) } }389 .focusable().focusEffectDisabled()390 .onKeyPress(.delete) { guard controller.editing == nil else { return .ignored }; controller.removeSelection(); return .handled }391 .onKeyPress(.escape) {392 if controller.editing != nil { controller.editing = nil; return .handled }393 if controller.connectingFrom != nil { controller.connectingFrom = nil; return .handled }394 if !controller.selection.isEmpty { controller.selection = []; return .handled }395 return .ignored396 }397 }398 }399400 private func links(_ size: CGSize) -> some View {401 Canvas(opaque: false, rendersAsynchronously: false) { context, _ in402 for connection in controller.board.connections {403 guard let a = controller.board.card(connection.from), let b = controller.board.card(connection.to) else { continue }404 let start = screen(a.center, size), end = screen(b.center, size)405 var path = Path()406 path.move(to: start)407 let bend = (end.x - start.x) * 0.4408 path.addCurve(to: end, control1: CGPoint(x: start.x + bend, y: start.y), control2: CGPoint(x: end.x - bend, y: end.y))409 context.stroke(path, with: .linearGradient(Gradient(colors: [Aura.Palette.violet.opacity(0.8), Aura.Palette.cyan.opacity(0.8)]), startPoint: start, endPoint: end),410 style: StrokeStyle(lineWidth: max(1.2, 2 * controller.viewport.scale), lineCap: .round))411 }412 }413 .allowsHitTesting(false)414 .accessibilityHidden(true)415 }416417 private func groupFrame(_ group: CanvasGroup, _ frame: CGRect, _ size: CGSize) -> some View {418 let color = Aura.Palette.identity(group.colorIndex)419 let scale = controller.viewport.scale420 return RoundedRectangle(cornerRadius: 18 * scale, style: .continuous)421 .fill(color.opacity(0.07))422 .overlay(RoundedRectangle(cornerRadius: 18 * scale, style: .continuous).strokeBorder(color.opacity(0.45), style: StrokeStyle(lineWidth: 1.2, dash: [6, 4])))423 .overlay(alignment: .topLeading) {424 AuraChip(text: group.name, symbol: "square.on.square.dashed", tint: color).padding(6).opacity(scale > 0.45 ? 1 : 0)425 .contextMenu { Button(L("Ungroup")) { controller.mutate { $0.ungroup(group.id) } } }426 }427 .frame(width: frame.width * scale, height: frame.height * scale)428 .position(screen(CGPoint(x: frame.midX, y: frame.midY), size))429 .allowsHitTesting(scale > 0.45)430 }431432 private func guideLines(_ size: CGSize) -> some View {433 Canvas { context, canvasSize in434 for x in controller.guides.verticalGuides {435 let sx = screen(CGPoint(x: x, y: 0), size).x436 var path = Path(); path.move(to: CGPoint(x: sx, y: 0)); path.addLine(to: CGPoint(x: sx, y: canvasSize.height))437 context.stroke(path, with: .color(Aura.Palette.cyan.opacity(0.8)), style: StrokeStyle(lineWidth: 1, dash: [4, 3]))438 }439 for y in controller.guides.horizontalGuides {440 let sy = screen(CGPoint(x: 0, y: y), size).y441 var path = Path(); path.move(to: CGPoint(x: 0, y: sy)); path.addLine(to: CGPoint(x: canvasSize.width, y: sy))442 context.stroke(path, with: .color(Aura.Palette.cyan.opacity(0.8)), style: StrokeStyle(lineWidth: 1, dash: [4, 3]))443 }444 }445 .allowsHitTesting(false)446 .accessibilityHidden(true)447 }448449 private func bottomBar(_ size: CGSize) -> some View {450 HStack(spacing: 6) {451 if let from = controller.connectingFrom, let card = controller.board.card(from) {452 Label(L("Tap a card to connect it to “%@”", card.title.isEmpty ? L("this card") : card.title), systemImage: "point.topleft.down.to.point.bottomright.curvepath").font(.callout).lineLimit(1)453 Button(L("Cancel")) { controller.connectingFrom = nil }.buttonStyle(.bordered)454 } else if !controller.selection.isEmpty {455 Text(L("%d selected", controller.selection.count)).font(.callout.weight(.medium)).padding(.horizontal, 6)456 if controller.selection.count == 1, let id = controller.selection.first {457 AuraIconButton(symbol: "point.topleft.down.to.point.bottomright.curvepath", label: L("Connect to Another Card")) { controller.connectingFrom = id }458 }459 if controller.selection.count > 1 {460 AuraIconButton(symbol: "square.on.square.dashed", label: L("Group Selection")) {461 let ids = controller.selection462 controller.mutate { $0.group(ids, name: L("Group %d", $0.groups.count + 1)) }463 }464 }465 AuraIconButton(symbol: "trash", label: L("Delete Selection"), tint: .red) { AuraMotion.perform(.standard) { controller.removeSelection() } }466 }467 if controller.connectingFrom == nil {468 if !controller.selection.isEmpty { Rectangle().fill(Aura.Palette.hairline).frame(width: 1, height: 18).padding(.horizontal, 2) }469 AuraIconButton(symbol: "minus", label: L("Zoom Out")) { AuraMotion.perform(.standard) { controller.viewport.step(0.8, range: Self.zoomRange) } }470 Text("\(Int((controller.viewport.scale * 100).rounded())) %").font(.caption.monospacedDigit()).frame(width: 44)471 .accessibilityLabel(L("Zoom")).accessibilityValue("\(Int((controller.viewport.scale * 100).rounded())) %")472 AuraIconButton(symbol: "plus", label: L("Zoom In")) { AuraMotion.perform(.standard) { controller.viewport.step(1.25, range: Self.zoomRange) } }473 AuraIconButton(symbol: "arrow.up.left.and.arrow.down.right", label: L("Fit Canvas")) { AuraMotion.perform(.expressive) { controller.fit(in: size) } }474 }475 }476 .padding(.horizontal, 8).padding(.vertical, 5)477 .auraSurface(.floating, radius: 20)478 .animation(AuraMotion.animation(.spring, policy: policy), value: controller.selection.count)479 }480}481482/// One card on the canvas. It follows the pointer while dragged and snaps magnetically to its neighbours.483private struct CanvasCardView: View {484 let card: CanvasCard485 let controller: CanvasController486 let host: CanvasHost487 let scale: CGFloat488 let isDimmed: Bool489 let image: URL?490 @State private var dragStart: [UUID: CGPoint]?491 @State private var hovering = false492 @FocusState private var editorFocused: Bool493494 private var isSelected: Bool { controller.selection.contains(card.id) }495 private var isEditing: Bool { controller.editing == card.id }496 private var tint: Color { card.kind == .note ? Aura.Palette.identity(card.colorIndex + 2) : Aura.Palette.cyan }497498 var body: some View {499 content500 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)501 .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(card.kind == .note ? AnyShapeStyle(tint.opacity(0.16)) : AnyShapeStyle(Aura.Palette.card)))502 .auraSurface(.panel, radius: 14, luminous: isSelected || controller.connectingFrom == card.id)503 .opacity(isDimmed ? 0.25 : 1)504 .scaleEffect(hovering && dragStart == nil ? 1.015 : 1)505 .animation(AuraMotion.animation(.quick), value: hovering)506 .onHover { hovering = $0 }507 .onTapGesture(count: 2) { if card.kind == .note || card.kind == .text { controller.selection = [card.id]; controller.editing = card.id } else if let url = card.url.flatMap(URL.init(string:)) { host.open(url) } }508 .onTapGesture { controller.tapCard(card.id, extend: PlatformActions.isExtendingSelection) }509 .gesture(drag)510 .contextMenu { menu }511 .accessibilityElement(children: .combine)512 .accessibilityLabel(card.title.isEmpty ? (card.text.isEmpty ? (card.url ?? L("Card")) : card.text) : card.title)513 .accessibilityAddTraits(isSelected ? .isSelected : [])514 .accessibilityIdentifier("canvas-card")515 }516517 @ViewBuilder private var content: some View {518 switch card.kind {519 case .note, .text:520 VStack(alignment: .leading, spacing: 4) {521 if card.kind == .text { Image(systemName: "text.quote").font(.caption).foregroundStyle(.secondary) }522 if isEditing {523 TextEditor(text: Binding(get: { controller.board.card(card.id)?.text ?? "" }, set: { text in controller.mutate { board in if var c = board.card(card.id) { c.text = text; board.update(c) } } }))524 .font(.system(size: 13)).scrollContentBackground(.hidden).focused($editorFocused)525 .onAppear { editorFocused = true }526 } else {527 Text(card.text.isEmpty ? L("Double-click to write") : card.text).font(.system(size: 13)).foregroundStyle(card.text.isEmpty ? .tertiary : .primary)528 .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)529 }530 if let url = card.url, !isEditing { Text(URL(string: url)?.host ?? url).font(.caption2).foregroundStyle(.secondary).lineLimit(1) }531 }532 .padding(10)533 case .image, .capture:534 ZStack(alignment: .bottomLeading) {535 if let image, let loaded = PlatformImage(contentsOfFile: image.path) {536 Image(platformImage: loaded).resizable().aspectRatio(contentMode: .fill).frame(maxWidth: .infinity, maxHeight: .infinity).clipped()537 } else {538 VStack(spacing: 4) {539 Image(systemName: "photo").font(.title2).foregroundStyle(.tertiary)540 Text(L("Image kept on the device that added it")).font(.caption2).foregroundStyle(.secondary).multilineTextAlignment(.center)541 }542 .frame(maxWidth: .infinity, maxHeight: .infinity)543 }544 if !card.title.isEmpty {545 Text(card.title).font(.caption.weight(.medium)).lineLimit(1).padding(.horizontal, 8).padding(.vertical, 4)546 .background(.ultraThinMaterial, in: Capsule()).padding(6)547 }548 }549 .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))550 case .link, .tab, .pdf, .reference:551 HStack(alignment: .top, spacing: 10) {552 Image(systemName: card.kind == .pdf ? "doc.richtext" : (card.kind == .reference ? "quote.opening" : "globe"))553 .font(.system(size: 13, weight: .semibold)).foregroundStyle(Aura.Palette.accent)554 .frame(width: 28, height: 28).background(Circle().fill(Aura.Palette.accent.opacity(0.14)))555 VStack(alignment: .leading, spacing: 2) {556 Text(card.title.isEmpty ? (card.url ?? "") : card.title).font(.system(size: 13, weight: .medium)).lineLimit(2)557 Text(card.host).font(.caption).foregroundStyle(.secondary).lineLimit(1)558 if !card.text.isEmpty { Text(card.text).font(.caption).foregroundStyle(.secondary).lineLimit(2) }559 }560 Spacer(minLength: 0)561 }562 .padding(10)563 }564 }565566 @ViewBuilder private var menu: some View {567 if let url = card.url.flatMap(URL.init(string:)) {568 Button(L("Open")) { host.open(url) }569 Button(L("Copy Link")) { PlatformActions.copy(url.absoluteString) }570 }571 if card.kind == .note || card.kind == .text { Button(L("Edit")) { controller.selection = [card.id]; controller.editing = card.id } }572 Button(L("Connect to Another Card")) { controller.connectingFrom = card.id }573 if card.kind == .note {574 Menu(L("Colour")) {575 ForEach(0..<6, id: \.self) { index in Button(L("Colour %d", index + 1)) { controller.mutate { board in if var c = board.card(card.id) { c.colorIndex = index; board.update(c) } } } }576 }577 }578 if let groupID = card.groupID { Button(L("Remove from Group")) { controller.mutate { board in if var c = board.card(card.id) { c.groupID = nil; board.update(c) }; if !board.cards.contains(where: { $0.groupID == groupID }) { board.ungroup(groupID) } } } }579 Divider()580 Button(L("Delete"), role: .destructive) { controller.mutate { $0.remove([card.id]) }; controller.selection.remove(card.id) }581 }582583 private var drag: some Gesture {584 DragGesture(minimumDistance: 4, coordinateSpace: .global)585 .onChanged { value in586 guard !isEditing else { return }587 if dragStart == nil {588 if !isSelected { controller.selection = [card.id] }589 dragStart = Dictionary(uniqueKeysWithValues: controller.board.cards.filter { controller.selection.contains($0.id) }.map { ($0.id, CGPoint(x: $0.x, y: $0.y)) })590 }591 guard let start = dragStart, let mine = start[card.id] else { return }592 var frame = card.frame593 frame.origin = CGPoint(x: mine.x + value.translation.width / scale, y: mine.y + value.translation.height / scale)594 let snap = controller.board.snap(frame, excluding: Set(start.keys), distance: CanvasBoard.snapDistance / Double(max(scale, 0.3)))595 if snap.verticalGuides != controller.guides.verticalGuides || snap.horizontalGuides != controller.guides.horizontalGuides,596 !(snap.verticalGuides.isEmpty && snap.horizontalGuides.isEmpty) { AuraHaptics.play(.snap) }597 controller.guides = snap598 let dx = snap.origin.x - mine.x, dy = snap.origin.y - mine.y599 controller.mutate { board in600 for (id, origin) in start { if var c = board.card(id) { c.x = origin.x + dx; c.y = origin.y + dy; board.update(c) } }601 }602 }603 .onEnded { _ in dragStart = nil; controller.guides = CanvasBoard.Snap(origin: .zero) }604 }605}606607/// iPhone: the cards of the board as a vertical list — same data, a layout that fits the screen.608private struct CanvasCardList: View {609 @Bindable var controller: CanvasController610 let host: CanvasHost611612 var body: some View {613 let found = Set(controller.board.search(controller.query).map(\.id))614 let cards = controller.board.cards.sorted { $0.modifiedAt > $1.modifiedAt }.filter { controller.query.isEmpty || found.contains($0.id) }615 ScrollView {616 LazyVStack(spacing: 10) {617 AuraSearchField(text: $controller.query, placeholder: L("Search cards"), height: 38, fontSize: 15, identifier: "canvas-search")618 if cards.isEmpty {619 AuraEmptyState(symbol: "rectangle.3.group", title: controller.query.isEmpty ? L("An empty canvas") : L("No result"),620 message: controller.query.isEmpty ? L("Use Add to keep the current page, a note or what is on the clipboard.") : "").frame(minHeight: 280)621 }622 ForEach(cards) { card in623 CanvasCardView(card: card, controller: controller, host: host, scale: 1, isDimmed: false, image: controller.store.assetURL(card.asset, board: controller.board.id))624 .frame(maxWidth: .infinity).frame(minHeight: card.kind == .image || card.kind == .capture ? 180 : 76)625 .gesture(DragGesture(minimumDistance: 10_000))626 }627 }628 .padding(12)629 }630 .scrollDismissesKeyboard(.interactively)631 }632}633