axiom-textkit-ref

0
0
Source

TextKit 2 complete reference (architecture, migration, Writing Tools, SwiftUI TextEditor) through iOS 26

Install

mkdir -p .claude/skills/axiom-textkit-ref && curl -L -o skill.zip "https://mcp.directory/api/skills/download/7557" && unzip -o skill.zip -d .claude/skills/axiom-textkit-ref && rm skill.zip

Installs to .claude/skills/axiom-textkit-ref

About this skill

TextKit 2 Reference

Complete reference for TextKit 2 covering architecture, migration from TextKit 1, Writing Tools integration, and SwiftUI TextEditor with AttributedString through iOS 26.

Architecture

TextKit 2 uses MVC pattern with new classes optimized for correctness, safety, and performance.

Model Layer

NSTextContentManager (abstract)

  • Generates NSTextElement objects from backing store
  • Tracks element ranges within document
  • Default implementation: NSTextContentStorage

NSTextContentStorage

  • Uses NSTextStorage as backing store
  • Automatically divides content into NSTextParagraph elements
  • Generates updated elements when text changes

NSTextElement (abstract)

  • Represents portion of content (paragraph, attachment, custom type)
  • Immutable value semantics
  • Properties cannot change after creation
  • Default implementation: NSTextParagraph

NSTextParagraph

  • Represents single paragraph
  • Contains range within document

Controller Layer

NSTextLayoutManager

  • Replaces TextKit 1's NSLayoutManager
  • NO glyph APIs (abstracts away glyphs entirely)
  • Takes elements, lays out into container, generates layout fragments
  • Always uses noncontiguous layout

NSTextLayoutFragment

  • Immutable layout information for one or more elements
  • Key properties:
    • textLineFragments — array of NSTextLineFragment
    • layoutFragmentFrame — layout bounds within container
    • renderingSurfaceBounds — actual drawing bounds (can exceed frame)

NSTextLineFragment

  • Measurement info for single line of text
  • Used for line counting and geometric queries

View Layer

NSTextViewportLayoutController

  • Source of truth for viewport layout
  • Coordinates visible-only layout
  • Calls delegate methods: willLayout, configureRenderingSurface, didLayout

NSTextContainer

  • Provides geometric information for layout destination
  • Can define exclusion paths (non-rectangular layout)

Object-Based Ranges

NSTextLocation (protocol)

  • Represents single location in text
  • Replaces integer indices
  • Supports structured documents (e.g., DOM with nested elements)

NSTextRange

  • Start and end locations (end is excluded)
  • Can represent nested structure
  • Incompatible with NSRange for non-linear documents

NSTextSelection

  • Contains: granularity, affinity, possibly disjoint ranges
  • Read-only properties
  • Immutable value semantics

NSTextSelectionNavigation

  • Performs actions on selections
  • Returns new NSTextSelection instances
  • Handles bidirectional text correctly

Core Design Principles

1. Correctness — No Glyph APIs

From WWDC 2021:

"TextKit 2 abstracts away glyph handling to provide a consistent experience for international text."

Why no glyphs?

Problem: In scripts like Kannada and Arabic:

  • One glyph can represent multiple characters (ligatures)
  • One character can split into multiple glyphs
  • Glyphs reorder during shaping
  • No correct character→glyph mapping

Example (Kannada word "October"):

  • Character 4 splits into 2 glyphs
  • Glyphs reorder before ligature application
  • Glyph 3 becomes conjoining form and moves below another glyph

Solution: Use NSTextLocation, NSTextRange, NSTextSelection instead of glyph indices.

2. Safety — Value Semantics

Immutable objects:

  • NSTextElement
  • NSTextLayoutFragment
  • NSTextLineFragment
  • NSTextSelection

Benefits:

  • No unintended sharing
  • No side effects from mutations
  • Easier to reason about state

Pattern: To change layout/selection, create new instances with desired changes.

3. Performance — Viewport Layout

Always Noncontiguous: TextKit 2 performs layout only for visible content + overscroll region.

