Heirloom

APPLE MULTIPLATFORM APP

A local-first native multiplatform app (iOS 17, iPadOS 17, macOS 14, visionOS 1) for documenting people, typed kinship relationships, and family archives without recurring server costs or vendor lock-in. Migrated from a Next.js and Supabase web prototype to SwiftUI, SwiftData, private CloudKit storage, and a zero-dependency 120Hz spatial canvas engine.

Highlights

  • Single multiplatform Apple target (iOS 17, iPadOS 17, macOS 14, visionOS 1) in 22 Swift files (1,913 LOC) with zero third-party dependencies
  • Local-first persistence on SwiftData and the user's private iCloud database (CloudKit) with automatic local SQLite fallback
  • Hybrid immediate/retained SwiftUI Canvas with zero-write 120Hz card dragging, LOD grid culling, and O(V + E) cycle-safe generational seeding
  • Split-authority two-way Apple Contacts sync (CNContactStore) that prevents conflict loops and preserves non-family labels
  • CKShare-ready FamilyArchive root aggregate and TEI-XML/CIDOC-CRM-aligned schema with deferred models for events, artifacts, media, and oral histories

Heirloom: Local-First Spatial Kinship & Family Archive Engine

A UX engineering and digital humanities case study on local-first graph architecture, interactive canvas performance, and archival data stewardship

AttributeDetail
Platform TargetsSingle multiplatform target: iOS 17, iPadOS 17, macOS 14, visionOS 1 (project.yml)
Core StackSwiftUI, SwiftData, CloudKit (NSPersistentCloudKitContainer), Contacts (CNContactStore), PhotosUI, CoreGraphics
Footprint22 Swift files, 1,913 LOC, 0 third-party dependencies
Architectural PivotMigrated from a centralized Next.js + Supabase web prototype (main) to a local-first native Apple app (native-apple-app)
Repositorygithub.com/ryanrclewis/heirloom (opens in a new tab) (currently private; architecture diagrams, schema specs, and code-derived UI renderings are included below)

1. Overview & Context

Heirloom is a native multiplatform app for personal and family archiving. It is built to document people, typed kinship relationships, and biographical notes, with room already laid out in the schema for historical events, physical keepsakes, digitized media, and oral histories. [INSERT PERSONAL EXAMPLE HERE]

On the surface, it behaves like a tactile, Freeform-style spatial board where you can explore and arrange a family graph across iPhone, iPad, Mac, and Apple Vision Pro. Under the hood, though, it grew out of two practical problems that show up right where UX engineering meets university digital humanities and archival work:

  1. Keeping archives alive without a server bill (Digital Humanities): Hosted web apps are the default for a reason. They are quick to prototype and easy to send around as a link. The catch is that personal archives, community oral-history projects, and grant-funded academic prosopography work (for those less familiar, prosopography is the study of historical groups through shared biographical records) have a bad habit of dying the moment hosting stops. When a centralized database like Supabase or PostgreSQL loses grant funding, shifts pricing, or gets left behind by a maintainer, the cultural record tends to go down with it. Heirloom intentionally moved away from a hosted web stack to a local-first, user-owned persistence setup backed by on-device SQLite (SwiftData) and the user's private iCloud database (CloudKit). That removes recurring server burn and vendor lock-in while keeping the archive usable offline.
  2. Spatial control without tanking frame rates (UX Engineering): Automated graph layout tools, like layered Sugiyama diagrams or force-directed graphs, are convenient when you just want nodes on a screen, yet they erase the mental map a person builds when organizing their own family. Meanwhile, naive reactive UI bindings fall apart quickly under 120Hz ProMotion drag gestures and constant cloud sync writes. Heirloom solves this with a hybrid immediate/retained rendering pipeline, zero-write ephemeral drag state, deterministic O(V + E) cycle-safe generational seeding, and persistent world-space coordinates that stay consistent from one device to the next.

2. A Quick Look at the Interface

