oficina / docs Public

Merge the native sync-batching line into main

Brings native/sync-batching (5c177f9) onto main; it contains
native/document-windows, testflight, docs-toolbar-stability and
sparkle-updates. Adds batched uploads, instant local drafts with an
owner-scoped idempotent creation_token (migration 0008, already applied
on edge since 2026-09-20), queued renames and POST /d/{sqid}/title.
Edge already serves 5c177f9; this brings main level with it.
Reviewed by Fable 5.1 on discussion #63.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from merge/native-sync-batching into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7543cf5ad22a603ed33eb668abffa65bf3c58519 parent ae22c11
94 files changed, +3,571 −154
  • docs/superpowers/specs/2026-09-20-mac-document-windows.md +85 −0
  • internal/docs/app.go +1 −0
  • internal/docs/handlers.go +54 −1
  • internal/docs/migrations/0008_document_creation_token.sql +2 −0
  • internal/docs/models.go +2 −1
  • internal/docs/native_test.go +51 −0
  • internal/docs/store.go +37 −0
  • native/INSTANT-DOCUMENTS.md +28 −0
  • native/PrivacyInfo.xcprivacy +17 −0
  • native/apple/Package.resolved +11 −2
  • native/apple/Package.swift +8 −2
  • native/apple/Sources/DocsApp/DocsAccountWindow.swift +52 −0
  • native/apple/Sources/DocsApp/DocsApp.swift +24 −10
  • native/apple/Sources/DocsApp/DocsDocumentWindow.swift +23 −0
  • native/apple/Sources/DocsApp/DocsWindowCommands.swift +48 −0
  • native/apple/Sources/DocsApp/DocsWindows.swift +63 −0
  • native/apple/Sources/DocsKit/CRDTReplica.swift +12 −1
  • native/apple/Sources/DocsKit/DocsAccountActions.swift +10 −0
  • native/apple/Sources/DocsKit/DocsDocumentMenu.swift +28 −0
  • native/apple/Sources/DocsKit/DocsEditorCommands.swift +58 −0
  • native/apple/Sources/DocsKit/DocsEditorContext.swift +21 −0
  • native/apple/Sources/DocsKit/DocsFonts.swift +1 −0
  • native/apple/Sources/DocsKit/DocsLayoutManager.swift +70 −0
  • native/apple/Sources/DocsKit/DocsMacStrings.swift +5 −0
  • native/apple/Sources/DocsKit/DocsModel.swift +142 −14
  • native/apple/Sources/DocsKit/DocsPagedTextView.swift +86 −21
  • native/apple/Sources/DocsKit/DocsPaging.swift +28 −2
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +205 −35
  • native/apple/Sources/DocsKit/DocumentBlockSpacing.swift +54 −0
  • native/apple/Sources/DocsKit/DocumentCommands.swift +3 −1
  • native/apple/Sources/DocsKit/DocumentExportControls.swift +9 −0
  • native/apple/Sources/DocsKit/DocumentInlineCode.swift +38 −0
  • native/apple/Sources/DocsKit/DocumentPageLayout.swift +64 −0
  • native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift +21 −0
  • native/apple/Sources/DocsKit/DocumentThumbnail.swift +3 −1
  • native/apple/Sources/DocsKit/DocumentToolbarSelection.swift +38 −0
  • native/apple/Sources/DocsKit/EditorToolbar.swift +39 −20
  • native/apple/Sources/DocsKit/NativeDocumentTextView.swift +17 −3
  • native/apple/Sources/DocsKit/NativeTextProjection.swift +53 −6
  • native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/ar.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/bn.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/en.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/es.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/ga.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/hi.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/ja.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/pt.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/ru.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/vi.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/yue.lproj/Mac.strings +51 −0
  • native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings +2 −0
  • native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Mac.strings +51 −0
  • native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift +179 −0
  • native/apple/Tests/DocsKitTests/DocumentDraftTests.swift +72 −0
  • native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift +113 −0
  • native/apple/Tests/DocsKitTests/DocumentRenderReconciliationTests.swift +49 −0
  • native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift +61 −0
  • native/apple/Tests/DocsKitTests/DocumentToolbarSelectionTests.swift +82 −0
  • native/apple/Tests/DocsKitTests/DocumentTypographyTests.swift +47 −0
  • native/apple/Tests/DocsKitTests/HomeLoadingTests.swift +22 −0
  • native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift +44 −0
  • native/crdt/examples/caret_fixture.rs +11 −0
  • native/crdt/src/lib.rs +22 −9
  • native/crdt/tests/replica.rs +24 −0
  • native/ios/Assets.xcassets/AppIcon.appiconset/AppIcon.png binary
  • native/ios/Info.plist +35 −0
  • native/ios/project.yml +44 −24
  • native/mac-updates.json +6 −0
  • native/macos/AppIcon.icns binary
  • native/macos/AppStore.entitlements +12 −0
  • native/macos/Info.plist +43 −0
  • native/macos/project.yml +54 −0
  • native/scripts/build-mac.sh +2 −1
  • native/scripts/test-document-drafts.py +77 −0
  • native/scripts/test-document-window.py +63 −0
  • native/scripts/test-home-loading.py +36 −0
  • native/scripts/test-sync-latency.py +61 −0
  • native/smoke/document-window/Package.resolved +23 −0
  • native/smoke/document-window/Package.swift +7 −0
  • native/smoke/document-window/README.md +41 −0
  • native/smoke/document-window/Sources/DocsWindowCommands.swift +1 −0
  • native/smoke/document-window/Sources/DocsWindows.swift +1 −0
  • native/smoke/document-window/Sources/Smoke.swift +192 −0

CI passed — run details