TextKit 1:

  • Optional noncontiguous layout (boolean property)
  • No visibility into layout state
  • Can't control which parts get laid out

TextKit 2:

  • Always noncontiguous
  • Viewport defines visible area
  • Consistent layout info for viewport
  • Notifications for viewport layout updates

Viewport Delegate Methods:

  1. textViewportLayoutControllerWillLayout(_:) — setup before layout
  2. textViewportLayoutController(_:configureRenderingSurfaceFor:) — per fragment
  3. textViewportLayoutControllerDidLayout(_:) — cleanup after layout

Migration from TextKit 1

Key Paradigm Shift

TextKit 1TextKit 2
GlyphsElements
NSRangeNSTextLocation/NSTextRange
NSLayoutManagerNSTextLayoutManager
Glyph APIsNO glyph APIs
Optional noncontiguousAlways noncontiguous
NSTextStorage directlyVia NSTextContentManager

API Naming Heuristics

From WWDC 2022:

  • .offset in name → TextKit 1
  • .location in name → TextKit 2

NSRange ↔ NSTextRange Conversion

NSRange → NSTextRange:

// UITextView/NSTextView
let nsRange = NSRange(location: 0, length: 10)

// Via content manager
let startLocation = textContentManager.location(
    textContentManager.documentRange.location,
    offsetBy: nsRange.location
)!
let endLocation = textContentManager.location(
    startLocation,
    offsetBy: nsRange.length
)!
let textRange = NSTextRange(location: startLocation, end: endLocation)

NSTextRange → NSRange:

let startOffset = textContentManager.offset(
    from: textContentManager.documentRange.location,
    to: textRange.location
)
let length = textContentManager.offset(
    from: textRange.location,
    to: textRange.endLocation
)
let nsRange = NSRange(location: startOffset, length: length)

Glyph API Replacements

NO direct glyph API equivalents. Must use higher-level structures.

Example (TextKit 1 - counting lines):

// TextKit 1 - iterate glyphs
var lineCount = 0
let glyphRange = layoutManager.glyphRange(for: textContainer)
for glyphIndex in glyphRange.location..<NSMaxRange(glyphRange) {
    let lineRect = layoutManager.lineFragmentRect(
        forGlyphAt: glyphIndex,
        effectiveRange: nil
    )
    // Count unique rects...
}

Replacement (TextKit 2 - enumerate fragments):

// TextKit 2 - enumerate layout fragments
var lineCount = 0
textLayoutManager.enumerateTextLayoutFragments(
    from: textLayoutManager.documentRange.location,
    options: [.ensuresLayout]
) { fragment in
    lineCount += fragment.textLineFragments.count
    return true
}

Compatibility Mode (UITextView/NSTextView)

Automatic Fallback to TextKit 1: Happens when you access .layoutManager property.

Warning (WWDC 2022):

"Accessing textView.layoutManager triggers TK1 fallback"

Once fallback occurs:

  • No automatic way back to TextKit 2
  • Expensive to switch
  • Lose UI state (selection, scroll position)
  • One-way operation

Prevent Fallback:

  1. Check .textLayoutManager first (TextKit 2)
  2. Only access .layoutManager in else clause
  3. Opt out at initialization if TK1 required
// Check TextKit 2 first
if let textLayoutManager = textView.textLayoutManager {
    // TextKit 2 code
} else if let layoutManager = textView.layoutManager {
    // TextKit 1 fallback (old OS versions)
}

Debug Fallback:

  • UIKit: Breakpoint on _UITextViewEnablingCompatibilityMode
  • AppKit: Subscribe to willSwitchToNSLayoutManagerNotification

NSTextView Opt-In (macOS)

Create TextKit 2 NSTextView:

let textLayoutManager = NSTextLayoutManager()
let textContainer = NSTextContainer()
textLayoutManager.textContainer = textContainer

let textView = NSTextView(frame: .zero, textContainer: textContainer)
// textView.textLayoutManager now available

New Convenience Constructor:

// iOS 16+ / macOS 13+
let textView = UITextView(usingTextLayoutManager: true)
let nsTextView = NSTextView(usingTextLayoutManager: true)

Delegate Hooks

NSTextContentStorageDelegate

Customize attributes without modifying storage:

func textContentStorage(
    _ textContentStorage: NSTextContentStorage,
    textParagraphWith range: NSRange
) -> NSTextParagraph? {
    // Modify attributes for display
    var attributedString = textContentStorage.attributedString!
        .attributedSubstring(from: range)

    // Add custom attributes
    if isComment(range) {
        attributedString.addAttribute(
            .foregroundColor,
            value: UIColor.systemIndigo,
            range: NSRange(location: 0, length: attributedString.length)
        )
    }

    return NSTextParagraph(attributedString: attributedString)
}

Filter elements (hide/show content):

func textContentManager(
    _ textContentManager: NSTextContentManager,
    shouldEnumerate textElement: NSTextElement,
    options: NSTextContentManager.EnumerationOptions
) -> Bool {
    // Return false to hide element
    if hideComments && isComment(textElement) {
        return false
    }
    return true
}

NSTextLayoutManagerDelegate

Provide custom layout fragments:

func textLayoutManager(
    _ textLayoutManager: NSTextLayoutManager,
    textLayoutFragmentFor location: NSTextLocation,
    in textElement: NSTextElement
) -> NSTextLayoutFragment {
    // Return custom fragment for special styling
    if isComment(textElement) {
        return BubbleLayoutFragment(
            textElement: textElement,
            range: textElement.elementRange
        )
    }
    return NSTextLayoutFragment(
        textElement: textElement,
        range: textElement.elementRange
    )
}

NSTextViewportLayoutController.Delegate

Viewport layout lifecycle:

func textViewportLayoutControllerWillLayout(_ controller: NSTextViewportLayoutController) {
    // Prepare for layout: clear sublayers, begin animation
}

func textViewportLayoutController(
    _ controller: NSTextViewportLayoutController,
    configureRenderingSurfaceFor textLayoutFragment: NSTextLayoutFragment
) {
    // Update geometry for each visible fragment
    let layer = getOrCreateLayer(for: textLayoutFragment)
    layer.frame = textLayoutFragment

---

*Content truncated.*

axiom-swiftdata

CharlesWiltgen

Use when working with SwiftData - @Model definitions, @Query in SwiftUI, @Relationship macros, ModelContext patterns, CloudKit integration, iOS 26+ features, and Swift 6 concurrency with @MainActor — Apple's native persistence framework

11

axiom-swiftui-nav-diag

CharlesWiltgen

Use when debugging navigation not responding, unexpected pops, deep links showing wrong screen, state lost on tab switch or background, crashes in navigationDestination, or any SwiftUI navigation failure - systematic diagnostics with production crisis defense

21

axiom-ios-build

CharlesWiltgen

Use when ANY iOS build fails, test crashes, Xcode misbehaves, or environment issue occurs before debugging code. Covers build failures, compilation errors, dependency conflicts, simulator problems, environment-first diagnostics.

151

axiom-ios-vision

CharlesWiltgen

Use when implementing ANY computer vision feature - image analysis, object detection, pose detection, person segmentation, subject lifting, hand/body pose tracking.

21

axiom-haptics

CharlesWiltgen

Use when implementing haptic feedback, Core Haptics patterns, audio-haptic synchronization, or debugging haptic issues - covers UIFeedbackGenerator, CHHapticEngine, AHAP patterns, and Apple's Causality-Harmony-Utility design principles from WWDC 2021

20

axiom-in-app-purchases

CharlesWiltgen

Use when implementing in-app purchases, StoreKit 2, subscriptions, or transaction handling - testing-first workflow with .storekit configuration, StoreManager architecture, transaction verification, subscription management, and restore purchases for consumables, non-consumables, and auto-renewable subscriptions

10

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

9521,094

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

846846

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

571700

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

548492

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

673466

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

514280

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.