Baton

The guide

Lists

A list that pages in the store. loadNext on the lens, and a directive to add or remove an edge.

A list that pages is a Relay connection, in a fragment of its own. The fragment owns the pagination. The store owns the merged pages. A mutation adds or removes an edge with a directive, and the view reads the list like any other field. This chapter is that fragment, what the store holds after each page, and the edge directives.

The fragment that owns the list#

Three directives make a connection. @connection(key:) names the list in the store. @refetchable(queryName:) gives the fragment a query of its own, which is how the next page is fetched. @argumentDefinitions declares the page size and the cursor as the fragment's arguments, so the screen's query need not know them.

IssueList.swift

import Baton
import SwiftUI

struct IssueList: View {
    @Fragment("""
    fragment IssueList_repository on Repository
    @refetchable(queryName: "IssueListPaginationQuery")
    @argumentDefinitions(
      count: {type: "Int", defaultValue: 20}
      cursor: {type: "String"}
    ) {
      issues(first: $count, after: $cursor, states: OPEN)
      @connection(key: "IssueList_issues") {
        edges { node { id ...IssueRow_issue } }
      }
    }
    """)
    var repository: IssueList_repository

    var body: some View {
        let issues = repository.issues
        ForEach(issues.nodes) { issue in
            IssueRow(issue: issue.issueRow)
        }
        if issues.hasNext {
            ProgressView().task {
                try? await issues.loadNext()
            }
        }
    }
}

struct IssueRow: View {
    @Fragment("""
    fragment IssueRow_issue on Issue {
      number
      title
    }
    """)
    var issue: IssueRow_issue

    var body: some View {
        Text("#\(issue.number) \(issue.title)")
    }
}

struct RepositoryScreen: View {
    @Query("""
    query RepositoryQuery($owner: String!, $name: String!) {
      repository(owner: $owner, name: $name) {
        nameWithOwner
        ...IssueList_repository
      }
    }
    """)
    var repository: RepositoryQuery

    var body: some View {
        switch repository.phase {
        case .ready(let data):
            if let repo = data.repository {
                List { IssueList(repository: repo.issueList) }
                    .navigationTitle(repo.nameWithOwner)
            }
        case .loading:
            ProgressView()
        case .failed(let error):
            ErrorView(error) { repository.retry() }
        }
    }
}
Plate 1. The connection fragment, the row it spreads, and the screen that spreads it. The screen's query never mentions first or after.

The lens of a connection reads nodes, the records in order across every page, and also hasNext, isLoadingNext, and pageInfo with its cursors. connectionID is the key an edge directive names the list by. loadNext(count) fetches the next page with the fragment's query and its arguments. refetch() on the fragment's own lens fetches the first page again and replaces the list.

The lens of IssueList_repository, a fragment, reads a record of type Repository:

accessorreadsas
issuesissuesa lens of IssueConnection
  edgesedgesa lens of IssueEdge, a list, optional
    nodenodea lens of Issue, optional
      idida scalar
      issueRowthe parent's recordthe lens of IssueRow_issue
    cursorcursora scalar
  pageInfopageInfoa lens of PageInfo
    endCursorendCursora scalar, optional
    hasNextPagehasNextPagea scalar
idida scalar
Plate 2. The connection as the compiler reported it. The paging surface is generated beside these accessors.

What the store holds#

The connection lives under its key in the store, apart from the pages. A page is a slot of its own under the field's storage key, notes(first:2). The connection record under the key, __TestNotes_notes_connection, links the edges of every page in order. A refetch replaces the merged edges with the first page. A page fetched after a cursor that is no longer the connection's end is ignored.

A view attaches a handle for TestNotesQuery(id: "1") under storeOrNetwork, named notes; the transport answers its fetch with tests/notes-page-1.json.

tests/notes-page-1.json
{
  "data": {
    "character": {
      "id": "1",
      "name": "Rick Sanchez",
      "notes": {
        "totalCount": 5,
        "edges": [
          {
            "cursor": "c1",
            "node": {
              "__typename": "Note",
              "id": "n1",
              "text": "Wubba lubba dub dub"
            }
          },
          {
            "cursor": "c2",
            "node": {
              "__typename": "Note",
              "id": "n2",
              "text": "Portal gun needs charging"
            }
          }
        ],
        "pageInfo": {
          "endCursor": "c2",
          "hasNextPage": true
        }
      }
    }
  }
}

The store after the step, tests/notes-page-1.store.json

