/duology:duo-continuityfrom duology
Guides preserving app state across iPhone Duo fold/unfold transitions. Covers @Observable, @SceneStorage, NavigationPath, ScrollPosition, and other state containers to prevent reset on resize.
Ships in duology. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Apple says your app resizes when someone opens or closes iPhone Duo (Tech Talk 111461). Your content moves to the other display, and the window changes size and usually its horizontal size class. State survives only if it lives above the part of the view tree that the change rebuilds. This skill tells you where to put each kind of state and how to prove it survives.
Load other skills for neighbouring work: duo-layout (size classes, ArrangementView, the even split), duo-navigation (bars, sidebars, sheets), duo-testing (test setup on the Duo simulator).
Labels: measured means we ran it on the iPhone Duo simulator (iOS 27.1). Fold results come from flipping the size class from code, the change a fold makes to your views, because our probes can't fold the simulator themselves; see references/evidence.md. Unverified means we could not confirm it. Everything else comes from Apple's pages, linked inline. Full source list: reference/sources.md.
Don't look for one. The iOS 27.1 SDK has no fold, pose or posture symbol, and the hinge APIs only report status and angle (API index). Apple states the goal, not a tool. The HIG asks you to keep functionality and the state of elements the same on both displays. Tech Talk 111466 says people open and close the phone often, so the app must stay predictable. Tech Talk 111463 keeps scrolling content in place because moving it breaks continuity. You reach that goal with ordinary SwiftUI and UIKit state tools. (Apple's "Continuity" feature, Handoff between devices, is unrelated.)
| Change | What your app sees |
|---|---|
| Close or open | Content moves between displays. The width changes and the horizontal size class flips: compact outside, regular inside. |
| Partially open | The window stays on the inner display. A division region (the fold) becomes active. |
| Rotate | Width and height swap. The inner display doesn't honour your supported orientations, so don't rely on them. |
| Split View, pinned Picture in Picture | The window gets narrower or shorter. |
| Combinations | Rotate, then close. Close while scrolling. Open while typing. Each step is another resize. |
onAppear and no scene disconnect, and the scene stayed active with no .inactive (duo-transitions evidence, duo-scenes evidence). Unverified: a real iPhone Duo, and what the keyboard does when the window changes display. Still save on .background.if/else or switch on size class, a ViewThatFits that picks another child, or an .id tied to layout gives views a new identity. SwiftUI drops their @State, takes keyboard focus away, runs onAppear again, cancels their .task, and closes sheets attached to them.onAppear, a UIKit trait handler that rebuilds child view controllers, an onDisappear that pauses or clears.| State | Keep it in | Tool |
|---|---|---|
| Scroll position | the model, as an item ID | ScrollPosition + scrollTargetLayout() (iOS 18); scrollPosition(id:anchor:) (iOS 17) |
| Playback | one player owned by a model | AVPlayer, VideoPlayer(player:) |
| Text and selection | the model | TextEditor(text:selection:), TextSelection (iOS 18) |
| Keyboard focus | @FocusState on a view whose identity never changes | focused(_:equals:) |
| Form input | a draft struct in the model | @Observable, @Bindable |
| Selected item, navigation stack | the model | NavigationSplitView selection, NavigationPath |
| Uploads, downloads | a service object, never a view | a Task the service keeps |
| Sign-in | an app-level session object, secrets in the Keychain | Keychain Services |
| Open sheet or alert | the item in the model, the modifier on a stable view | sheet(item:onDismiss:content:) |
Put screen state in an @Observable model (Observation). Create one per window in the window's root view, which never changes identity, and pass it down with .environment. Section 3 shows that root. Keep @State for values you are happy to lose, such as a press highlight. Data shared by every window (a store, the signed-in user) goes one level up, in the App. The snippets below use this model.
import SwiftUI
import Observation
struct Item: Identifiable, Hashable, Codable, Sendable {
let id: Int
var title: String
}
@MainActor @Observable
final class LibraryModel {
var items: [Item] = []
var selection: Item.ID? // drives the detail column
var path = NavigationPath() // pushed screens in the detail
var scroll = ScrollPosition(idType: Item.ID.self) // where the feed is
var draft = "" // text being typed
var draftSelection: TextSelection? // the selection in that text
var sheetItem: Item? // the open sheet, if any
private var didLoad = false
func loadIfNeeded() async {
guard !didLoad else { return } // a fold never refetches
didLoad = true
items = (1...200).map { Item(id: $0, title: "Item \($0)") } // your fetch here
}
}
Don't branch between containers on size class. Pick a layout and keep the same children (AnyLayout changes the layout without destroying the subviews' state).
import SwiftUI
struct CommentsPane: View {
@State private var reply = "" // lost on every fold in the bad version
var body: some View { TextField("Reply", text: $reply) }
}
// Bad: each branch is a different identity, so a fold resets CommentsPane.
struct ArticleScreenBad: View {
@Environment(\.horizontalSizeClass) private var sizeClass
var body: some View {
if sizeClass == .compact {
VStack { Text("Article"); CommentsPane() }
} else {
HStack { Text("Article"); CommentsPane() }
}
}
}
// Good: one identity, two layouts.
struct ArticleScreen: View {
@Environment(\.horizontalSizeClass) private var sizeClass
var body: some View {
let layout = sizeClass == .compact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout {
Text("Article")
CommentsPane()
}
}
}
if/else, every flip gave the child a new @State, ran onAppear again and cancelled its .task. With AnyLayout, the child appeared once for the whole run..id(_:) only for data identity, such as .id(item.id) to reset a detail on purpose. Changing the value resets the view's state (id(_:)). Never .id(sizeClass), .id(proxy.size) or .id(UUID()).NavigationStack for NavigationSplitView by size class. The split view collapses to a stack on its own.ArrangementView or the even split from duo-layout. Both take each pane once, with no branch. A split ArrangementView can hide its secondary view when it can't split (see duo-layout), so keep that view's state in the model.Keep the selection and the path in the model. NavigationSplitView collapses to one stack when the phone closes and shows the detail when something is selected (NavigationSplitView). If you switch panes yourself and opening the phone pops a pushed screen, pop it after the unfold animation (references/swiftui.md).
import SwiftUI
struct LibrarySplitView: View {
@Environment(LibraryModel.self) private var model
var body: some View {
@Bindable var model = model
NavigationSplitView {
List(model.items, selection: $model.selection) { item in
Text(item.title)
}
} detail: {
NavigationStack(path: $model.path) {
if let item = model.items.first(where: { $0.id == model.selection }) {
NavigationLink("Related", value: item.id + 1)
.navigationTitle(item.title)
.navigationDestination(for: Item.ID.self) { Text("Item \($0)") }
}
}
}
}
}
struct WindowRoot: View {
@State private var model = LibraryModel() // one per window, lives as long as the window
var body: some View {
LibrarySplitView()
.environment(model)
.task { await model.loadIfNeeded() } // WindowRoot never changes identity
}
}
init(preferredCompactColumn:sidebar:detail:) (iOS 17) is a hint for the column shown after the collapse. Keep that binding in the model too. Measured: with an item selected, the collapse hid the sidebar although the binding said .sidebar. Check what you get in Device Hub.@SceneStorage. Use it so the window comes back after the system ends the app: save the selection and path.codable when the scene goes to the background (NavigationPath, SceneStorage). Keep it small and never store secrets in it. Code: references/swiftui.md.import SwiftUI
struct FeedView: View {
@Environment(LibraryModel.self) private var model
@Environment(\.horizontalSizeClass) private var sizeClass
var body: some View {
@Bindable var model = model
let count = sizeClass == .compact ? 2 : 4 // even column counts
ScrollView {
LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: count)) {
ForEach(model.items) { Text($0.title) }
}
.scrollTargetLayout()
}
.scrollPosition($model.scroll, anchor: .top)
}
}
scrollPosition(id:) did not move a List. Use ScrollViewReader for a List, or a ScrollView with a lazy stack when you need ID positions. One exception, measured in the gallery: long text that reflows while the system margins arrive late lost its paragraph with ScrollPosition; a ScrollViewReader.scrollTo by the saved ID after the width settles kept it (gallery README).loadIfNeeded()), from a view that never changes identity. Or use .task(id:) keyed on the data, such as item.id, never on layout..task when its view goes away or changes identity (task). Never start an upload, a download or a payment from .task or onAppear inside a layout branch. Start it from a button action in a service object. Code: references/swiftui.md.onDisappear. A fold can trigger it.import SwiftUI
struct NoteEditor: View {
@Bindable var model: LibraryModel
@FocusState private var isFocused: Bool // lives in this view, so keep its identity stable
@Environment(\.horizontalSizeClass) private var sizeClass
var body: some View {
let layout = sizeClass == .compact ? AnyLayout(VStackLayout()) : AnyLayout(HStackLayout())
layout {
TextEditor(text: $model.draft, selection: $model.draftSelection)
.focused($isFocused)
Text("\(model.draft.count) characters")
}
}
}
if/else lost it: its @FocusState became nil.$model.form.name (references/swiftui.md).AVPlayer once, in a model owned by the window root. Views only show it: VideoPlayer(player: playback.player). Measured: a model-owned AVPlayer kept playing while VideoPlayer was torn down and rebuilt on each flip.@State private var player = AVPlayer(url:) in a view below a layout switch. A fold starts a new player from zero.AVPlayerViewController: references/swiftui.md, references/uikit.md..sheet, .fullScreenCover, .alert and .confirmationDialog to a view that never changes identity, usually the window root. Drive them from the model. Measured: a sheet attached inside an if/else closed when the size class flipped, and its isPresented binding stayed true. The model and the screen disagreed. The same sheet on the root stayed up.onAppear below a layout switch; a fold would start it again. Unverified: whether a web sign-in sheet in flight survives a fold. Start it from the root to be safe.Keep the same view controllers and views. Change layout in place; don't rebuild. Keep the top item in view when the column count changes.
import UIKit
// Give it a compositional layout that reads the size class; see references/uikit.md.
final class FeedViewController: UICollectionViewController {
private var pendingAnchor: IndexPath?
override func viewDidLoad() {
super.viewDidLoad()
registerForTraitChanges([UITraitHorizontalSizeClass.self]) { (self: Self, _: UITraitCollection) in
self.pendingAnchor = self.pendingAnchor ?? self.collectionView.indexPathsForVisibleItems.min()
}
}
override func viewWillTransition(to size: CGSize, with coordinator: any UIViewControllerTransitionCoordinator) {
pendingAnchor = pendingAnchor ?? collectionView.indexPathsForVisibleItems.min() // before the resize
super.viewWillTransition(to: size, with: coordinator)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
guard let anchor = pendingAnchor else { return }
pendingAnchor = nil
collectionView.scrollToItem(at: anchor, at: .top, animated: false) // after the new layout
}
}
traitCollectionDidChange(_:), deprecated in iOS 17 (Adapting your app when traits change). viewWillTransition(to:with:) runs before the size changes; always call super. Unverified: the size-transition path, because the open simulator refused a rotation request from code.reloadData() or replace child view controllers in either handler.XCUIDevice.shared.orientation on the closed Duo did not resize the app (open: unverified).XCUIDevice has no fold control, and simctl and devicectl have no pose command. So a test, skipped by default, waits while you press the pose buttons and the rotate button in Device Hub, then compares the summary. Steps, matrix and full test code: references/testing.md.if sizeClass == .compact { A } else { B } where A and B hold the same stateful views.id(UUID()), .id(sizeClass), .id(geometry.size) or any .id fed by layout.onAppear { load() } or .task { await upload() } below a layout switch; onDisappear { player.pause() } or a form cleared in onDisappear@State private var player = AVPlayer(...) in a leaf viewNavigationStack in one branch and NavigationSplitView in the other; .sheet or .alert attached inside a size-class branchtraitCollectionDidChange(_:), reloadData() or new child view controllers on a trait change; restoring a saved contentOffset after a layout change@Observable model created once per window in a root view that never changes identity.AnyLayout, ArrangementView or one container. No if/else between containers, and no .id fed by size, size class or a fresh UUID.NavigationSplitView handles open and closed; @SceneStorage restores them after a relaunch and holds no secrets..task or onAppear.AVPlayer, owned by a model above the layout switch; no pause in onDisappear.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub kimeur/duology --plugin duology6 skills in this plugin
/duo-layoutCore layout rules for iPhone Duo, Apple's foldable. Use when content lands in the fold, a screen breaks on the inner or outer display, or you write SwiftUI or UIKit layout for a foldable. Covers size classes instead of UIScreen.main, idiom or orientation, asymmetric safe areas and margins, reserved regions (ReservedRegion, reservedRegions(kind:options:), .division, .occlusion, .includeInactive), ArrangementView and UIArrangementViewController (split and overlay styles), an even custom split (EvenSplit) for two halves that must always show, even grid columns, and keeping controls off the fold./duo-navigationGets toolbars, navigation bars, tab bars, split views and sheets right on iPhone Duo, Apple's foldable, where bars move into one vertical bar on the side of the outer display and of the inner display in landscape. Use it when bars go vertical, items overflow or vanish, an app draws its own custom bottom bar (UIToolbar, or a SwiftUI row in safeAreaInset or an overlay), toolbar or Menu buttons are icon-only, tabs should become a sidebar on the inner display, a sheet should sit to one side or off the fold, or code touches toolbarVerticalBehavior, toolbarVerticalEdge, axisBehavior, visibilityPriority, topBarPinnedTrailing, ToolbarOverflowMenu, toolbarVerticalCompressionBehavior, defaultTabBarPlacement, presentationPlacement, NavigationSplitView, preferredVerticalBarBehavior, verticalBarEdge, pinnedTrailingGroup, additionalOverflowItems, UITabBarController.Sidebar.preferredPlacement or UISheetPresentationController.preferredPlacement.Other plugins' skills for the same job