diff --git a/docs/superpowers/specs/2026-09-20-mac-document-windows.md b/docs/superpowers/specs/2026-09-20-mac-document-windows.md
new file mode 100644
index 0000000..abefde8
--- /dev/null
+++ b/docs/superpowers/specs/2026-09-20-mac-document-windows.md
@@ -0,0 +1,85 @@
+# Mac document windows — 2026-09-20
+
+Paul requests a separate Home launcher and document windows for Docs and Sheets.
+This extends the native Apple specs; editors remain native and server-backed.
+
+Home is a singleton with a Recent sidebar and searchable thumbnail grid. Templates
+are deferred until template creation exists. Each open document has an independent
+model, live stream, selection and save queue. Window identity includes the account
+and document; opening an existing document focuses it. Document/session state remains in memory; credentials retain the existing
+Keychain handling and are never encoded in scene restoration values. Missing restored sessions return
+the user to Home. File > Recent and Window > Home remain available with no editor.
+Recent entries are held in memory for this iteration, scoped to the account session.
+
+Mac document windows have no app navigation sidebar. Existing editing and file
+actions move into menu-bar commands targeted at the focused scene. Standard native
+text responder actions remain available in text fields. Docs adds a document-only
+inspector and zoom starting at 100%; zoom changes display scale, never text wrapping.
+No server page-settings API exists: inspector exposes existing personal layout
+settings and document information, without pretending to persist new paper settings.
+
+Sheets edits in the selected cell, preserving drafts on failed save and respecting
+existing write serialization. Header buttons select whole rows/columns. Double-click
+on column boundaries autosizes using displayed text/font measurements and existing
+size endpoint; menu alternative provided. Remove only the grid's outer focus effect,
+retain cell selection and keyboard focus. Enter/Tab commit; Escape discards.
+
+Docs rendering investigation compares web CSS/font and page geometry against TextKit.
+Use identical bundled fonts, logical width, sizes, paragraph spacing and line height.
+Native optimistic edits must not be overwritten by stale projection generations or
+IME composition. Avoid unnecessary complete attributed storage replacement and
+selection resets; preserve model render acknowledgement. Exact cross-engine layout
+parity requires measured fixture verification, not a compilation claim.
+
+Validate Mac builds, existing native tests and focused regression cases; exercise
+window/menu targeting and editing where UI automation is available. Build iOS to
+check shared code. No merge, deployment or app publication is part of this change.
+
+Review: GPT-6 Astra (high), 2026-09-20. Required invariants incorporated:
+window keys combine canonical origin, account identity and document identity;
+clients are immutable per window. Sign out is unavailable until that account's
+windows close; switching the launcher account leaves those windows intact.
+Close/quit guards cover in-flight, queued, failed and composing edits. Window
+registry lifecycle ends only after the actual guarded close. Edit commands obey
+the first responder, not merely the focused scene. Render reconciliation compares
+actual optimistic text storage, updates CRDT metadata and acknowledges visually
+equal generations. Zoom keeps logical layout independent of magnified viewport.
+
+## Verification and remaining coverage
+
+Implementation reviewed by GPT-6 Astra (high), including a final account-isolation
+and localization review. Both native Mac test suites and iOS simulator builds pass.
+A synthetic AppKit interaction fixture exercises Sheets typing successive characters,
+failed-save draft retention, Escape, and whole-row/column selection. A live SwiftUI
+scene probe verified File actions and Window > Home after closing Home.
+
+Docs regression tests cover minimal text-storage reconciliation, metadata-only
+updates and fixed logical page width. Deliberately restoring full storage replacement
+and viewport-dependent width made the corresponding tests fail. A synthetic WebKit
+fixture matches native heading, bold and body line breaks and body line spacing.
+
+The follow-up comparison suite loads the production web CSS, bundled fonts and
+pages.mjs pagination functions directly into WebKit. It covers nested lists and
+quotes, heading margins, serif/monospace fonts, inline code including a code span
+starting on a wrapped line, mixed 72pt text, whole-block pagination and an oversized
+first paragraph. Native Mac pagination now uses the same 648pt top-level-block
+budget, an 18pt separator and collapsed surrounding margins. It does not insert
+characters or change CRDT data. Font struts and per-run half-leading determine
+line height; nested margins are collapsed before TextKit layout.
+
+Storage edits invalidate separator offsets immediately, including optimistic edits
+and marked-text composition. A regression test inserts, composes and deletes before
+an existing separator. Unchanged view layouts reuse the measured pagination plan.
+Deliberately removing code-start padding and storage invalidation made their tests
+fail for the intended reasons; the restored implementations pass.
+
+Follow-up review: GPT-6 Astra (high), 2026-09-20; no remaining blocker in the bounded
+source review. Docs validation: 39 XCTest cases plus 15 Swift Testing cases pass,
+as does the iOS simulator build. The web comparison allows one CSS pixel for
+per-line metric rounding and 1.5pt accumulated position error across a long fixture.
+These are measured layout results, not a claim of pixel-identical rasterization or
+proof for every possible document. iOS retains its existing responsive paginator;
+the document-window pagination change targets Mac as requested.
+
+Builds are local ad-hoc Mac applications, not signed distribution or TestFlight
+releases. No server deployment, merge or publication was performed.
diff --git a/internal/docs/app.go b/internal/docs/app.go
index ccfb4e0..2422f7f 100644
--- a/internal/docs/app.go
+++ b/internal/docs/app.go
@@ -593,6 +593,7 @@ func New(cfg Config) (*App, error) {
// check of its own — a person's document titles are theirs.
r.Get("/documents/search", h.searchJSON)
r.Get("/d/{sqid}", h.show)
+ r.Post("/d/{sqid}/title", h.rename)
// Task 5: the update log, what the browser's editor reads to
// build its Yjs doc (GET) and posts new edits back through
// (POST) — see handlers.go's updatesGet/updatesPost. Neither
diff --git a/internal/docs/handlers.go b/internal/docs/handlers.go
index a0b6c73..3bfc1f8 100644
--- a/internal/docs/handlers.go
+++ b/internal/docs/handlers.go
@@ -11,6 +11,7 @@ import (
"strings"
"time"
+ "github.com/google/uuid"
"gorm.io/gorm"
"amadan.net/oficina/estilo.git/savestatus"
@@ -347,12 +348,30 @@ func (h *handlers) create(w http.ResponseWriter, r *http.Request) {
return
}
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusBadRequest)
+ return
+ }
+ token := r.PostFormValue("creation_token")
+ if token != "" {
+ parsed, err := uuid.Parse(token)
+ if err != nil {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusBadRequest)
+ return
+ }
+ token = parsed.String()
+ }
title := strings.TrimSpace(r.PostFormValue("title"))
+ if len(title) > 1024 {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusBadRequest)
+ return
+ }
if title == "" {
title = rastrillo.T(r, "docs.document.untitled")
}
- doc, err := h.store.Create(r.Context(), owner, title)
+ doc, err := h.store.CreateDraft(r.Context(), owner, title, token)
if err != nil {
h.logger.Error("docs: create document", "err", err)
http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
@@ -1002,3 +1021,37 @@ func formatWhen(now, t time.Time) string {
}
return t.Format("Jan 2, 2006")
}
+
+func (h *handlers) rename(w http.ResponseWriter, r *http.Request) {
+ doc, ok := h.getDocumentForUpdates(w, r)
+ if !ok {
+ return
+ }
+ actor, err := h.actor(r)
+ if err != nil {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
+ return
+ }
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ if err := r.ParseForm(); err != nil {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusBadRequest)
+ return
+ }
+ title := strings.TrimSpace(r.PostFormValue("title"))
+ if title == "" {
+ title = rastrillo.T(r, "docs.document.untitled")
+ }
+ if len(title) > 1024 {
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusBadRequest)
+ return
+ }
+ if err := h.store.Rename(r.Context(), actor, doc, title); err != nil {
+ if errors.Is(err, ErrNotWritable) || errors.Is(err, gorm.ErrRecordNotFound) {
+ http.Error(w, rastrillo.T(r, "docs.error.notfound"), http.StatusNotFound)
+ return
+ }
+ http.Error(w, rastrillo.T(r, "docs.error.generic"), h.internalFailureStatus())
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+}
diff --git a/internal/docs/migrations/0008_document_creation_token.sql b/internal/docs/migrations/0008_document_creation_token.sql
new file mode 100644
index 0000000..8c5e65c
--- /dev/null
+++ b/internal/docs/migrations/0008_document_creation_token.sql
@@ -0,0 +1,2 @@
+ALTER TABLE documents ADD COLUMN creation_token TEXT;
+CREATE UNIQUE INDEX documents_creation ON documents(owner_id, creation_token);
diff --git a/internal/docs/models.go b/internal/docs/models.go
index 6758361..bfc6c6f 100644
--- a/internal/docs/models.go
+++ b/internal/docs/models.go
@@ -49,7 +49,8 @@ type Document struct {
Sqid string `gorm:"column:sqid;uniqueIndex;not null"`
Title string `gorm:"column:title;not null"`
- OwnerID int64 `gorm:"column:owner_id;not null;index"`
+ OwnerID int64 `gorm:"column:owner_id;not null;index;uniqueIndex:documents_creation,priority:1"`
+ CreationToken *string `gorm:"column:creation_token;uniqueIndex:documents_creation,priority:2"`
GUID string `gorm:"column:guid;not null"`
ClientID uint64 `gorm:"column:client_id;not null"`
diff --git a/internal/docs/native_test.go b/internal/docs/native_test.go
index 7402a12..d0cbf19 100644
--- a/internal/docs/native_test.go
+++ b/internal/docs/native_test.go
@@ -160,3 +160,54 @@ func TestNativePublicLinkShownOnceAndAnonymousRefused(t *testing.T) {
t.Fatalf("anonymous native creation: %d", got.Code)
}
}
+
+func TestNativeDraftCreationRetryAndRename(t *testing.T) {
+ app := members(t, "alice@example.com,bob@example.com")
+ alice := signInCookies(t, app, "alice@example.com")
+ bob := signInCookies(t, app, "bob@example.com")
+ const form = "creation_token=dd1f5245-2d96-4f11-af6b-350de8c32896"
+ // Concurrent/lost-response retries must all resolve the same owner-scoped token.
+ results := make(chan *httptest.ResponseRecorder, 8)
+ for i := 0; i < 8; i++ {
+ go func() { results <- nativeRequest(app, alice, "POST", "/documents", form) }()
+ }
+ var sqid string
+ for i := 0; i < 8; i++ {
+ got := <-results
+ var doc struct{ Sqid string }
+ if got.Code != 201 || json.Unmarshal(got.Body.Bytes(), &doc) != nil {
+ t.Fatalf("create: %d %s", got.Code, got.Body.String())
+ }
+ if sqid != "" && sqid != doc.Sqid {
+ t.Fatal("retry created another document")
+ }
+ sqid = doc.Sqid
+ }
+ path := "/d/" + sqid
+ if got := nativeRequest(app, alice, "POST", path+"/title", "title=Renamed"); got.Code != 204 {
+ t.Fatalf("rename: %d %s", got.Code, got.Body.String())
+ }
+ var replay struct{ Sqid, Title string }
+ got := nativeRequest(app, alice, "POST", "/documents", form+"&title=Old")
+ if json.Unmarshal(got.Body.Bytes(), &replay) != nil || replay.Sqid != sqid || replay.Title != "Renamed" {
+ t.Fatalf("replay overwrote title: %s", got.Body.String())
+ }
+ if got := nativeRequest(app, bob, "POST", path+"/title", "title=Stolen"); got.Code != 404 {
+ t.Fatalf("stranger rename: %d", got.Code)
+ }
+ nativeRequest(app, alice, "POST", path+"/share", "address=bob%40example.com&role=reader")
+ if got := nativeRequest(app, bob, "POST", path+"/title", "title=Reader"); got.Code != 404 {
+ t.Fatalf("reader rename: %d", got.Code)
+ }
+ nativeRequest(app, alice, "POST", path+"/share", "address=bob%40example.com&role=writer")
+ if got := nativeRequest(app, bob, "POST", path+"/title", "title=Writer"); got.Code != 204 {
+ t.Fatalf("writer rename: %d", got.Code)
+ }
+ if got := nativeRequest(app, alice, "POST", path+"/title", "title="+strings.Repeat("a", 1025)); got.Code != 400 {
+ t.Fatalf("oversized title: %d", got.Code)
+ }
+ other := nativeRequest(app, bob, "POST", "/documents", form)
+ if json.Unmarshal(other.Body.Bytes(), &replay) != nil || replay.Sqid == sqid {
+ t.Fatal("creation token escaped owner scope")
+ }
+}
diff --git a/internal/docs/store.go b/internal/docs/store.go
index f96c9bd..414ea2c 100644
--- a/internal/docs/store.go
+++ b/internal/docs/store.go
@@ -279,6 +279,12 @@ func (s *Store) seedIfEnabled(ctx context.Context, newOwner int64, email string)
// SKILL.md §3: "Creating takes the owner from the session, never the
// form."
func (s *Store) Create(ctx context.Context, owner int64, title string) (*Document, error) {
+ return s.CreateDraft(ctx, owner, title, "")
+}
+
+// CreateDraft makes retries after a lost acknowledgement return the same document.
+// The token is scoped to the authenticated owner, never a document capability.
+func (s *Store) CreateDraft(ctx context.Context, owner int64, title, token string) (*Document, error) {
actor := s.ownerActor(ctx, owner)
if err := s.requireMember(ctx, actor); err != nil {
return nil, err
@@ -309,6 +315,21 @@ func (s *Store) Create(ctx context.Context, owner int64, title string) (*Documen
if err := s.requireMember(ctx, actor); err != nil {
return err
}
+ if token != "" {
+ var existing Document
+ err := tx.Where("owner_id = ? AND creation_token = ?", owner, token).First(&existing).Error
+ if err == nil {
+ if existing.DeletedAt != nil {
+ return gorm.ErrRecordNotFound
+ }
+ *doc = existing
+ return s.requireMember(ctx, actor)
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return err
+ }
+ doc.CreationToken = &token
+ }
if err := tx.Create(doc).Error; err != nil {
return err
}
@@ -891,3 +912,19 @@ func (s *Store) ApplyUpdate(ctx context.Context, doc *Document, actor Actor, upd
return assignedSeq, nil
}
+
+// Rename repeats write authorization within the transaction, as ApplyUpdate does.
+func (s *Store) Rename(ctx context.Context, actor Actor, doc *Document, title string) error {
+ if err := s.checkPermission(ctx, s.db.WithContext(ctx), actor, doc.ID, permissionWrite); err != nil {
+ return err
+ }
+ return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite); err != nil {
+ return err
+ }
+ if err := s.permissionScope(ctx, tx.Model(&Document{}), actor, permissionWrite).Where("documents.id = ? AND documents.deleted_at IS NULL", doc.ID).Updates(map[string]any{"title": title, "updated_at": time.Now().UTC()}).Error; err != nil {
+ return err
+ }
+ return s.checkPermission(ctx, tx, actor, doc.ID, permissionWrite)
+ })
+}
diff --git a/native/INSTANT-DOCUMENTS.md b/native/INSTANT-DOCUMENTS.md
new file mode 100644
index 0000000..19526d1
--- /dev/null
+++ b/native/INSTANT-DOCUMENTS.md
@@ -0,0 +1,28 @@
+# Immediate native documents
+
+New reserves an account-bound window and opens a local untitled replica. The
+initial paragraph and first editable generation are ready before the text view
+is exposed; no server request blocks the editor. Attachment preserves the
+window ID, text view, replica, generations, and selection.
+
+The draft owns a UUID creation token. POST /documents accepts creation_token;
+migration 0008 adds a nullable token with a unique (owner_id, creation_token)
+index. Creation and lookup run under the writer transaction. Replays return the
+existing document and never overwrite a later title. The token is not authority:
+creation still requires membership and derives its owner from the session.
+
+Drafts count as unsaved before initialization. Save/close awaits creation and
+queued content/title writes; failure retains the draft and token for retry.
+Discard changes the epoch so late responses cannot attach or upload discarded
+content. A server may already have created an empty document before cancellation.
+Local draft state is held in memory with the existing close/quit guards.
+
+Double-clicking the title or File > Rename document opens the same title input.
+The model owns that buffer so Save/close also commits it; Escape cancels it.
+Titles over 1024 UTF-8 bytes remain editable with an error. Rename uses the
+existing document write authorization inside the authenticated, CSRF-protected
+POST /d/{sqid}/title route. Pending titles survive capability refreshes.
+
+Deploy the backend migration/routes before publishing the native client. Older
+servers do not provide idempotent creation. Tests are documented in
+smoke/document-window/README.md. Design and implementation reviewed by GPT-6 Astra.
diff --git a/native/PrivacyInfo.xcprivacy b/native/PrivacyInfo.xcprivacy
new file mode 100644
index 0000000..79bc9e2
--- /dev/null
+++ b/native/PrivacyInfo.xcprivacy
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>NSPrivacyAccessedAPITypes</key>
+ <array>
+ <dict>
+ <key>NSPrivacyAccessedAPIType</key>
+ <string>NSPrivacyAccessedAPICategoryUserDefaults</string>
+ <key>NSPrivacyAccessedAPITypeReasons</key>
+ <array>
+ <string>CA92.1</string>
+ </array>
+ </dict>
+ </array>
+</dict>
+</plist>
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved
index c55671a..b524238 100644
--- a/native/apple/Package.resolved
+++ b/native/apple/Package.resolved
@@ -1,12 +1,21 @@
{
- "originHash" : "282a01a805ab90a6af712b45ea6b83e818878fd0896bf6a3ca7b45243a1afd4f",
+ "originHash" : "9f8c968e09f32ff2986c7249d011e7c8981f1171a5abe4d00e8b4e6680ad2777",
"pins" : [
{
"identity" : "native",
"kind" : "remoteSourceControl",
"location" : "https://amadan.net/rastrillo/native",
"state" : {
- "revision" : "a49307c29cf36dff2cf423c3f98b38269ce9a553"
+ "revision" : "229525909e1d6ac3b6a353d1c4d022798b0e9a24"
+ }
+ },
+ {
+ "identity" : "sparkle",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/sparkle-project/Sparkle",
+ "state" : {
+ "revision" : "ac2def288cbff5cfc7df3ffef6abdf45b72bcb0a",
+ "version" : "2.9.6"
}
}
],
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index 679dca9..b1be08e 100644
--- a/native/apple/Package.swift
+++ b/native/apple/Package.swift
@@ -1,11 +1,17 @@
// swift-tools-version: 6.2
import PackageDescription
+import Foundation
+
+let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) }
+ ?? .package(url: "https://amadan.net/rastrillo/native", revision: "229525909e1d6ac3b6a353d1c4d022798b0e9a24")
+
let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)],
products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])],
- dependencies: [.package(url: "https://amadan.net/rastrillo/native", revision: "a49307c29cf36dff2cf423c3f98b38269ce9a553")],
+ dependencies: [sharedNative],
targets: [
.binaryTarget(name: "DocsCRDT", path: "Artifacts/DocsCRDT.xcframework"),
.target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources")]),
- .executableTarget(name: "DocsMac", dependencies: ["DocsKit", .product(name: "RastrilloApple", package: "native")], path: "Sources/DocsApp"),
+ .executableTarget(name: "DocsMac", dependencies: [.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS])), "DocsKit", .product(name: "RastrilloApple", package: "native")], path: "Sources/DocsApp"),
.testTarget(name: "DocsKitTests", dependencies: ["DocsKit"]),
+ .testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", .product(name: "RastrilloApple", package: "native")]),
])
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift
new file mode 100644
index 0000000..4ae4781
--- /dev/null
+++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift
@@ -0,0 +1,52 @@
+import RastrilloApple
+import DocsKit
+import SwiftUI
+
+/// Each window owns its navigation and model lifetime. Switching an account in
+/// one window must never discard another window's unconfirmed edits.
+struct DocsAccountWindow: View {
+ @StateObject private var connection = NativeConnection(defaultServer: "https://docs.oficina.works")
+ #if os(macOS)
+ @Bindable var windows: DocsWindows
+ @Environment(\.openWindow) private var openWindow
+ #endif
+ var body: some View {
+ Group {
+ if let client = connection.client {
+ #if os(macOS)
+ if let account = connection.activeAccountID {
+ DocsWorkspace(client: client, accounts: connection.showAccounts, signOut: {
+ guard connection.activeAccountID == account, windows.canSignOut(account) else { return }
+ windows.entries.removeAll { $0.account == account }
+ connection.signOut()
+ }, createDocument: {
+ guard connection.activeAccountID == account else { return }
+ let id = windows.reserveDraft(account: account, client: client)
+ openWindow(id: "document", value: id)
+ }, canSignOut: windows.canSignOut(account), createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested, openDocument: { document, title in
+ guard connection.activeAccountID == account else { return }
+ let id = windows.reserve(account: account, document: document, title: title, client: client)
+ openWindow(id: "document", value: id)
+ }, updateRecents: { documents in
+ guard connection.activeAccountID == account else { return }
+ windows.updateRecents(documents, account: account, client: client)
+ })
+ .id(account)
+ }
+ #else
+ DocsWorkspace(client: client, accounts: connection.showAccounts, signOut: connection.signOut)
+ .id(connection.activeAccountID)
+ #endif
+ } else {
+ NativeAccountsView("Oficina Docs", systemImage: "doc.text", connection: connection)
+ }
+ }.onOpenURL(perform: connection.handleOpenURL)
+ #if os(macOS)
+ .onChange(of: windows.accountsRequested, initial: true) { _, requested in
+ if requested && connection.client == nil { windows.accountsRequested = false }
+ }
+ .focusedSceneValue(\.docsWindowAccount, connection.activeAccountID)
+ .onChange(of: connection.activeAccountID, initial: true) { _, value in windows.activeAccount = value }
+ #endif
+ }
+}
diff --git a/native/apple/Sources/DocsApp/DocsApp.swift b/native/apple/Sources/DocsApp/DocsApp.swift
index e4da282..e11d2f0 100644
--- a/native/apple/Sources/DocsApp/DocsApp.swift
+++ b/native/apple/Sources/DocsApp/DocsApp.swift
@@ -1,21 +1,35 @@
+#if os(macOS) && canImport(RastrilloMacUpdates)
+import RastrilloMacUpdates
+#endif
import DocsKit
import RastrilloApple
import SwiftUI
@main struct DocsApp: App {
+ #if os(macOS) && canImport(RastrilloMacUpdates)
+ @State private var updater = NativeUpdater()
+ #endif
#if os(macOS)
+ @State private var windows = DocsWindows()
@NSApplicationDelegateAdaptor(DocsApplicationDelegate.self) private var appDelegate
#endif
- @StateObject private var connection = NativeConnection(defaultServer: "https://docs.oficina.works")
var body: some Scene {
- WindowGroup {
- if let client = connection.client {
- DocsWorkspace(client: client, signOut: connection.signOut)
- } else {
- NativeSignInView("Oficina Docs", systemImage: "doc.text", connection: connection)
- }
- }
- #if os(macOS)
- .defaultSize(width: 1120, height: 820)
+ #if os(macOS)
+ Window(docsMacString("Home"), id: "home") { DocsAccountWindow(windows: windows) }
+ .defaultSize(width: 1000, height: 760)
+ .commands {
+ DocsWindowCommands(windows: windows)
+ DocsEditorCommands()
+ #if canImport(RastrilloMacUpdates)
+ NativeUpdateCommands(updater: updater)
#endif
+ }
+ WindowGroup(docsMacString("Docs"), id: "document", for: UUID.self) { $id in
+ DocsDocumentWindow(windows: windows, id: id)
}
+ .defaultSize(width: 1120, height: 820)
+ .restorationBehavior(.disabled)
+ #else
+ WindowGroup { DocsAccountWindow() }
+ #endif
+ }
}
diff --git a/native/apple/Sources/DocsApp/DocsDocumentWindow.swift b/native/apple/Sources/DocsApp/DocsDocumentWindow.swift
new file mode 100644
index 0000000..0fdf391
--- /dev/null
+++ b/native/apple/Sources/DocsApp/DocsDocumentWindow.swift
@@ -0,0 +1,23 @@
+#if os(macOS)
+import DocsKit
+import SwiftUI
+
+struct DocsDocumentWindow: View {
+ let windows: DocsWindows
+ let id: UUID?
+ @Environment(\.openWindow) private var openWindow
+ var body: some View {
+ if let entry = windows.entries.first(where: { $0.id == id }) {
+ DocsWorkspace(client: entry.client, signOut: {}, documentID: entry.document, newDocument: entry.isDraft, documentChanged: { document, title in windows.attach(entry.id, document: document, title: title) })
+ .id(entry.id)
+ .focusedSceneValue(\.docsWindowAccount, entry.account)
+ .onAppear { windows.setOpen(entry.id, true) }
+ .onDisappear { windows.setOpen(entry.id, false) }
+ } else {
+ ContentUnavailableView { Label(docsMacString("Open a document from Home"), systemImage: "house") } actions: {
+ Button(docsMacString("Home")) { openWindow(id: "home") }
+ }
+ }
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsApp/DocsWindowCommands.swift b/native/apple/Sources/DocsApp/DocsWindowCommands.swift
new file mode 100644
index 0000000..28ea9d7
--- /dev/null
+++ b/native/apple/Sources/DocsApp/DocsWindowCommands.swift
@@ -0,0 +1,48 @@
+#if os(macOS)
+import SwiftUI
+import DocsKit
+
+struct DocsWindowCommands: Commands {
+ let windows: DocsWindows
+ @FocusedValue(\.docsWindowAccount) private var account
+ @FocusedValue(\.docsAccountActions) private var accountActions
+ @Environment(\.openWindow) private var openWindow
+ var body: some Commands {
+ CommandGroup(after: .appSettings) {
+ Button(docsMacString("Accounts")) {
+ if let action = accountActions?.accounts { action() }
+ else { windows.accountsRequested = true; openWindow(id: "home") }
+ }.disabled(accountActions?.canManage == false)
+ Button(docsMacString("Sign out")) { accountActions?.signOut() }
+ .disabled(accountActions?.canSignOut != true)
+ Divider()
+ }
+
+ CommandGroup(replacing: .newItem) {
+ Button(docsMacString("New document")) {
+ if let entry = windows.entries.first(where: { $0.account == account && $0.isOpen }) {
+ let id = windows.reserveDraft(account: entry.account, client: entry.client)
+ openWindow(id: "document", value: id)
+ } else {
+ windows.createRequested = true
+ openWindow(id: "home")
+ }
+ }.keyboardShortcut("n")
+ Menu(docsMacString("Recent")) {
+ ForEach(windows.entries.filter { $0.account == (account ?? windows.activeAccount) }.prefix(20)) { entry in
+ Button(entry.title) {
+ windows.setOpen(entry.id, true)
+ openWindow(id: "document", value: entry.id)
+ }
+ }
+ if !windows.entries.contains(where: { $0.account == (account ?? windows.activeAccount) }) {
+ Text(docsMacString("No recent documents"))
+ }
+ }
+ Divider()
+ DocsDocumentMenu()
+ }
+
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsApp/DocsWindows.swift b/native/apple/Sources/DocsApp/DocsWindows.swift
new file mode 100644
index 0000000..41a682d
--- /dev/null
+++ b/native/apple/Sources/DocsApp/DocsWindows.swift
@@ -0,0 +1,63 @@
+#if os(macOS)
+import Foundation
+import DocsKit
+import Observation
+import RastrilloApple
+import SwiftUI
+
+/// Scene values are opaque IDs, never credentials. Reserve before opening a scene.
+@MainActor @Observable final class DocsWindows {
+ struct Entry: Identifiable {
+ let id: UUID
+ let account: String
+ var document: String
+ let client: NativeHTTP
+ var title: String
+ var isOpen = false
+ var isDraft = false
+ }
+ var entries: [Entry] = []
+ var activeAccount: String?
+ var createRequested = false
+ var accountsRequested = false
+ func reserve(account: String, document: String, title: String, client: NativeHTTP) -> UUID {
+ if let index = entries.firstIndex(where: { $0.account == account && $0.client.origin == client.origin && $0.document == document }) {
+ var entry = entries.remove(at: index)
+ entry.title = title
+ entry.isOpen = true
+ entries.insert(entry, at: 0)
+ return entry.id
+ }
+ let entry = Entry(id: UUID(), account: account, document: document, client: client, title: title, isOpen: true)
+ entries.insert(entry, at: 0)
+ return entry.id
+ }
+ func reserveDraft(account: String, client: NativeHTTP) -> UUID {
+ let id = UUID()
+ entries.insert(Entry(id: id, account: account, document: "draft-" + id.uuidString, client: client, title: docsMacString("Untitled document"), isOpen: true, isDraft: true), at: 0)
+ return id
+ }
+ func attach(_ id: UUID, document: String, title: String) {
+ guard let index = entries.firstIndex(where: { $0.id == id }) else { return }
+ entries[index].document = document; entries[index].title = title; entries[index].isDraft = false
+ let account = entries[index].account
+ entries.removeAll { $0.id != id && !$0.isOpen && $0.account == account && $0.document == document }
+ }
+ func updateRecents(_ documents: [(String, String)], account: String, client: NativeHTTP) {
+ for (document, title) in documents {
+ if let index = entries.firstIndex(where: { $0.account == account && $0.client.origin == client.origin && $0.document == document }) {
+ entries[index].title = title
+ } else {
+ entries.append(Entry(id: UUID(), account: account, document: document, client: client, title: title))
+ }
+ }
+ }
+ func setOpen(_ id: UUID, _ value: Bool) {
+ if let index = entries.firstIndex(where: { $0.id == id }) {
+ if !value && entries[index].isDraft { entries.remove(at: index) } else { entries[index].isOpen = value }
+ }
+ }
+ func canSignOut(_ account: String?) -> Bool { !entries.contains { $0.account == account && $0.isOpen } }
+}
+extension FocusedValues { @Entry var docsWindowAccount: String? }
+#endif
diff --git a/native/apple/Sources/DocsKit/CRDTReplica.swift b/native/apple/Sources/DocsKit/CRDTReplica.swift
index c1b9b7e..f9b987e 100644
--- a/native/apple/Sources/DocsKit/CRDTReplica.swift
+++ b/native/apple/Sources/DocsKit/CRDTReplica.swift
@@ -24,6 +24,7 @@ actor CRDTReplica {
}
}
private var authority: Sandbox?
+ private var merger: Sandbox?
private var opened = false
private var sources: [UInt64: Sandbox] = [:]
private var sourceSnapshots: [UInt64: Data] = [:]
@@ -34,7 +35,7 @@ actor CRDTReplica {
private let guid: String
enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit }
init(guid: String) { self.guid = guid }
- func close() { opened = false; authority = nil; sources.removeAll(); sourceSnapshots.removeAll(); lastGood = Data() }
+ func close() { opened = false; authority = nil; merger = nil; sources.removeAll(); sourceSnapshots.removeAll(); lastGood = Data() }
private func fresh(update: Data) throws -> (UInt64, Sandbox) {
let sandbox = try Sandbox()
var client = UInt64(UInt32.random(in: 1...UInt32.max))
@@ -107,6 +108,16 @@ actor CRDTReplica {
// clocks from a partially executed command. UI reports undo loss.
authority = try? fresh(update: lastGood).1
}
+ func mergeUpdates(_ updates: [Data]) throws -> Data {
+ guard let first = updates.first else { throw Failure.rejected }
+ if updates.count == 1 { return first }
+ guard opened else { throw Failure.unavailable }
+ if merger == nil { merger = try Sandbox() }
+ var envelope = Data([253])
+ for update in updates { envelope.append(update) }
+ do { return try merger!.invoke(envelope) }
+ catch { merger = nil; throw error }
+ }
func apply(_ update: Data) throws -> CRDTProjection {
let authority = try currentAuthority()
do {
diff --git a/native/apple/Sources/DocsKit/DocsAccountActions.swift b/native/apple/Sources/DocsKit/DocsAccountActions.swift
new file mode 100644
index 0000000..8bca77a
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsAccountActions.swift
@@ -0,0 +1,10 @@
+#if os(macOS)
+import SwiftUI
+public struct DocsAccountActions {
+ public let accounts: (() -> Void)?
+ public let signOut: () -> Void
+ public let canManage: Bool
+ public let canSignOut: Bool
+}
+extension FocusedValues { @Entry public var docsAccountActions: DocsAccountActions? }
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsDocumentMenu.swift b/native/apple/Sources/DocsKit/DocsDocumentMenu.swift
new file mode 100644
index 0000000..728a9b8
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsDocumentMenu.swift
@@ -0,0 +1,28 @@
+#if os(macOS)
+import SwiftUI
+
+public struct DocsDocumentMenu: View {
+ @FocusedValue(\.docsEditor) private var editor
+ public init() {}
+ public var body: some View {
+ Group {
+ Button { editor?.rename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) }
+ .keyboardShortcut("r", modifiers: [.command, .shift]).disabled(editor?.model.detail?.can_write != true)
+ Button(docsMacString("Save")) { if let editor { Task { _ = await editor.model.saveAll() } } }
+ .keyboardShortcut("s").disabled(editor == nil)
+ Menu(docsMacString("Export")) {
+ Button(docsMacString("PDF…")) { editor?.exportRequest.wrappedValue = "pdf" }
+ Button(docsMacString("Markdown…")) { editor?.exportRequest.wrappedValue = "markdown" }
+ }.disabled(editor == nil || editor?.model.isDraft == true)
+ Button(docsMacString("Share…")) {
+ if let editor { Task { if await editor.model.saveAll() { editor.sharing.wrappedValue = true } } }
+ }.disabled(editor?.model.detail?.can_share != true)
+
+ Divider()
+
+ Button(docsMacString("Print…")) { editor?.exportRequest.wrappedValue = "print" }.keyboardShortcut("p").disabled(editor == nil || editor?.model.isDraft == true)
+
+ }
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsEditorCommands.swift b/native/apple/Sources/DocsKit/DocsEditorCommands.swift
new file mode 100644
index 0000000..91c1104
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsEditorCommands.swift
@@ -0,0 +1,58 @@
+#if os(macOS)
+import AppKit
+import SwiftUI
+
+public struct DocsEditorCommands: Commands {
+ @FocusedValue(\.docsEditor) private var editor
+ public init() {}
+ public var body: some Commands {
+
+ CommandGroup(replacing: .printItem) {}
+
+ CommandMenu(docsMacString("Format")) {
+ Group {
+ Button(docsMacString("Bold")) { editor?.actions?.perform("bold") }.keyboardShortcut("b")
+ Button(docsMacString("Italic")) { editor?.actions?.perform("italic") }.keyboardShortcut("i")
+ Button(docsMacString("Inline code")) { editor?.actions?.perform("code") }
+ Menu(docsMacString("Paragraph style")) {
+ Button(docsMacString("Normal")) { editor?.actions?.block("paragraph") }
+ ForEach(1...6, id: \.self) { level in
+ Button(String(format: docsMacString("Heading %d"), level)) { editor?.actions?.block("heading", level: level) }
+ }
+ Button(docsMacString("Bullet list")) { editor?.actions?.block("bullet_list") }
+ Button(docsMacString("Numbered list")) { editor?.actions?.block("ordered_list") }
+ Button(docsMacString("Block quote")) { editor?.actions?.block("blockquote") }
+ }
+ Menu(docsMacString("Font")) {
+ ForEach(["sans", "serif", "mono"], id: \.self) { family in
+ Button(String(localized: String.LocalizationValue("docs.editor.toolbar.font." + family), bundle: DocsResources.bundle)) { editor?.actions?.format("font_" + family, exclusive: ["font_sans", "font_serif", "font_mono"]) }
+ }
+ }
+ Menu(docsMacString("Size")) {
+ ForEach([8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 72], id: \.self) { size in
+ Button(size.formatted()) { editor?.actions?.format("size_\(size)", exclusive: [8,9,10,11,12,14,18,24,36,48,72].map { "size_\($0)" } + ["size_sm", "size_lg", "size_xl"]) }
+ }
+ }
+ Menu(docsMacString("Alignment")) {
+ ForEach(["left", "center", "right"], id: \.self) { value in
+ Button(String(localized: String.LocalizationValue("docs.editor.toolbar.align." + value), bundle: DocsResources.bundle)) { editor?.actions?.blockAttribute("align", value: value == "left" ? nil : value) }
+ }
+ }
+ Button(docsMacString("Indent")) { editor?.actions?.perform("indent") }
+ Button(docsMacString("Outdent")) { editor?.actions?.perform("outdent") }
+ Button(docsMacString("Clear formatting")) { editor?.actions?.perform("clear-format") }
+ }.disabled(editor?.actions?.isEnabled != true || !(NSApp.keyWindow?.firstResponder is DocsTextView))
+ }
+ CommandGroup(after: .toolbar) {
+ Menu(docsMacString("Zoom")) {
+ ForEach([0.5, 0.75, 1.0, 1.25, 1.5, 2.0], id: \.self) { value in
+ Button { editor?.zoom.wrappedValue = value } label: { Text(value, format: .percent) }
+ }
+ }.disabled(editor == nil)
+ Button(docsMacString("Actual size")) { editor?.zoom.wrappedValue = 1 }.keyboardShortcut("0").disabled(editor == nil)
+ Button(docsMacString("Document inspector")) { editor?.inspecting.wrappedValue.toggle() }.disabled(editor == nil)
+ if let editor { Toggle(docsMacString("Pages"), isOn: editor.paged) }
+ }
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsEditorContext.swift b/native/apple/Sources/DocsKit/DocsEditorContext.swift
new file mode 100644
index 0000000..9b9ac73
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsEditorContext.swift
@@ -0,0 +1,21 @@
+#if os(macOS)
+import AppKit
+import RastrilloApple
+import SwiftUI
+
+struct DocsEditorContext {
+ let model: DocsModel
+ let rename: () -> Void
+ let client: NativeHTTP
+ let zoom: Binding<Double>
+ let paged: Binding<Bool>
+ let inspecting: Binding<Bool>
+ let sharing: Binding<Bool>
+ let exportRequest: Binding<String?>
+ @MainActor var actions: DocumentCommands? {
+ guard NSApp.keyWindow?.firstResponder is DocsTextView, let projection = model.projection else { return nil }
+ return DocumentCommands(model: model, content: NativeTextProjection.render(projection))
+ }
+}
+extension FocusedValues { @Entry var docsEditor: DocsEditorContext? }
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsFonts.swift b/native/apple/Sources/DocsKit/DocsFonts.swift
index a8328d4..d73fbe8 100644
--- a/native/apple/Sources/DocsKit/DocsFonts.swift
+++ b/native/apple/Sources/DocsKit/DocsFonts.swift
@@ -28,6 +28,7 @@ typealias DocsPlatformFont = UIFont
else if key == "size_lg" { size = 14 }
else if key == "size_xl" { size = 18 }
}
+ if marks["code"] != nil { size *= 0.85 }
let family = marks["font_mono"] != nil || marks["code"] != nil ? "Mono" : marks["font_serif"] != nil ? "Serif" : "Sans"
let bold = marks["strong"] != nil || heading
let italic = marks["em"] != nil
diff --git a/native/apple/Sources/DocsKit/DocsLayoutManager.swift b/native/apple/Sources/DocsKit/DocsLayoutManager.swift
new file mode 100644
index 0000000..206380b
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsLayoutManager.swift
@@ -0,0 +1,70 @@
+#if os(macOS)
+import AppKit
+
+extension NSAttributedString.Key {
+ static let docsBaseFont = NSAttributedString.Key("OficinaDocsBaseFont")
+ static let docsLeading = NSAttributedString.Key("OficinaDocsLeading")
+}
+
+/// CSS line boxes include the paragraph's font strut and each inline run's
+/// half-leading. TextKit's single paragraph multiplier cannot express that when
+/// a line mixes font families or sizes.
+@MainActor final class DocsLayoutManager: NSLayoutManager, @preconcurrency NSLayoutManagerDelegate {
+ private(set) var storageRevision: UInt64 = 0
+ override func processEditing(for textStorage: NSTextStorage, edited editMask: NSTextStorageEditActions,
+ range newCharRange: NSRange, changeInLength delta: Int, invalidatedRange invalidatedCharRange: NSRange) {
+ super.processEditing(for: textStorage, edited: editMask, range: newCharRange,
+ changeInLength: delta, invalidatedRange: invalidatedCharRange)
+ storageRevision &+= 1
+ for container in textContainers {
+ (container.textView as? DocsPagedTextView)?.invalidatePagination()
+ }
+ }
+ override init() { super.init(); usesFontLeading = false; delegate = self }
+ required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
+ override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: NSPoint) {
+ super.drawBackground(forGlyphRange: glyphsToShow, at: origin)
+ guard let storage = textStorage, let container = textContainers.first as? DocsPageTextContainer else { return }
+ let characters = characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)
+ storage.enumerateAttribute(.docsQuoteBorders, in: characters) { value, range, _ in
+ guard let borders = value as? [CGFloat] else { return }
+ let glyphs = self.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
+ var bounds = self.boundingRect(forGlyphRange: glyphs, in: container)
+ bounds.origin.y += origin.y
+ NSColor(white: 200.0 / 255, alpha: 1).setFill()
+ for inset in borders {
+ CGRect(x: origin.x + container.geometry.textX + inset, y: bounds.minY, width: 2.25, height: bounds.height).fill()
+ }
+ }
+ }
+ func layoutManager(_ layoutManager: NSLayoutManager, shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<NSRect>,
+ lineFragmentUsedRect: UnsafeMutablePointer<NSRect>, baselineOffset: UnsafeMutablePointer<CGFloat>,
+ in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool {
+ guard let storage = textStorage, glyphRange.length > 0 else { return false }
+ let range = characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
+ guard range.location < storage.length,
+ let base = storage.attribute(.docsBaseFont, at: range.location, effectiveRange: nil) as? NSFont,
+ let leading = storage.attribute(.docsLeading, at: range.location, effectiveRange: nil) as? CGFloat else { return false }
+ var above: CGFloat = 0, below: CGFloat = 0
+ func include(_ font: NSFont) {
+ let halfLeading = (font.pointSize * leading - font.ascender + font.descender) / 2
+ above = max(above, font.ascender + halfLeading)
+ below = max(below, -font.descender + halfLeading)
+ }
+ include(base)
+ var attachment = false
+ storage.enumerateAttributes(in: range) { attributes, _, _ in
+ if let font = attributes[.font] as? NSFont { include(font) }
+ if attributes[.attachment] != nil { attachment = true }
+ }
+ guard !attachment else { return false }
+ let end = NSMaxRange(range)
+ let endsParagraph = end > 0 && (storage.string as NSString).character(at: end - 1) == 10
+ let style = storage.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle
+ lineFragmentRect.pointee.size.height = above + below + (endsParagraph ? style?.paragraphSpacing ?? 0 : 0)
+ lineFragmentUsedRect.pointee.size.height = above + below
+ baselineOffset.pointee = above
+ return true
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocsMacStrings.swift b/native/apple/Sources/DocsKit/DocsMacStrings.swift
new file mode 100644
index 0000000..d93cae4
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocsMacStrings.swift
@@ -0,0 +1,5 @@
+import Foundation
+
+public func docsMacString(_ key: String) -> String {
+ NSLocalizedString(key, tableName: "Mac", bundle: DocsResources.bundle, comment: "")
+}
diff --git a/native/apple/Sources/DocsKit/DocsModel.swift b/native/apple/Sources/DocsKit/DocsModel.swift
index d1527bc..545f7f0 100644
--- a/native/apple/Sources/DocsKit/DocsModel.swift
+++ b/native/apple/Sources/DocsKit/DocsModel.swift
@@ -3,6 +3,9 @@ import Observation
import RastrilloApple
@MainActor @Observable final class DocsModel {
+ enum ListState { case loading, loaded, failed }
+ var listState = ListState.loading
+ private var listRequest = UUID()
var documents: [DocumentSummary] = []
var canCreate = false
var errorKey: String?
@@ -14,6 +17,16 @@ import RastrilloApple
var inputPaused = false
var explicitCommandRevision: UInt64 = 0
var loading = false
+ var creatingDocument = false
+ private var lifetime = UUID()
+ private(set) var draftToken: String?
+ private var creationTask: Task<Void, Never>?
+ private var pendingTitle: String?
+ var renameInput: String?
+ private var titleRevision: UInt64 = 0
+ var isDraft: Bool { draftToken != nil }
+ var editorIdentity = UUID()
+
var selection = NSRange(location: 0, length: 0)
var typingMarks: [String: JSONValue]?
private var replica: CRDTReplica?
@@ -26,29 +39,102 @@ import RastrilloApple
private var documentEpoch = UUID()
private let publications = DocumentPublication()
private let client: NativeHTTP
- init(client: NativeHTTP) { self.client = client }
+ init(client: NativeHTTP, draft: Bool = false) { self.client = client; if draft { draftToken = UUID().uuidString } }
var hasPendingInput: Bool { !editing.isEmpty || editingTask != nil }
- var hasUnsavedChanges: Bool { composing || !pending.isEmpty || !editing.isEmpty || editingTask != nil }
+ var hasUnsavedChanges: Bool { (renameInput != nil && renameInput != detail?.title) || isDraft || pendingTitle != nil || composing || !pending.isEmpty || !editing.isEmpty || editingTask != nil }
func load(query: String = "") async {
+ let request = UUID(); listRequest = request
+ listState = .loading
do {
var components = URLComponents(); components.queryItems = [URLQueryItem(name: "q", value: query)]
let q = (components.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B")
let response: DocumentList = try await client.request("/?\(q)")
+ guard listRequest == request, !Task.isCancelled else { return }
documents = response.documents; canCreate = response.can_create
- } catch { errorKey = "docs.error.generic" }
+ listState = .loaded; errorKey = nil
+ } catch {
+ guard listRequest == request else { return }
+ listState = .failed; errorKey = "docs.error.generic"
+ }
+ }
+ /// The editor and its initial paragraph are local. Server acknowledgement
+ /// only attaches an identity; it never reconstructs the editor or selection.
+ func newDraft() async {
+ guard detail == nil, replica == nil else { return }
+ if draftToken == nil { draftToken = UUID().uuidString }
+ let epoch = documentEpoch
+ let guid = UUID().uuidString
+ let local = CRDTReplica(guid: guid)
+ loading = true
+ defer { if documentEpoch == epoch { loading = false } }
+ do {
+ _ = try await local.open(update: Data())
+ let (update, _) = try await local.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ guard documentEpoch == epoch else { await local.close(); return }
+ replica = local; pending.append(update)
+ detail = DocumentDetail(sqid: "draft-" + draftToken!, title: String(localized: "docs.document.untitled", bundle: DocsResources.bundle), guid: guid, can_write: true, can_share: false)
+ await publish()
+ guard documentEpoch == epoch else { return }
+ startCreation()
+ } catch { if documentEpoch == epoch { errorKey = "native.pending" } }
+ }
+ private func startCreation() {
+ guard creationTask == nil, draftToken != nil else { return }
+ creatingDocument = true
+ let epoch = documentEpoch
+ creationTask = Task {
+ await attachDraft(epoch: epoch)
+ if documentEpoch == epoch { creationTask = nil; creatingDocument = false }
+ }
}
- func create(title: String) async {
+ private func attachDraft(epoch: UUID) async {
+ guard let token = draftToken, let local = replica else { return }
do {
- var form = URLComponents(); form.queryItems = [URLQueryItem(name: "title", value: title)]
- let (data, status) = try await client.response("/documents", method: "POST", body: Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8), contentType: "application/x-www-form-urlencoded")
+ let body = Self.form(["title": detail?.title ?? "", "creation_token": token])
+ let (data, status) = try await client.response("/documents", method: "POST", body: body, contentType: "application/x-www-form-urlencoded")
guard status == 201 else { throw CRDTReplica.Failure.rejected }
let item = try JSONDecoder().decode(DocumentSummary.self, from: data)
- await load(); await open(item.sqid)
- } catch { errorKey = "docs.error.generic" }
+ guard documentEpoch == epoch else { return }
+ let attached: DocumentDetail = try await client.request("/d/\(item.sqid)")
+ let reply = try await client.responseDetails("/d/\(item.sqid)/updates", maxBytes: 8 * 1024 * 1024)
+ guard reply.status == 200, let seq = Int64(reply.header("Docs-Seq") ?? ""), attached.can_write else { throw CRDTReplica.Failure.rejected }
+ guard documentEpoch == epoch else { return }
+ if !reply.data.isEmpty { _ = try await local.apply(reply.data) }
+ guard documentEpoch == epoch else { return }
+ detail = DocumentDetail(sqid: attached.sqid, title: pendingTitle ?? attached.title, guid: attached.guid, can_write: attached.can_write, can_share: attached.can_share)
+ draftToken = nil; sequence = seq; errorKey = nil
+ // Do not publish while native callbacks are still in flight.
+ if !hasPendingInput { await publish() }
+ guard documentEpoch == epoch else { return }
+ streamTask = Task { [weak self] in await self?.listen(item.sqid) }
+ await flush()
+ } catch { if documentEpoch == epoch { errorKey = "native.pending" } }
+ }
+ private static func form(_ values: [String: String]) -> Data {
+ var form = URLComponents()
+ form.queryItems = values.map { URLQueryItem(name: $0.key, value: $0.value) }
+ return Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8)
+ }
+ @discardableResult func commitRename() -> Bool {
+ guard let value = renameInput else { return true }
+ guard rename(value) else { return false }
+ renameInput = nil
+ return true
+ }
+ @discardableResult func rename(_ value: String) -> Bool {
+ guard let detail, detail.can_write else { return false }
+ let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ let title = trimmed.isEmpty ? String(localized: "docs.document.untitled", bundle: DocsResources.bundle) : trimmed
+ guard title.utf8.count <= 1024 else { errorKey = "docs.error.generic"; return false }
+ guard title != detail.title else { return true }
+ self.detail = DocumentDetail(sqid: detail.sqid, title: title, guid: detail.guid, can_write: detail.can_write, can_share: detail.can_share)
+ pendingTitle = title; titleRevision &+= 1
+ Task { await flush() }
+ return true
}
func open(_ sqid: String) async {
guard !hasUnsavedChanges else { errorKey = "native.pending"; return }
- let epoch = UUID(); documentEpoch = epoch
+ let epoch = UUID(); documentEpoch = epoch; editorIdentity = UUID()
streamTask?.cancel(); streamTask = nil
let previous = replica; replica = nil; detail = nil; projection = nil
loading = true; errorKey = nil
@@ -63,7 +149,7 @@ import RastrilloApple
let replica = CRDTReplica(guid: detail.guid)
let projection = try await replica.open(update: reply.data)
guard documentEpoch == epoch else { await replica.close(); return }
- self.replica = replica; self.projection = projection; self.detail = detail; sequence = seq
+ self.replica = replica; self.detail = detail; sequence = seq
projectionGeneration = 0; renderedGeneration = 0
selection = NSRange(location: 0, length: 0); typingMarks = nil
composing = false; inputPaused = false
@@ -131,6 +217,11 @@ import RastrilloApple
} catch { if documentEpoch == epoch { errorKey = "native.recovered" } }
}
func retry() async {
+ if isDraft {
+ if replica == nil { await newDraft() } else { startCreation() }
+ await creationTask?.value
+ return
+ }
if inputPaused {
let epoch = documentEpoch
if let detail { await refreshAccess(detail.sqid, epoch: epoch) }
@@ -140,6 +231,7 @@ import RastrilloApple
} else { await flush() }
}
func stop() async {
+ lifetime = UUID()
guard !hasUnsavedChanges else { return }
documentEpoch = UUID(); streamTask?.cancel(); streamTask = nil
let previous = replica; replica = nil; detail = nil; projection = nil
@@ -149,6 +241,8 @@ import RastrilloApple
/// update remains part of the shared document, as in the web editor.
func discardAll() async {
documentEpoch = UUID()
+ creationTask?.cancel(); creationTask = nil; creatingDocument = false
+ draftToken = nil; pendingTitle = nil; renameInput = nil
streamTask?.cancel(); streamTask = nil
editingTask?.cancel(); editingTask = nil
pending.removeAll(); editing.removeAll(); saving = false
@@ -159,24 +253,53 @@ import RastrilloApple
if let previous { await previous.close() }
}
func saveAll() async -> Bool {
+ guard commitRename() else { return false }
+ if isDraft { startCreation(); await creationTask?.value }
if let editingTask { await editingTask.value }
while saving { try? await Task.sleep(for: .milliseconds(20)) }
await flush()
return !hasUnsavedChanges
}
func flush() async {
- guard !saving, let detail else { return }; saving = true
+ guard !isDraft, !saving, let detail, let replica else { return }; saving = true
let epoch = documentEpoch
defer { if documentEpoch == epoch { saving = false } }
- while let update = pending.first {
+ while !pending.isEmpty || pendingTitle != nil {
+ if let title = pendingTitle {
+ do {
+ let (_, status) = try await client.response("/d/\(detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded")
+ guard documentEpoch == epoch else { return }
+ guard status == 204 else { throw CRDTReplica.Failure.rejected }
+ if pendingTitle == title { pendingTitle = nil }
+ } catch { if documentEpoch == epoch { errorKey = "native.pending" }; return }
+ }
+ if pending.isEmpty { continue }
do {
+ // A slow request must not leave one full round trip per keypress.
+ // Keep the captured prefix until acknowledgement; edits appended
+ // during either await belong to the next batch.
+ var bytes = 0
+ let batch = pending.prefix { update in
+ guard bytes == 0 || bytes + update.count <= 512 * 1024 else { return false }
+ bytes += update.count
+ return true
+ }
+ var count = batch.count
+ let update: Data
+ do { update = try await replica.mergeUpdates(Array(batch)) }
+ catch {
+ // An optimization hitting its sandbox limit must not block saving.
+ update = batch.first!
+ count = 1
+ }
+ guard documentEpoch == epoch else { return }
let (_, status) = try await client.response("/d/\(detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream")
guard documentEpoch == epoch else { return }
guard status == 204 else {
if status == 401 || status == 403 || status == 404 { await refreshAccess(detail.sqid, epoch: epoch) }
throw CRDTReplica.Failure.rejected
}
- pending.removeFirst()
+ pending.removeFirst(count)
} catch { if documentEpoch == epoch { errorKey = "native.pending" }; return }
}
if errorKey == "native.pending" || errorKey == "docs.editor.status.retrying" { errorKey = nil }
@@ -216,12 +339,17 @@ import RastrilloApple
}
/// Revalidate capability after stream/write rejection while retaining the draft.
private func refreshAccess(_ sqid: String, epoch: UUID) async {
+ let revision = titleRevision
+ let hadPendingTitle = pendingTitle != nil
do {
let reply = try await client.responseDetails("/d/\(sqid)", maxBytes: 1024 * 1024)
guard documentEpoch == epoch else { return }
if reply.status == 200 {
let current = try JSONDecoder().decode(DocumentDetail.self, from: reply.data)
- detail = current
+ // The GET may have read its title before a rename acknowledged.
+ // Clearing pendingTitle must not let that old reply win afterward.
+ let title = pendingTitle ?? ((hadPendingTitle || titleRevision != revision) ? (detail?.title ?? current.title) : current.title)
+ detail = DocumentDetail(sqid: current.sqid, title: title, guid: current.guid, can_write: current.can_write, can_share: current.can_share)
if !current.can_write { inputPaused = true }
} else if [401, 403, 404].contains(reply.status) {
inputPaused = true
diff --git a/native/apple/Sources/DocsKit/DocsPagedTextView.swift b/native/apple/Sources/DocsKit/DocsPagedTextView.swift
index 2acd1a5..3ed20fc 100644
--- a/native/apple/Sources/DocsKit/DocsPagedTextView.swift
+++ b/native/apple/Sources/DocsKit/DocsPagedTextView.swift
@@ -5,60 +5,124 @@ import AppKit
@MainActor class DocsPagedTextView: NSTextView {
var paged = false { didSet { if oldValue != paged { needsLayout = true; needsDisplay = true } } }
private var updatingGeometry = false
+ private var updatingPagination = false
+ private var separators: [CGFloat] = []
+ private var measuredRevision: UInt64?
+ private var measuredWidth: CGFloat = 0
+ private var measuredPaged = false
+ private var measuredContent: NSAttributedString?
+ func invalidatePagination() {
+ measuredRevision = nil
+ // TextKit may ask for caret geometry before the next NSView layout.
+ // Prepare the complete page plan now, on an independent layout stack.
+ if !updatingGeometry { updatePagination() }
+ needsLayout = true
+ }
override init(frame frameRect: NSRect, textContainer container: NSTextContainer?) {
let storage = NSTextStorage()
- let manager = NSLayoutManager()
+ let manager = DocsLayoutManager()
+ manager.usesFontLeading = false
let pages = DocsPageTextContainer(size: CGSize(width: max(320, frameRect.width), height: 1_000_000))
pages.lineFragmentPadding = 0
storage.addLayoutManager(manager)
manager.addTextContainer(pages)
super.init(frame: frameRect, textContainer: pages)
textContainerInset = .zero
- isVerticallyResizable = true
+ // This view owns its paginated height; NSTextView auto-sizing uses a
+ // different used rect and briefly clips the current line during input.
+ isVerticallyResizable = false
isHorizontallyResizable = false
- drawsBackground = false
+ drawsBackground = true
textColor = .black
}
override convenience init(frame: NSRect) { self.init(frame: frame, textContainer: nil) }
required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
+ // Page margins are already part of DocsPageTextContainer's line geometry.
+ // NSTextView's inferred origin moves during incremental layout and can put
+ // its native insertion indicator at a different origin from the glyphs.
+ override var textContainerOrigin: NSPoint { .zero }
+ override func didChangeText() {
+ // Size the document before AppKit scrolls the newly edited caret.
+ needsLayout = true
+ layoutSubtreeIfNeeded()
+ super.didChangeText()
+ }
+ private var viewportWidth: CGFloat { max(636, enclosingScrollView?.contentView.bounds.width ?? bounds.width) }
+ private func updatePagination() {
+ guard !updatingPagination else { return }
+ updatingPagination = true
+ defer { updatingPagination = false }
+ guard let pages = textContainer as? DocsPageTextContainer,
+ let manager = layoutManager as? DocsLayoutManager, let storage = textStorage else { return }
+ let width = viewportWidth
+ let size = CGSize(width: width, height: 1_000_000)
+ if pages.size != size { pages.size = size }
+ pages.geometry = DocsPageGeometry(viewportWidth: width, paged: false)
+ let revision = manager.storageRevision
+ guard measuredRevision != revision || measuredWidth != width || measuredPaged != paged else { return }
+ let content = paged ? DocumentPageLayout.measurementContent(storage) : nil
+ if measuredWidth == width, measuredPaged == paged, let content, measuredContent?.isEqual(to: content) == true {
+ measuredRevision = revision
+ return
+ }
+ var plan = DocumentPageLayout.Result()
+ if let content {
+ // Never clear the live container to measure unpaginated content: doing
+ // so exposes a second set of caret/scroll coordinates during edits.
+ let measurement = NSTextStorage(attributedString: content)
+ let measurementManager = DocsLayoutManager()
+ let measurementContainer = DocsPageTextContainer(size: size)
+ measurementContainer.lineFragmentPadding = 0
+ measurementContainer.geometry = pages.geometry
+ measurement.addLayoutManager(measurementManager)
+ measurementManager.addTextContainer(measurementContainer)
+ measurementManager.ensureLayout(for: measurementContainer)
+ plan = DocumentPageLayout.measure(storage: measurement, manager: measurementManager, container: measurementContainer)
+ }
+ if pages.blockStarts != plan.starts || separators != plan.separators { needsDisplay = true }
+ pages.blockStarts = plan.starts
+ separators = plan.separators
+ measuredRevision = revision; measuredWidth = width; measuredPaged = paged
+ measuredContent = content
+ }
override func layout() {
- super.layout()
guard !updatingGeometry, let pages = textContainer as? DocsPageTextContainer,
let manager = layoutManager else { return }
updatingGeometry = true
defer { updatingGeometry = false }
- let width = max(160, enclosingScrollView?.contentSize.width ?? bounds.width)
- let size = CGSize(width: width, height: 1_000_000)
- if pages.size != size { pages.size = size }
- pages.geometry = DocsPageGeometry(viewportWidth: width, paged: paged)
+ updatePagination()
+ // AppKit must only lay out the caret after final page coordinates exist.
+ super.layout()
manager.ensureLayout(for: pages)
- let height = pages.geometry.documentHeight(usedHeight: manager.usedRect(for: pages).maxY)
+ let width = viewportWidth
+ let bottom = manager.numberOfGlyphs > 0
+ ? manager.lineFragmentRect(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil).maxY : DocsPageGeometry.verticalMargin
+ let height = pages.geometry.documentHeight(usedHeight: bottom)
if abs(frame.width - width) > 0.5 || abs(frame.height - height) > 0.5 {
setFrameSize(CGSize(width: width, height: height))
}
- needsDisplay = true
}
- override func draw(_ dirtyRect: NSRect) {
+ override func drawBackground(in dirtyRect: NSRect) {
+ NSGraphicsContext.saveGraphicsState()
+ defer { NSGraphicsContext.restoreGraphicsState() }
+ dirtyRect.clip()
NSColor.windowBackgroundColor.setFill()
dirtyRect.fill()
if let pages = textContainer as? DocsPageTextContainer {
let geometry = pages.geometry
+ NSColor.white.setFill()
+ CGRect(x: geometry.paperX, y: 0, width: geometry.paperWidth, height: bounds.height).fill()
if paged {
- for page in geometry.page(at: dirtyRect.minY)...geometry.page(at: dirtyRect.maxY) {
- NSColor.white.setFill()
- geometry.pageRect(page).fill()
+ for (index, y) in separators.enumerated() where y + 18 >= dirtyRect.minY && y <= dirtyRect.maxY {
+ NSColor.windowBackgroundColor.setFill()
+ CGRect(x: geometry.paperX, y: y, width: geometry.paperWidth, height: 18).fill()
let label = String(localized: "docs.editor.page.number", bundle: DocsResources.bundle)
- .replacingOccurrences(of: "{n}", with: String(page + 1))
- (label as NSString).draw(at: CGPoint(x: geometry.paperX + geometry.paperWidth - 80,
- y: CGFloat(page) * geometry.stride + DocsPageGeometry.paperHeight - 35),
+ .replacingOccurrences(of: "{n}", with: String(index + 2))
+ (label as NSString).draw(at: CGPoint(x: geometry.paperX + geometry.paperWidth - 80, y: y + 3),
withAttributes: [.font: NSFont.systemFont(ofSize: 10), .foregroundColor: NSColor.darkGray])
}
- } else {
- NSColor.white.setFill()
- CGRect(x: geometry.paperX, y: 0, width: geometry.paperWidth, height: bounds.height).fill()
}
}
- super.draw(dirtyRect)
}
}
#else
@@ -70,6 +134,7 @@ import UIKit
override init(frame: CGRect = .zero, textContainer: NSTextContainer? = nil) {
let storage = NSTextStorage()
let manager = NSLayoutManager()
+ manager.usesFontLeading = false
let pages = DocsPageTextContainer(size: CGSize(width: max(320, frame.width), height: 1_000_000))
pages.lineFragmentPadding = 0
storage.addLayoutManager(manager)
diff --git a/native/apple/Sources/DocsKit/DocsPaging.swift b/native/apple/Sources/DocsKit/DocsPaging.swift
index aadca0f..8717aef 100644
--- a/native/apple/Sources/DocsKit/DocsPaging.swift
+++ b/native/apple/Sources/DocsKit/DocsPaging.swift
@@ -14,7 +14,13 @@ struct DocsPageGeometry: Equatable, Sendable {
static let paperHeight: CGFloat = 792
static let verticalMargin: CGFloat = 72
static let gap: CGFloat = 24
- var paperWidth: CGFloat { min(612, max(160, viewportWidth - 24)) }
+ var paperWidth: CGFloat {
+ #if os(macOS)
+ 612
+ #else
+ min(612, max(160, viewportWidth - 24))
+ #endif
+ }
var paperX: CGFloat { max(0, (viewportWidth - paperWidth) / 2) }
var sideMargin: CGFloat { paperWidth < 480 ? 20 : 72 }
var textX: CGFloat { paperX + sideMargin }
@@ -50,6 +56,11 @@ struct DocsPageGeometry: Equatable, Sendable {
}
final class DocsPageTextContainer: NSTextContainer {
+ #if os(macOS)
+ var blockStarts: [Int: CGFloat] = [:] {
+ didSet { if oldValue != blockStarts { layoutManager?.textContainerChangedGeometry(self) } }
+ }
+ #endif
var geometry = DocsPageGeometry(viewportWidth: 612, paged: false) {
didSet {
if oldValue != geometry { layoutManager?.textContainerChangedGeometry(self) }
@@ -62,6 +73,21 @@ final class DocsPageTextContainer: NSTextContainer {
remaining remainingRect: UnsafeMutablePointer<CGRect>?
) -> CGRect {
remainingRect?.pointee = .zero
- return geometry.lineRect(proposedRect)
+ var rect = geometry.lineRect(proposedRect)
+ #if os(macOS)
+ if let top = blockStarts[characterIndex] { rect.origin.y = max(rect.minY, top) }
+ #endif
+ if let storage = layoutManager?.textStorage, characterIndex < storage.length {
+ if characterIndex == 0, let margin = storage.attribute(.docsFirstMargin, at: 0, effectiveRange: nil) as? CGFloat {
+ rect.origin.y = max(rect.minY, DocsPageGeometry.verticalMargin + margin)
+ }
+ var range = NSRange()
+ if let padding = storage.attribute(.docsCodeStart, at: characterIndex, effectiveRange: &range) as? CGFloat,
+ range.location == characterIndex {
+ rect.origin.x += padding
+ rect.size.width = max(0, rect.width - padding)
+ }
+ }
+ return rect
}
}
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index fc412e7..5c28ab3 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -3,21 +3,36 @@ import SwiftUI
@MainActor public struct DocsWorkspace: View {
@State private var model: DocsModel
@State private var query = ""
- @State private var newTitle = ""
- @State private var creating = false
+ @State private var renaming = false
+ @FocusState private var titleFocused: Bool
+ private let newDocument: Bool
+ private let createDocument: (() -> Void)?
+ private let documentChanged: ((String, String) -> Void)?
@AppStorage("docs.view.paged") private var paged = true
@State private var sharing = false
+ @State private var exportRequest: String?
+ @Environment(\.openWindow) private var openWindow
@State private var jumping = false
@State private var discarding = false
@State private var images = DocsImageStore()
@State private var column: NavigationSplitViewColumn = .sidebar
+ private let updateRecents: (([(String, String)]) -> Void)?
+ private let canSignOut: Bool
+ @Binding private var accountsRequested: Bool
+ @Binding private var createRequested: Bool
+ private let documentID: String?
+ private let openDocument: ((String, String) -> Void)?
+ @State private var zoom = 1.0
+ @State private var inspecting = false
private let signOut: () -> Void
+ private let accounts: (() -> Void)?
private let client: NativeHTTP
- public init(client: NativeHTTP, signOut: @escaping () -> Void) {
- _model = State(initialValue: DocsModel(client: client)); self.signOut = signOut; self.client = client
+ public init(client: NativeHTTP, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) {
+ self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument
+ self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged
+ _model = State(initialValue: DocsModel(client: client, draft: newDocument)); self.signOut = signOut; self.accounts = accounts; self.client = client
}
- public var body: some View {
- NavigationSplitView(preferredCompactColumn: $column) {
+ private var library: some View {
List {
ForEach(model.documents) { document in
Button { Task { await model.open(document.sqid) } } label: {
@@ -29,11 +44,102 @@ import SwiftUI
.onSubmit(of: .search) { Task { await model.load(query: query) } }
.navigationTitle(Text("native.docs", bundle: DocsResources.bundle))
.toolbar {
+ if let accounts {
+ ToolbarItem(placement: .navigation) {
+ Button(docsMacString("Accounts"), systemImage: "chevron.backward", action: accounts).disabled(model.hasUnsavedChanges || model.creatingDocument)
+ }
+ }
+
+ ToolbarItemGroup {
DocsJumpControls(presented: $jumping)
- if model.canCreate { Button { creating = true } label: { Label { Text("docs.list.create.label", bundle: DocsResources.bundle) } icon: { Image(systemName: "plus") } }.accessibilityIdentifier("docs.create") }
- Button { if !model.hasUnsavedChanges { signOut() } } label: { Text("docs.signout.label", bundle: DocsResources.bundle) }.disabled(model.hasUnsavedChanges)
+ if model.canCreate { Button { beginDocument() } label: { Label { Text("docs.list.create.label", bundle: DocsResources.bundle) } icon: { Image(systemName: "plus") } }.accessibilityIdentifier("docs.create") }
+ Button { if !model.hasUnsavedChanges && !model.creatingDocument { signOut() } } label: { Text("docs.signout.label", bundle: DocsResources.bundle) }.disabled(model.hasUnsavedChanges || model.creatingDocument)
+ }
}
- } detail: {
+ }
+ public var body: some View {
+ Group {
+ #if os(macOS)
+ if documentID != nil || newDocument { editor } else { home }
+ #else
+ NavigationSplitView(preferredCompactColumn: $column) { library } detail: { editor }
+ #endif
+ }
+
+ .onChange(of: model.documents.map { "\($0.sqid)\u{0}\($0.title)" }) {
+ if query.isEmpty { updateRecents?(model.documents.map { ($0.sqid, $0.title) }) }
+ }
+ .onChange(of: accountsRequested && !model.creatingDocument, initial: true) { _, ready in
+ if ready { accountsRequested = false; accounts?() }
+ }
+ .onChange(of: createRequested, initial: true) { _, requested in
+ if requested && documentID == nil { beginDocument(); createRequested = false }
+ }
+ .task { if newDocument { await model.newDraft() } else if let documentID { await model.open(documentID) } else { await model.load() } }
+ .onChange(of: model.renameInput) { _, value in if value == nil { renaming = false } }
+ .onChange(of: [model.detail?.sqid, model.detail?.title]) {
+ if !model.isDraft, let detail = model.detail { documentChanged?(detail.sqid, detail.title) }
+ }
+ .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: client) }
+ .onDisappear { Task { await model.stop() } }
+ #if os(macOS)
+ .background { DocsCloseGuard(hasUnsaved: { model.hasUnsavedChanges }, save: { await model.saveAll() }, discard: { await model.discardAll() }).frame(width: 0, height: 0) }
+ #endif
+ .onChange(of: model.detail?.sqid) { if model.detail != nil { column = .detail } }
+ .confirmationDialog(Text("native.discard.title", bundle: DocsResources.bundle), isPresented: $discarding, titleVisibility: .visible) {
+ Button(role: .destructive) { Task { await model.discardAll(); column = .sidebar } } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
+ Button(role: .cancel) {} label: { Text("native.close.pending.cancel", bundle: DocsResources.bundle) }
+ } message: {
+ Text("native.close.pending.detail", bundle: DocsResources.bundle)
+ }
+ .sheet(isPresented: $sharing) {
+ if let detail = model.detail { DocsSharingView(client: client, sqid: detail.sqid) }
+ }
+ }
+ private func beginDocument() {
+ #if os(macOS)
+ createDocument?()
+ #else
+ Task {
+ guard await model.saveAll() else { return }
+ await model.discardAll()
+ await model.newDraft()
+ }
+ #endif
+ }
+ private func beginRename() {
+ model.renameInput = model.detail?.title ?? ""
+ renaming = true; titleFocused = true
+ }
+ private func finishRename() {
+ guard renaming else { return }
+ if model.commitRename() { renaming = false }
+ }
+ private var documentTitle: some View {
+ Group {
+ if renaming {
+ TextField(String(localized: "docs.list.create.placeholder", bundle: DocsResources.bundle), text: Binding(get: { model.renameInput ?? model.detail?.title ?? "" }, set: { model.renameInput = $0 }))
+ .accessibilityIdentifier("docs.document.title")
+ .textFieldStyle(.plain).frame(minWidth: 180, maxWidth: 480)
+ .focused($titleFocused).onSubmit { finishRename() }
+ .onChange(of: titleFocused) { _, focused in if !focused { finishRename() } }
+ #if os(macOS)
+ .onExitCommand { model.renameInput = nil; renaming = false }
+ #endif
+ } else {
+ Text(model.detail?.title ?? " ")
+ .lineLimit(1).frame(minHeight: 20)
+ .onTapGesture(count: 2) { if model.detail?.can_write == true { beginRename() } }
+ .contextMenu {
+ Button { beginRename() } label: { Text("docs.document.rename", bundle: DocsResources.bundle) }
+ .disabled(model.detail?.can_write != true)
+ .keyboardShortcut("r", modifiers: [.command, .shift])
+ }
+ .accessibilityAction(named: Text("docs.document.rename", bundle: DocsResources.bundle)) { beginRename() }
+ }
+ }
+ }
+ private var editor: some View {
VStack(spacing: 0) {
if let key = model.errorKey {
HStack {
@@ -49,22 +155,32 @@ import SwiftUI
let documentPath = "/d/" + (model.detail?.sqid ?? "")
let text = NativeTextProjection.render(projection, images: images.images(forDocumentPath: documentPath, client: client))
EditorToolbar(model: model, content: text)
+ Divider()
NativeDocumentTextView(content: text, generation: model.projectionGeneration, didRender: model.didRender, compositionChanged: model.compositionChanged, isEditable: model.detail?.can_write == true && !model.inputPaused, paged: paged, pendingInput: model.hasPendingInput, canRender: model.canRender, currentSelection: model.currentSelection, selection: $model.selection, edit: model.enqueue, action: { action in
- if action == "jump" { jumping = true; return true }
+ if action == "jump" {
+ #if os(macOS)
+ openWindow(id: "home")
+ #else
+ jumping = true
+ #endif
+ return true
+ }
return DocumentCommands(model: model, content: text).perform(action)
- }, selectionMoved: model.selectionMovedExplicitly, canAction: { action in model.detail?.can_write == true && !model.hasPendingInput && !model.composing && !model.inputPaused && (action == "undo" ? projection.canUndo : projection.canRedo) }, explicitCommandRevision: model.explicitCommandRevision)
- .id(model.detail?.sqid)
+ }, selectionMoved: model.selectionMovedExplicitly, canAction: { action in model.detail?.can_write == true && !model.hasPendingInput && !model.composing && !model.inputPaused && (action == "undo" ? projection.canUndo : projection.canRedo) }, explicitCommandRevision: model.explicitCommandRevision, zoom: zoom)
+ .id(model.editorIdentity)
.task(id: [documentPath] + DocsImageStore.sources(in: projection)) { await images.load(sources: DocsImageStore.sources(in: projection), client: client, documentPath: documentPath) }
} else {
ContentUnavailableView { Label { Text("native.open", bundle: DocsResources.bundle) } icon: { Image(systemName: "doc.text") } }
}
}.navigationTitle(model.detail?.title ?? "")
+ .toolbar { ToolbarItem(placement: .principal) { documentTitle } }
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
+ #if os(iOS)
.toolbar {
DocsJumpControls(presented: $jumping)
- if let detail = model.detail {
+ if let detail = model.detail, !model.isDraft {
Toggle(isOn: $paged) { Text("docs.editor.menu.view.paged", bundle: DocsResources.bundle) }
DocumentExportControls(client: client, sqid: detail.sqid, title: detail.title) {
return await model.saveAll()
@@ -77,28 +193,82 @@ import SwiftUI
} label: { Label { Text("docs.share.title", bundle: DocsResources.bundle) } icon: { Image(systemName: "person.badge.plus") } }
}
}
- }
- .task { await model.load() }
- .sheet(isPresented: $jumping) { DocsJumpSheet(model: model, client: client) }
- .onDisappear { Task { await model.stop() } }
- #if os(macOS)
- .background { DocsCloseGuard(hasUnsaved: { model.hasUnsavedChanges }, save: { await model.saveAll() }, discard: { await model.discardAll() }).frame(width: 0, height: 0) }
- #endif
- .onChange(of: model.detail?.sqid) { if model.detail != nil { column = .detail } }
- .confirmationDialog(Text("native.discard.title", bundle: DocsResources.bundle), isPresented: $discarding, titleVisibility: .visible) {
- Button(role: .destructive) { Task { await model.discardAll(); column = .sidebar } } label: { Text("native.discard.action", bundle: DocsResources.bundle) }
- Button(role: .cancel) {} label: { Text("native.close.pending.cancel", bundle: DocsResources.bundle) }
- } message: {
- Text("native.close.pending.detail", bundle: DocsResources.bundle)
- }
- .sheet(isPresented: $sharing) {
- if let detail = model.detail { DocsSharingView(client: client, sqid: detail.sqid) }
- }
- .sheet(isPresented: $creating) {
- Form {
- TextField(String(localized: "docs.list.create.placeholder", bundle: DocsResources.bundle), text: $newTitle)
- Button { let title = newTitle; newTitle = ""; creating = false; Task { await model.create(title: title) } } label: { Text("docs.list.create.label", bundle: DocsResources.bundle) }.accessibilityIdentifier("docs.create.submit")
- }.padding().presentationDetents([.medium])
+ #else
+ .background {
+ if let detail = model.detail, !model.isDraft {
+ DocumentExportControls(client: client, sqid: detail.sqid, title: detail.title, prepare: { await model.saveAll() }, request: $exportRequest)
+ .frame(width: 0, height: 0).hidden().accessibilityHidden(true)
+ }
+ }
+ .toolbar { Button(docsMacString("Inspector"), systemImage: "sidebar.right") { inspecting.toggle() } }
+ // A closed SwiftUI inspector can repeatedly invalidate hosting-view
+ // constraints on macOS 27 while the editor loads. Keep this panel in
+ // the ordinary view layout so opening a document has stable sizing.
+ .safeAreaInset(edge: .trailing, spacing: 0) {
+ if inspecting {
+ Form {
+ LabeledContent(docsMacString("Document"), value: model.detail?.title ?? "")
+ Picker(docsMacString("Zoom"), selection: $zoom) {
+ ForEach([0.5, 0.75, 1.0, 1.25, 1.5, 2.0], id: \.self) { value in
+ Text(value, format: .percent).tag(value)
+ }
+ }
+ Toggle(docsMacString("Pages"), isOn: $paged)
+ if let projection = model.projection {
+ DocsToolsControls(projection: projection, content: NativeTextProjection.render(projection), selection: model.selection)
+ }
+ }.formStyle(.grouped).frame(width: 280)
+ .frame(maxHeight: .infinity)
+ .background(.background)
+ .overlay(alignment: .leading) { Divider() }
+ }
+ }
+ .focusedSceneValue(\.docsEditor, DocsEditorContext(model: model, rename: beginRename, client: client, zoom: $zoom, paged: $paged, inspecting: $inspecting, sharing: $sharing, exportRequest: $exportRequest))
+ #endif
+
+ }
+ #if os(macOS)
+ private var home: some View {
+ NavigationSplitView {
+ List { Label(docsMacString("Recent"), systemImage: "clock").listRowBackground(Color.accentColor.opacity(0.12)) }
+ .navigationSplitViewColumnWidth(min: 160, ideal: 190, max: 240)
+ } detail: {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 24) {
+ Text(docsMacString("Recent documents")).font(.largeTitle.bold())
+ if let error = model.errorKey {
+ Text(LocalizedStringKey(error), bundle: DocsResources.bundle).foregroundStyle(.red)
+ Button(docsMacString("Retry")) { Task { await model.load(query: query) } }
+ }
+ LazyVGrid(columns: [GridItem(.adaptive(minimum: 180, maximum: 240))], spacing: 24) {
+ ForEach(model.documents) { document in
+ Button { openDocument?(document.sqid, document.title) } label: {
+ VStack(alignment: .leading, spacing: 10) {
+ DocumentThumbnail(data: document.thumbnail, width: 170, height: 220)
+ Text(document.title).font(.headline).lineLimit(2)
+ if document.shared == true { Label(docsMacString("Shared"), systemImage: "person.2").font(.caption) }
+ }.frame(maxWidth: .infinity, alignment: .leading).padding(12)
+ }.buttonStyle(.plain)
+ }
+ }
+ if model.listState == .loading { ProgressView().frame(maxWidth: .infinity) }
+ if model.listState == .loaded && model.documents.isEmpty && !query.isEmpty {
+ ContentUnavailableView { Text("docs.list.search.none.title", bundle: DocsResources.bundle) } description: { Text("docs.list.search.none.body", bundle: DocsResources.bundle) }
+ }
+ if model.listState == .loaded && model.documents.isEmpty && query.isEmpty {
+ ContentUnavailableView(docsMacString("No documents"), systemImage: "doc.text", description: Text(docsMacString("Create a document to get started.")))
+ }
+ }.padding(28)
+ }
+ .navigationTitle(docsMacString("Home"))
+ .searchable(text: $query, prompt: Text("docs.list.search.label", bundle: DocsResources.bundle))
+ .onSubmit(of: .search) { Task { await model.load(query: query) } }
+ .focusedSceneValue(\.docsAccountActions, DocsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.creatingDocument, canSignOut: canSignOut && !model.creatingDocument))
+ .toolbar {
+ Button(docsMacString("New document"), systemImage: "plus") { beginDocument() }.disabled(!model.canCreate)
+ }
}
}
+ #endif
+
}
diff --git a/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift b/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift
new file mode 100644
index 0000000..819b99c
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocumentBlockSpacing.swift
@@ -0,0 +1,54 @@
+import Foundation
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+extension NSAttributedString.Key { static let docsFirstMargin = NSAttributedString.Key("OficinaDocsFirstMargin") }
+
+/// Collapse CSS block margins before handing paragraphs to TextKit, whose
+/// paragraph spacing otherwise adds adjacent margins together.
+@MainActor enum DocumentBlockSpacing {
+ private struct Block { var id: String; var before: CGFloat; var after: CGFloat }
+ static func apply(_ nodes: [CRDTNode], to output: NSMutableAttributedString) {
+ let blocks = nodes.enumerated().flatMap { index, node in
+ flatten(node, clearBefore: index == 0, clearAfter: index == nodes.count - 1)
+ }
+ guard let first = blocks.first, output.length > 0 else { return }
+ output.addAttribute(.docsFirstMargin, value: first.before, range: NSRange(location: 0, length: 1))
+ var ranges: [String: NSRange] = [:]
+ output.enumerateAttribute(.docsBlock, in: NSRange(location: 0, length: output.length)) { value, range, _ in
+ guard let id = value as? String else { return }
+ ranges[id] = ranges[id].map { NSUnionRange($0, range) } ?? range
+ }
+ for (index, block) in blocks.enumerated() {
+ guard let range = ranges[block.id], let existing = output.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle,
+ let style = existing.mutableCopy() as? NSMutableParagraphStyle else { continue }
+ style.paragraphSpacingBefore = 0
+ style.paragraphSpacing = index + 1 < blocks.count ? max(block.after, blocks[index + 1].before) : block.after
+ output.addAttribute(.paragraphStyle, value: style, range: range)
+ }
+ }
+ static func margins(_ node: CRDTNode) -> (CGFloat, CGFloat) {
+ let blocks = flatten(node)
+ return (blocks.first?.before ?? 0, blocks.last?.after ?? 0)
+ }
+ private static func flatten(_ node: CRDTNode, clearBefore: Bool = false, clearAfter: Bool = false) -> [Block] {
+ if ["bullet_list", "ordered_list", "list_item", "blockquote"].contains(node.type) {
+ let children = node.children ?? []
+ var blocks = children.enumerated().flatMap { index, child in
+ flatten(child, clearAfter: node.type == "list_item" && index == children.count - 1)
+ }
+ guard !blocks.isEmpty else { return [] }
+ if node.type == "blockquote" {
+ blocks[0].before = max(clearBefore ? 0 : 12, blocks[0].before)
+ blocks[blocks.count - 1].after = max(clearAfter ? 0 : 12, blocks[blocks.count - 1].after)
+ }
+ return blocks
+ }
+ let level = node.type == "heading" ? max(1, min(6, Int(node.attrs?["level"] ?? "1") ?? 1)) : 0
+ let size: CGFloat = level == 1 ? 19.2 : level == 2 ? 15.6 : level == 3 ? 13.2 : 12
+ return [Block(id: node.id, before: level > 0 && !clearBefore ? size * 1.5 : 0, after: level > 0 && !clearAfter ? size * 0.5 : 0)]
+ }
+}
diff --git a/native/apple/Sources/DocsKit/DocumentCommands.swift b/native/apple/Sources/DocsKit/DocumentCommands.swift
index e234cd8..930ec44 100644
--- a/native/apple/Sources/DocsKit/DocumentCommands.swift
+++ b/native/apple/Sources/DocsKit/DocumentCommands.swift
@@ -3,8 +3,9 @@ import Foundation
@MainActor struct DocumentCommands {
let model: DocsModel
let content: NSAttributedString
+ var isAvailable: Bool { model.detail?.can_write == true && !model.inputPaused }
var isEnabled: Bool {
- model.detail?.can_write == true && !model.composing && !model.hasPendingInput
+ isAvailable && !model.composing && !model.hasPendingInput
&& model.renderedGeneration == model.projectionGeneration
}
func hasMark(_ name: String) -> Bool {
@@ -19,6 +20,7 @@ import Foundation
}
return active
}
+ var selectedBlock: CRDTNode? { selectedBlocks.first.flatMap { path(to: $0)?.last } }
func hasBlock(_ type: String) -> Bool {
guard let id = selectedBlocks.first else { return false }
return path(to: id)?.contains { $0.type == type } == true
diff --git a/native/apple/Sources/DocsKit/DocumentExportControls.swift b/native/apple/Sources/DocsKit/DocumentExportControls.swift
index a154f98..7db4b70 100644
--- a/native/apple/Sources/DocsKit/DocumentExportControls.swift
+++ b/native/apple/Sources/DocsKit/DocumentExportControls.swift
@@ -27,18 +27,27 @@ struct ExportedDocument: Transferable {
let sqid: String
let title: String
let prepare: () async -> Bool
+ @Binding var request: String?
@State private var document: ExportedDocument?
@State private var exporting = false
@State private var working = false
@State private var active = true
@State private var type = UTType.pdf
@State private var failed = false
+ init(client: NativeHTTP, sqid: String, title: String, prepare: @escaping () async -> Bool, request: Binding<String?> = .constant(nil)) {
+ self.client = client; self.sqid = sqid; self.title = title; self.prepare = prepare; self._request = request
+ }
var body: some View {
Menu {
Button { Task { await download(pdf: true, printDocument: false) } } label: { Text("docs.export.pdf.label", bundle: DocsResources.bundle) }
Button { Task { await download(pdf: false, printDocument: false) } } label: { Text("docs.export.markdown.label", bundle: DocsResources.bundle) }
Button { Task { await download(pdf: true, printDocument: true) } } label: { Text("docs.editor.menu.file.print", bundle: DocsResources.bundle) }
} label: { Image(systemName: "square.and.arrow.up") }
+ .onChange(of: request) { _, value in
+ guard let value else { return }
+ request = nil
+ Task { await download(pdf: value != "markdown", printDocument: value == "print") }
+ }
.disabled(working || exporting)
.accessibilityLabel(Text("native.export", bundle: DocsResources.bundle))
.fileExporter(isPresented: $exporting, item: document, contentTypes: [type], defaultFilename: title, onCompletion: { result in
diff --git a/native/apple/Sources/DocsKit/DocumentInlineCode.swift b/native/apple/Sources/DocsKit/DocumentInlineCode.swift
new file mode 100644
index 0000000..aa9e128
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocumentInlineCode.swift
@@ -0,0 +1,38 @@
+import Foundation
+#if os(macOS)
+import AppKit
+#else
+import UIKit
+#endif
+
+extension NSAttributedString.Key { static let docsCodeStart = NSAttributedString.Key("OficinaDocsCodeStart") }
+
+/// Inline decoration uses glyph advances, never extra characters: CRDT and
+/// clipboard offsets continue to refer to the authored text.
+@MainActor enum DocumentInlineCode {
+ static func apply(to output: NSMutableAttributedString) {
+ var spans: [NSRange] = []
+ output.enumerateAttribute(.docsMarks, in: NSRange(location: 0, length: output.length)) { value, range, _ in
+ guard let data = value as? Data,
+ let marks = try? JSONDecoder().decode([String: JSONValue].self, from: data), marks["code"] != nil else { return }
+ if let last = spans.last, NSMaxRange(last) == range.location { spans[spans.count - 1] = NSUnionRange(last, range) }
+ else { spans.append(range) }
+ }
+ for range in spans where range.length > 0 {
+ guard let font = output.attribute(.font, at: range.location, effectiveRange: nil) as? DocsPlatformFont else { continue }
+ let padding = font.pointSize * 0.35
+ let paragraph = (output.string as NSString).paragraphRange(for: NSRange(location: range.location, length: 0))
+ output.addAttribute(.docsCodeStart, value: padding,
+ range: (output.string as NSString).rangeOfComposedCharacterSequence(at: range.location))
+ if paragraph.location != range.location && range.location > 0 {
+ output.addAttribute(.kern, value: padding, range: (output.string as NSString).rangeOfComposedCharacterSequence(at: range.location - 1))
+ }
+ output.addAttribute(.kern, value: padding, range: (output.string as NSString).rangeOfComposedCharacterSequence(at: NSMaxRange(range) - 1))
+ #if os(macOS)
+ output.addAttribute(.backgroundColor, value: NSColor(white: 240.0 / 255, alpha: 1), range: range)
+ #else
+ output.addAttribute(.backgroundColor, value: UIColor(white: 240.0 / 255, alpha: 1), range: range)
+ #endif
+ }
+ }
+}
diff --git a/native/apple/Sources/DocsKit/DocumentPageLayout.swift b/native/apple/Sources/DocsKit/DocumentPageLayout.swift
new file mode 100644
index 0000000..9ae7f8f
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocumentPageLayout.swift
@@ -0,0 +1,64 @@
+#if os(macOS)
+import AppKit
+
+extension NSAttributedString.Key {
+ static let docsTopBlock = NSAttributedString.Key("OficinaDocsTopBlock")
+ static let docsMarginBefore = NSAttributedString.Key("OficinaDocsMarginBefore")
+ static let docsMarginAfter = NSAttributedString.Key("OficinaDocsMarginAfter")
+}
+
+/// Mirrors pages.mjs: keep top-level blocks intact and put a visual separator
+/// before the next block exceeding the 648pt text budget. All offsets are layout
+/// only; an oversized paragraph/list is never split or rewritten to make a page.
+@MainActor enum DocumentPageLayout {
+ struct Result {
+ var starts: [Int: CGFloat] = [:]
+ var separators: [CGFloat] = []
+ }
+ /// Mapping IDs, formatting marks and colors do not affect glyph positions.
+ /// Retain only layout inputs so metadata acknowledgements reuse pagination.
+ static func measurementContent(_ storage: NSAttributedString) -> NSAttributedString {
+ let keys: Set<NSAttributedString.Key> = [.font, .paragraphStyle, .kern, .ligature, .baselineOffset,
+ .attachment, .expansion, .obliqueness, .writingDirection, .verticalGlyphForm,
+ .superscript, .docsBaseFont, .docsLeading, .docsCodeStart, .docsFirstMargin,
+ .docsTopBlock, .docsMarginBefore, .docsMarginAfter]
+ let result = NSMutableAttributedString(string: storage.string)
+ storage.enumerateAttributes(in: NSRange(location: 0, length: storage.length)) { attributes, range, _ in
+ result.setAttributes(attributes.filter { keys.contains($0.key) }, range: range)
+ }
+ return result
+ }
+ static func measure(storage: NSTextStorage, manager: NSLayoutManager, container: NSTextContainer) -> Result {
+ var result = Result()
+ var pageTop: CGFloat?
+ var added: CGFloat = 0
+ var previousMargin: CGFloat = 0
+ storage.enumerateAttribute(.docsTopBlock, in: NSRange(location: 0, length: storage.length)) { value, range, _ in
+ guard value != nil else { return }
+ let glyphs = manager.glyphRange(forCharacterRange: range, actualCharacterRange: nil)
+ var top = CGFloat.greatestFiniteMagnitude
+ var bottom: CGFloat = 0
+ manager.enumerateLineFragments(forGlyphRange: glyphs) { rect, used, _, _, _ in
+ top = min(top, rect.minY); bottom = max(bottom, used.maxY)
+ }
+ guard bottom > top else { return }
+ let before = storage.attribute(.docsMarginBefore, at: range.location, effectiveRange: nil) as? CGFloat ?? 0
+ let after = storage.attribute(.docsMarginAfter, at: range.location, effectiveRange: nil) as? CGFloat ?? 0
+ defer { previousMargin = after }
+ if let currentTop = pageTop {
+ if bottom - currentTop > 648 {
+ // Collapse margins independently on either side of the gap.
+ let collapsed = max(previousMargin, before)
+ let separator = top + added - collapsed + max(previousMargin, 12)
+ let extra = max(previousMargin, 12) + 18 + max(before, 12) - collapsed
+ added += extra
+ result.starts[range.location] = top + added
+ result.separators.append(separator)
+ pageTop = top
+ }
+ } else { pageTop = top }
+ }
+ return result
+ }
+}
+#endif
diff --git a/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift b/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift
new file mode 100644
index 0000000..4c0d9bb
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocumentRenderReconciliation.swift
@@ -0,0 +1,21 @@
+import Foundation
+
+/// Reconcile against optimistic native storage, not the last published snapshot.
+/// Equal visible text can still carry a new CRDT node mapping after publication.
+@MainActor enum DocumentRenderReconciliation {
+ static func apply(_ content: NSAttributedString, to storage: NSMutableAttributedString) {
+ guard !storage.isEqual(to: content) else { return }
+ storage.beginEditing()
+ defer { storage.endEditing() }
+ if let (range, replacement) = DocumentComposition.replacement(before: storage.string, after: content.string) {
+ storage.replaceCharacters(in: range, with: replacement)
+ }
+ content.enumerateAttributes(in: NSRange(location: 0, length: content.length)) { attributes, range, _ in
+ var changed = false
+ storage.enumerateAttributes(in: range) { current, _, stop in
+ if !NSDictionary(dictionary: current).isEqual(to: attributes) { changed = true; stop.pointee = true }
+ }
+ if changed { storage.setAttributes(attributes, range: range) }
+ }
+ }
+}
diff --git a/native/apple/Sources/DocsKit/DocumentThumbnail.swift b/native/apple/Sources/DocsKit/DocumentThumbnail.swift
index 6bca7f0..dd1f6e7 100644
--- a/native/apple/Sources/DocsKit/DocumentThumbnail.swift
+++ b/native/apple/Sources/DocsKit/DocumentThumbnail.swift
@@ -13,6 +13,8 @@ struct DocumentThumbnailData: Decodable, Sendable {
struct DocumentThumbnail: View {
let data: DocumentThumbnailData?
+ var width: CGFloat = 34
+ var height: CGFloat = 44
var body: some View {
Canvas { context, size in
guard let data, data.width > 0, data.height > 0 else { return }
@@ -25,7 +27,7 @@ struct DocumentThumbnail: View {
}
}
.foregroundStyle(.secondary)
- .frame(width: 34, height: 44)
+ .frame(width: width, height: height)
.background(.background)
.clipShape(.rect(cornerRadius: 3))
.overlay { RoundedRectangle(cornerRadius: 3).strokeBorder(.quaternary) }
diff --git a/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift b/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift
new file mode 100644
index 0000000..b6e330b
--- /dev/null
+++ b/native/apple/Sources/DocsKit/DocumentToolbarSelection.swift
@@ -0,0 +1,38 @@
+import Foundation
+
+/// Only read formatting from a selection whose projection has caught up with
+/// native text input. While it catches up, the toolbar keeps its last valid state.
+struct DocumentToolbarSelection: Equatable {
+ var marks: Set<String> = []
+ var blocks: Set<String> = []
+ var style = "paragraph"
+ var font = "sans"
+ var size = 12
+ var alignment = "left"
+ var canUndo = false
+ var canRedo = false
+ var hasSelection = false
+
+ var styleLabel: String {
+ if style.hasPrefix("heading"), let level = Int(style.dropFirst(7)) {
+ return String(format: docsMacString("Heading %d"), level)
+ }
+ return String(localized: "docs.editor.toolbar.block.paragraph", bundle: DocsResources.bundle)
+ }
+ init() {}
+
+ @MainActor init?(commands: DocumentCommands) {
+ guard commands.isEnabled else { return nil }
+ marks = Set(["strong", "em", "code"].filter { commands.hasMark($0) })
+ blocks = Set(["bullet_list", "ordered_list", "blockquote"].filter { commands.hasBlock($0) })
+ if let block = commands.selectedBlock {
+ style = block.type == "heading" ? "heading" + (block.attrs?["level"] ?? "1") : "paragraph"
+ alignment = block.attrs?["align"] ?? "left"
+ }
+ font = ["serif", "mono"].first { commands.hasMark("font_" + $0) } ?? "sans"
+ size = [8,9,10,11,12,14,18,24,36,48,72].first { commands.hasMark("size_\($0)") } ?? (commands.hasMark("size_sm") ? 10 : commands.hasMark("size_lg") ? 14 : commands.hasMark("size_xl") ? 18 : 12)
+ canUndo = commands.model.projection?.canUndo == true
+ canRedo = commands.model.projection?.canRedo == true
+ hasSelection = commands.model.selection.length > 0
+ }
+}
diff --git a/native/apple/Sources/DocsKit/EditorToolbar.swift b/native/apple/Sources/DocsKit/EditorToolbar.swift
index e4931a9..20a3db8 100644
--- a/native/apple/Sources/DocsKit/EditorToolbar.swift
+++ b/native/apple/Sources/DocsKit/EditorToolbar.swift
@@ -2,55 +2,74 @@ import SwiftUI
@MainActor struct EditorToolbar: View {
@Bindable var model: DocsModel
let content: NSAttributedString
+ @State private var settledSelection = DocumentToolbarSelection()
+ private var selection: DocumentToolbarSelection { currentSelection ?? settledSelection }
+ private var currentSelection: DocumentToolbarSelection? { DocumentToolbarSelection(commands: actions) }
var body: some View {
+ let selection = self.selection
ScrollView(.horizontal) {
HStack(spacing: 12) {
- command("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: model.projection?.canUndo == true)
- command("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: model.projection?.canRedo == true)
+ command("docs.editor.toolbar.undo", icon: "arrow.uturn.backward", op: "undo", enabled: selection.canUndo)
+ command("docs.editor.toolbar.redo", icon: "arrow.uturn.forward", op: "redo", enabled: selection.canRedo)
Divider().frame(height: 24)
Menu {
Button { block("paragraph") } label: { Text("docs.editor.toolbar.block.paragraph", bundle: DocsResources.bundle) }
ForEach(1...3, id: \.self) { level in
Button { block("heading", level: level) } label: { Text(LocalizedStringKey("docs.editor.toolbar.block.heading\(level)"), bundle: DocsResources.bundle) }
}
- } label: { Image(systemName: "paragraphsign") }.accessibilityLabel(Text("native.style", bundle: DocsResources.bundle))
- ForEach(["bullet_list", "ordered_list", "blockquote"], id: \.self) { type in
- Button { block(type) } label: { Image(systemName: type == "bullet_list" ? "list.bullet" : type == "ordered_list" ? "list.number" : "text.quote") }
- .accessibilityLabel(Text(LocalizedStringKey("native." + type), bundle: DocsResources.bundle))
- .foregroundStyle(actions.hasBlock(type) ? Color.accentColor : Color.primary)
- .accessibilityAddTraits(actions.hasBlock(type) ? .isSelected : [])
- }
- mark("docs.editor.toolbar.bold", icon: "bold", name: "strong")
- mark("docs.editor.toolbar.italic", icon: "italic", name: "em")
- mark("docs.editor.toolbar.code", icon: "chevron.left.forwardslash.chevron.right", name: "code")
+ } label: { Text(selection.styleLabel).frame(minWidth: 100, alignment: .leading) }.accessibilityLabel(Text("native.style", bundle: DocsResources.bundle))
Menu {
ForEach(["sans", "serif", "mono"], id: \.self) { family in
Button { format("font_" + family, exclusive: ["font_sans", "font_serif", "font_mono"]) } label: { Text(LocalizedStringKey("docs.editor.toolbar.font." + family), bundle: DocsResources.bundle) }
}
- } label: { Image(systemName: "textformat") }.accessibilityLabel(Text("native.font", bundle: DocsResources.bundle))
+ } label: { Text(LocalizedStringKey("docs.editor.toolbar.font." + selection.font), bundle: DocsResources.bundle).frame(minWidth: 80, alignment: .leading) }.accessibilityLabel(Text("native.font", bundle: DocsResources.bundle))
Menu {
ForEach([12, 8, 9, 10, 11, 14, 18, 24, 36, 48, 72], id: \.self) { size in
Button(size.formatted()) { format("size_\(size)", exclusive: [8,9,10,11,12,14,18,24,36,48,72].map { "size_\($0)" } + ["size_sm", "size_lg", "size_xl"]) }
}
- } label: { Image(systemName: "textformat.size") }.accessibilityLabel(Text("native.size", bundle: DocsResources.bundle))
+ } label: { Text(selection.size.formatted()).frame(minWidth: 32) }.accessibilityLabel(Text("native.size", bundle: DocsResources.bundle))
+ Divider().frame(height: 24)
+ mark("docs.editor.toolbar.bold", icon: "bold", name: "strong", active: selection.marks.contains("strong"))
+ mark("docs.editor.toolbar.italic", icon: "italic", name: "em", active: selection.marks.contains("em"))
+ mark("docs.editor.toolbar.code", icon: "chevron.left.forwardslash.chevron.right", name: "code", active: selection.marks.contains("code"))
+ Divider().frame(height: 24)
ForEach(["left", "center", "right"], id: \.self) { alignment in
Button { blockAttribute("align", value: alignment) } label: { Image(systemName: "text.align" + alignment) }
.accessibilityLabel(Text(LocalizedStringKey("docs.editor.toolbar.align." + alignment), bundle: DocsResources.bundle))
+ .foregroundStyle(selection.alignment == alignment ? Color.accentColor : Color.primary)
+ .accessibilityAddTraits(selection.alignment == alignment ? .isSelected : [])
+ }
+ Divider().frame(height: 24)
+ ForEach(["bullet_list", "ordered_list", "blockquote"], id: \.self) { type in
+ Button { block(type) } label: { Image(systemName: type == "bullet_list" ? "list.bullet" : type == "ordered_list" ? "list.number" : "text.quote") }
+ .accessibilityLabel(Text(LocalizedStringKey("native." + type), bundle: DocsResources.bundle))
+ .foregroundStyle(selection.blocks.contains(type) ? Color.accentColor : Color.primary)
+ .accessibilityAddTraits(selection.blocks.contains(type) ? .isSelected : [])
}
command("docs.editor.menu.format.indent", icon: "increase.indent", op: "indent", enabled: true)
command("docs.editor.menu.format.outdent", icon: "decrease.indent", op: "outdent", enabled: true)
- command("docs.editor.menu.format.clear", icon: "eraser", op: "clear-format", enabled: model.selection.length > 0)
- }.buttonStyle(.borderless).padding(12)
- }.disabled(!actions.isEnabled)
+ command("docs.editor.menu.format.clear", icon: "eraser", op: "clear-format", enabled: selection.hasSelection)
+ }.buttonStyle(.borderless).padding(.horizontal, 12).padding(.vertical, 8)
+ }
+ .scrollIndicators(.hidden)
+ .fixedSize(horizontal: false, vertical: true)
+ .accessibilityIdentifier("docs.formatting-toolbar")
+ // Replica work briefly gates commands on every keystroke. Keep that
+ // synchronization gate out of disabled styling so the bar does not blink.
+ .disabled(!actions.isAvailable)
+ .allowsHitTesting(actions.isEnabled)
+ .onChange(of: currentSelection, initial: true) { _, value in
+ if let value { settledSelection = value }
+ }
}
private func command(_ key: String, icon: String, op: String, enabled: Bool) -> some View {
Button { actions.perform(op) } label: { Image(systemName: icon) }
.accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)).disabled(!enabled)
}
- private func mark(_ key: String, icon: String, name: String) -> some View {
+ private func mark(_ key: String, icon: String, name: String, active: Bool) -> some View {
Button { format(name) } label: { Image(systemName: icon) }.accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle))
- .foregroundStyle(actions.hasMark(name) ? Color.accentColor : Color.primary)
- .accessibilityAddTraits(actions.hasMark(name) ? .isSelected : [])
+ .foregroundStyle(active ? Color.accentColor : Color.primary)
+ .accessibilityAddTraits(active ? .isSelected : [])
}
private var actions: DocumentCommands { DocumentCommands(model: model, content: content) }
private func format(_ name: String, exclusive: [String] = []) { actions.format(name, exclusive: exclusive) }
diff --git a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
index 6d4429f..9750b5a 100644
--- a/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
+++ b/native/apple/Sources/DocsKit/NativeDocumentTextView.swift
@@ -17,12 +17,18 @@ struct NativeDocumentTextView: NSViewRepresentable {
var selectionMoved: @MainActor () -> Void = {}
var canAction: @MainActor (String) -> Bool = { _ in false }
var explicitCommandRevision: UInt64 = 0
+ var zoom: Double = 1
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeNSView(context: Context) -> NSScrollView {
let scroll = NSScrollView()
scroll.hasVerticalScroller = true
+ scroll.hasHorizontalScroller = true
+ scroll.minMagnification = 0.5
+ scroll.maxMagnification = 3
+ scroll.allowsMagnification = false
+ scroll.magnification = 4.0 / 3.0
let text = DocsTextView(frame: .zero)
- text.isVerticallyResizable = true
+ text.isVerticallyResizable = false
text.autoresizingMask = [.width]
scroll.documentView = text
text.delegate = context.coordinator
@@ -46,6 +52,11 @@ struct NativeDocumentTextView: NSViewRepresentable {
}
func updateNSView(_ scroll: NSScrollView, context: Context) {
guard let text = scroll.documentView as? NSTextView else { return }
+ let magnification = zoom * 4.0 / 3.0
+ if abs(scroll.magnification - magnification) > 0.001 {
+ scroll.setMagnification(magnification, centeredAt: scroll.contentView.bounds.origin)
+ text.needsLayout = true
+ }
context.coordinator.applyRender(self, to: text)
}
@MainActor final class Coordinator: NSObject, NSTextViewDelegate {
@@ -74,8 +85,9 @@ struct NativeDocumentTextView: NSViewRepresentable {
defer { applying = false }
rendered = NSAttributedString(attributedString: candidate.content)
generation = candidate.generation
- text.textStorage?.setAttributedString(candidate.content)
- text.setSelectedRange(NSRange(location: min(selected.location, candidate.content.length), length: min(selected.length, max(0, candidate.content.length - selected.location))))
+ if let storage = text.textStorage { DocumentRenderReconciliation.apply(candidate.content, to: storage) }
+ let range = NSRange(location: min(selected.location, candidate.content.length), length: min(selected.length, max(0, candidate.content.length - selected.location)))
+ if text.selectedRange() != range { text.setSelectedRange(range) }
candidate.didRender(candidate.generation)
}
func ruleEdit(_ command: [String: JSONValue]) -> Bool {
@@ -114,6 +126,7 @@ struct NativeDocumentTextView: NSViewRepresentable {
}
func textViewDidChangeSelection(_ notification: Notification) {
guard let text = notification.object as? NSTextView else { return }
+ guard !applying else { return }
let selected = text.selectedRange()
if selected.length == 0 && selected.location == text.string.utf16.count && text.string.hasSuffix("\n") {
text.setSelectedRange(NSRange(location: max(0, selected.location - 1), length: 0)); return
@@ -147,6 +160,7 @@ struct NativeDocumentTextView: UIViewRepresentable {
var selectionMoved: @MainActor () -> Void = {}
var canAction: @MainActor (String) -> Bool = { _ in false }
var explicitCommandRevision: UInt64 = 0
+ var zoom: Double = 1
func makeCoordinator() -> Coordinator { Coordinator(self) }
func makeUIView(context: Context) -> UITextView {
let text = DocsTextView()
diff --git a/native/apple/Sources/DocsKit/NativeTextProjection.swift b/native/apple/Sources/DocsKit/NativeTextProjection.swift
index a958aca..5f13ed9 100644
--- a/native/apple/Sources/DocsKit/NativeTextProjection.swift
+++ b/native/apple/Sources/DocsKit/NativeTextProjection.swift
@@ -11,12 +11,23 @@ extension NSAttributedString.Key {
static let docsNode = NSAttributedString.Key("OficinaDocsNode")
static let docsBlock = NSAttributedString.Key("OficinaDocsBlock")
static let docsOffset = NSAttributedString.Key("OficinaDocsOffset")
+ static let docsQuoteBorders = NSAttributedString.Key("OficinaDocsQuoteBorders")
static let docsMarks = NSAttributedString.Key("OficinaDocsMarks")
}
@MainActor enum NativeTextProjection {
static func render(_ projection: CRDTProjection, images: [String: DocsPlatformImage] = [:]) -> NSAttributedString {
let output = NSMutableAttributedString(string: "")
- for node in projection.children { append(node, to: output, depth: 0, lists: [], images: images) }
+ for node in projection.children {
+ let start = output.length
+ append(node, to: output, depth: 0, lists: [], images: images)
+ #if os(macOS)
+ let margins = DocumentBlockSpacing.margins(node)
+ output.addAttributes([.docsTopBlock: node.id, .docsMarginBefore: margins.0, .docsMarginAfter: margins.1],
+ range: NSRange(location: start, length: output.length - start))
+ #endif
+ }
+ DocumentBlockSpacing.apply(projection.children, to: output)
+ DocumentInlineCode.apply(to: output)
return output
}
private static func append(_ node: CRDTNode, to output: NSMutableAttributedString, depth: Int, lists: [NSTextList], images: [String: DocsPlatformImage], containers: [DocsClipboardContainer] = []) {
@@ -34,18 +45,54 @@ extension NSAttributedString.Key {
}
let start = output.length
let style = NSMutableParagraphStyle()
- style.paragraphSpacing = 8
+ style.paragraphSpacing = 0
style.textLists = lists
let indent = max(0, min(8, Int(node.attrs?["indent"] ?? "0") ?? 0))
- style.headIndent = CGFloat(depth * 24 + indent * 36)
+ style.headIndent = containers.reduce(CGFloat(indent * 36)) { offset, container in
+ offset + (container.type == "list_item" ? 16.8 : container.type == "blockquote" ? 14.25 : 0)
+ }
style.firstLineHeadIndent = style.headIndent
switch node.attrs?["align"] { case "center": style.alignment = .center; case "right": style.alignment = .right; default: style.alignment = .left }
let heading = node.type == "heading" ? max(1, min(6, Int(node.attrs?["level"] ?? "1") ?? 1)) : 0
#if os(macOS)
style.headerLevel = heading
#endif
- let base = heading > 0 ? max(14, 28 - CGFloat(heading * 3)) : 12
- var baseAttributes: [NSAttributedString.Key: Any] = [.paragraphStyle: style, .font: font(marks: node.type == "code_block" ? ["code": .object([:])] : [:], size: base, heading: heading > 0), .docsBlock: node.id, .docsBlockType: node.type, .docsHeading: heading]
+ let base: CGFloat = heading == 1 ? 19.2 : heading == 2 ? 15.6 : heading == 3 ? 13.2 : 12
+ let leading: CGFloat = heading > 0 ? 1.3 : 1.4
+ var inheritedMarks: [String: JSONValue] = [:]
+ if heading >= 4 || containers.contains(where: { $0.type == "blockquote" }) { inheritedMarks["em"] = .object([:]) }
+ if node.type == "code_block" { inheritedMarks["code"] = .object([:]) }
+ let baseFont = font(marks: inheritedMarks, size: base, heading: heading > 0)
+ #if os(macOS)
+ let naturalHeight = NSLayoutManager().defaultLineHeight(for: baseFont)
+ #else
+ let naturalHeight = baseFont.lineHeight
+ #endif
+ style.lineHeightMultiple = base * leading / naturalHeight
+ style.minimumLineHeight = base * leading
+ if heading > 0 {
+ style.paragraphSpacingBefore = base * 1.5
+ style.paragraphSpacing = base * 0.5
+ }
+ var baseAttributes: [NSAttributedString.Key: Any] = [.paragraphStyle: style, .font: baseFont, .docsBlock: node.id, .docsBlockType: node.type, .docsHeading: heading]
+ #if os(macOS)
+ baseAttributes[.docsBaseFont] = baseFont
+ baseAttributes[.docsLeading] = leading
+ #endif
+ var quoteBorders: [CGFloat] = []
+ var containerIndent: CGFloat = 0
+ for container in containers {
+ if container.type == "blockquote" { quoteBorders.append(containerIndent); containerIndent += 14.25 }
+ if container.type == "list_item" { containerIndent += 16.8 }
+ }
+ if !quoteBorders.isEmpty {
+ baseAttributes[.docsQuoteBorders] = quoteBorders
+ #if os(macOS)
+ baseAttributes[.foregroundColor] = NSColor(white: 74.0 / 255, alpha: 1)
+ #else
+ baseAttributes[.foregroundColor] = UIColor(white: 74.0 / 255, alpha: 1)
+ #endif
+ }
baseAttributes[.docsBlockAttributes] = try? JSONEncoder().encode(node.attrs ?? [:])
baseAttributes[.docsClipboardContainers] = try? JSONEncoder().encode(containers)
if node.type == "horizontal_rule" {
@@ -59,7 +106,7 @@ extension NSAttributedString.Key {
for run in child.runs ?? [] {
var attributes = baseAttributes
let marks = run.marks ?? [:]
- var visualMarks = marks
+ var visualMarks = inheritedMarks.merging(marks, uniquingKeysWith: { _, authored in authored })
if node.type == "code_block" { visualMarks["code"] = .object([:]) }
attributes[.font] = font(marks: visualMarks, size: base, heading: heading > 0)
attributes[.docsNode] = child.id
diff --git a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings
index cc349a4..0bd2e88 100644
--- a/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ar.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "إلغاء";
"native.discard.title" = "هل تريد تجاهل التغييرات غير المحفوظة؟";
"native.discard.action" = "تجاهل التغييرات";
+
+"docs.document.rename" = "إعادة تسمية المستند";
diff --git a/native/apple/Sources/DocsKit/Resources/ar.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/ar.lproj/Mac.strings
new file mode 100644
index 0000000..0f71091
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/ar.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "الحسابات";
+"Actual size" = "الحجم الفعلي";
+"Alignment" = "المحاذاة";
+"Block quote" = "كتلة اقتباس";
+"Bold" = "عريض";
+"Bullet list" = "قائمة نقطية";
+"Cell contents" = "محتوى الخلية";
+"Clear formatting" = "مسح التنسيق";
+"Close this account’s document windows before signing out." = "أغلق نوافذ مستندات هذا الحساب قبل تسجيل الخروج.";
+"Create a document to get started." = "ستظهر المستندات التي تنشئها هنا، بدءًا بالأحدث.";
+"Docs" = "Docs";
+"Document" = "المستند";
+"Document inspector" = "خصائص المستند";
+"Double-click to fit column to contents" = "انقر مرتين لملاءمة العمود للمحتوى";
+"Edit %@" = "تحرير %@";
+"Export" = "تصدير";
+"Fit column to contents" = "ملاءمة العمود للمحتوى";
+"Font" = "الخط";
+"Format" = "تنسيق";
+"Heading %d" = "العنوان %d";
+"Home" = "الرئيسية";
+"Indent" = "زيادة المسافة البادئة";
+"Inline code" = "شيفرة";
+"Inspector" = "خصائص المستند";
+"Italic" = "مائل";
+"Markdown…" = "Markdown";
+"New document" = "مستند جديد";
+"No documents" = "لا توجد مستندات بعد";
+"No recent documents" = "لا توجد مستندات بعد";
+"Normal" = "نص أساسي";
+"Numbered list" = "قائمة مرقّمة";
+"Open a document from Home" = "افتح مستندًا من الرئيسية";
+"Outdent" = "تقليل المسافة البادئة";
+"PDF…" = "PDF";
+"Pages" = "صفحات";
+"Paragraph style" = "نمط الفقرة";
+"Print…" = "طباعة";
+"Recent" = "الأخيرة";
+"Recent documents" = "المستندات الأخيرة";
+"Recent spreadsheets" = "جداول البيانات الأخيرة";
+"Retry" = "إعادة المحاولة";
+"Save" = "حفظ";
+"Select column %@" = "تحديد العمود %@";
+"Select row %d" = "تحديد الصف %d";
+"Shared" = "تمت مشاركتها معك";
+"Share…" = "مشاركة";
+"Sign out" = "تسجيل الخروج";
+"Size" = "الحجم";
+"Zoom" = "التكبير";
+
+"Untitled document" = "مستند بلا عنوان";
diff --git a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings
index 00830d4..f047d80 100644
--- a/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/bn.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "বাতিল করুন";
"native.discard.title" = "অসংরক্ষিত পরিবর্তন বাতিল করবেন?";
"native.discard.action" = "পরিবর্তন বাতিল করুন";
+
+"docs.document.rename" = "নথির নাম পরিবর্তন করুন";
diff --git a/native/apple/Sources/DocsKit/Resources/bn.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/bn.lproj/Mac.strings
new file mode 100644
index 0000000..e5ef63c
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/bn.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "অ্যাকাউন্ট";
+"Actual size" = "প্রকৃত আকার";
+"Alignment" = "প্রান্তিককরণ";
+"Block quote" = "উদ্ধৃতির ব্লক";
+"Bold" = "গাঢ়";
+"Bullet list" = "বুলেটযুক্ত তালিকা";
+"Cell contents" = "ঘরের বিষয়বস্তু";
+"Clear formatting" = "বিন্যাস মুছুন";
+"Close this account’s document windows before signing out." = "সাইন আউট করার আগে এই অ্যাকাউন্টের নথির উইন্ডোগুলি বন্ধ করুন।";
+"Create a document to get started." = "আপনার তৈরি নথি এখানে দেখা যাবে, নতুনগুলো আগে।";
+"Docs" = "Docs";
+"Document" = "নথি";
+"Document inspector" = "নথি পরিদর্শক";
+"Double-click to fit column to contents" = "বিষয়বস্তু অনুযায়ী কলাম মাপতে দুবার ক্লিক করুন";
+"Edit %@" = "%@ সম্পাদনা করুন";
+"Export" = "রপ্তানি";
+"Fit column to contents" = "বিষয়বস্তু অনুযায়ী কলাম মাপুন";
+"Font" = "ফন্ট";
+"Format" = "বিন্যাস";
+"Heading %d" = "শিরোনাম %d";
+"Home" = "হোম";
+"Indent" = "ইন্ডেন্ট বাড়ান";
+"Inline code" = "কোড";
+"Inspector" = "নথি পরিদর্শক";
+"Italic" = "তির্যক";
+"Markdown…" = "Markdown";
+"New document" = "নতুন নথি";
+"No documents" = "এখনও কোনো নথি নেই";
+"No recent documents" = "এখনও কোনো নথি নেই";
+"Normal" = "মূল পাঠ্য";
+"Numbered list" = "সংখ্যাযুক্ত তালিকা";
+"Open a document from Home" = "হোম থেকে একটি নথি খুলুন";
+"Outdent" = "ইন্ডেন্ট কমান";
+"PDF…" = "PDF";
+"Pages" = "পৃষ্ঠাভিত্তিক";
+"Paragraph style" = "অনুচ্ছেদের শৈলী";
+"Print…" = "প্রিন্ট করুন";
+"Recent" = "সাম্প্রতিক";
+"Recent documents" = "সাম্প্রতিক নথি";
+"Recent spreadsheets" = "সাম্প্রতিক স্প্রেডশিট";
+"Retry" = "আবার চেষ্টা করুন";
+"Save" = "সংরক্ষণ করুন";
+"Select column %@" = "কলাম %@ নির্বাচন করুন";
+"Select row %d" = "সারি %d নির্বাচন করুন";
+"Shared" = "আপনার সঙ্গে শেয়ার করা";
+"Share…" = "শেয়ার করুন";
+"Sign out" = "সাইন আউট করুন";
+"Size" = "আকার";
+"Zoom" = "জুম";
+
+"Untitled document" = "শিরোনামহীন নথি";
diff --git a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings
index 1957c21..806b558 100644
--- a/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/en.lproj/Localizable.strings
@@ -175,3 +175,5 @@
"native.close.pending.cancel" = "Cancel";
"native.discard.title" = "Discard unsaved changes?";
"native.discard.action" = "Discard changes";
+
+"docs.document.rename" = "Rename document";
diff --git a/native/apple/Sources/DocsKit/Resources/en.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/en.lproj/Mac.strings
new file mode 100644
index 0000000..257c19e
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/en.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "Accounts";
+"Actual size" = "Actual size";
+"Alignment" = "Alignment";
+"Block quote" = "Block quote";
+"Bold" = "Bold";
+"Bullet list" = "Bulleted list";
+"Cell contents" = "Cell contents";
+"Clear formatting" = "Clear formatting";
+"Close this account’s document windows before signing out." = "Close this account’s document windows before signing out.";
+"Create a document to get started." = "Documents you create will show up here, newest first.";
+"Docs" = "Docs";
+"Document" = "Document";
+"Document inspector" = "Document inspector";
+"Double-click to fit column to contents" = "Double-click to fit column to contents";
+"Edit %@" = "Edit %@";
+"Export" = "Export";
+"Fit column to contents" = "Fit column to contents";
+"Font" = "Font";
+"Format" = "Format";
+"Heading %d" = "Heading %d";
+"Home" = "Home";
+"Indent" = "Increase indent";
+"Inline code" = "Code";
+"Inspector" = "Document inspector";
+"Italic" = "Italic";
+"Markdown…" = "Markdown";
+"New document" = "New document";
+"No documents" = "No documents yet";
+"No recent documents" = "No documents yet";
+"Normal" = "Body text";
+"Numbered list" = "Numbered list";
+"Open a document from Home" = "Open a document from Home";
+"Outdent" = "Decrease indent";
+"PDF…" = "PDF";
+"Pages" = "Paged";
+"Paragraph style" = "Paragraph style";
+"Print…" = "Print";
+"Recent" = "Recent";
+"Recent documents" = "Recent documents";
+"Recent spreadsheets" = "Recent spreadsheets";
+"Retry" = "Try again";
+"Save" = "Save";
+"Select column %@" = "Select column %@";
+"Select row %d" = "Select row %d";
+"Shared" = "Shared with you";
+"Share…" = "Share";
+"Sign out" = "Sign out";
+"Size" = "Size";
+"Zoom" = "Zoom";
+
+"Untitled document" = "Untitled document";
diff --git a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings
index 884f4ec..9f6a7d4 100644
--- a/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/es.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "Cancelar";
"native.discard.title" = "¿Descartar los cambios sin guardar?";
"native.discard.action" = "Descartar cambios";
+
+"docs.document.rename" = "Cambiar nombre del documento";
diff --git a/native/apple/Sources/DocsKit/Resources/es.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/es.lproj/Mac.strings
new file mode 100644
index 0000000..3568620
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/es.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "Cuentas";
+"Actual size" = "Tamaño real";
+"Alignment" = "Alineación";
+"Block quote" = "Cita en bloque";
+"Bold" = "Negrita";
+"Bullet list" = "Lista con viñetas";
+"Cell contents" = "Contenido de la celda";
+"Clear formatting" = "Borrar formato";
+"Close this account’s document windows before signing out." = "Cierra las ventanas de documentos de esta cuenta antes de cerrar sesión.";
+"Create a document to get started." = "Los documentos que crees aparecerán aquí, empezando por los más recientes.";
+"Docs" = "Docs";
+"Document" = "Documento";
+"Document inspector" = "Inspector del documento";
+"Double-click to fit column to contents" = "Haz doble clic para ajustar la columna al contenido";
+"Edit %@" = "Editar %@";
+"Export" = "Exportar";
+"Fit column to contents" = "Ajustar columna al contenido";
+"Font" = "Fuente";
+"Format" = "Formato";
+"Heading %d" = "Título %d";
+"Home" = "Inicio";
+"Indent" = "Aumentar sangría";
+"Inline code" = "Código";
+"Inspector" = "Inspector del documento";
+"Italic" = "Cursiva";
+"Markdown…" = "Markdown";
+"New document" = "Nuevo documento";
+"No documents" = "Aún no hay documentos";
+"No recent documents" = "Aún no hay documentos";
+"Normal" = "Texto del cuerpo";
+"Numbered list" = "Lista numerada";
+"Open a document from Home" = "Abre un documento desde Inicio";
+"Outdent" = "Reducir sangría";
+"PDF…" = "PDF";
+"Pages" = "Por páginas";
+"Paragraph style" = "Estilo de párrafo";
+"Print…" = "Imprimir";
+"Recent" = "Recientes";
+"Recent documents" = "Documentos recientes";
+"Recent spreadsheets" = "Hojas de cálculo recientes";
+"Retry" = "Reintentar";
+"Save" = "Guardar";
+"Select column %@" = "Seleccionar columna %@";
+"Select row %d" = "Seleccionar fila %d";
+"Shared" = "Compartidos contigo";
+"Share…" = "Compartir";
+"Sign out" = "Cerrar sesión";
+"Size" = "Tamaño";
+"Zoom" = "Zoom";
+
+"Untitled document" = "Documento sin título";
diff --git a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings
index b1287de..cae893b 100644
--- a/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ga.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "Cealaigh";
"native.discard.title" = "Scrios na hathruithe gan sábháil?";
"native.discard.action" = "Scrios athruithe";
+
+"docs.document.rename" = "Athainmnigh an doiciméad";
diff --git a/native/apple/Sources/DocsKit/Resources/ga.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/ga.lproj/Mac.strings
new file mode 100644
index 0000000..4be5249
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/ga.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "Cuntais";
+"Actual size" = "Fíormhéid";
+"Alignment" = "Ailíniú";
+"Block quote" = "Athfhriotal i mbloc";
+"Bold" = "Trom";
+"Bullet list" = "Liosta le hurchair";
+"Cell contents" = "Ábhar na cille";
+"Clear formatting" = "Glan an fhormáidiú";
+"Close this account’s document windows before signing out." = "Dún fuinneoga cáipéisí an chuntais seo sula síníonn tú amach.";
+"Create a document to get started." = "Beidh na doiciméid a chruthaíonn tú anseo, na cinn is nua ar dtús.";
+"Docs" = "Docs";
+"Document" = "Cáipéis";
+"Document inspector" = "Cigire cáipéise";
+"Double-click to fit column to contents" = "Déchliceáil chun an colún a oiriúnú don ábhar";
+"Edit %@" = "Cuir %@ in eagar";
+"Export" = "Easpórtáil";
+"Fit column to contents" = "Oiriúnaigh an colún don ábhar";
+"Font" = "Cló";
+"Format" = "Formáid";
+"Heading %d" = "Ceannteideal %d";
+"Home" = "Baile";
+"Indent" = "Méadaigh an eangú";
+"Inline code" = "Cód";
+"Inspector" = "Cigire cáipéise";
+"Italic" = "Iodálach";
+"Markdown…" = "Markdown";
+"New document" = "Doiciméad nua";
+"No documents" = "Níl aon doiciméid ann fós";
+"No recent documents" = "Níl aon doiciméid ann fós";
+"Normal" = "Téacs coirp";
+"Numbered list" = "Liosta uimhrithe";
+"Open a document from Home" = "Oscail cáipéis ón mBaile";
+"Outdent" = "Laghdaigh an eangú";
+"PDF…" = "PDF";
+"Pages" = "Leathanaigh";
+"Paragraph style" = "Stíl ailt";
+"Print…" = "Priontáil";
+"Recent" = "Le déanaí";
+"Recent documents" = "Cáipéisí le déanaí";
+"Recent spreadsheets" = "Scarbhileoga le déanaí";
+"Retry" = "Bain triail eile as";
+"Save" = "Sábháil";
+"Select column %@" = "Roghnaigh colún %@";
+"Select row %d" = "Roghnaigh ró %d";
+"Shared" = "Comhroinnte leat";
+"Share…" = "Comhroinn";
+"Sign out" = "Sínigh amach";
+"Size" = "Méid";
+"Zoom" = "Súmáil";
+
+"Untitled document" = "Doiciméad gan teideal";
diff --git a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings
index 153a256..5b468f9 100644
--- a/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/hi.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "रद्द करें";
"native.discard.title" = "बिना सहेजे बदलाव छोड़ें?";
"native.discard.action" = "बदलाव छोड़ें";
+
+"docs.document.rename" = "दस्तावेज़ का नाम बदलें";
diff --git a/native/apple/Sources/DocsKit/Resources/hi.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/hi.lproj/Mac.strings
new file mode 100644
index 0000000..3919264
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/hi.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "खाते";
+"Actual size" = "वास्तविक आकार";
+"Alignment" = "संरेखण";
+"Block quote" = "ब्लॉक उद्धरण";
+"Bold" = "बोल्ड";
+"Bullet list" = "बुलेट वाली सूची";
+"Cell contents" = "सेल की सामग्री";
+"Clear formatting" = "फ़ॉर्मैटिंग हटाएँ";
+"Close this account’s document windows before signing out." = "साइन आउट करने से पहले इस खाते की दस्तावेज़ विंडो बंद करें।";
+"Create a document to get started." = "आपके बनाए दस्तावेज़ यहाँ दिखेंगे, सबसे नए पहले।";
+"Docs" = "Docs";
+"Document" = "दस्तावेज़";
+"Document inspector" = "दस्तावेज़ निरीक्षक";
+"Double-click to fit column to contents" = "सामग्री के अनुसार आकार बदलने के लिए डबल-क्लिक करें";
+"Edit %@" = "%@ संपादित करें";
+"Export" = "निर्यात";
+"Fit column to contents" = "सामग्री के अनुसार स्तंभ का आकार बदलें";
+"Font" = "फ़ॉन्ट";
+"Format" = "फ़ॉर्मैट";
+"Heading %d" = "शीर्षक %d";
+"Home" = "होम";
+"Indent" = "इंडेंट बढ़ाएँ";
+"Inline code" = "कोड";
+"Inspector" = "दस्तावेज़ निरीक्षक";
+"Italic" = "इटैलिक";
+"Markdown…" = "Markdown";
+"New document" = "नया दस्तावेज़";
+"No documents" = "अभी कोई दस्तावेज़ नहीं";
+"No recent documents" = "अभी कोई दस्तावेज़ नहीं";
+"Normal" = "मुख्य पाठ";
+"Numbered list" = "क्रमांकित सूची";
+"Open a document from Home" = "होम से दस्तावेज़ खोलें";
+"Outdent" = "इंडेंट घटाएँ";
+"PDF…" = "PDF";
+"Pages" = "पृष्ठों में";
+"Paragraph style" = "अनुच्छेद शैली";
+"Print…" = "प्रिंट करें";
+"Recent" = "हाल के";
+"Recent documents" = "हाल के दस्तावेज़";
+"Recent spreadsheets" = "हाल की स्प्रेडशीट";
+"Retry" = "फिर कोशिश करें";
+"Save" = "सहेजें";
+"Select column %@" = "स्तंभ %@ चुनें";
+"Select row %d" = "पंक्ति %d चुनें";
+"Shared" = "आपके साथ शेयर किए गए";
+"Share…" = "शेयर करें";
+"Sign out" = "साइन आउट करें";
+"Size" = "आकार";
+"Zoom" = "ज़ूम";
+
+"Untitled document" = "बिना शीर्षक का दस्तावेज़";
diff --git a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings
index 6aa890a..e02a00c 100644
--- a/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ja.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "キャンセル";
"native.discard.title" = "未保存の変更を破棄しますか?";
"native.discard.action" = "変更を破棄";
+
+"docs.document.rename" = "ドキュメント名を変更";
diff --git a/native/apple/Sources/DocsKit/Resources/ja.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/ja.lproj/Mac.strings
new file mode 100644
index 0000000..1b9af06
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/ja.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "アカウント";
+"Actual size" = "実際のサイズ";
+"Alignment" = "配置";
+"Block quote" = "引用ブロック";
+"Bold" = "太字";
+"Bullet list" = "箇条書き";
+"Cell contents" = "セルの内容";
+"Clear formatting" = "書式をクリア";
+"Close this account’s document windows before signing out." = "サインアウトする前に、このアカウントの書類ウインドウを閉じてください。";
+"Create a document to get started." = "作成したドキュメントが新しい順にここに表示されます。";
+"Docs" = "Docs";
+"Document" = "書類";
+"Document inspector" = "書類インスペクタ";
+"Double-click to fit column to contents" = "ダブルクリックで列幅を内容に合わせる";
+"Edit %@" = "%@ を編集";
+"Export" = "書き出す";
+"Fit column to contents" = "列幅を内容に合わせる";
+"Font" = "フォント";
+"Format" = "書式";
+"Heading %d" = "見出し %d";
+"Home" = "ホーム";
+"Indent" = "インデントを増やす";
+"Inline code" = "コード";
+"Inspector" = "書類インスペクタ";
+"Italic" = "斜体";
+"Markdown…" = "Markdown";
+"New document" = "新規ドキュメント";
+"No documents" = "ドキュメントはまだありません";
+"No recent documents" = "ドキュメントはまだありません";
+"Normal" = "本文";
+"Numbered list" = "番号付きリスト";
+"Open a document from Home" = "ホームから書類を開く";
+"Outdent" = "インデントを減らす";
+"PDF…" = "PDF";
+"Pages" = "ページ区切り";
+"Paragraph style" = "段落スタイル";
+"Print…" = "プリント";
+"Recent" = "最近使った項目";
+"Recent documents" = "最近の書類";
+"Recent spreadsheets" = "最近のスプレッドシート";
+"Retry" = "再試行";
+"Save" = "保存";
+"Select column %@" = "列 %@ を選択";
+"Select row %d" = "行 %d を選択";
+"Shared" = "あなたと共有";
+"Share…" = "共有";
+"Sign out" = "サインアウト";
+"Size" = "サイズ";
+"Zoom" = "ズーム";
+
+"Untitled document" = "無題のドキュメント";
diff --git a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings
index aaa738c..e2f7b7f 100644
--- a/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/pt.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "Cancelar";
"native.discard.title" = "Descartar alterações não salvas?";
"native.discard.action" = "Descartar alterações";
+
+"docs.document.rename" = "Renomear documento";
diff --git a/native/apple/Sources/DocsKit/Resources/pt.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/pt.lproj/Mac.strings
new file mode 100644
index 0000000..a859c91
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/pt.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "Contas";
+"Actual size" = "Tamanho real";
+"Alignment" = "Alinhamento";
+"Block quote" = "Citação em bloco";
+"Bold" = "Negrito";
+"Bullet list" = "Lista com marcas";
+"Cell contents" = "Conteúdo da célula";
+"Clear formatting" = "Limpar formatação";
+"Close this account’s document windows before signing out." = "Feche as janelas de documentos desta conta antes de terminar a sessão.";
+"Create a document to get started." = "Os documentos que criar aparecem aqui, começando pelos mais recentes.";
+"Docs" = "Docs";
+"Document" = "Documento";
+"Document inspector" = "Inspetor do documento";
+"Double-click to fit column to contents" = "Clique duas vezes para ajustar a coluna ao conteúdo";
+"Edit %@" = "Editar %@";
+"Export" = "Exportar";
+"Fit column to contents" = "Ajustar coluna ao conteúdo";
+"Font" = "Tipo de letra";
+"Format" = "Formato";
+"Heading %d" = "Título %d";
+"Home" = "Início";
+"Indent" = "Aumentar avanço";
+"Inline code" = "Código";
+"Inspector" = "Inspetor do documento";
+"Italic" = "Itálico";
+"Markdown…" = "Markdown";
+"New document" = "Novo documento";
+"No documents" = "Ainda não há documentos";
+"No recent documents" = "Ainda não há documentos";
+"Normal" = "Corpo do texto";
+"Numbered list" = "Lista numerada";
+"Open a document from Home" = "Abra um documento no Início";
+"Outdent" = "Diminuir avanço";
+"PDF…" = "PDF";
+"Pages" = "Paginado";
+"Paragraph style" = "Estilo de parágrafo";
+"Print…" = "Imprimir";
+"Recent" = "Recentes";
+"Recent documents" = "Documentos recentes";
+"Recent spreadsheets" = "Folhas de cálculo recentes";
+"Retry" = "Tentar novamente";
+"Save" = "Guardar";
+"Select column %@" = "Selecionar coluna %@";
+"Select row %d" = "Selecionar linha %d";
+"Shared" = "Partilhados consigo";
+"Share…" = "Partilhar";
+"Sign out" = "Terminar sessão";
+"Size" = "Tamanho";
+"Zoom" = "Zoom";
+
+"Untitled document" = "Documento sem título";
diff --git a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings
index 193dd55..d7ff633 100644
--- a/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/ru.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "Отмена";
"native.discard.title" = "Отменить несохранённые изменения?";
"native.discard.action" = "Отменить изменения";
+
+"docs.document.rename" = "Переименовать документ";
diff --git a/native/apple/Sources/DocsKit/Resources/ru.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/ru.lproj/Mac.strings
new file mode 100644
index 0000000..83aa91e
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/ru.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "Учётные записи";
+"Actual size" = "Фактический размер";
+"Alignment" = "Выравнивание";
+"Block quote" = "Блок цитаты";
+"Bold" = "Полужирный";
+"Bullet list" = "Маркированный список";
+"Cell contents" = "Содержимое ячейки";
+"Clear formatting" = "Очистить форматирование";
+"Close this account’s document windows before signing out." = "Перед выходом закройте окна документов этой учётной записи.";
+"Create a document to get started." = "Созданные вами документы появятся здесь, начиная с самых новых.";
+"Docs" = "Docs";
+"Document" = "Документ";
+"Document inspector" = "Инспектор документа";
+"Double-click to fit column to contents" = "Дважды щёлкните для подгонки ширины столбца";
+"Edit %@" = "Изменить %@";
+"Export" = "Экспорт";
+"Fit column to contents" = "Подогнать ширину столбца";
+"Font" = "Шрифт";
+"Format" = "Формат";
+"Heading %d" = "Заголовок %d";
+"Home" = "Главная";
+"Indent" = "Увеличить отступ";
+"Inline code" = "Код";
+"Inspector" = "Инспектор документа";
+"Italic" = "Курсив";
+"Markdown…" = "Markdown";
+"New document" = "Новый документ";
+"No documents" = "Документов пока нет";
+"No recent documents" = "Документов пока нет";
+"Normal" = "Основной текст";
+"Numbered list" = "Нумерованный список";
+"Open a document from Home" = "Откройте документ на главной";
+"Outdent" = "Уменьшить отступ";
+"PDF…" = "PDF";
+"Pages" = "Постраничный";
+"Paragraph style" = "Стиль абзаца";
+"Print…" = "Печать";
+"Recent" = "Недавние";
+"Recent documents" = "Недавние документы";
+"Recent spreadsheets" = "Недавние таблицы";
+"Retry" = "Повторить попытку";
+"Save" = "Сохранить";
+"Select column %@" = "Выбрать столбец %@";
+"Select row %d" = "Выбрать строку %d";
+"Shared" = "Доступные вам";
+"Share…" = "Поделиться";
+"Sign out" = "Выйти";
+"Size" = "Размер";
+"Zoom" = "Масштаб";
+
+"Untitled document" = "Документ без названия";
diff --git a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings
index 5a86ee7..d33401d 100644
--- a/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/vi.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "Hủy";
"native.discard.title" = "Hủy các thay đổi chưa lưu?";
"native.discard.action" = "Hủy thay đổi";
+
+"docs.document.rename" = "Đổi tên tài liệu";
diff --git a/native/apple/Sources/DocsKit/Resources/vi.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/vi.lproj/Mac.strings
new file mode 100644
index 0000000..fb823d0
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/vi.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "Tài khoản";
+"Actual size" = "Kích thước thực";
+"Alignment" = "Căn chỉnh";
+"Block quote" = "Khối trích dẫn";
+"Bold" = "Đậm";
+"Bullet list" = "Danh sách dấu đầu dòng";
+"Cell contents" = "Nội dung ô";
+"Clear formatting" = "Xóa định dạng";
+"Close this account’s document windows before signing out." = "Đóng các cửa sổ tài liệu của tài khoản này trước khi đăng xuất.";
+"Create a document to get started." = "Tài liệu bạn tạo sẽ xuất hiện ở đây, mới nhất trước.";
+"Docs" = "Docs";
+"Document" = "Tài liệu";
+"Document inspector" = "Thuộc tính tài liệu";
+"Double-click to fit column to contents" = "Nhấp đúp để khớp cột với nội dung";
+"Edit %@" = "Sửa %@";
+"Export" = "Xuất";
+"Fit column to contents" = "Khớp cột với nội dung";
+"Font" = "Phông chữ";
+"Format" = "Định dạng";
+"Heading %d" = "Tiêu đề %d";
+"Home" = "Trang chủ";
+"Indent" = "Tăng thụt lề";
+"Inline code" = "Mã";
+"Inspector" = "Thuộc tính tài liệu";
+"Italic" = "Nghiêng";
+"Markdown…" = "Markdown";
+"New document" = "Tài liệu mới";
+"No documents" = "Chưa có tài liệu";
+"No recent documents" = "Chưa có tài liệu";
+"Normal" = "Văn bản nội dung";
+"Numbered list" = "Danh sách đánh số";
+"Open a document from Home" = "Mở tài liệu từ Trang chủ";
+"Outdent" = "Giảm thụt lề";
+"PDF…" = "PDF";
+"Pages" = "Theo trang";
+"Paragraph style" = "Kiểu đoạn văn";
+"Print…" = "In";
+"Recent" = "Gần đây";
+"Recent documents" = "Tài liệu gần đây";
+"Recent spreadsheets" = "Bảng tính gần đây";
+"Retry" = "Thử lại";
+"Save" = "Lưu";
+"Select column %@" = "Chọn cột %@";
+"Select row %d" = "Chọn hàng %d";
+"Shared" = "Được chia sẻ với bạn";
+"Share…" = "Chia sẻ";
+"Sign out" = "Đăng xuất";
+"Size" = "Kích cỡ";
+"Zoom" = "Thu phóng";
+
+"Untitled document" = "Tài liệu chưa đặt tên";
diff --git a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings
index d86be15..a8db880 100644
--- a/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/yue.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "取消";
"native.discard.title" = "放棄未儲存嘅變更?";
"native.discard.action" = "放棄變更";
+
+"docs.document.rename" = "重新命名文件";
diff --git a/native/apple/Sources/DocsKit/Resources/yue.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/yue.lproj/Mac.strings
new file mode 100644
index 0000000..2657f81
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/yue.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "帳戶";
+"Actual size" = "實際大小";
+"Alignment" = "對齊";
+"Block quote" = "引文區塊";
+"Bold" = "粗體";
+"Bullet list" = "項目符號清單";
+"Cell contents" = "儲存格內容";
+"Clear formatting" = "清除格式";
+"Close this account’s document windows before signing out." = "登出前請先關閉此帳戶嘅文件視窗。";
+"Create a document to get started." = "你建立嘅文件會喺呢度顯示,最新嘅排最前。";
+"Docs" = "Docs";
+"Document" = "文件";
+"Document inspector" = "文件檢查器";
+"Double-click to fit column to contents" = "按兩下以按內容調整欄寬";
+"Edit %@" = "編輯 %@";
+"Export" = "輸出";
+"Fit column to contents" = "按內容調整欄寬";
+"Font" = "字體";
+"Format" = "格式";
+"Heading %d" = "標題 %d";
+"Home" = "主頁";
+"Indent" = "增加縮排";
+"Inline code" = "程式碼";
+"Inspector" = "文件檢查器";
+"Italic" = "斜體";
+"Markdown…" = "Markdown";
+"New document" = "新增文件";
+"No documents" = "仲未有文件";
+"No recent documents" = "仲未有文件";
+"Normal" = "內文";
+"Numbered list" = "編號清單";
+"Open a document from Home" = "由主頁開啟文件";
+"Outdent" = "減少縮排";
+"PDF…" = "PDF";
+"Pages" = "分頁";
+"Paragraph style" = "段落樣式";
+"Print…" = "列印";
+"Recent" = "最近項目";
+"Recent documents" = "最近文件";
+"Recent spreadsheets" = "最近試算表";
+"Retry" = "再試一次";
+"Save" = "儲存";
+"Select column %@" = "選取 %@ 欄";
+"Select row %d" = "選取第 %d 行";
+"Shared" = "同你分享嘅文件";
+"Share…" = "分享";
+"Sign out" = "登出";
+"Size" = "大小";
+"Zoom" = "縮放";
+
+"Untitled document" = "未命名文件";
diff --git a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings
index 1faafe8..d01ecfb 100644
--- a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings
+++ b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Localizable.strings
@@ -171,3 +171,5 @@
"native.close.pending.cancel" = "取消";
"native.discard.title" = "放弃未保存的更改?";
"native.discard.action" = "放弃更改";
+
+"docs.document.rename" = "重命名文档";
diff --git a/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Mac.strings b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Mac.strings
new file mode 100644
index 0000000..6db2e5c
--- /dev/null
+++ b/native/apple/Sources/DocsKit/Resources/zh-Hans.lproj/Mac.strings
@@ -0,0 +1,51 @@
+"Accounts" = "账户";
+"Actual size" = "实际大小";
+"Alignment" = "对齐";
+"Block quote" = "块引用";
+"Bold" = "粗体";
+"Bullet list" = "项目符号列表";
+"Cell contents" = "单元格内容";
+"Clear formatting" = "清除格式";
+"Close this account’s document windows before signing out." = "退出登录前请关闭此账户的文档窗口。";
+"Create a document to get started." = "您创建的文档会显示在这里,最新的排在最前面。";
+"Docs" = "Docs";
+"Document" = "文档";
+"Document inspector" = "文档检查器";
+"Double-click to fit column to contents" = "双击以根据内容调整列宽";
+"Edit %@" = "编辑 %@";
+"Export" = "导出";
+"Fit column to contents" = "根据内容调整列宽";
+"Font" = "字体";
+"Format" = "格式";
+"Heading %d" = "标题 %d";
+"Home" = "主页";
+"Indent" = "增加缩进";
+"Inline code" = "代码";
+"Inspector" = "文档检查器";
+"Italic" = "斜体";
+"Markdown…" = "Markdown";
+"New document" = "新建文档";
+"No documents" = "还没有文档";
+"No recent documents" = "还没有文档";
+"Normal" = "正文";
+"Numbered list" = "编号列表";
+"Open a document from Home" = "从主页打开文档";
+"Outdent" = "减少缩进";
+"PDF…" = "PDF";
+"Pages" = "分页";
+"Paragraph style" = "段落样式";
+"Print…" = "打印";
+"Recent" = "最近项目";
+"Recent documents" = "最近文档";
+"Recent spreadsheets" = "最近电子表格";
+"Retry" = "重试";
+"Save" = "保存";
+"Select column %@" = "选择 %@ 列";
+"Select row %d" = "选择第 %d 行";
+"Shared" = "与您共享";
+"Share…" = "共享";
+"Sign out" = "退出登录";
+"Size" = "大小";
+"Zoom" = "缩放";
+
+"Untitled document" = "无标题文档";
diff --git a/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift b/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift
new file mode 100644
index 0000000..33f0e99
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/BrowserTypographyTests.swift
@@ -0,0 +1,179 @@
+#if os(macOS)
+import AppKit
+import WebKit
+import XCTest
+@testable import DocsKit
+
+/// Measures the production stylesheet, not a second copy of its typography rules.
+@MainActor final class BrowserTypographyTests: XCTestCase {
+ func testRichTextLineBreaksMatchBrowser() async throws {
+ let prose = "A shared document keeps the same words on each line across the browser and native editor. This deliberately long sentence exercises the available measure and the selected font metrics."
+ let cases: [(String, CRDTNode, String)] = [
+ ("heading4", block("h4", prose, type: "heading", attrs: ["level": "4"]), "<h4>\(prose)</h4>"),
+ ("list", CRDTNode(id: "list", type: "bullet_list", children: [CRDTNode(id: "item", type: "list_item", children: [block("li", prose)])]), "<ul><li><p>\(prose)</p></li></ul>"),
+ ("nested-list", CRDTNode(id: "outer", type: "bullet_list", children: [CRDTNode(id: "outerItem", type: "list_item", children: [CRDTNode(id: "inner", type: "ordered_list", children: [CRDTNode(id: "innerItem", type: "list_item", children: [block("nested", prose)])])])]), "<ul><li><ol><li><p>\(prose)</p></li></ol></li></ul>"),
+ ("quote", CRDTNode(id: "quote", type: "blockquote", children: [block("qp", prose)]), "<blockquote><p>\(prose)</p></blockquote>"),
+ ("serif", block("serif", prose, marks: ["font_serif": .object([:])]), "<p><span class='docs-font-serif'>\(prose)</span></p>"),
+ ("mono", block("mono", prose, marks: ["font_mono": .object([:])]), "<p><span class='docs-font-mono'>\(prose)</span></p>"),
+ ("large", block("large", prose, marks: ["size_24": .object([:])]), "<p><span class='docs-size-24'>\(prose)</span></p>"),
+ ("mixed-size", CRDTNode(id: "mixedSize", type: "paragraph", children: [CRDTNode(id: "mixedSizet", type: "text", runs: [CRDTRun(insert: "Large", marks: ["size_72": .object([:])]), CRDTRun(insert: " " + prose + " " + prose)])]), "<p><span class='docs-size-72'>Large</span> \(prose) \(prose)</p>"),
+ ("mixed-code-wrap", CRDTNode(id: "wrap", type: "paragraph", children: [CRDTNode(id: "wrapt", type: "text", runs: [CRDTRun(insert: String(repeating: "Wide words ", count: 7)), CRDTRun(insert: "WRAPPEDCODE " + prose, marks: ["code": .object([:])])])]), "<p>\(String(repeating: "Wide words ", count: 7))<code>WRAPPEDCODE \(prose)</code></p>"),
+ ("mixed-code", CRDTNode(id: "mixed", type: "paragraph", children: [CRDTNode(id: "mixedt", type: "text", runs: [CRDTRun(insert: "Before 🧪 "), CRDTRun(insert: prose, marks: ["code": .object([:])]), CRDTRun(insert: " after.")])]), "<p>Before 🧪 <code>\(prose)</code> after.</p>"),
+ ("code", block("code", prose, marks: ["code": .object([:])]), "<p><code>\(prose)</code></p>"),
+ ]
+ for (name, node, html) in cases {
+ let browser = try await browserLines(html)
+ let native = nativeLines([node])
+ XCTAssertEqual(native.map(\.text), browser.map(\.text), name)
+ if name == "mixed-size", native.count > 2, browser.count > 2 {
+ XCTAssertEqual(native.last!.y - native[native.count - 2].y, browser.last!.y - browser[browser.count - 2].y, accuracy: 0.76)
+ }
+ for (lhs, rhs) in zip(native, browser) {
+ XCTAssertEqual(lhs.x, rhs.x, accuracy: 0.76, "\(name): text origin")
+ if !name.hasPrefix("mixed") { XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 0.76, "\(name): line spacing") }
+ }
+ }
+ }
+
+ func testAdjacentHeadingMarginsCollapse() async throws {
+ let text = "A heading with a predictable measure"
+ let nodes = (0..<4).map { block("h\($0)", text, type: "heading", attrs: ["level": "2"]) }
+ let browser = try await browserLines(String(repeating: "<h2>\(text)</h2>", count: 4))
+ let native = nativeLines(nodes)
+ XCTAssertEqual(native.count, browser.count)
+ for (lhs, rhs) in zip(native, browser) {
+ XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 0.76)
+ }
+ }
+
+ func testNestedBlockSpacingMatchesBrowser() async throws {
+ let text = "A repeated heading inside a quote"
+ let nodes = (0..<5).map { index in CRDTNode(id: "quote\(index)", type: "blockquote", children: [block("nestedHeading\(index)", text, type: "heading", attrs: ["level": "2"])]) }
+ let html = String(repeating: "<blockquote><h2>\(text)</h2></blockquote>", count: 5)
+ let browser = try await browserLines(html, includeBounds: true)
+ let native = nativeLines(nodes, includeBounds: true)
+ XCTAssertEqual(native.map(\.text), browser.map(\.text))
+ for (lhs, rhs) in zip(native, browser) {
+ if lhs.text == "[bottom]" { XCTAssertEqual(lhs.y, rhs.y, accuracy: 0.76) }
+ else { XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 0.76) }
+ }
+ }
+
+ func testPageBreaksMatchBrowserAndPreserveWholeBlocks() async throws {
+ let prose = "A page keeps this whole paragraph together. "
+ let nodes = (0..<18).map { block("p\($0)", String(repeating: prose, count: $0 == 0 ? 160 : 8)) }
+ let html = nodes.map { "<p>\($0.plainText)</p>" }.joined()
+ let browser = try await browserLines(html, paged: true)
+ let native = nativeLines(nodes, paged: true)
+ XCTAssertEqual(native.map(\.text), browser.map(\.text))
+ XCTAssertGreaterThan(native.filter { $0.text == "[page]" }.count, 1)
+ for (lhs, rhs) in zip(native, browser) {
+ if lhs.text == "[page]" {
+ XCTAssertEqual(lhs.y - 72, rhs.y, accuracy: 1.5, "page separator")
+ } else {
+ XCTAssertEqual(lhs.y - native[0].y, rhs.y - browser[0].y, accuracy: 1.5, lhs.text)
+ }
+ }
+ }
+
+ private func block(_ id: String, _ text: String, type: String = "paragraph", attrs: [String: String]? = nil, marks: [String: JSONValue]? = nil) -> CRDTNode {
+ CRDTNode(id: id, type: type, attrs: attrs, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: marks)])])
+ }
+
+ struct Line: Decodable { var text: String; var x: Double; var y: Double }
+ private func nativeLines(_ nodes: [CRDTNode], paged: Bool = false, includeBounds: Bool = false) -> [Line] {
+ let storage = NSTextStorage(attributedString: NativeTextProjection.render(CRDTProjection(children: nodes, canUndo: false, canRedo: false)))
+ let manager = DocsLayoutManager()
+ let container = DocsPageTextContainer(size: CGSize(width: 636, height: 100000))
+ container.geometry = DocsPageGeometry(viewportWidth: 636, paged: false)
+ container.lineFragmentPadding = 0
+ storage.addLayoutManager(manager); manager.addTextContainer(container)
+ manager.ensureLayout(for: container)
+ let pages = paged ? DocumentPageLayout.measure(storage: storage, manager: manager, container: container) : DocumentPageLayout.Result()
+ container.blockStarts = pages.starts
+ manager.ensureLayout(for: container)
+ var lines: [Line] = []
+ var contentBottom: CGFloat = 72
+ manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { rect, _, _, range, _ in
+ contentBottom = max(contentBottom, rect.maxY)
+ let chars = manager.characterRange(forGlyphRange: range, actualGlyphRange: nil)
+ let text = (storage.string as NSString).substring(with: chars).trimmingCharacters(in: .whitespacesAndNewlines)
+ let location = manager.location(forGlyphAt: range.location)
+ lines.append(Line(text: text, x: rect.minX + location.x - container.geometry.textX, y: rect.minY))
+ }
+ lines += pages.separators.map { Line(text: "[page]", x: 0, y: $0) }
+ if includeBounds { lines.append(Line(text: "[bottom]", x: 0, y: contentBottom - 72)) }
+ return lines
+ }
+
+ private func browserLines(_ html: String, paged: Bool = false, includeBounds: Bool = false) async throws -> [Line] {
+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let source = try String(contentsOf: root.appendingPathComponent("internal/docs/views/show.html"), encoding: .utf8)
+ let start = try XCTUnwrap(source.range(of: "<style>"))
+ let end = try XCTUnwrap(source.range(of: "</style>", range: start.upperBound..<source.endIndex))
+ var css = String(source[start.upperBound..<end.lowerBound])
+ css = css.replacingOccurrences(of: #"\{\{range \.FontFaces\}\}[\s\S]*?\{\{end\}\}"#, with: "", options: .regularExpression)
+ for family in ["Sans", "Serif", "Mono"] {
+ for face in ["Regular", "Bold", "Italic", "BoldItalic"] {
+ let font = try XCTUnwrap(DocsResources.bundle.url(forResource: "Liberation\(family)-\(face)", withExtension: "ttf"))
+ let data = try Data(contentsOf: font).base64EncodedString()
+ css += "@font-face{font-family:'Docs \(family)';src:url(data:font/ttf;base64,\(data));font-weight:\(face.contains("Bold") ? 700 : 400);font-style:\(face.contains("Italic") ? "italic" : "normal");}"
+ }
+ }
+ let pageSource = try String(contentsOf: root.appendingPathComponent("fixtures/pages.mjs"), encoding: .utf8)
+ let measureStart = try XCTUnwrap(pageSource.range(of: "function breakPositions(view)"))
+ let measureEnd = try XCTUnwrap(pageSource.range(of: "// pagesPlugin draws"))
+ let gapStart = try XCTUnwrap(pageSource.range(of: "function gapElement(number, pageLabel)"))
+ let pageScript = "const PAGE_CONTENT_PX=864;" + pageSource[measureStart.lowerBound..<measureEnd.lowerBound] + pageSource[gapStart.lowerBound...]
+ let view = WKWebView(frame: CGRect(x: 0, y: 0, width: 1000, height: 1200))
+ let navigation = Navigation()
+ view.navigationDelegate = navigation
+ await withCheckedContinuation { continuation in
+ navigation.loaded = { continuation.resume() }
+ view.loadHTMLString("<!doctype html><meta charset='utf-8'><style>\(css) body{margin:0} [docs-text]{width:624px;display:flow-root;--rst-sp-6:24px}</style><main docs-text>\(html)</main>", baseURL: nil)
+ }
+ let script = """
+ await document.fonts.ready;
+ const root = document.querySelector('[docs-text]'), origin = root.getBoundingClientRect();
+ \(paged ? pageScript : "")
+ if (\(paged ? "true" : "false")) {
+ const blocks = [...root.children];
+ const view = {state:{doc:{forEach:callback=>blocks.forEach((node,i)=>callback(node,i))}},nodeDOM:i=>blocks[i]};
+ let previous = '';
+ for (let pass=0; pass<10; pass++) {
+ const positions=breakPositions(view), key=positions.join(',');
+ if (key===previous) break;
+ previous=key;
+ root.querySelectorAll('[docs-page-gap]').forEach(el=>el.remove());
+ positions.forEach((position,i)=>root.insertBefore(gapElement(i+2),blocks[position]));
+ if (pass===9) throw new Error('Pagination did not converge');
+ }
+ }
+ const lines = [];
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
+ let node;
+ while (node = walker.nextNode()) {
+ if (node.parentElement.closest('[docs-page-gap]')) continue;
+ for (let i = 0; i < node.length; i++) {
+ const range = document.createRange(); range.setStart(node,i); range.setEnd(node,i+1);
+ const box = range.getBoundingClientRect(), previous = lines.at(-1);
+ if (!previous || box.y >= previous.bottom - .1 || box.bottom <= previous.top + .1)
+ lines.push({text:node.textContent[i], x:(box.x-origin.x)*.75,y:(box.y-origin.y)*.75,top:box.y,bottom:box.bottom});
+ else { previous.text += node.textContent[i]; previous.top=Math.min(previous.top,box.y); previous.bottom=Math.max(previous.bottom,box.bottom); }
+ }
+ }
+ for (const line of lines) line.text = line.text.trim();
+ for (const gap of root.querySelectorAll('[docs-page-gap]')) lines.push({text:'[page]',x:0,y:(gap.getBoundingClientRect().y-origin.y)*.75});
+ if (\(includeBounds ? "true" : "false")) lines.push({text:"[bottom]",x:0,y:root.getBoundingClientRect().height*.75});
+ return JSON.stringify(lines);
+ """
+ let json = try await view.callAsyncJavaScript(script, contentWorld: .page) as! String
+ return try JSONDecoder().decode([Line].self, from: Data(json.utf8))
+ }
+
+ private final class Navigation: NSObject, WKNavigationDelegate {
+ var loaded: (() -> Void)?
+ func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { loaded?(); loaded = nil }
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/DocumentDraftTests.swift b/native/apple/Tests/DocsKitTests/DocumentDraftTests.swift
new file mode 100644
index 0000000..ef989be
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocumentDraftTests.swift
@@ -0,0 +1,72 @@
+import Foundation
+import RastrilloApple
+import XCTest
+@testable import DocsKit
+
+final class DocumentDraftTests: XCTestCase {
+ @MainActor func testImmediateDraftLostAcknowledgementRenameAndDiscard() async throws {
+ guard let origin = ProcessInfo.processInfo.environment["DOCS_DRAFT_TEST_ORIGIN"] else { throw XCTSkip("Run test-document-drafts.py") }
+ let client = NativeHTTP(origin: URL(string: origin)!)
+ let model = DocsModel(client: client, draft: true)
+ XCTAssertTrue(model.hasUnsavedChanges, "Protect the window before the first suspension")
+ let start = ContinuousClock.now
+ await model.newDraft()
+ XCTAssertLessThan(start.duration(to: .now), .milliseconds(500), "Opening cannot wait for the server")
+ XCTAssertNotNil(model.projection)
+ XCTAssertTrue(model.isDraft)
+ let identity = model.editorIdentity
+ for command in [
+ ["op": JSONValue.string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("Draft text!")],
+ ["op": .string("display_edit"), "at": .number(10), "length": .number(1), "text": .string("")]
+ ] {
+ model.didRender(model.projectionGeneration)
+ XCTAssertTrue(model.enqueue(command))
+ while model.hasPendingInput { try await Task.sleep(for: .milliseconds(5)) }
+ }
+ model.rename("My document")
+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))
+ while model.creatingDocument && .now < deadline { try await Task.sleep(for: .milliseconds(10)) }
+ XCTAssertTrue(model.isDraft, "The fixture drops the first creation acknowledgement")
+ XCTAssertEqual(model.projection?.children.map(\.plainText), ["Draft text"])
+ await model.retry()
+ let saved = await model.saveAll()
+ XCTAssertTrue(saved)
+ try await Task.sleep(for: .milliseconds(1000)) // Let the stale metadata reply finish.
+ XCTAssertEqual(model.editorIdentity, identity)
+ XCTAssertEqual(model.detail?.title, "My document")
+ struct Stats: Decodable { let documents: Int; let updates: [Data]; let title: String; let creations: Int; let metadata: Int }
+ let stats: Stats = try await client.request("/stats")
+ XCTAssertEqual(stats.documents, 1)
+ XCTAssertEqual(stats.creations, 2)
+ XCTAssertEqual(stats.title, "My document")
+ XCTAssertGreaterThanOrEqual(stats.metadata, 2, "Reconnection must refresh capabilities while rename is pending")
+ let peer = CRDTReplica(guid: "different-server-guid")
+ _ = try await peer.open(update: Data())
+ for update in stats.updates { _ = try await peer.apply(update) }
+ let projected = try await peer.projection()
+ XCTAssertEqual(projected.children.map(\.plainText), ["Draft text"], "Insertions and deletes converge across GUIDs")
+ await peer.close(); await model.stop()
+
+ let closing = DocsModel(client: client, draft: true)
+ await closing.newDraft()
+ closing.renameInput = String(repeating: "a", count: 1025)
+ let refused = await closing.saveAll()
+ XCTAssertFalse(refused)
+ XCTAssertNotNil(closing.renameInput, "Invalid title must remain editable")
+ closing.renameInput = "Saved on close"
+ let closed = await closing.saveAll()
+ XCTAssertTrue(closed, "Close-save must await creation and the pending title")
+ XCTAssertFalse(closing.isDraft)
+ await closing.stop()
+ let beforeDiscard: Stats = try await client.request("/stats")
+ let discarded = DocsModel(client: client, draft: true)
+ await discarded.newDraft()
+ try await Task.sleep(for: .milliseconds(100))
+ await discarded.discardAll()
+ try await Task.sleep(for: .milliseconds(1200))
+ XCTAssertNil(discarded.detail)
+ XCTAssertFalse(discarded.hasUnsavedChanges)
+ let after: Stats = try await client.request("/stats")
+ XCTAssertEqual(after.updates.count, beforeDiscard.updates.count, "Late creation must not upload a discarded draft")
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift b/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift
new file mode 100644
index 0000000..6a64cff
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocumentPageEditingTests.swift
@@ -0,0 +1,113 @@
+#if os(macOS)
+import AppKit
+import XCTest
+@testable import DocsKit
+
+@MainActor final class DocumentPageEditingTests: XCTestCase {
+ func testOptimisticAndMarkedEditsInvalidatePageOffsets() throws {
+ let nodes = (0..<100).map { index in
+ CRDTNode(id: "p\(index)", type: "paragraph", children: [CRDTNode(id: "t\(index)", type: "text", runs: [CRDTRun(insert: "A paragraph kept together when pages are recalculated.")])])
+ }
+ let view = DocsPagedTextView(frame: CGRect(x: 0, y: 0, width: 636, height: 800))
+ let storage = try XCTUnwrap(view.textStorage)
+ storage.setAttributedString(NativeTextProjection.render(CRDTProjection(children: nodes, canUndo: false, canRedo: false)))
+ view.paged = true
+ view.layout()
+ let container = try XCTUnwrap(view.textContainer as? DocsPageTextContainer)
+ XCTAssertFalse(container.blockStarts.isEmpty)
+ let initial = container.blockStarts
+ let insertion = String(repeating: "Inserted text before the boundary. ", count: 20)
+ storage.replaceCharacters(in: NSRange(location: 0, length: 0), with: insertion)
+ assertBlockStarts(container, storage)
+ view.layout()
+ XCTAssertNotEqual(initial, container.blockStarts)
+ assertBlockStarts(container, storage)
+ view.setSelectedRange(NSRange(location: 0, length: 0))
+ view.setMarkedText("日本語", selectedRange: NSRange(location: 3, length: 0), replacementRange: NSRange(location: 0, length: 0))
+ assertBlockStarts(container, storage)
+ view.layout()
+ assertBlockStarts(container, storage)
+ view.unmarkText()
+ storage.replaceCharacters(in: NSRange(location: 0, length: 3 + insertion.utf16.count), with: "")
+ assertBlockStarts(container, storage)
+ view.layout()
+ XCTAssertEqual(container.blockStarts, initial)
+ XCTAssertEqual(storage.string, nodes.map(\.plainText).joined(separator: "\n") + "\n")
+ }
+
+ func testMetadataReconciliationNeverExposesUnpaginatedCaretGeometry() throws {
+ let nodes = (0..<1000).map { index in
+ CRDTNode(id: "p\(index)", type: "paragraph", children: [CRDTNode(id: "t\(index)", type: "text", runs: [CRDTRun(insert: "A paragraph kept together when pages are recalculated.")])])
+ }
+ let view = DocsPagedTextView(frame: CGRect(x: 0, y: 0, width: 636, height: 800))
+ let storage = try XCTUnwrap(view.textStorage)
+ storage.setAttributedString(NativeTextProjection.render(CRDTProjection(children: nodes, canUndo: false, canRedo: false)))
+ view.paged = true
+ view.layout()
+ let manager = try XCTUnwrap(view.layoutManager)
+ let container = try XCTUnwrap(view.textContainer as? DocsPageTextContainer)
+ XCTAssertGreaterThanOrEqual(container.blockStarts.count, 2)
+ let selected = storage.length - 3
+ view.setSelectedRange(NSRange(location: selected, length: 0))
+ func caretY() -> CGFloat {
+ manager.ensureLayout(for: container)
+ return manager.lineFragmentRect(forGlyphAt: manager.glyphIndexForCharacter(at: selected), effectiveRange: nil).minY
+ }
+ let before = caretY()
+ let start = ContinuousClock.now
+ for generation in 0..<10 {
+ storage.addAttribute(NSAttributedString.Key("MetadataOnly"), value: generation, range: NSRange(location: 0, length: storage.length))
+ XCTAssertEqual(caretY(), before, accuracy: 0.01, "AppKit can query the caret before the next view layout")
+ }
+ print("Ten metadata updates in a 1,000-paragraph document:", start.duration(to: .now))
+ view.layout()
+ XCTAssertEqual(caretY(), before, accuracy: 0.01)
+ XCTAssertEqual(view.selectedRange(), NSRange(location: selected, length: 0))
+ }
+
+ func testCaretBackgroundErasureStaysInsideRequestedRectangle() throws {
+ let view = DocsPagedTextView(frame: CGRect(x: 0, y: 0, width: 636, height: 800))
+ view.layout()
+ let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 100, pixelsHigh: 100,
+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,
+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0))
+ let context = try XCTUnwrap(NSGraphicsContext(bitmapImageRep: bitmap))
+ NSGraphicsContext.saveGraphicsState()
+ defer { NSGraphicsContext.restoreGraphicsState() }
+ NSGraphicsContext.current = context
+ NSColor.red.setFill()
+ CGRect(x: 0, y: 0, width: 100, height: 100).fill()
+ view.drawBackground(in: CGRect(x: 40, y: 40, width: 20, height: 20))
+ XCTAssertEqual(try XCTUnwrap(bitmap.colorAt(x: 20, y: 20)).greenComponent, 0, accuracy: 0.01,
+ "Erasing one caret must not paint over neighboring glyphs")
+ XCTAssertGreaterThan(try XCTUnwrap(bitmap.colorAt(x: 50, y: 50)).greenComponent, 0.9)
+ }
+
+ func testTypingKeepsCaretInsidePageBoundsWithStableOrigin() throws {
+ let nodes = (0..<60).map { index in
+ CRDTNode(id: "p\(index)", type: "paragraph", children: [CRDTNode(id: "t\(index)", type: "text", runs: [CRDTRun(insert: String(repeating: "A paragraph that wraps across lines. ", count: 8))])])
+ }
+ let view = DocsTextView(frame: CGRect(x: 0, y: 0, width: 900, height: 800))
+ view.textStorage!.setAttributedString(NativeTextProjection.render(CRDTProjection(children: nodes, canUndo: false, canRedo: false)))
+ view.paged = true
+ view.layout()
+ view.setSelectedRange(NSRange(location: view.string.utf16.count - 1, length: 0))
+ for text in ["\n", "a", "\n", "b"] {
+ view.insertText(text, replacementRange: view.selectedRange())
+ view.layoutManager!.ensureLayout(for: view.textContainer!)
+ let glyph = view.layoutManager!.glyphIndexForCharacter(at: view.selectedRange().location)
+ let line = view.layoutManager!.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
+ XCTAssertEqual(view.textContainerOrigin, .zero)
+ XCTAssertGreaterThanOrEqual(view.bounds.maxY, line.maxY)
+ }
+ }
+
+ private func assertBlockStarts(_ container: DocsPageTextContainer, _ storage: NSTextStorage) {
+ for location in container.blockStarts.keys {
+ var range = NSRange()
+ XCTAssertNotNil(storage.attribute(.docsTopBlock, at: location, effectiveRange: &range))
+ XCTAssertEqual(range.location, location, "A separator must never move into a paragraph")
+ }
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/DocumentRenderReconciliationTests.swift b/native/apple/Tests/DocsKitTests/DocumentRenderReconciliationTests.swift
new file mode 100644
index 0000000..e106250
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocumentRenderReconciliationTests.swift
@@ -0,0 +1,49 @@
+import Foundation
+import XCTest
+#if os(macOS)
+import AppKit
+#endif
+@testable import DocsKit
+
+final class DocumentRenderReconciliationTests: XCTestCase {
+ @MainActor func testAcknowledgedOptimisticTextUpdatesMappingWithoutReplacingCharacters() {
+ #if os(macOS)
+ let storage = NSTextStorage(string: "Hello 😀\n", attributes: [.docsNode: "old", .docsOffset: 0, .font: NSFont.systemFont(ofSize: 12)])
+ let observer = StorageObserver()
+ storage.delegate = observer
+ let next = NSAttributedString(string: storage.string, attributes: [.docsNode: "published", .docsOffset: 7, .font: NSFont.systemFont(ofSize: 12)])
+ DocumentRenderReconciliation.apply(next, to: storage)
+ XCTAssertEqual(storage.string, next.string)
+ XCTAssertEqual(storage.attribute(.docsNode, at: 0, effectiveRange: nil) as? String, "published")
+ XCTAssertEqual(storage.attribute(.docsOffset, at: 0, effectiveRange: nil) as? Int, 7)
+ XCTAssertFalse(observer.editedCharacters)
+ XCTAssertTrue(observer.editedAttributes)
+ #endif
+ }
+ @MainActor func testRemoteReplacementPreservesUnicodeAndAllAttributes() {
+ let storage = NSMutableAttributedString(string: "A😀old Z", attributes: [.docsNode: "old"])
+ let next = NSMutableAttributedString(string: "A😁日本語 Z", attributes: [.docsNode: "new"])
+ next.addAttribute(.docsOffset, value: 12, range: NSRange(location: 3, length: 3))
+ DocumentRenderReconciliation.apply(next, to: storage)
+ XCTAssertTrue(storage.isEqual(to: next))
+ }
+ #if os(macOS)
+ @MainActor func testMacLogicalPaperWidthDoesNotReflowAtNarrowZoomedViewport() {
+ let narrow = DocsPageGeometry(viewportWidth: 350, paged: true)
+ let wide = DocsPageGeometry(viewportWidth: 1200, paged: true)
+ XCTAssertEqual(narrow.textWidth, 468)
+ XCTAssertEqual(wide.textWidth, narrow.textWidth)
+ XCTAssertEqual(narrow.paperWidth, 612)
+ }
+ #endif
+}
+#if os(macOS)
+@MainActor private final class StorageObserver: NSObject, @preconcurrency NSTextStorageDelegate {
+ var editedCharacters = false
+ var editedAttributes = false
+ func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: NSTextStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) {
+ editedCharacters = editedCharacters || editedMask.contains(.editedCharacters)
+ editedAttributes = editedAttributes || editedMask.contains(.editedAttributes)
+ }
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift b/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift
new file mode 100644
index 0000000..a8c9ddf
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocumentSyncIntegrationTests.swift
@@ -0,0 +1,61 @@
+import Foundation
+import RastrilloApple
+import XCTest
+@testable import DocsKit
+
+final class DocumentSyncIntegrationTests: XCTestCase {
+ func testFailedMergeCannotPoisonEditorOrNextMerge() async throws {
+ let replica = CRDTReplica(guid: "merge-isolation")
+ _ = try await replica.open(update: Data())
+ _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")])
+ do {
+ _ = try await replica.mergeUpdates([Data([255]), Data([255])])
+ XCTFail("Malformed updates must fail")
+ } catch { }
+ _ = try await replica.projection()
+ let (first, _) = try await replica.command(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("a")])
+ let (second, projection) = try await replica.command(["op": .string("display_edit"), "at": .number(1), "length": .number(0), "text": .string("b")])
+ let merged = try await replica.mergeUpdates([first, second])
+ XCTAssertFalse(merged.isEmpty)
+ let after = try await replica.projection()
+ XCTAssertEqual(after.children.map(\.plainText), projection.children.map(\.plainText))
+ await replica.close()
+ }
+ @MainActor func testTypingDoesNotAccumulateOneRoundTripPerKeystroke() async throws {
+ guard let origin = ProcessInfo.processInfo.environment["DOCS_SYNC_TEST_ORIGIN"] else {
+ throw XCTSkip("Run native/scripts/test-sync-latency.py for the delayed HTTP fixture")
+ }
+ let client = NativeHTTP(origin: URL(string: origin)!)
+ let model = DocsModel(client: client)
+ await model.open("fixture")
+ XCTAssertNotNil(model.projection)
+ model.didRender(model.projectionGeneration)
+ for _ in 0..<20 {
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(0), "length": .number(0), "text": .string("X")]))
+ while model.hasPendingInput { try await Task.sleep(for: .milliseconds(1)) }
+ model.didRender(model.projectionGeneration)
+ try await Task.sleep(for: .milliseconds(50))
+ }
+ let finishedTyping = ContinuousClock.now
+ let deadline = finishedTyping.advanced(by: .seconds(15))
+ while model.hasUnsavedChanges && ContinuousClock.now < deadline {
+ await model.flush()
+ try await Task.sleep(for: .milliseconds(10))
+ }
+ XCTAssertFalse(model.hasUnsavedChanges)
+ let lag = finishedTyping.duration(to: .now)
+ struct Stats: Decodable { let updates: [Data] }
+ let stats: Stats = try await client.request("/stats")
+ print("SYNC: 20 edits, 250ms/request, uploads=\(stats.updates.count), catch-up after typing=\(lag)")
+ XCTAssertLessThanOrEqual(stats.updates.count, 10, "Unsent edits must share a request")
+ XCTAssertLessThan(lag, .seconds(1), "Typing must not leave a growing serial-request backlog")
+ let (initial, _) = try await client.response("/d/fixture/updates")
+ let peer = CRDTReplica(guid: "sync-fixture")
+ _ = try await peer.open(update: initial)
+ for update in stats.updates { _ = try await peer.apply(update) }
+ let projection = try await peer.projection()
+ XCTAssertEqual(projection.children.map(\.plainText), model.projection?.children.map(\.plainText), "A receiver must get every edit")
+ await peer.close()
+ await model.stop()
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/DocumentToolbarSelectionTests.swift b/native/apple/Tests/DocsKitTests/DocumentToolbarSelectionTests.swift
new file mode 100644
index 0000000..a53aaeb
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocumentToolbarSelectionTests.swift
@@ -0,0 +1,82 @@
+import Foundation
+import RastrilloApple
+import XCTest
+@testable import DocsKit
+
+final class DocumentToolbarSelectionTests: XCTestCase {
+ @MainActor func testTypingKeepsPresentationAvailableWhileCommandsWaitForProjection() async throws {
+ let model = DocsModel(client: NativeHTTP(origin: URL(string: "https://example.invalid")!))
+ model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false)
+ model.projection = CRDTProjection(children: [], canUndo: true, canRedo: false)
+ let content = NSMutableAttributedString(string: "bold\n")
+ content.addAttribute(.docsMarks, value: try JSONEncoder().encode(["strong": JSONValue.object([:])]), range: NSRange(location: 0, length: 4))
+ model.selection = NSRange(location: 4, length: 0)
+ let commands = DocumentCommands(model: model, content: content)
+ let settled = try XCTUnwrap(DocumentToolbarSelection(commands: commands))
+ XCTAssertEqual(settled.marks, ["strong"])
+ XCTAssertTrue(settled.canUndo)
+
+ // Native input advances the caret before the replica publishes its text.
+ XCTAssertTrue(model.enqueue(["op": .string("display_edit"), "at": .number(4), "length": .number(0), "text": .string("!!")]))
+ model.selection = NSRange(location: 6, length: 0)
+ XCTAssertTrue(model.hasPendingInput)
+ XCTAssertTrue(commands.isAvailable, "Transient input must not dim the whole toolbar")
+ XCTAssertFalse(commands.isEnabled)
+ XCTAssertNil(DocumentToolbarSelection(commands: commands), "Do not replace the bold highlight using stale text")
+ XCTAssertFalse(commands.format("em"), "Formatting must still reject an unacknowledged selection")
+ XCTAssertNil(model.typingMarks)
+ await model.discardAll()
+
+ // A new projection still needs the native view's acknowledgement.
+ model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false)
+ model.projection = CRDTProjection(children: [], canUndo: true, canRedo: false)
+ model.projectionGeneration = 2
+ model.selection = NSRange(location: 4, length: 0)
+ XCTAssertTrue(commands.isAvailable)
+ XCTAssertNil(DocumentToolbarSelection(commands: commands))
+ model.didRender(2)
+ XCTAssertEqual(DocumentToolbarSelection(commands: commands), settled)
+ model.selection = NSRange(location: 0, length: 2)
+ XCTAssertTrue(try XCTUnwrap(DocumentToolbarSelection(commands: commands)).hasSelection)
+ }
+
+ @MainActor func testToolbarLabelsFollowHeadingFontSizeAndAlignment() throws {
+ let model = DocsModel(client: NativeHTTP(origin: URL(string: "https://example.invalid")!))
+ model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false)
+ model.projection = CRDTProjection(children: [CRDTNode(id: "heading", type: "heading", attrs: ["level": "2", "align": "center"], children: [CRDTNode(id: "text", type: "text", runs: [CRDTRun(insert: "Title", marks: ["font_serif": .object([:]), "size_24": .object([:])])])])], canUndo: false, canRedo: false)
+ model.selection = NSRange(location: 1, length: 0)
+ let state = try XCTUnwrap(DocumentToolbarSelection(commands: DocumentCommands(model: model, content: NativeTextProjection.render(model.projection!))))
+ XCTAssertEqual(state.style, "heading2")
+ XCTAssertEqual(state.font, "serif")
+ XCTAssertEqual(state.size, 24)
+ XCTAssertEqual(state.alignment, "center")
+ for level in 4...6 {
+ model.projection?.children[0].attrs?["level"] = String(level)
+ let imported = try XCTUnwrap(DocumentToolbarSelection(commands: DocumentCommands(model: model, content: NativeTextProjection.render(model.projection!))))
+ XCTAssertEqual(imported.styleLabel, String(format: docsMacString("Heading %d"), level))
+ }
+ for (mark, expected) in [("size_sm", 10), ("size_lg", 14), ("size_xl", 18)] {
+ model.typingMarks = [mark: .object([:])]
+ let legacy = try XCTUnwrap(DocumentToolbarSelection(commands: DocumentCommands(model: model, content: NativeTextProjection.render(model.projection!))))
+ XCTAssertEqual(legacy.size, expected)
+ }
+ }
+
+ @MainActor func testReadOnlyAndPausedInputRemainDisabled() {
+ let model = DocsModel(client: NativeHTTP(origin: URL(string: "https://example.invalid")!))
+ let commands = DocumentCommands(model: model, content: NSAttributedString(string: ""))
+ model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: false, can_share: false)
+ XCTAssertFalse(commands.isAvailable)
+ XCTAssertFalse(commands.format("strong"))
+ model.detail = DocumentDetail(sqid: "fixture", title: "Fixture", guid: "fixture", can_write: true, can_share: false)
+ model.inputPaused = true
+ XCTAssertFalse(commands.isAvailable)
+ XCTAssertFalse(commands.format("strong"))
+ model.inputPaused = false
+ model.composing = true
+ XCTAssertTrue(commands.isAvailable)
+ XCTAssertFalse(commands.isEnabled)
+ XCTAssertNil(DocumentToolbarSelection(commands: commands))
+ XCTAssertFalse(commands.format("strong"))
+ }
+}
diff --git a/native/apple/Tests/DocsKitTests/DocumentTypographyTests.swift b/native/apple/Tests/DocsKitTests/DocumentTypographyTests.swift
new file mode 100644
index 0000000..cbf9db5
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/DocumentTypographyTests.swift
@@ -0,0 +1,47 @@
+#if os(macOS)
+import AppKit
+import XCTest
+@testable import DocsKit
+
+final class DocumentTypographyTests: XCTestCase {
+ // Synthetic fixture also measured in WebKit at 96 CSS px/in with the same
+ // bundled Liberation fonts and the production [docs-text] CSS rules.
+ @MainActor func testBrowserFixtureLineBreaks() throws {
+ let heading = "A shared document with consistent typography on every screen"
+ let bold = "This is a synthetic layout fixture for the native and browser editors. The same bundled font, page width and paragraph styles must produce the same line breaks, including a long sentence that wraps across several lines."
+ let body = "The quick brown fox jumps over the lazy dog. A small change in font metrics can move the final word onto another line, so this paragraph deliberately includes enough words to exercise wrapping at a fixed document width."
+ func block(_ id: String, _ text: String, heading: Bool = false, strong: Bool = false) -> CRDTNode {
+ CRDTNode(id: id, type: heading ? "heading" : "paragraph", attrs: heading ? ["level": "1"] : nil, children: [CRDTNode(id: id + "t", type: "text", runs: [CRDTRun(insert: text, marks: strong ? ["strong": .object([:])] : nil)])])
+ }
+ let projection = CRDTProjection(children: [block("h", heading, heading: true), block("b", bold, strong: true), block("gap", ""), block("p", body)], canUndo: false, canRedo: false)
+ let storage = NSTextStorage(attributedString: NativeTextProjection.render(projection))
+ let manager = NSLayoutManager()
+ manager.usesFontLeading = false
+ let container = DocsPageTextContainer(size: CGSize(width: 636, height: 100000))
+ container.geometry = DocsPageGeometry(viewportWidth: 636, paged: false)
+ container.lineFragmentPadding = 0
+ storage.addLayoutManager(manager); manager.addTextContainer(container)
+ manager.ensureLayout(for: container)
+ var lines: [String] = []
+ var heights: [CGFloat] = []
+ manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { rect, _, _, range, _ in
+ let chars = manager.characterRange(forGlyphRange: range, actualGlyphRange: nil)
+ let line = (storage.string as NSString).substring(with: chars).trimmingCharacters(in: .whitespacesAndNewlines)
+ if !line.isEmpty { lines.append(line); heights.append(rect.height) }
+ }
+ XCTAssertEqual(heights[2], 16.8, accuracy: 0.01)
+ XCTAssertEqual(heights[3], 16.8, accuracy: 0.01)
+ XCTAssertEqual(lines, Self.browserLines)
+ }
+ private static let browserLines: [String] = [
+ "A shared document with consistent typography on",
+ "every screen",
+ "This is a synthetic layout fixture for the native and browser editors. The same",
+ "bundled font, page width and paragraph styles must produce the same line",
+ "breaks, including a long sentence that wraps across several lines.",
+ "The quick brown fox jumps over the lazy dog. A small change in font metrics can move",
+ "the final word onto another line, so this paragraph deliberately includes enough words to",
+ "exercise wrapping at a fixed document width."
+]
+}
+#endif
diff --git a/native/apple/Tests/DocsKitTests/HomeLoadingTests.swift b/native/apple/Tests/DocsKitTests/HomeLoadingTests.swift
new file mode 100644
index 0000000..3ceb4c3
--- /dev/null
+++ b/native/apple/Tests/DocsKitTests/HomeLoadingTests.swift
@@ -0,0 +1,22 @@
+import Foundation
+import RastrilloApple
+import XCTest
+@testable import DocsKit
+
+final class HomeLoadingTests: XCTestCase {
+ @MainActor func testLoadingSuccessAndFailureAreDistinct() async throws {
+ guard let origin = ProcessInfo.processInfo.environment["HOME_LOADING_TEST_ORIGIN"] else {
+ throw XCTSkip("Run the delayed home-list fixture")
+ }
+ let model = DocsModel(client: NativeHTTP(origin: URL(string: origin)!))
+ XCTAssertEqual(model.listState, .loading)
+ for expected in [1, 0, -1, 1] {
+ let request = Task { await model.load() }
+ try await Task.sleep(for: .milliseconds(25))
+ XCTAssertEqual(model.listState, .loading, "Never classify an in-flight request as empty")
+ await request.value
+ XCTAssertEqual(model.listState, expected == -1 ? .failed : .loaded)
+ if expected >= 0 { XCTAssertEqual(model.documents.count, expected) }
+ }
+ }
+}
diff --git a/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift b/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift
new file mode 100644
index 0000000..e81c94a
--- /dev/null
+++ b/native/apple/Tests/DocsWindowTests/WindowRoutingTests.swift
@@ -0,0 +1,44 @@
+#if os(macOS)
+import Foundation
+import Testing
+import RastrilloApple
+@testable import DocsMac
+
+@MainActor @Test func windowsReuseDocumentsWithinAccountAndOriginOnly() {
+ let windows = DocsWindows()
+ let first = NativeHTTP(origin: URL(string: "https://first.invalid")!)
+ let second = NativeHTTP(origin: URL(string: "https://second.invalid")!)
+ let document: String = "same"
+ let id = windows.reserve(account: "a", document: document, title: "One", client: first)
+ #expect(windows.reserve(account: "a", document: document, title: "Renamed", client: first) == id)
+ #expect(windows.entries.count == 1)
+ #expect(!windows.canSignOut("a"))
+ #expect(windows.reserve(account: "b", document: document, title: "Other account", client: first) != id)
+ #expect(windows.reserve(account: "a", document: document, title: "Other server", client: second) != id)
+ #expect(windows.entries.count == 3)
+ windows.setOpen(id, false)
+ #expect(!windows.canSignOut("a"))
+ for entry in windows.entries where entry.account == "a" { windows.setOpen(entry.id, false) }
+ #expect(windows.canSignOut("a"))
+ windows.updateRecents([(document, "Current title")], account: "a", client: first)
+ #expect(windows.entries.first(where: { $0.id == id })?.title == "Current title")
+ #expect(windows.entries.first(where: { $0.id == id })?.isOpen == false)
+}
+@MainActor @Test func draftWindowsKeepAccountAndIdentityThroughAttachment() {
+ let windows = DocsWindows()
+ let client = NativeHTTP(origin: URL(string: "https://draft.invalid")!)
+ let first = windows.reserveDraft(account: "a", client: client)
+ let second = windows.reserveDraft(account: "a", client: client)
+ #expect(first != second)
+ #expect(!windows.canSignOut("a"))
+ windows.activeAccount = "b"
+ windows.attach(first, document: "created", title: "Renamed")
+ #expect(windows.entries.first(where: { $0.id == first })?.account == "a")
+ #expect(windows.entries.first(where: { $0.id == first })?.isDraft == false)
+ #expect(windows.reserve(account: "a", document: "created", title: "Renamed", client: client) == first)
+ windows.setOpen(second, false)
+ #expect(!windows.entries.contains(where: { $0.id == second }))
+ windows.setOpen(first, false)
+ #expect(windows.canSignOut("a"))
+}
+#endif
diff --git a/native/crdt/examples/caret_fixture.rs b/native/crdt/examples/caret_fixture.rs
new file mode 100644
index 0000000..aeaaad4
--- /dev/null
+++ b/native/crdt/examples/caret_fixture.rs
@@ -0,0 +1,11 @@
+use docs_native_crdt::Editor;
+use serde_json::json;
+fn main() {
+ let mut editor = Editor::new("window-smoke", 17);
+ for index in 0..60 {
+ editor.command(&json!({"op":"insert_element", "at":index, "type":"paragraph"})).unwrap();
+ let block = editor.projection()["children"][index]["id"].as_str().unwrap().to_owned();
+ editor.command(&json!({"op":"insert_text", "node":block, "at":0, "text":format!("Paragraph {}. {}", index + 1, "Synthetic text with enough words to wrap onto several lines in a document window. ".repeat(3))})).unwrap();
+ }
+ std::fs::write(std::env::args().nth(1).expect("output path"), editor.snapshot()).unwrap();
+}
diff --git a/native/crdt/src/lib.rs b/native/crdt/src/lib.rs
index 2d36459..351d83a 100644
--- a/native/crdt/src/lib.rs
+++ b/native/crdt/src/lib.rs
@@ -12,6 +12,7 @@ use serde_json::{json, Value};
use std::{cell::RefCell, collections::HashSet, sync::Arc};
use yrs::{Doc, OffsetKind, Options, ReadTxn, StateVector, Transact, UndoManager, Update};
use yrs::updates::decoder::{Decode, Decoder, DecoderV1};
+use yrs::updates::encoder::Encode;
pub struct Editor {
doc: Doc,
@@ -34,15 +35,7 @@ impl Editor {
pub fn apply(&self, bytes: &[u8]) -> Result<(), &'static str> { self.apply_origin(bytes, false) }
pub fn apply_local(&self, bytes: &[u8]) -> Result<(), &'static str> { self.apply_origin(bytes, true) }
fn apply_origin(&self, bytes: &[u8], local: bool) -> Result<(), &'static str> {
- let mut remaining = bytes;
- let mut updates = Vec::new();
- while !remaining.is_empty() {
- let mut decoder = DecoderV1::from(remaining);
- updates.push(Update::decode(&mut decoder).map_err(|_| "invalid_update")?);
- let trailing = decoder.read_to_end().map_err(|_| "invalid_update")?.len();
- if trailing >= remaining.len() { return Err("invalid_update"); }
- remaining = &remaining[remaining.len() - trailing..];
- }
+ let updates = decode_updates(bytes)?;
let mut txn = self.doc.transact_mut_with(if local { "native-edit" } else { "remote" });
for update in updates { txn.apply_update(update).map_err(|_| "invalid_update")?; }
Ok(())
@@ -122,7 +115,27 @@ pub extern "C" fn docs_editor_output_ptr() -> u32 { OUTPUT.with(|out| out.borrow
#[no_mangle]
pub extern "C" fn docs_editor_output_len() -> u32 { OUTPUT.with(|out| out.borrow().len() as u32) }
+fn decode_updates(mut remaining: &[u8]) -> Result<Vec<Update>, &'static str> {
+ let mut updates = Vec::new();
+ while !remaining.is_empty() {
+ let mut decoder = DecoderV1::from(remaining);
+ updates.push(Update::decode(&mut decoder).map_err(|_| "invalid_update")?);
+ let trailing = decoder.read_to_end().map_err(|_| "invalid_update")?.len();
+ if trailing >= remaining.len() { return Err("invalid_update"); }
+ remaining = &remaining[remaining.len() - trailing..];
+ }
+ Ok(updates)
+}
+
pub fn dispatch(bytes: &[u8]) -> Result<Vec<u8>, &'static str> {
+ // Merge pending writes without constructing a document: pending structs may
+ // depend on state already held by the server. Snapshotting an empty document
+ // would silently lose those structs and deletes.
+ if bytes.first() == Some(&253) {
+ let updates = decode_updates(&bytes[1..])?;
+ if updates.is_empty() { return Err("invalid_update"); }
+ return Ok(Update::merge_updates(updates).encode_v1());
+ }
// Binary envelope avoids expanding an 8MiB log into JSON byte numbers.
if matches!(bytes.first(), Some(254 | 255)) {
return EDITOR.with(|cell| {
diff --git a/native/crdt/tests/replica.rs b/native/crdt/tests/replica.rs
index f371073..4256d08 100644
--- a/native/crdt/tests/replica.rs
+++ b/native/crdt/tests/replica.rs
@@ -278,3 +278,27 @@ fn input_rules_transform_and_backspace_restore_typed_prefix() {
assert_eq!(plain(&editor.projection()), format!("{prefix} "));
}
}
+
+#[test]
+fn merged_pending_updates_preserve_dependencies_deletes_and_duplicate_delivery() {
+ use yrs::updates::decoder::{Decode, Decoder, DecoderV1};
+ use yrs::Update;
+ let mut writer = Editor::new("batch", 201);
+ let (_, node) = paragraph(&mut writer, "original");
+ let initial = writer.snapshot();
+ let mut bytes = vec![253];
+ bytes.extend(writer.command(&json!({"op":"replace_text","node":node,"at":8,"length":0,"text":" added"})).unwrap());
+ bytes.extend(writer.command(&json!({"op":"replace_text","node":node,"at":0,"length":3,"text":"new"})).unwrap());
+ bytes.extend(writer.command(&json!({"op":"format","node":node,"at":0,"length":3,"marks":{"strong":{}}})).unwrap());
+ let merged = docs_native_crdt::dispatch(&bytes).unwrap();
+ // A POST must contain exactly one Yjs v1 update, not concatenated messages.
+ let mut decoder = DecoderV1::from(merged.as_slice());
+ Update::decode(&mut decoder).unwrap();
+ assert!(decoder.read_to_end().unwrap().is_empty());
+ let receiver = Editor::new("batch", 202);
+ receiver.apply(&initial).unwrap();
+ receiver.apply(&merged).unwrap();
+ receiver.apply(&merged).unwrap();
+ assert_eq!(receiver.projection()["children"], writer.projection()["children"]);
+ assert!(docs_native_crdt::dispatch(&[253, 255]).is_err());
+}
diff --git a/native/ios/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/native/ios/Assets.xcassets/AppIcon.appiconset/AppIcon.png
index b85bf23..8d1d92c 100644
Binary files a/native/ios/Assets.xcassets/AppIcon.appiconset/AppIcon.png and b/native/ios/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ
diff --git a/native/ios/Info.plist b/native/ios/Info.plist
new file mode 100644
index 0000000..bdaf0f0
--- /dev/null
+++ b/native/ios/Info.plist
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>$(PRODUCT_NAME)</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleURLTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleTypeRole</key>
+ <string>Editor</string>
+ <key>CFBundleURLName</key>
+ <string>works.oficina.docs.signin</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>works.oficina.docs</string>
+ </array>
+ </dict>
+ </array>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+</dict>
+</plist>
diff --git a/native/ios/project.yml b/native/ios/project.yml
index d46d360..9bd5386 100644
--- a/native/ios/project.yml
+++ b/native/ios/project.yml
@@ -8,55 +8,74 @@ packages:
path: ../apple
RastrilloNative:
url: https://amadan.net/rastrillo/native
- revision: a49307c29cf36dff2cf423c3f98b38269ce9a553
+ revision: 229525909e1d6ac3b6a353d1c4d022798b0e9a24
settings:
base:
SWIFT_VERSION: '6.0'
CODE_SIGN_STYLE: Automatic
- MARKETING_VERSION: '0.1.0'
+ MARKETING_VERSION: 0.1.0
CURRENT_PROJECT_VERSION: '1'
targets:
DocsPhone:
type: application
platform: iOS
- sources: [../apple/Sources/DocsApp, Assets.xcassets]
+ sources:
+ - ../apple/Sources/DocsApp
+ - Assets.xcassets
+ - path: ../LICENSE.lucide
+ buildPhase: resources
+ - path: ../PrivacyInfo.xcprivacy
+ buildPhase: resources
dependencies:
- - package: DocsNative
- product: DocsKit
- - package: RastrilloNative
- product: RastrilloApple
+ - package: DocsNative
+ product: DocsKit
+ - package: RastrilloNative
+ product: RastrilloApple
settings:
base:
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
- PRODUCT_BUNDLE_IDENTIFIER: net.amadan.oficina.docs.ios
- TARGETED_DEVICE_FAMILY: '1,2'
- GENERATE_INFOPLIST_FILE: YES
+ PROVISIONING_PROFILE_SPECIFIER: $(OFICINA_PROVISIONING_PROFILE)
+ PRODUCT_BUNDLE_IDENTIFIER: works.oficina.docs
+ TARGETED_DEVICE_FAMILY: 1,2
+ GENERATE_INFOPLIST_FILE: true
INFOPLIST_KEY_CFBundleDisplayName: Oficina Docs
- INFOPLIST_KEY_UILaunchScreen_Generation: YES
+ INFOPLIST_KEY_UILaunchScreen_Generation: true
+ info:
+ path: Info.plist
+ properties:
+ CFBundleURLTypes:
+ - CFBundleURLName: works.oficina.docs.signin
+ CFBundleURLSchemes:
+ - works.oficina.docs
+ CFBundleTypeRole: Editor
+ CFBundleShortVersionString: $(MARKETING_VERSION)
+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
DocsReviewPhone:
type: application
platform: iOS
- sources: [Review]
+ sources:
+ - Review
dependencies:
- - package: DocsNative
- product: DocsKit
- - package: RastrilloNative
- product: RastrilloApple
+ - package: DocsNative
+ product: DocsKit
+ - package: RastrilloNative
+ product: RastrilloApple
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: net.amadan.oficina.docs.review
- TARGETED_DEVICE_FAMILY: '1,2'
- GENERATE_INFOPLIST_FILE: YES
- INFOPLIST_KEY_UILaunchScreen_Generation: YES
+ TARGETED_DEVICE_FAMILY: 1,2
+ GENERATE_INFOPLIST_FILE: true
+ INFOPLIST_KEY_UILaunchScreen_Generation: true
DocsPhoneUITests:
type: bundle.ui-testing
platform: iOS
- sources: [UITests]
+ sources:
+ - UITests
dependencies:
- - target: DocsReviewPhone
+ - target: DocsReviewPhone
settings:
base:
- GENERATE_INFOPLIST_FILE: YES
+ GENERATE_INFOPLIST_FILE: true
TEST_TARGET_NAME: DocsReviewPhone
schemes:
DocsReviewPhone:
@@ -64,6 +83,7 @@ schemes:
targets:
DocsReviewPhone: all
test:
- targets: [DocsPhoneUITests]
+ targets:
+ - DocsPhoneUITests
environmentVariables:
- DOCS_NATIVE_REVIEW_INPUT: "$(DOCS_NATIVE_REVIEW_INPUT)"
+ DOCS_NATIVE_REVIEW_INPUT: $(DOCS_NATIVE_REVIEW_INPUT)
diff --git a/native/mac-updates.json b/native/mac-updates.json
new file mode 100644
index 0000000..ea18077
--- /dev/null
+++ b/native/mac-updates.json
@@ -0,0 +1,6 @@
+{
+ "bundle_id": "net.amadan.oficina.docs",
+ "feed_url": "https://raw.amadan.net/oficina/native-releases/main/docs/appcast.xml",
+ "public_ed_key": "/FxO7cZnM7P5c9ZrUPUJvpCnR65sNmrzte+I5vHarE8=",
+ "keychain_account": "oficina"
+}
diff --git a/native/macos/AppIcon.icns b/native/macos/AppIcon.icns
new file mode 100644
index 0000000..da1a204
Binary files /dev/null and b/native/macos/AppIcon.icns differ
diff --git a/native/macos/AppStore.entitlements b/native/macos/AppStore.entitlements
new file mode 100644
index 0000000..a046386
--- /dev/null
+++ b/native/macos/AppStore.entitlements
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.files.user-selected.read-write</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
+</dict>
+</plist>
diff --git a/native/macos/Info.plist b/native/macos/Info.plist
new file mode 100644
index 0000000..b787815
--- /dev/null
+++ b/native/macos/Info.plist
@@ -0,0 +1,43 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>CFBundleDevelopmentRegion</key>
+ <string>$(DEVELOPMENT_LANGUAGE)</string>
+ <key>CFBundleDisplayName</key>
+ <string>Oficina Docs</string>
+ <key>CFBundleExecutable</key>
+ <string>$(EXECUTABLE_NAME)</string>
+ <key>CFBundleIconFile</key>
+ <string>AppIcon</string>
+ <key>CFBundleIdentifier</key>
+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
+ <key>CFBundleInfoDictionaryVersion</key>
+ <string>6.0</string>
+ <key>CFBundleName</key>
+ <string>Oficina Docs</string>
+ <key>CFBundlePackageType</key>
+ <string>APPL</string>
+ <key>CFBundleShortVersionString</key>
+ <string>$(MARKETING_VERSION)</string>
+ <key>CFBundleURLTypes</key>
+ <array>
+ <dict>
+ <key>CFBundleTypeRole</key>
+ <string>Editor</string>
+ <key>CFBundleURLName</key>
+ <string>works.oficina.docs.signin</string>
+ <key>CFBundleURLSchemes</key>
+ <array>
+ <string>works.oficina.docs</string>
+ </array>
+ </dict>
+ </array>
+ <key>CFBundleVersion</key>
+ <string>$(CURRENT_PROJECT_VERSION)</string>
+ <key>LSApplicationCategoryType</key>
+ <string>public.app-category.productivity</string>
+ <key>NSHighResolutionCapable</key>
+ <true/>
+</dict>
+</plist>
diff --git a/native/macos/project.yml b/native/macos/project.yml
new file mode 100644
index 0000000..c2e6d94
--- /dev/null
+++ b/native/macos/project.yml
@@ -0,0 +1,54 @@
+name: DocsMacStore
+options:
+ deploymentTarget:
+ macOS: '26.0'
+packages:
+ DocsNative:
+ path: ../apple
+ RastrilloNative:
+ url: https://amadan.net/rastrillo/native
+ revision: 229525909e1d6ac3b6a353d1c4d022798b0e9a24
+settings:
+ base:
+ SWIFT_VERSION: '6.0'
+ CODE_SIGN_STYLE: Automatic
+ MARKETING_VERSION: 0.1.0
+ CURRENT_PROJECT_VERSION: '3'
+ ENABLE_HARDENED_RUNTIME: true
+targets:
+ DocsMacStore:
+ type: application
+ platform: macOS
+ sources:
+ - ../apple/Sources/DocsApp
+ - path: AppIcon.icns
+ buildPhase: resources
+ - path: ../LICENSE.lucide
+ buildPhase: resources
+ - path: ../PrivacyInfo.xcprivacy
+ buildPhase: resources
+ dependencies:
+ - package: DocsNative
+ product: DocsKit
+ - package: RastrilloNative
+ product: RastrilloApple
+ info:
+ path: Info.plist
+ properties:
+ CFBundleDisplayName: Oficina Docs
+ CFBundleName: Oficina Docs
+ CFBundleShortVersionString: $(MARKETING_VERSION)
+ CFBundleVersion: $(CURRENT_PROJECT_VERSION)
+ CFBundleIconFile: AppIcon
+ LSApplicationCategoryType: public.app-category.productivity
+ NSHighResolutionCapable: true
+ CFBundleURLTypes:
+ - CFBundleURLName: works.oficina.docs.signin
+ CFBundleURLSchemes:
+ - works.oficina.docs
+ CFBundleTypeRole: Editor
+ settings:
+ base:
+ PROVISIONING_PROFILE_SPECIFIER: $(OFICINA_PROVISIONING_PROFILE)
+ PRODUCT_BUNDLE_IDENTIFIER: works.oficina.docs
+ CODE_SIGN_ENTITLEMENTS: AppStore.entitlements
diff --git a/native/scripts/build-mac.sh b/native/scripts/build-mac.sh
index 0deb596..5ab8cd4 100755
--- a/native/scripts/build-mac.sh
+++ b/native/scripts/build-mac.sh
@@ -3,4 +3,5 @@ set -eu
cd "$(dirname "$0")/.."
if [ "${OFICINA_SKIP_PREPARE:-0}" != 1 ]; then scripts/build-crdt.sh; fi
swift package --package-path apple resolve
-python3 apple/.build/checkouts/native/tools/bundle-mac.py . Docs
+shared_native="${OFICINA_NATIVE_PACKAGE_PATH:-apple/.build/checkouts/native}"
+python3 "$shared_native/tools/bundle-mac.py" . Docs "$@"
diff --git a/native/scripts/test-document-drafts.py b/native/scripts/test-document-drafts.py
new file mode 100644
index 0000000..bb25747
--- /dev/null
+++ b/native/scripts/test-document-drafts.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""Exercise editable local drafts while creation is slow and its first reply is lost."""
+import base64
+import http.server
+import json
+import os
+from pathlib import Path
+import socket
+import subprocess
+import threading
+import time
+import urllib.parse
+root = Path(__file__).resolve().parents[2]
+class Handler(http.server.BaseHTTPRequestHandler):
+ documents = {}
+ updates = []
+ creations = 0
+ title = ""
+ renames = 0
+ metadata = 0
+ streams = 0
+ def reply(self, status, data=b"", **headers):
+ self.send_response(status)
+ self.send_header("Content-Length", str(len(data)))
+ for key, value in headers.items(): self.send_header(key, value)
+ self.end_headers()
+ try: self.wfile.write(data)
+ except (BrokenPipeError, ConnectionResetError): pass
+ def do_POST(self):
+ cls = type(self)
+ data = self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ form = urllib.parse.parse_qs(data.decode()) if self.path == "/documents" or self.path.endswith("/title") else {}
+ if self.path == "/documents":
+ cls.creations += 1
+ number = cls.creations
+ token = form["creation_token"][0]
+ cls.documents.setdefault(token, str(len(cls.documents) + 1))
+ time.sleep(1)
+ if number == 1:
+ self.connection.shutdown(socket.SHUT_RDWR)
+ self.connection.close()
+ return
+ self.reply(201, json.dumps(dict(sqid=cls.documents[token], title="Untitled document")).encode())
+ elif self.path.endswith("/title"):
+ cls.renames += 1
+ time.sleep(0.3)
+ if cls.renames == 1:
+ self.reply(503)
+ else:
+ cls.title = form["title"][0]
+ self.reply(204)
+ else:
+ cls.updates.append(base64.b64encode(data).decode())
+ self.reply(204)
+ def do_GET(self):
+ cls = type(self)
+ if self.path == "/stats":
+ self.reply(200, json.dumps(dict(documents=len(cls.documents), updates=cls.updates, title=cls.title, creations=cls.creations, metadata=cls.metadata)).encode())
+ elif self.path.endswith("/stream"):
+ cls.streams += 1
+ if cls.streams == 1:
+ self.reply(503)
+ return
+ self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.end_headers()
+ self.wfile.write(b"data: 0\n\n"); self.wfile.flush(); time.sleep(5)
+ elif "/updates" in self.path:
+ self.reply(200, **{"Docs-Seq": "0"})
+ else:
+ cls.metadata += 1
+ if cls.metadata == 2: time.sleep(0.9) # Old title arrives after rename acknowledgement.
+ self.reply(200, json.dumps(dict(sqid=self.path.split("/")[-1], title="Untitled document", guid="server-guid", can_write=True, can_share=True)).encode())
+ def log_message(self, *_): pass
+with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ result = subprocess.run(["swift", "test", "--package-path", str(root / "native/apple"), "--filter", "DocumentDraftTests"], env=dict(os.environ, DOCS_DRAFT_TEST_ORIGIN=f"http://127.0.0.1:{server.server_port}"), timeout=180)
+ server.shutdown()
+ raise SystemExit(result.returncode)
diff --git a/native/scripts/test-document-window.py b/native/scripts/test-document-window.py
new file mode 100644
index 0000000..1c586c3
--- /dev/null
+++ b/native/scripts/test-document-window.py
@@ -0,0 +1,63 @@
+#!/usr/bin/env python3
+"""Exercise the real SwiftUI window on a logged-in Mac using only a local fixture."""
+import http.server
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import threading
+import time
+
+root = Path(__file__).resolve().parents[2]
+fixture_name = os.environ.get("DOCS_SMOKE_FIXTURE", "letter")
+assert fixture_name in {"letter", "documentation"}
+fixture = Path(os.environ["DOCS_SMOKE_UPDATE"]).read_bytes() if "DOCS_SMOKE_UPDATE" in os.environ else (root / "internal/docs/seeddata" / (fixture_name + ".update.bin")).read_bytes()
+
+draft = os.environ.get("DOCS_SMOKE_DRAFT") == "1"
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path.endswith("/stream"):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.end_headers()
+ self.wfile.write(b"data: 0\n\n")
+ self.wfile.flush()
+ time.sleep(20)
+ return
+ if "/updates" in self.path:
+ data = b"" if draft else fixture
+ else:
+ time.sleep(0.3) # Include loading -> editor layout transition.
+ data = json.dumps(dict(sqid="fixture", title="Window smoke fixture", guid="window-smoke",
+ can_write=True, can_share=False)).encode()
+ self.send_response(200)
+ self.send_header("Docs-Seq", "0")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_POST(self):
+ self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ if self.path == "/documents":
+ time.sleep(2)
+ data = json.dumps(dict(sqid="fixture", title="Window smoke fixture")).encode()
+ self.send_response(201); self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
+ else:
+ self.send_response(204)
+ self.end_headers()
+
+ def log_message(self, *_):
+ pass
+
+with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ env = dict(os.environ, DOCS_SMOKE_ORIGIN=f"http://127.0.0.1:{server.server_port}")
+ result = subprocess.run(["swift", "run", "--package-path", str(root / "native/smoke/document-window")],
+ env=env, timeout=180, stdout=subprocess.PIPE, text=True)
+ print(result.stdout, end="")
+ server.shutdown()
+ if result.returncode == 0 and "PASS: document loads," not in result.stdout:
+ sys.exit("Smoke process exited before completing its assertions")
+ raise SystemExit(result.returncode)
diff --git a/native/scripts/test-home-loading.py b/native/scripts/test-home-loading.py
new file mode 100644
index 0000000..1efe5aa
--- /dev/null
+++ b/native/scripts/test-home-loading.py
@@ -0,0 +1,36 @@
+#!/usr/bin/env python3
+"""Verify loading/populated/empty/failure/retry against delayed HTTP responses."""
+import http.server
+import json
+import os
+from pathlib import Path
+import subprocess
+import threading
+import time
+
+APP = "Docs"
+root = Path(__file__).resolve().parents[2]
+class Handler(http.server.BaseHTTPRequestHandler):
+ count = 0
+ def do_GET(self):
+ type(self).count += 1
+ number = type(self).count
+ time.sleep(0.2)
+ item = ({"sqid": "fixture", "title": "Fixture"} if APP == "Docs" else
+ {"ID": 1, "Title": "Fixture", "TabID": 1, "TabName": "Sheet1"})
+ items = [] if number == 2 else [item]
+ payload = {"documents": items, "can_create": True} if APP == "Docs" else {"Sheets": items}
+ data = json.dumps(payload).encode()
+ self.send_response(503 if number == 3 else 200)
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+ def log_message(self, *_):
+ pass
+with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ result = subprocess.run(["swift", "test", "--package-path", str(root / "native/apple"),
+ "--filter", "HomeLoadingTests"],
+ env=dict(os.environ, HOME_LOADING_TEST_ORIGIN=f"http://127.0.0.1:{server.server_port}"), timeout=180)
+ server.shutdown()
+ raise SystemExit(result.returncode)
diff --git a/native/scripts/test-sync-latency.py b/native/scripts/test-sync-latency.py
new file mode 100644
index 0000000..ed4ae2a
--- /dev/null
+++ b/native/scripts/test-sync-latency.py
@@ -0,0 +1,61 @@
+#!/usr/bin/env python3
+"""Measure native upload backlog against a delayed loopback server with fixture data."""
+import base64
+import http.server
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import threading
+import time
+
+root = Path(__file__).resolve().parents[2]
+fixture = (root / "internal/docs/seeddata/letter.update.bin").read_bytes()
+updates = []
+lock = threading.Lock()
+fail_once = "--fail-once" in sys.argv
+
+class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path.endswith("/stream"):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.end_headers()
+ self.wfile.write(b"data: 0\n\n")
+ self.wfile.flush()
+ time.sleep(30)
+ return
+ if self.path == "/stats":
+ with lock:
+ data = json.dumps(dict(updates=updates)).encode()
+ elif "/updates" in self.path:
+ data = fixture
+ else:
+ data = json.dumps(dict(sqid="fixture", title="Sync fixture", guid="sync-fixture",
+ can_write=True, can_share=False)).encode()
+ self.send_response(200)
+ self.send_header("Docs-Seq", "0")
+ self.send_header("Content-Length", str(len(data)))
+ self.end_headers()
+ self.wfile.write(data)
+
+ def do_POST(self):
+ body = self.rfile.read(int(self.headers.get("Content-Length", "0")))
+ # Deterministic request latency, not an artificial client debounce.
+ time.sleep(0.25)
+ with lock:
+ updates.append(base64.b64encode(body).decode())
+ self.send_response(503 if fail_once and len(updates) == 1 else 204)
+ self.end_headers()
+
+ def log_message(self, *_):
+ pass
+
+with http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ env = dict(os.environ, DOCS_SYNC_TEST_ORIGIN=f"http://127.0.0.1:{server.server_port}")
+ result = subprocess.run(["swift", "test", "--package-path", str(root / "native/apple"),
+ "--filter", "DocumentSyncIntegrationTests"], env=env, timeout=240)
+ server.shutdown()
+ raise SystemExit(result.returncode)
diff --git a/native/smoke/document-window/Package.resolved b/native/smoke/document-window/Package.resolved
new file mode 100644
index 0000000..97c1f2e
--- /dev/null
+++ b/native/smoke/document-window/Package.resolved
@@ -0,0 +1,23 @@
+{
+ "originHash" : "b431b6e11c703561af9cea92a342e39b35786f2616f8b5e3d4ab22ca3a406a4f",
+ "pins" : [
+ {
+ "identity" : "native",
+ "kind" : "remoteSourceControl",
+ "location" : "https://amadan.net/rastrillo/native",
+ "state" : {
+ "revision" : "229525909e1d6ac3b6a353d1c4d022798b0e9a24"
+ }
+ },
+ {
+ "identity" : "sparkle",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/sparkle-project/Sparkle",
+ "state" : {
+ "revision" : "ac2def288cbff5cfc7df3ffef6abdf45b72bcb0a",
+ "version" : "2.9.6"
+ }
+ }
+ ],
+ "version" : 3
+}
diff --git a/native/smoke/document-window/Package.swift b/native/smoke/document-window/Package.swift
new file mode 100644
index 0000000..61a51d6
--- /dev/null
+++ b/native/smoke/document-window/Package.swift
@@ -0,0 +1,7 @@
+// swift-tools-version: 6.2
+import PackageDescription
+let package = Package(name: "DocumentWindowSmoke", platforms: [.macOS(.v26)],
+ dependencies: [.package(path: "../../apple")],
+ targets: [.executableTarget(name: "DocumentWindowSmoke", dependencies: [
+ .product(name: "DocsKit", package: "apple")
+ ], path: "Sources")])
diff --git a/native/smoke/document-window/README.md b/native/smoke/document-window/README.md
new file mode 100644
index 0000000..112687c
--- /dev/null
+++ b/native/smoke/document-window/README.md
@@ -0,0 +1,41 @@
+# Document window smoke test
+
+Run `python3 native/scripts/test-document-window.py` from a logged-in macOS
+session. It opens a temporary app window and needs permission to become active.
+No account, production service, or user document is used: a loopback HTTP server
+serves the repository's synthetic letter seed.
+
+The test exercises the public DocsWorkspace in a SwiftUI document scene. It waits
+for the editor to load, opens/closes the inspector eight times through the native
+menu, checks the editor gains/loses panel space, resizes the window, and verifies
+that the same text view retains its content and selection.
+
+Regression: Docs 0.1.1 (3) could crash opening its first document on macOS 27.
+Restoring the `.inspector` container reproduces SIGTRAP with AppKit's “more Update
+Constraints in Window passes than there are views” exception. The docked settings
+panel avoids that container. The negative and fixed scene runs were verified on
+macOS 27 build 26A5388g; the user report was build 26A428.
+
+The typing regression now sends native key events and checks the actual
+NSTextInsertionIndicator against glyph geometry and document bounds, including
+repeated Enter presses. To exercise multiple pages (the short seeds do not):
+
+```sh
+cargo run --manifest-path native/crdt/Cargo.toml --example caret_fixture -- /tmp/docs-caret.bin
+DOCS_SMOKE_UPDATE=/tmp/docs-caret.bin python3 native/scripts/test-document-window.py
+```
+
+The generated fixture has 60 independent paragraphs. Optional
+`DOCS_SMOKE_SCREENSHOT=/tmp/docs-caret.png` captures the window after typing.
+The same executable imports the real window command source through symlinks and
+verifies Accounts/Sign out are in the app menu and Accounts reopens closed Home.
+
+To exercise immediate untitled creation, use `DOCS_SMOKE_DRAFT=1 python3 native/scripts/test-document-window.py`.
+The server deliberately waits two seconds. The test types before acknowledgement,
+asserts the same text view and content survive attachment, and saves an actively
+edited header title without pressing Return. Both modes then test Enter/caret
+geometry, inspector resizing, and native account menus.
+
+`python3 native/scripts/test-document-drafts.py` covers lost creation replies,
+retry identity, pending edits and deletes across different document GUIDs,
+rename during reconnect, oversized title retention, close-save, and discard.
diff --git a/native/smoke/document-window/Sources/DocsWindowCommands.swift b/native/smoke/document-window/Sources/DocsWindowCommands.swift
new file mode 120000
index 0000000..7f0dc8a
--- /dev/null
+++ b/native/smoke/document-window/Sources/DocsWindowCommands.swift
@@ -0,0 +1 @@
+../../../apple/Sources/DocsApp/DocsWindowCommands.swift
\ No newline at end of file
diff --git a/native/smoke/document-window/Sources/DocsWindows.swift b/native/smoke/document-window/Sources/DocsWindows.swift
new file mode 120000
index 0000000..e67e0f0
--- /dev/null
+++ b/native/smoke/document-window/Sources/DocsWindows.swift
@@ -0,0 +1 @@
+../../../apple/Sources/DocsApp/DocsWindows.swift
\ No newline at end of file
diff --git a/native/smoke/document-window/Sources/Smoke.swift b/native/smoke/document-window/Sources/Smoke.swift
new file mode 100644
index 0000000..15d3cda
--- /dev/null
+++ b/native/smoke/document-window/Sources/Smoke.swift
@@ -0,0 +1,192 @@
+import AppKit
+import DocsKit
+import RastrilloApple
+import SwiftUI
+
+@MainActor private enum SmokeRun { static var started = false }
+
+@main struct DocumentWindowSmoke: App {
+ @State private var windows = DocsWindows()
+ var body: some Scene {
+ Window("Smoke Home", id: "home") { Launcher(windows: windows) }
+ WindowGroup("Smoke Document", id: "document", for: String.self) { _ in
+ DocsWorkspace(client: NativeHTTP(origin: URL(string: ProcessInfo.processInfo.environment["DOCS_SMOKE_ORIGIN"]!)!),
+ signOut: {}, documentID: "fixture", newDocument: ProcessInfo.processInfo.environment["DOCS_SMOKE_DRAFT"] == "1")
+ }.defaultSize(width: 1120, height: 820)
+ .restorationBehavior(.disabled)
+ .commands { DocsEditorCommands(); DocsWindowCommands(windows: windows) }
+ }
+}
+
+private struct Launcher: View {
+ let windows: DocsWindows
+ @Environment(\.openWindow) private var openWindow
+ var body: some View {
+ Text("Synthetic document window smoke test").frame(width: 400, height: 200)
+ .task {
+ guard !SmokeRun.started else { return }
+ SmokeRun.started = true
+ NSApp.setActivationPolicy(.regular)
+ openWindow(id: "document", value: "fixture")
+ if ProcessInfo.processInfo.environment["DOCS_SMOKE_DRAFT"] == "1" {
+ let start = ContinuousClock.now
+ var draftEditor: NSTextView?
+ var draftWindow: NSWindow?
+ for _ in 0..<20 {
+ if let window = NSApp.windows.first(where: { $0.title == docsMacString("Untitled document") }), let editor = window.contentView.flatMap(findEditor) {
+ draftWindow = window; draftEditor = editor; break
+ }
+ try? await Task.sleep(for: .milliseconds(50))
+ }
+ guard let window = draftWindow, let editor = draftEditor else { fatalError("Local editor waited for server creation") }
+ precondition(start.duration(to: .now) < .seconds(1))
+ NSApp.activate(ignoringOtherApps: true)
+ window.makeKeyAndOrderFront(nil); window.makeFirstResponder(editor)
+ editor.insertText("Instant draft", replacementRange: NSRange(location: 0, length: 0))
+ for _ in 0..<80 {
+ if window.title == "Window smoke fixture" { break }
+ try? await Task.sleep(for: .milliseconds(50))
+ }
+ precondition(window.title == "Window smoke fixture")
+ precondition(window.contentView.flatMap(findEditor) === editor, "Server attachment replaced the editor")
+ precondition(editor.string.contains("Instant draft"), "Creation lost locally typed text")
+ print("PASS: draft editor appears before delayed creation and keeps its text view and typing")
+ await exercise(window, editor: editor)
+ return
+ }
+ for _ in 0..<100 {
+ if let window = NSApp.windows.first(where: { $0.title == "Window smoke fixture" }),
+ let editor = window.contentView.flatMap(findEditor), !editor.string.isEmpty {
+ await exercise(window, editor: editor)
+ return
+ }
+ try? await Task.sleep(for: .milliseconds(100))
+ }
+ fatalError("Document editor did not load")
+ }
+ }
+ @MainActor private func findEditor(_ view: NSView) -> NSTextView? {
+ if let text = view as? NSTextView, text.accessibilityIdentifier() == "docs.editor" { return text }
+ return view.subviews.lazy.compactMap(findEditor).first
+ }
+ @MainActor private func menuItem(_ title: String, in menu: NSMenu) -> NSMenuItem? {
+ for item in menu.items {
+ if item.title == title { return item }
+ if let submenu = item.submenu, let match = menuItem(title, in: submenu) { return match }
+ }
+ return nil
+ }
+ @MainActor private func exercise(_ window: NSWindow, editor: NSTextView) async {
+ NSApp.activate(ignoringOtherApps: true)
+ window.makeKeyAndOrderFront(nil)
+ window.makeFirstResponder(editor)
+ editor.setSelectedRange(NSRange(location: 1, length: 2))
+ try? await Task.sleep(for: .milliseconds(500))
+ let original = editor.string
+ for step in 0..<8 {
+ try? await Task.sleep(for: .milliseconds(200))
+ guard let menu = NSApp.mainMenu, let initial = menuItem(docsMacString("Document inspector"), in: menu), let submenu = initial.menu else {
+ fatalError("Document inspector command unavailable")
+ }
+ submenu.delegate?.menuNeedsUpdate?(submenu)
+ submenu.update()
+ guard let item = menuItem(docsMacString("Document inspector"), in: menu), item.isEnabled else {
+ fatalError("Inspector command disabled in document window")
+ }
+ let beforeWidth = editor.enclosingScrollView!.frame.width
+ item.menu?.performActionForItem(at: item.menu!.index(of: item))
+ try? await Task.sleep(for: .milliseconds(200))
+ precondition(abs(editor.enclosingScrollView!.frame.width - beforeWidth) > 200, "Inspector did not change editor space")
+ window.setContentSize(NSSize(width: step.isMultiple(of: 2) ? 900 : 1200, height: 760))
+ try? await Task.sleep(for: .milliseconds(200))
+ window.contentView?.layoutSubtreeIfNeeded()
+ precondition(window.contentView.flatMap(findEditor) === editor, "Inspector recreated editor")
+ precondition(editor.string == original && editor.selectedRange() == NSRange(location: 1, length: 2), "Panel lost content or selection")
+ }
+ // Save while the title field is still active, without submitting Return.
+ if let menu = NSApp.mainMenu, let rename = menuItem("Rename document", in: menu) {
+ rename.menu?.delegate?.menuNeedsUpdate?(rename.menu!)
+ rename.menu?.update()
+ guard let currentRename = menuItem("Rename document", in: menu), currentRename.isEnabled else { fatalError("Rename disabled in writable document") }
+ currentRename.menu?.performActionForItem(at: currentRename.menu!.index(of: currentRename))
+ try? await Task.sleep(for: .milliseconds(200))
+ func findTitle(_ view: NSView) -> NSTextField? {
+ if let field = view as? NSTextField, field.isEditable { return field }
+ return view.subviews.lazy.compactMap(findTitle).first
+ }
+ guard let root = window.contentView?.superview, let field = findTitle(root) else { fatalError("Editable header title missing") }
+ field.selectText(nil)
+ guard let input = field.currentEditor() as? NSTextView else { fatalError("Title has no field editor") }
+ input.selectAll(nil); input.insertText("Renamed from header", replacementRange: input.selectedRange())
+ try? await Task.sleep(for: .milliseconds(200))
+ guard let save = menuItem(docsMacString("Save"), in: menu) else { fatalError("Save unavailable") }
+ save.menu?.performActionForItem(at: save.menu!.index(of: save))
+ try? await Task.sleep(for: .milliseconds(300))
+ precondition(window.title == "Renamed from header", "Save lost the active title input")
+ print("PASS: Save commits active header title without Return")
+ } else { fatalError("Rename command missing") }
+ window.makeFirstResponder(editor)
+ editor.setSelectedRange(NSRange(location: editor.string.utf16.count - 1, length: 0))
+ NSApp.activate(ignoringOtherApps: true)
+ window.makeKeyAndOrderFront(nil)
+ window.makeFirstResponder(editor)
+ editor.scrollRangeToVisible(editor.selectedRange())
+ try? await Task.sleep(for: .milliseconds(100))
+ func indicators(_ view: NSView) -> [NSView] {
+ (view is NSTextInsertionIndicator ? [view] : []) + view.subviews.flatMap(indicators)
+ }
+ func record(_ phase: String) {
+ let manager = editor.layoutManager!
+ manager.ensureLayout(for: editor.textContainer!)
+ let glyph = manager.glyphIndexForCharacter(at: min(editor.selectedRange().location, editor.string.utf16.count - 1))
+ let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
+ let rect = editor.firstRect(forCharacterRange: editor.selectedRange(), actualRange: nil)
+ precondition(editor.textContainerOrigin == .zero, "Native caret origin drifted")
+ precondition(rect.height > 0, "Caret clipped outside editor bounds")
+ precondition(editor.bounds.maxY >= line.maxY, "Editor shrank below current line")
+ let visible = indicators(window.contentView!).filter { !$0.isHidden }
+ precondition(visible.count == 1, "Expected exactly one visible native insertion indicator; count=\(visible.count), phase=\(phase), editable=\(editor.isEditable), attached=\(editor.window === window), key=\(window.isKeyWindow), responder=\(String(describing: window.firstResponder))")
+ for indicator in visible {
+ let actual = indicator.convert(indicator.bounds, to: editor)
+ precondition(abs(actual.minY - line.minY) < 1, "Native insertion indicator disagrees with glyphs")
+ }
+
+ }
+ for character in "\nCaret stability after Enter.\nSecond line.\nThird line." {
+ window.makeKeyAndOrderFront(nil)
+ window.makeFirstResponder(editor)
+ let before = editor.selectedRange().location
+ let typed = character == "\n" ? "\r" : String(character)
+ let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: typed, charactersIgnoringModifiers: typed, isARepeat: false, keyCode: character == "\n" ? 36 : 0)!
+ editor.keyDown(with: event)
+ record("immediate")
+ let immediate = editor.firstRect(forCharacterRange: editor.selectedRange(), actualRange: nil)
+ try? await Task.sleep(for: .milliseconds(100))
+ precondition(editor.selectedRange().location == before + String(character).utf16.count, "Typing moved selection unexpectedly")
+ record("settled")
+ let settled = editor.firstRect(forCharacterRange: editor.selectedRange(), actualRange: nil)
+ precondition(abs(immediate.minY - settled.minY) < 1, "Caret jumped after publication")
+ }
+ if let path = ProcessInfo.processInfo.environment["DOCS_SMOKE_SCREENSHOT"], let view = window.contentView,
+ let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) {
+ view.cacheDisplay(in: view.bounds, to: bitmap)
+ try? bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path))
+ }
+ print("PASS: document loads, inspector toggles, window resizes, editor and selection persist, Enter and typing keep caret geometry stable")
+ NSApp.windows.first(where: { $0.title == "Smoke Home" })?.close()
+ window.makeKeyAndOrderFront(nil)
+ guard let menu = NSApp.mainMenu, let appMenu = menu.items.first?.submenu else { fatalError("App menu missing") }
+ appMenu.delegate?.menuNeedsUpdate?(appMenu)
+ appMenu.update()
+ guard let accounts = menuItem(docsMacString("Accounts"), in: appMenu), accounts.isEnabled,
+ let signOut = menuItem(docsMacString("Sign out"), in: appMenu), !signOut.isEnabled else {
+ fatalError("Account commands missing or unsafe in document window")
+ }
+ accounts.menu!.performActionForItem(at: accounts.menu!.index(of: accounts))
+ try? await Task.sleep(for: .milliseconds(300))
+ precondition(windows.accountsRequested, "Accounts action did not reach launcher")
+ precondition(NSApp.windows.contains { $0.title == "Smoke Home" && $0.isVisible }, "Accounts did not reopen Home")
+ print("PASS: account commands live in app menu and Accounts reopens closed Home")
+ NSApp.terminate(nil)
+ }
+}