Character:1Character
__TestNotes_notes_connectionCharacter:1:__TestNotes_notes_connection
id"1"
name"Rick Sanchez"
notes(first:2)Character:1:notes(first:2)
Character:1:__TestNotes_notes_connectionNoteConnection
edges[ Character:1:notes(first:2):edges:0, Character:1:notes(first:2):edges:1 ]
pageInfoCharacter:1:__TestNotes_notes_connection:pageInfo
totalCount5
Character:1:__TestNotes_notes_connection:pageInfoPageInfo
endCursor"c2"
hasNextPagetrue
Character:1:notes(first:2)NoteConnection
edges[ Character:1:notes(first:2):edges:0, Character:1:notes(first:2):edges:1 ]
pageInfoCharacter:1:notes(first:2):pageInfo
totalCount5
Character:1:notes(first:2):edges:0NoteEdge
cursor"c1"
nodeNote:n1
Character:1:notes(first:2):edges:1NoteEdge
cursor"c2"
nodeNote:n2
Character:1:notes(first:2):pageInfoPageInfo
endCursor"c2"
hasNextPagetrue
Note:n1Note
id"n1"
text"Wubba lubba dub dub"
Note:n2Note
id"n2"
text"Portal gun needs charging"
client:rootQuery
character(id:"1")Character:1
Plate 3. The specification's connection script goes step by step: the first page, the second merged, a refetch that replaces, and an edge appended by a mutation. A page fetched after a cursor the connection has moved past is ignored by the merge, and it notifies nothing.

Edge directives#

A mutation that adds to or removes from a list says so on its payload. The store does the edit in the same batch as the payload's own records.

  • @appendEdge(connections:) and @prependEdge(connections:) go on a payload field that is an edge.
  • @appendNode(connections:, edgeTypeName:) and @prependNode(connections:, edgeTypeName:) go on a payload field that is a node.
  • @deleteEdge(connections:) goes on a payload field holding the id of the node to remove from the lists.
  • @deleteRecord goes on a payload field holding the id of a record to delete outright. Every list skips that record, and every link reads it as null.

The connections variable carries the connection ids the view read from its lenses, so the same mutation can add to one list or to three. Nothing edits the cache by hand, and nothing has to know which screens show the list.

CommentComposer.swift

import Baton
import SwiftUI

struct CommentComposer: View {
    let subjectID: String
    let connectionID: String
    @State private var text = ""

    @Mutation("""
    mutation CommentComposerAddComment($input: AddCommentInput!, $connections: [ID!]!) {
      addComment(input: $input) {
        commentEdge @appendEdge(connections: $connections) {
          node { id bodyText author { login } }
        }
      }
    }
    """)
    var addComment: CommentComposerAddComment.Action

    var body: some View {
        HStack {
            TextField("Leave a comment", text: $text)
            Button("Comment") {
                let body = text
                Task {
                    try await addComment(
                        input: AddCommentInput(body: body, subjectId: subjectID),
                        connections: [connectionID]
                    )
                    text = ""
                }
            }
            .disabled(text.isEmpty || addComment.isInFlight)
        }
    }
}
Plate 4. A comment appended to the issue's comments. The composer takes the connectionID the list's lens read and passes it in connections.

The server answers TestAddNote(characterId: "1", text: "Appended", connections: ["Character:1:__TestNotes_notes_connection"]) with tests/add-note-n9.json, and the environment commits it as a server batch.

tests/add-note-n9.json
{
  "data": {
    "addNote": {
      "noteEdge": {
        "cursor": "c9",
        "node": {
          "id": "n9",
          "text": "Appended"
        }
      }
    }
  }
}
A lens readsand finds
notes · character.notes.edges.2.node.textAppended
notes · character.notes.edges.3.node.textnull

The store after the step, scripts/connections-inserted.store.json

Character:1Character
__TestNotes_notes_connectionCharacter:1:__TestNotes_notes_connection
id"1"
name"Rick Sanchez"
notes(after:"c2",first:2)Character:1:notes(after:"c2",first:2)
notes(first:2)Character:1:notes(first:2)
Character:1:__TestNotes_notes_connectionNoteConnection
__connection_next_edge_index1
edges[ Character:1:notes(first:2):edges:0, Character:1:notes(first:2):edges:1, Character:1:__TestNotes_notes_connection:edges:0 ]
pageInfoCharacter:1:__TestNotes_notes_connection:pageInfo
totalCount5
Character:1:__TestNotes_notes_connection:edges:0NoteEdge
cursor"c9"
nodeNote:n9
Character:1:__TestNotes_notes_connection:pageInfoPageInfo
endCursor"c2"
hasNextPagetrue
Character:1:notes(after:"c2",first:2):edges:0NoteEdge
cursor"c3"
nodeNote:n3
Character:1:notes(after:"c2",first:2):edges:1NoteEdge
cursor"c4"
nodeNote:n4
Character:1:notes(after:"c2",first:2):pageInfoPageInfo
endCursor"c4"
hasNextPagetrue
Character:1:notes(first:2)NoteConnection
edges[ Character:1:notes(first:2):edges:0, Character:1:notes(first:2):edges:1 ]
pageInfoCharacter:1:notes(first:2):pageInfo
totalCount5
Character:1:notes(first:2):edges:0NoteEdge
cursor"c1"
nodeNote:n1
Character:1:notes(first:2):edges:1NoteEdge
cursor"c2"
nodeNote:n2
Character:1:notes(first:2):pageInfoPageInfo
endCursor"c2"
hasNextPagetrue
Note:n1Note
id"n1"
text"Wubba lubba dub dub"
Note:n2Note
id"n2"
text"Portal gun needs charging"
Note:n3Note
id"n3"
text"Get Schwifty"
Note:n4Note
id"n4"
text"Avoid the Citadel"
Note:n9Note
id"n9"
text"Appended"
client:rootQuery
character(id:"1")Character:1
node(id:"1")Character:1
client:root:mutationMutation
addNoteclient:root:mutation:addNote
client:root:mutation:addNoteAddNotePayload
noteEdgeclient:root:mutation:addNote:noteEdge
client:root:mutation:addNote:noteEdgeNoteEdge
cursor"c9"
nodeNote:n9
Plate 5. What @appendEdge leaves in the store is the new note's record, the new edge, and the connection's edge list one longer, with no refetch.

