Spotlight indexing

From gustavscirulis/snapgrid · View interactive version

Spotlight indexing is an AI agent skill from the GitHub repository gustavscirulis/snapgrid. Generates Core Spotlight indexing infrastructure for making app content searchable via system Spotlight with rich attributes and deep link integration. Use when user wants to index content for Spotlight search, Siri suggestions, or system-wide searchability.

How to use this skill

Skill file

Spotlight Indexing Generator

Generate production Core Spotlight indexing infrastructure — makes app content searchable via Spotlight (and Siri suggestions). Indexes items with rich attributes, handles search continuation into your app, and manages index lifecycle.

When This Skill Activates

Use this skill when the user:

Pre-Generation Checks

1. Project Context Detection

2. Existing CoreSpotlight Detection

Search for existing Spotlight code:

Glob: **/*Spotlight*.swift, **/*Searchable*.swift, **/*CSSearchable*.swift
Grep: "CoreSpotlight" or "CSSearchableIndex" or "CSSearchableItem"

If existing Spotlight code found:

3. Deep Linking Detection

Search for existing deep link or navigation setup:

Grep: "NavigationPath" or "onOpenURL" or "NSUserActivity" or "DeepLink"

If deep linking exists:

4. Entitlements Check

Verify CoreSpotlight doesn't require special entitlements (it doesn't — it's a standard framework), but check if the app uses App Groups for shared index across extensions.

Configuration Questions

Ask user via AskUserQuestion:

  1. Content types to index?
  1. Include thumbnails?
  1. Indexing strategy?
  1. Include Siri suggestions / shortcuts?

Generation Process

Step 1: Read Templates

Read templates.md for production Swift code.

Read patterns.md for architecture guidance and best practices.

Step 2: Create Core Files

Generate these files:

  1. SpotlightIndexable.swift — Protocol any model can conform to
  2. SpotlightIndexManager.swift — Actor wrapping CSSearchableIndex with batching
  3. SpotlightAttributeBuilder.swift — Fluent builder for CSSearchableItemAttributeSet

Step 3: Create Integration Files

  1. SpotlightSearchHandler.swift — Handles NSUserActivity continuation from Spotlight taps

Step 4: Create Optional Files

Based on configuration:

Step 5: Determine File Location

Check project structure:

Output Format

After generation, provide:

Files Created

SpotlightIndexing/
├── SpotlightIndexable.swift        # Protocol for indexable models
├── SpotlightIndexManager.swift     # Actor-based index management
├── SpotlightAttributeBuilder.swift # Fluent attribute builder
├── SpotlightSearchHandler.swift    # Handle Spotlight tap continuation
└── SpotlightSyncModifier.swift     # Auto index/deindex ViewModifier (optional)

Integration with Content Creation/Update

Make a model searchable:

// Conform your model to SpotlightIndexable
struct Article: SpotlightIndexable {
    let id: UUID
    let title: String
    let body: String
    let author: String
    let tags: [String]

    var spotlightID: String { id.uuidString }
    var spotlightTitle: String { title }
    var spotlightDescription: String { String(body.prefix(300)) }
    var spotlightKeywords: [String] { tags + [author] }
    var spotlightThumbnailData: Data? { nil }
    var spotlightDomainIdentifier: String { "com.myapp.articles" }
}

Index on create, remove on delete:

func createArticle(_ article: Article) async throws {
    try await repository.save(article)
    await SpotlightIndexManager.shared.index(items: [article])
}

func deleteArticle(_ article: Article) async throws {
    try await repository.delete(article)
    await SpotlightIndexManager.shared.remove(identifiers: [article.spotlightID])
}

Batch reindex (e.g., on first launch):

func reindexAllContent() async {
    let articles = await repository.fetchAll()
    await SpotlightIndexManager.shared.reindexAll(items: articles, domain: "com.myapp.articles")
}

Handle Spotlight tap (App or Scene delegate):

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onContinueUserActivity(CSSearchableItemActionType) { activity in
                    SpotlightSearchHandler.shared.handle(activity)
                }
        }
    }
}

Auto index/deindex with ViewModifier:

struct ArticleDetailView: View {
    let article: Article

    var body: some View {
        ScrollView {
            Text(article.body)
        }
        .spotlightIndexed(article)  // Indexes on appear, deindexes on disappear
    }
}

Testing

@Test
func indexAndRetrieveItem() async throws {
    let manager = SpotlightIndexManager(index: MockSearchableIndex())
    let article = Article(id: UUID(), title: "Test", body: "Body", author: "Author", tags: ["swift"])

    await manager.index(items: [article])
    #expect(manager.indexedCount == 1)
}

@Test
func batchIndexChunksCorrectly() async throws {
    let mockIndex = MockSearchableIndex()
    let manager = SpotlightIndexManager(index: mockIndex, batchSize: 10)
    let items = (0..<25).map { makeArticle(index: $0) }

    await manager.index(items: items)
    #expect(mockIndex.indexCallCount == 3)  // 10 + 10 + 5
}

@Test
func handleSpotlightContinuation() async throws {
    let handler = SpotlightSearchHandler()
    let activity = NSUserActivity(activityType: CSSearchableItemActionType)
    activity.userInfo = [CSSearchableItemActivityIdentifier: "article-123"]

    let itemID = handler.extractItemID(from: activity)
    #expect(itemID == "article-123")
}

Common Patterns

Index Item on Create

Every time a model is created or updated, index it immediately:

await SpotlightIndexManager.shared.index(items: [newItem])

Remove on Delete

When content is deleted, remove it from the index:

await SpotlightIndexManager.shared.remove(identifiers: [item.spotlightID])

Batch Reindex

After app update or data migration, reindex all content:

await SpotlightIndexManager.shared.reindexAll(items: allItems, domain: "com.myapp.articles")

Handle Search Continuation

When user taps a Spotlight result, the app receives an NSUserActivity. Extract the item ID and navigate:

.onContinueUserActivity(CSSearchableItemActionType) { activity in
    if let id = activity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
        navigationPath.append(Route.detail(id: id))
    }
}

Gotchas

Index Size Limits

Thumbnail Size for Performance

CSSearchableIndex.default() Thread Safety

Handling App Launch from Spotlight Tap

Index Maintenance on App Update

Domain Identifiers

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.