Because the repository is currently private and live Xcode Simulator capture is not available in a headless environment, the visuals below were generated deterministically from the actual SwiftUI view geometry, the SampleData seed graph (SampleData.swift), the TreeLayout spacing math (TreeLayout.swift), the EdgesCanvas cubic Bézier control points (EdgesCanvas.swift), and the warm archival sepia AccentColor (#996F5A, Contents.json).

Heirloom Freeform Family Tree Canvas rendered from SampleData and TreeLayout geometry
Heirloom Freeform Family Tree Canvas rendered from SampleData and TreeLayout geometry
  • Infinite Spatial Canvas (FamilyTreeView.swift). A three-generation sample archive (The Lewis Family) seeded by TreeLayout and adjusted through free-dragging (Anna Lewis has been pulled off the initial grid with her saved (positionX, positionY) position). Line styles carry the relationship meaning directly: solid secondary cubic Béziers for parent-child lineage, pink dashed curves for spouses, and blue dotted curves for siblings.
Heirloom iOS Sheet Flows showing PersonDetailView, PersonEditView, and cross-platform ContactPickerView
Heirloom iOS Sheet Flows showing PersonDetailView, PersonEditView, and cross-platform ContactPickerView
  • Inspection, Editing, and OS Integration. The read-only PersonDetailView.swift translates directed graph edges into subject-relative labels through Person.connections(). PersonEditView.swift handles archival biographical fields and transactional rollback, while ContactPickerView.swift gives you a single searchable address-book sheet that works across iOS, macOS, and visionOS.

3. System Architecture & The Pivot from Web to Native

High-Level Architecture Overview

Heirloom Native Multiplatform System Architecture Diagram
Heirloom Native Multiplatform System Architecture Diagram

Why Rewrite from Next.js + Supabase (v0) to Native SwiftUI + CloudKit (v1)?

Heirloom actually started as a web app built on Next.js and Supabase, complete with PostgreSQL tables, authentication, and email invitations. That prototype did its job by validating the core archival entities, but once I started thinking about how a family or scholarly archive needs to survive for ten or twenty years, four real issues stood out:

  1. Ongoing Maintenance Costs: Running a multi-tenant PostgreSQL database, an auth provider, and blob storage creates permanent overhead. That exact ongoing bill is what breaks so many digital humanities tools and personal side projects once a grant wraps up or a project shifts into quiet maintenance mode.
  2. Privacy and Trust: Families and community archivists are understandably cautious about uploading sensitive biographical details, portraits of living relatives, and private oral histories to a third-party startup's database. Handing identity and storage over to the user's own iCloud Private Database let me drop custom auth tables (profiles, invitations) altogether and keep custody with the person curating the archive.
  3. OS Data Silos: A web app sits behind a browser wall. It cannot natively read from or write back to a user's system address book (CNContactStore) to keep birthdays, portraits, and family relations in sync across the rest of their devices.
  4. Canvas Feel and Multi-Device Reach: Native SwiftUI paired with CoreGraphics Canvas gives direct, hardware-accelerated access to touch, trackpad, and spatial (visionOS) gestures without fighting DOM layout reflows.

Data Schema Migration Mapping (v0 → v1)

Legacy Supabase Table (v0)Native SwiftData @Model (v1)Status & Archival Design Notes
family_membersPersonImplemented; adds contactIdentifier, world-space (positionX, positionY), and @Attribute(.externalStorage) portrait (CKAsset)
relationshipsRelationshipImplemented; kept as an explicit directed edge (person1 → person2) rather than implicit arrays
(implicit tenant)FamilyArchiveNew single root aggregate; cascades deletes and sets up zero-migration CKShare collaboration later
timeline_events / event_peopleEvent (DeferredModels.swift)Deferred schema stub; models many-to-many historical events with typed eventType and location
objectsHeirloom (DeferredModels.swift)Deferred schema stub; models physical artifact provenance (countryOfOrigin, manufacturer, dateReceived, originalOwner)
mediaMediaItem (DeferredModels.swift)Deferred schema stub; digitized primary sources backed by CKAsset external storage
member_storiesStory (DeferredModels.swift)Deferred schema stub; Storyworth-style prompted oral history and narrative entries
profiles / auth / invitationsRemovedReplaced by native iCloud account identity; multi-user collaboration is deferred cleanly to CKShare

4. Data Modeling & CloudKit Schema Decisions

Entity-Relationship Model

erDiagram
    FAMILY_ARCHIVE ||--o{ PERSON : "owns (cascade)"
    FAMILY_ARCHIVE ||--o{ RELATIONSHIP : "owns (cascade)"
    PERSON ||--o{ RELATIONSHIP : "outgoing (person1)"
    PERSON ||--o{ RELATIONSHIP : "incoming (person2)"
    FAMILY_ARCHIVE ||..o{ EVENT : "deferred"
    FAMILY_ARCHIVE ||..o{ HEIRLOOM_OBJECT : "deferred"
    PERSON ||..o{ MEDIA_ITEM : "deferred"
    PERSON ||..o{ STORY : "deferred"

    FAMILY_ARCHIVE {
        UUID uuid
        String title
        Date createdAt
    }

    PERSON {
        UUID uuid
        String firstName
        String middleName
        String lastName
        String maidenName
        Date birthDate
        Date deathDate
        Bool isLiving
        String genderRaw
        Data avatar_CKAsset
        String contactIdentifier
        Double positionX
        Double positionY
    }

    RELATIONSHIP {
        UUID uuid
        String kindRaw
        Date createdAt
    }

How the Persistence Layer Holds Together

  1. Playing by CloudKit's Rules: Apple's NSPersistentCloudKitContainer is picky, and if your schema breaks its record-zone constraints it will quietly refuse to sync. Across FamilyArchive.swift, Person.swift, and Relationship.swift, every model sticks to four strict rules:
    • No @Attribute(.unique) constraints. Uniqueness cannot be enforced atomically across offline devices, so each record carries an app-level uuid: UUID for stable cross-device identity independent of SwiftData's store-local PersistentIdentifier.
    • Optional or defaulted attributes, and explicit inverse relationships. Every relationship is optional and explicitly paired (@Relationship(inverse: \Relationship.person1) and person2).
    • Raw-string enum backing (genderRaw, kindRaw). Persisting Swift enums directly can make schema evolution brittle if cases change down the road. Instead, the enums in Enums.swift are backed by plain String columns with safe computed fallbacks (Gender(rawValue: genderRaw) ?? .unspecified).
    • External blob storage (@Attribute(.externalStorage)). Portraits (Person.avatar: Data?) live outside the main SQLite rows and automatically map to CKAsset in CloudKit, which keeps graph queries fast and avoids row bloat.
  2. One Root Aggregate for Future Sharing: Grouping both Person and Relationship under a single FamilyArchive root pays off later. When it is time to support shared archives (whether across extended family or inside a university research seminar), a single CKShare (CloudKit's native sharing primitive) can be attached to the FamilyArchive record without reshaping the database.
  3. Explicit Directed Edges and Perspective Lookup: Instead of scattering parents: [Person], spouses: [Person], and siblings: [Person] arrays onto Person, kinship is stored as a uniform directed edge (person1 → person2). PersonRelationships.swift implements Person.connections(), which walks both outgoingRelationships and incomingRelationships and translates each edge into the right label from the current person's point of view. For instance, if self == person1 and kind == .parent, the other person shows up as .child; if self == person2, they show up as .parent. On the write side, AddRelationshipView.swift turns natural UI phrasing ("{other} is {person}'s parent/child") into canonical .parent edges on insert.
  4. Three-Tier Store Bootstrapping: ModelContainer+Heirloom.swift tries to open a private CloudKit-backed container (.automatic) first. If the app is running unsigned or without iCloud entitlements (which happens all the time for open-source contributors, academic evaluators, and CI simulators), it falls back cleanly to a local-only SQLite store (.none). It also exposes an in-memory .preview container preloaded with SampleData.swift.
  5. Honest Date-Uncertainty Formatting: Real family and historical records rarely come with neat, complete dates. Person.lifespan (Person.swift) accounts for all four partial-knowledge states alongside isLiving: "1942 – 2009", "b. 1942", "1942 – ?", "? – 2009", or "".

5. Under the Hood: The Spatial Canvas & Graph Engine

The heart of the frontend is the Freeform-style spatial board in FamilyTreeView.swift. The main goal here was making panning, pinch-zooming, and card dragging feel immediate and steady without hammering the persistence layer.

Hybrid Immediate + Retained Rendering Pipeline

flowchart LR
    subgraph State["Reactive & Ephemeral State"]
        SD["SwiftData @Query<br/>(people, relationships)"]
        VP["Viewport @State<br/>(scale, offset)"]
        DR["Ephemeral @State<br/>nodeDrag (translation)"]
    end

    subgraph Seed["Pure Layout Boundary"]
        TL["TreeLayout.layout()<br/>O(V+E) Cycle-Safe DFS"]
    end

    subgraph Transform["Coordinate Projection"]
        CT["CanvasTransform<br/>screen = world * scale + offset"]
    end

    subgraph Render["ZStack Compositor"]
        BG["GridBackground<br/>Immediate Canvas (LOD > 8pt)"]
        EC["GraphConnectors<br/>Immediate Canvas (Cubic Béziers)"]
        NV["PersonNodeView<br/>Retained SwiftUI Cards"]
    end

    SD -->|"Unplaced nodes only"| TL
    TL -->|"Seed (positionX, positionY)"| SD
    SD --> CT
    VP --> CT
    DR -->|"Live Δ / scale (0 DB writes)"| EC
    DR -->|"Live screen Δ (120Hz)"| NV
    CT --> BG
    CT --> EC
    CT --> NV
    DR -->|".onEnded commit"| SD

Five Frontend Patterns Doing the Heavy Lifting

  1. Keeping World Space Separate from Screen Space: Every Person stores its location in invariant World Coordinates (positionX: Double?, positionY: Double?, bridged through Person.canvasPosition: CGPoint?). A small value type, CanvasTransform (EdgesCanvas.swift), handles projecting world points onto the screen: screen(p) = (p.x · scale + offset.x, p.y · scale + offset.y). Because stored positions do not care about viewport size, a tree arranged on a 27-inch Mac Studio syncs over CloudKit and centers cleanly on an iPhone screen (centerIfNeeded(in:) in FamilyTreeView.swift).
  2. Immediate-Mode SwiftUI.Canvas for Non-Interactive Layers: Spinning up hundreds of retained SwiftUI views for grid dots and relationship lines adds unnecessary overhead. Instead, GridBackground.swift and EdgesCanvas.swift draw straight into CoreGraphics-backed SwiftUI.Canvas layers with .allowsHitTesting(false). Only the interactive PersonNodeView cards (PersonNodeView.swift) live in the retained SwiftUI hierarchy, keeping layout passes and hit-testing proportional to node count O(V).
  3. Zero-Write Dragging (Stopping Sync Thrash): Writing person.canvasPosition inside DragGesture.onChanged would trigger SwiftData dirty tracking, SQLite commits, and CloudKit export notifications up to 120 times a second. To avoid that, FamilyTreeView keeps a lightweight NodeDrag(id: PersistentIdentifier, translation: CGSize) struct in ephemeral @State (FamilyTreeView.swift):
    • While you are actively dragging, nodeView(for:) adds nodeDrag.translation straight in screen space, and worldEdges computes translation / scale in world space so every attached Bézier curve stretches smoothly in lockstep with the card.
    • Only inside .onEnded (FamilyTreeView.swift) does the final world position get committed once to SwiftData and nodeDrag cleared.
  4. Clean Gesture Handoff: Interactive canvases get annoying fast when dragging a card accidentally pans the background or a slight finger wiggle cancels a tap. Heirloom keeps those gestures out of each other's way:
    • Each card attaches .highPriorityGesture(DragGesture(minimumDistance: 3)), so any drag past 3pt claims priority over the background SimultaneousGesture(DragGesture, MagnifyGesture).
    • The background pan gesture checks guard nodeDrag == nil else { return } so the viewport stays put while a card is moving.
    • Node .onTapGesture checks if nodeDrag == nil before opening PersonDetailView.
  5. Rendering Guardrails and LOD Culling: GridBackground.swift includes three small graphics safeguards that save a lot of headaches:
    • NaN / Infinity check (size.width.isFinite && size.height.isFinite) to prevent runaway loops during SwiftUI layout probing.
    • Level-of-Detail (LOD) culling (guard step > 8 else { return }): when you zoom out toward 0.3×, dot spacing drops below 8pt and stops drawing altogether, preventing moiré shimmer and pointless draw calls.
    • Viewport clamp (min(size, 4096)) to cap iteration bounds if a layout proposal ever comes in unbounded.

The Layout Engine (TreeLayout.swift)

TreeLayout is written as a pure value-type function, (people: [Person], relationships: [Relationship]) -> TreeLayoutResult, completely decoupled from SwiftUI views and database writes:

  • Adjacency Construction: Normalizes both .parent (p1 → p2) and .child (p1 → p2) into a parentsOf adjacency map while collecting .spouse pairs.
  • Cycle-Guarded Memoized Longest-Path DFS (O(V + E)): Assigns each person a generation depth based on the longest chain from a root ancestor (parents.isEmpty ? 0 : max(depth(parent)) + 1), tracking an active recursion stack visiting: Set<PersistentIdentifier>. If conflicting archival records ever introduce an accidental cycle, the guard safely returns 0 instead of crashing the stack.
  • Spouse Alignment Pass: Pulls married or partnered nodes down onto the deeper generation (max(gen[a], gen[b])) so couples still sit on the same horizontal row even when only one side of the family tree has ancestors entered.
  • Deterministic Row Ordering: Sorts each generation chronologically with an alphabetical tie-breaker: ($0.birthDate ?? .distantFuture, $0.displayName).
  • Non-Destructive Seeding: seedPositions() (FamilyTreeView.swift) only writes computed positions to unplaced nodes (canvasPosition == nil), leaving every card you have already placed by hand right where you put it.

6. Two-Way Apple Contacts Sync Without Conflict Loops

Anyone who has wired up two-way sync between two editable data stores (in this case, Heirloom's SwiftData graph and Apple's CNContactStore) knows how quickly you can end up with ping-pong overwrite loops or accidentally clobbering unrelated fields. ContactSync.swift and ContactsService.swift sidestep that structurally using Split-Authority Partitioning:

sequenceDiagram
    actor User
    participant UI as FamilyTreeView / ContactPickerView
    participant Sync as ContactSync
    participant Svc as ContactsService (CNContactStore)
    participant DB as SwiftData (Person)

    Note over UI,Svc: 1. Linking a Person (Off-Main-Actor Read)
    User->>UI: Tap "Choose from Contacts"
    UI->>Svc: requestAccess() (handles iOS 18 .limited)
    UI->>Svc: Task.detached -> allContacts()
    Svc-->>UI: [ContactSummary] (Sendable value snapshots)
    User->>UI: Select Contact
    UI->>Sync: ContactSync.apply(summary, to: person)
    Sync->>DB: Store contactIdentifier + Name, Birthday, Portrait

    Note over UI,Svc: 2. Two-Way Sync (Split Authority — Zero Conflict Loops)
    User->>UI: Tap "Sync with Contacts"
    UI->>Sync: syncAll(people)
    loop Every linked Person
        Sync->>Svc: summary(for: contactIdentifier)
        Svc-->>Sync: Demographics (Authoritative Source = Contacts)
        Sync->>DB: Update firstName, lastName, birthDate, avatar
        Sync->>DB: Compute person.connections() (Authoritative Source = Heirloom)
        Sync->>Svc: writeRelations(managedLabels, to: contactIdentifier)
        Note right of Svc: Preserves non-family labels<br/>(assistant, manager, partner, etc.)
    end
    Sync-->>UI: Sync Result ("Updated N contacts, imported M")

How It Works in Practice

  • Unidirectional Field Ownership: Demographics (given name, family name, birthday, portrait) flow exclusively from Contacts → Heirloom. Kinship structure (parent, child, spouse, brother, sister) flows exclusively from Heirloom → Contacts. Because the two write sets never overlap, syncing is idempotent and stays free of merge conflicts.
  • Non-Destructive Relation Filtering: ContactsService.swift keeps an explicit managedRelationLabels allowlist of 5 kinship constants. Before executing a CNSaveRequest, writeRelations partitions existing contactRelations so any unrelated labels a user saved in Contacts (like assistant, manager, or partner) are left untouched (ContactsService.swift).
  • True Multiplatform Contact Picking: Apple's stock CNContactPickerViewController is iOS-only and does not share the write authorization needed for syncing relations back. ContactPickerView.swift replaces it with a 135-line pure SwiftUI searchable sheet backed by ContactsService, offloading full address-book enumeration to Task.detached(priority: .userInitiated) and passing immutable Sendable ContactSummary structs back to the main actor.
  • Forward Compatibility for iOS 18 Privacy: ContactsService.requestAccess() (ContactsService.swift) defensively accounts for iOS 18's .limited contact authorization (rawValue == 4) without breaking compilation against iOS 17 or macOS 14 SDKs.

7. Key Architectural Trade-Offs

Engineering DecisionChosen ApproachRejected AlternativeRationaleAccepted Trade-Off & Future Mitigation
Backend & Storage OwnershipSwiftData + Private CloudKit DB with transparent local SQLite fallbackHosted Next.js + Supabase PostgreSQLCuts out SaaS hosting costs, keeps archives working offline, and leaves sensitive family records in the user's handsTies runtime to the Apple ecosystem; mitigated later with open-standards export (GEDCOM 7.0, TEI-XML, JSON-LD)
Graph Edge RepresentationExplicit Relationship @Model (person1 → person2, kindRaw)Implicit to-many arrays (parents, spouses) on PersonGives uniform edge traversal for layout and rendering, matches relational and digital humanities schemas, and leaves room for citations, dates, and certaintyRequires inverse perspective projection (Person.connections()) and manual edge cleanup when a person is deleted
Spatial Layout StrategyHybrid: O(V + E) generational seed (TreeLayout) + saved Freeform (x, y)Purely algorithmic auto-layout (Sugiyama / force-directed)Respects the archivist's spatial memory and handles real-world non-nuclear kinships that break rigid tree layoutsNew nodes seeded into a heavily rearranged canvas can overlap user-placed cards; mitigated later with collision-aware seeding or a "Re-layout" action
Canvas Rendering StackHybrid immediate-mode SwiftUI.Canvas (grid + curves) + retained SwiftUI PersonNodeView cardsPure retained SwiftUI Path views OR pure Metal/CanvasAvoids O(V + E) view-tree bloat for connectors and dots while keeping native typography, Dynamic Type, and SwiftUI accessibility on cardsVery large graphs (500+ nodes) will eventually need viewport frustum culling for off-screen PersonNodeView instances
Drag State PersistenceEphemeral @State nodeDrag with a single commit on .onEndedDirect @Bindable writes to Person.positionX/Y on .onChangedKeeps 60/120Hz frame pacing steady and avoids SQLite and CloudKit write stormsTransient drag position lives outside the model until release, which is fine since each drag is atomic
Contacts SynchronizationSplit-authority (Demographics ← Contacts; Relations → Contacts)Full bidirectional merge on every field with timestampsNo conflict loops, predictable idempotency, and a clear mental model for everyday usersEdits made to a linked person's name inside Heirloom get overwritten by Contacts on the next sync; the UI makes that directionality clear
Contact Picker UICustom SwiftUI ContactPickerView over CNContactStoreCNContactPickerViewController (UIViewControllerRepresentable)One codebase across iOS, iPadOS, macOS, and visionOS, sharing the authorization needed for write-back syncRequires upfront Contacts permission before browsing, whereas iOS's out-of-process picker allows one-shot read access without permission
Project ConfigurationZero third-party dependencies + XcodeGen (project.yml)CocoaPods or heavy SPM graph librariesAvoids dependency rot for a tool meant to last decades; reproducible multiplatform builds in 57 lines of YAMLRelies on native Apple layout and drawing code instead of an off-the-shelf graph library

8. What Still Needs Hardening (and Where This Goes Next)

Shipping a v1 mostly means being honest about what is still rough around the edges. Walking through the current codebase line by line turns up six concrete things I want to tighten up, right alongside the longer-term archival roadmap.

Immediate UX Engineering & Concurrency Hardening

  1. Moving ContactSync.syncAll I/O Off the Main Actor: While ContactPickerView.load() properly detaches CNContactStore enumeration to a background thread, ContactSync.swift is currently annotated @MainActor and runs synchronous service.summary(for:) and service.writeRelations(...) calls inside its loop. Pulling those CNContactStore reads and writes into an actor or a Task.detached batch (passing Sendable value structs in and out) will prevent main-thread hitches once someone is syncing 50+ linked contacts.
  2. Focal-Point Pinch Zoom & Desktop Input Feel: In FamilyTreeView.swift, MagnifyGesture updates scale without compensating offset around the gesture's focal point (value.startAnchor), so the canvas currently zooms toward world origin (0, 0). Adding anchor-compensated zoom alongside macOS scroll-wheel zoom, keyboard shortcuts (⌘+, ⌘-, ⌘0), and trackpad inertia will bring desktop and iPad feel much closer to tools like Figma and Freeform.
  3. Scoped Transactional Editing Instead of Shared context.rollback(): Right now, PersonEditView.swift calls context.rollback() when you hit Cancel on an existing person. Because context is the shared main ModelContext, rolling it back could accidentally revert unrelated uncommitted changes (like a card drag that just finished). Moving edits into a value-type draft struct or a dedicated child ModelContext gets rid of that collateral rollback risk.
  4. Graph Integrity Checks & Layout Polish: AddRelationshipView.swift currently lets you add duplicate relationships or topological cycles. TreeLayout survives cycles safely without crashing, sure, but the archive itself shouldn't quietly accept them. Adding duplicate checks, cycle warnings, couple-adjacency grouping, and a multi-pass generation pass (updating descendants whenever a spouse gets leveled down) will make the graph engine much sturdier.
  5. Accessibility & Inclusive Navigation (WCAG / VoiceOver): Spatial canvases can easily shut out screen-reader and keyboard-only researchers if you aren't careful. Adding an accessible List or Outline companion view, VoiceOver rotor traversal across Person.connections(), and Reduce Motion transitions is essential, both as basic craft and for institutional ADA / Section 508 compliance in university settings.
  6. Automated Test Suite: The pure functional seams (TreeLayout, CanvasTransform, Person.connections(), Person.lifespan) and the in-memory ModelContainer.preview are already cleanly separated for fast unit tests. Writing Swift Testing suites to cover cyclic graphs, edge perspective symmetry, and split-authority relation filtering is an easy, practical win to knock out next.

Digital Humanities & Archival Roadmap

I staged the v1 schema so broader archival and scholarly features can layer in without tearing down the foundation:

  • Phase 2: Multi-Modal Archival Entities (DeferredModels.swift). Turn on Event (chronological timelines), Heirloom (material culture provenance: origin, manufacturer, original owner), MediaItem (high-resolution primary-source scans via CKAsset), and Story (oral history transcripts and prompted interviews), growing the single-tab RootView.swift into a multi-column NavigationSplitView archival workbench.
  • Phase 3: Collaborative Stewardship via CKShare. Attach a CKShare to the FamilyArchive root aggregate so extended families, community archives, or university research cohorts can co-curate records with role-based permissions, using the reserved Person.email field for card-claiming flows.
  • Phase 4: Open Scholarly Interchange & Provenance. Add lossless export and import for GEDCOM 7.0 (the genealogy standard), TEI-XML (<listPerson> and <listRelation> for digital editions), and JSON-LD / CIDOC-CRM (linked open data for museum and library repositories), alongside source-citation and certainty attributes on Relationship edges (such as "attested in 1940 Census" or "oral testimony (uncertain)").

A good archive should outlast the app you built it in, and getting those open export formats and collaborative workflows in place is what turns a neat personal tool into something families and researchers can actually trust with their history.


9. Codebase Index

ModuleKey FilesResponsibility
App Entry & ConfigHeirloomApp.swift, project.yml, Heirloom.entitlementsMultiplatform target spec (via XcodeGen, for those less familiar: a YAML-based Xcode project generator), iCloud/CloudKit & push entitlements, container injection
Persistence & SchemaModelContainer+Heirloom.swift, FamilyArchive.swift, Person.swift, Relationship.swift, DeferredModels.swift3-tier CloudKit/local/preview bootstrapping, CKShare-ready root aggregate, archival models & roadmap stubs
Spatial Canvas & LayoutFamilyTreeView.swift, TreeLayout.swift, EdgesCanvas.swift, GridBackground.swift, PersonNodeView.swiftWorld/screen transform, O(V + E) generational seeding, LOD dotted grid, cubic Bézier connectors, zero-write drag cards
OS InteroperabilityContactsService.swift, ContactSync.swift, ContactPickerView.swiftSplit-authority two-way Contacts sync, non-destructive label filtering, cross-platform searchable contact picker
CRUD & Shared UtilitiesPersonDetailView.swift, PersonEditView.swift, AddRelationshipView.swift, PersonRelationships.swift, Enums.swift, PlatformImage.swift, SampleData.swiftPerspective-projected profiles, transactional edit forms, lightweight UIKit/AppKit image bridge, seeded preview graph