A payload with no id has no field for @deleteRecord to sit on, so @deletes(type:, id:) goes on the mutation and names the record by its type and the variable its key is passed as. The store deletes that record as @deleteRecord does, in the optimistic layer and in the server's commit.

Lists paged by number#

Some schemas have no cursors. AniList pages every list by number: Page(page: 1, perPage: 50) { pageInfo { hasNextPage } media(...) }, with one pageInfo for whichever list the page is asked for, and the lists on an entity, Media.characters(page:, perPage:), page the same way. Baton does not pretend such a list is a connection. It says so with @paged(key:, page:), on the list field, inside the field that takes the page:

query SeasonQuery($page: Int!, $season: MediaSeason) {
  Page(page: $page, perPage: 50) {
    pageInfo { hasNextPage }
    media(season: $season, type: ANIME, sort: [POPULARITY_DESC])
      @paged(key: "SeasonQuery_media", page: $page) {
      id
      ...MediaCard_media
    }
  }
}

The pages merge into a record of their own in the store, under the list and its arguments, apart from the server's Page(page: 1, perPage: 50) record, which two lists may share. The first page replaces the merged list, the next appends, a page fetched again rewrites its elements in place. The lens over Page reads the merged media, and gains hasNext, which reads the merged pageInfo.hasNextPage and nothing else (AniList's total and lastPage are not to be trusted, and are not read), isLoadingNext, and loadNext(), which runs the screen's own query again with the next page number. No @refetchable fragment is needed; a refetch of the query replaces the list. The page variable is the operation's, declared Int!, and pageInfo { hasNextPage } is selected beside the list, or the compiler says what is missing.

A view attaches a handle for TestPagedNotesQuery(page: 1, authorId: "1") under storeOrNetwork, named notes; the transport answers its fetch with tests/paged-notes-1.json.

tests/paged-notes-1.json
{
  "data": {
    "page": {
      "pageInfo": {
        "hasNextPage": true,
        "currentPage": 1
      },
      "notes": [
        {
          "id": "n1",
          "text": "Wubba lubba dub dub"
        },
        {
          "id": "n2",
          "text": "Portal gun needs charging"
        }
      ]
    }
  }
}
A lens readsand finds
notes · page.notes.1.textPortal gun needs charging
notes · page.notes.2.textnull
notes · page.hasNexttrue

The store after the step, tests/paged-notes-1.store.json

Note:n1Note
id"n1"
text"Wubba lubba dub dub"
Note:n2Note
id"n2"
text"Portal gun needs charging"
client:rootQuery
__TestPagedNotes_notes_paged(authorId:"1",perPage:2)client:root:__TestPagedNotes_notes_paged(authorId:"1",perPage:2)
page(page:1,perPage:2)client:root:page(page:1,perPage:2)
client:root:__TestPagedNotes_notes_paged(authorId:"1",perPage:2)Page
__firstPage1
__pageLengths[2]
notes(authorId:"1")[ Note:n1, Note:n2 ]
pageInfoclient:root:__TestPagedNotes_notes_paged(authorId:"1",perPage:2):pageInfo
client:root:__TestPagedNotes_notes_paged(authorId:"1",perPage:2):pageInfoPageInfo
currentPage1
hasNextPagetrue
client:root:page(page:1,perPage:2)Page
notes(authorId:"1")[ Note:n1, Note:n2 ]
pageInfoclient:root:page(page:1,perPage:2):pageInfo
client:root:page(page:1,perPage:2):pageInfoPageInfo
currentPage1
hasNextPagetrue
Plate 6. The specification's paged script: the first page, the second merged, a second list under the same server page keeping its own flag, a page rewritten in place, a page past the end ignored, and a refetch that replaces.

A schema whose page info is not pageInfo { hasNextPage }, as the Rick and Morty API's info { next }, keeps reading one page per operation value: a screen with a page bar holds the current page's query, and the samples show one page at a time. The decision says what was chosen, what was not, and what would reopen it.

Keys in a lazy list#

Every lens carries its record's key, so a lazy list keys its items by that key. A row keeps its state while a refetch reorders the list.

ForEach(repository.issues.nodes) { issue in
    IssueRow(issue: issue.issueRow)
}

In Swift, ForEach takes a plural lens, a Baton.List, or a connection's nodes, through initializers Baton adds. They are keyed by the record, so no id: is needed.