diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8b26c6c..40d4e65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,8 @@ on: push: branches: [main] pull_request: + # Run on a branch without opening a pull request. + workflow_dispatch: permissions: contents: read diff --git a/README.md b/README.md index f8b5f8b..c104ac8 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,52 @@ Optional hooks: Inside a case, `LocalVCaseVariant.current` gives the axes and the fixture name. +### Per-case capture settings + +A case can change how it is captured. Every setting is optional, defaults to the host's +behaviour, and is written to the manifest's `capture` object only when set, so existing +cases, manifests and goldens are unchanged. + +| `@VCase` parameter | default | effect | +|---|---|---| +| `maxWidth` | `0` (host's bound, by default the viewport width) | width bound in dp of a component capture, for content wider than the host allows (a wide gallery) | +| `maxHeight` | `0` (host's bound, by default 4x the viewport height) | height bound in dp of a component capture | +| `settleFrames` | `-1` (host's `settleFrames`) | frames rendered before the captured one, e.g. `2` for a popup that lays itself out a frame late | +| `frameIntervalMs` | `-1` (host's `frameTimeNanos`) | frame `i` renders at `i * frameIntervalMs` ms; `0` renders every frame at time 0 | + +```kotlin +@VCase("ds.choice-list.gallery", maxWidth = 1600) // wider than the 1200dp gallery bound +@VCase("ds.tooltip.open", settleFrames = 2, frameIntervalMs = 0) // popup settled, animations not started +@VCase("ds.toast.shown", settleFrames = 20, frameIntervalMs = 16) // a 300 ms fade-in has finished +``` + +- `maxWidth` / `maxHeight` replace the bounds of the host's `CaptureSize.WrapContent`. A + screen is captured at its viewport, so the manifest check rejects them on screens. +- `settleFrames` applies to the capture pass. The measure pass of a component (which finds + its content size) keeps the host's count. +- `settleFrames = N, frameIntervalMs = 0` matches a hand-written + `repeat(N) { scene.render() }; scene.render()` on an `ImageComposeScene`: state, effects + and popups settle, while time-driven animations stay at their start. Give a positive + interval to let animations run. + +### Wide layouts and the mouse + +The pointer axis (`touch`, `fine`) is how a case asks for mouse sizing: +`pointer = ["fine"]`, or `["touch", "fine"]` for both. A wide layout (a desktop type scale, +larger panes) is a viewport with a size class: + +```kotlin +ManifestViewport("wide", 1200, 2400, 2f, optIn = true, sizeClass = VCaseSizeClass.WIDE) + +@VCase("ds.desktop-scale.gallery", viewport = ["wide"], pointer = ["fine", "touch"]) +``` + +The host reads `variant.axes.viewport.sizeClass` and `variant.axes.pointer` in `Wrap` and +pins the theme's layout and input modes with them. It should not derive them from the +capture size: a component is captured at its content size, which says nothing about the +window it was designed for. `sizeClass` is free text (`VCaseSizeClass.COMPACT` and `WIDE` are +the conventional names). It is not an axis of its own, so it never appears in file names. + ### 3. Add one test class ```kotlin @@ -164,10 +210,10 @@ export default function Variants() { return ; } | module | what | |---|---| -| `vcase-annotations` | `@VCase`, `@VCaseDivergence`, `VCaseKind`, axis model (`VCaseAxis`, `VCasePointer`, `VCaseViewport`, `VCaseAxisValues`). KMP, no dependencies. | -| `vcase-core` | JVM. Manifest model + JSON (`VCaseManifest`, `VCaseJson`), `ManifestValidation`, `VCaseIds`, `AxisExpansion` / `VCaseVariant`, `ManifestDiff`, `ImageCompare` / `PixelTolerance` / `RegionTolerance`, `CaptureMeta`, `GoldenStore` / `GoldenRun` / `RunSummary`, `HtmlReport`. | +| `vcase-annotations` | `@VCase`, `@VCaseDivergence`, `VCaseKind`, axis model (`VCaseAxis`, `VCasePointer`, `VCaseViewport`, `VCaseSizeClass`, `VCaseAxisValues`). KMP, no dependencies. | +| `vcase-core` | JVM. Manifest model + JSON (`VCaseManifest`, `ManifestCapture`, `VCaseJson`), `ManifestValidation`, `VCaseIds`, `AxisExpansion` / `VCaseVariant`, `ManifestDiff`, `ImageCompare` / `PixelTolerance` / `RegionTolerance`, `CaptureMeta`, `GoldenStore` / `GoldenRun` / `RunSummary`, `HtmlReport`. | | `vcase-compose-desktop` | JVM, Compose Desktop. `VCaseScanner` (ComposablePreviewScanner `JvmAnnotationScanner` + ClassGraph), `VCaseHost`, `CaptureSize`, `LocalVCaseVariant`, `DesktopRenderer` (ImageComposeScene, renderer `desktop-skiko`), `runVCases`, `VCaseDesktopConfig`, `VCaseDesktopTest`. | -| `samples/compose-desktop` | Four cases, a host, the one test class, committed goldens. | +| `samples/compose-desktop` | Seven cases (including a wide capture, a settled popup and a wide size class with both pointers), a host, the one test class, committed goldens. | ## Building diff --git a/docs/design.md b/docs/design.md index 1fc7654..825d5e2 100644 --- a/docs/design.md +++ b/docs/design.md @@ -113,6 +113,11 @@ Phase 1 additions to `vcase/1` (all optional, omitted from the JSON while unset) - `cases[].formerly`: previous ids. - `cases[].needsDevice`: the case can only be rendered on a device or emulator. - `divergences[].expires`: an ISO date. +- `viewport[].sizeClass`: the layout mode the host pins for the viewport (`compact`, `wide`). + It is not an axis and is not part of file names. +- `cases[].capture`: per-case capture settings, each optional: `maxWidth` / `maxHeight` + (dp bounds of a component capture), `settleFrames` (frames before the captured one) and + `frameIntervalMs` (frame `i` at `i * frameIntervalMs` ms; 0 = every frame at time 0). ### Id rules **[built]** @@ -165,7 +170,9 @@ fun ChannelMembersCase(data: MembersFixture) { `ScreenshotTimeContext`) and pinned fonts. The project injects its own theme and these freeze settings through a `VCaseHost` interface. The framework does not know about Raft. **[built]** Frames render at fixed times (`frameTimeNanos`), and density and font - scale come from the axes. + scale come from the axes. A case can override the frame plan (`settleFrames`, + `frameIntervalMs`) and the content-size bounds (`maxWidth`, `maxHeight`); the host maps + the viewport's `sizeClass` and the pointer axis to the theme's layout and input modes. - The data parameter's type follows from the fixture name. The adapter deserializes the generated JSON into it (kotlinx.serialization). **[planned]** In phase 1 cases have no parameters. A case with a parameter is reported as an error. The fixture name is diff --git a/docs/pilot-raft-mobile.md b/docs/pilot-raft-mobile.md index 3acd7e9..8c05fe2 100644 --- a/docs/pilot-raft-mobile.md +++ b/docs/pilot-raft-mobile.md @@ -103,7 +103,35 @@ tasks, and the legacy golden directory. harness does. Making `locale` a real axis changes the type styles, so it needs a re-record. - **Tests with interaction** (hover, pointer density, pull-down, toast timing) need more host hooks: settle frames per case, `LocalRaftSpinnerStillStep`, input injection. These - tests come last. + tests come last. Per-case settle frames, wide captures and the wide / mouse modes now + exist (see below); input injection does not. + +## Capture settings the remaining galleries need + +After batch 2, the remaining `RaftScreenshot` tests use three `capture` parameters that the +first host could not express. Each maps to a vcase setting: + +| `RaftScreenshot.capture(...)` | `@VCase` | legacy tests | +|---|---|---| +| `maxWidthDp = 1340 / 1400 / 1600` | `maxWidth = 1340 / 1400 / 1600` | ThemeDecor (`top_actions`), ChoicePicker, ChoiceList, Combobox (`sheet`) | +| `settleFrames = N` | `settleFrames = N, frameIntervalMs = 0` | AppRail, DisplayComponent, FrameInsets, InteractiveComponent, MessageReaction, MobileNavServer, PointerDensity, PreviewCard, SideActionColumn, SidebarSectionMouse, ThemeDecor, ToastHost, TopBar | +| `scale = RaftScale.Wide` | `viewport = ["wide"]` | DesktopScale, FitToolbar (`members_fine`), PointerDensity | +| `pointerInput = RaftPointerInput.Fine` | `pointer = ["fine"]` (`["fine", "touch"]` for both) | DesktopScale, FitToolbar (`members_fine`), PointerDensity, SidebarSectionMouse | + +Pixel parity notes: + +- `RaftScreenshot` renders every frame with `scene.render()`, that is at time 0, and measures + the content with one frame. `settleFrames = N, frameIntervalMs = 0` does the same: the + capture pass renders N + 1 frames at time 0, and the measure pass keeps the host's count + (0 for `RaftVCaseHost`, one frame). Without `frameIntervalMs = 0` the frames would step + 16 ms and animations would move. +- The host needs a `wide` viewport with the same bounds as `compact`: + `ManifestViewport("wide", 1200, 2400, 2f, optIn = true, sizeClass = VCaseSizeClass.WIDE)`, + and `Wrap` picks `RaftScale.Wide` from `variant.axes.viewport.sizeClass` (Compact + otherwise). Its golden names end in `,wide,fine` / `,wide,touch`. +- `maxWidth` replaces the host's `CaptureSize.WrapContent(1200, 2400)` width only; the + 2400 dp height bound stays. + - **Source line numbers in the manifest.** Editing above a case changes its `source` line, and the manifest check then asks for a `vcase.mode=scan`. This is by design (the manifest must equal the scan), but it is a real cost in review noise. diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@dark,desktop,fine.png b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@dark,desktop,fine.png new file mode 100644 index 0000000..7efa300 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@dark,desktop,fine.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@dark,desktop,touch.png b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@dark,desktop,touch.png new file mode 100644 index 0000000..e5de4e8 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@dark,desktop,touch.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@light,desktop,fine.png b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@light,desktop,fine.png new file mode 100644 index 0000000..14a8751 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@light,desktop,fine.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@light,desktop,touch.png b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@light,desktop,touch.png new file mode 100644 index 0000000..546adf5 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.button.desktop@light,desktop,touch.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.toolbar.wide@dark,phone.png b/samples/compose-desktop/goldens/desktop-skiko/ds.toolbar.wide@dark,phone.png new file mode 100644 index 0000000..d90e3d4 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.toolbar.wide@dark,phone.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.toolbar.wide@light,phone.png b/samples/compose-desktop/goldens/desktop-skiko/ds.toolbar.wide@light,phone.png new file mode 100644 index 0000000..9f48bc0 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.toolbar.wide@light,phone.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.tooltip.open@dark,phone.png b/samples/compose-desktop/goldens/desktop-skiko/ds.tooltip.open@dark,phone.png new file mode 100644 index 0000000..c3a9d13 Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.tooltip.open@dark,phone.png differ diff --git a/samples/compose-desktop/goldens/desktop-skiko/ds.tooltip.open@light,phone.png b/samples/compose-desktop/goldens/desktop-skiko/ds.tooltip.open@light,phone.png new file mode 100644 index 0000000..a741a0c Binary files /dev/null and b/samples/compose-desktop/goldens/desktop-skiko/ds.tooltip.open@light,phone.png differ diff --git a/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/CaptureCases.kt b/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/CaptureCases.kt new file mode 100644 index 0000000..c7db2a2 --- /dev/null +++ b/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/CaptureCases.kt @@ -0,0 +1,70 @@ +package dev.vcase.sample + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.BasicText +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.IntOffset +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Popup +import dev.vcase.VCase + +// Cases that change how they are captured, not only what they show. + +/** + * Wider than the 360dp phone viewport, which bounds a component by default: `maxWidth` lets + * the capture grow to the content instead of cutting it at 360dp. + */ +@VCase("ds.toolbar.wide", maxWidth = 720) +@Composable +fun WideToolbarCase() { + Row(Modifier.width(600.dp), horizontalArrangement = Arrangement.SpaceBetween) { + listOf("Bold", "Italic", "Link", "Quote", "Code", "List").forEach { SampleButton(it, ButtonKind.Secondary) } + } +} + +/** + * A tooltip open under its button. A popup lays itself out a frame after its anchor, so the + * capture waits two settle frames; at time 0 each, so a fade-in would not have started + * (`frameIntervalMs = 0`). + */ +@VCase("ds.tooltip.open", settleFrames = 2, frameIntervalMs = 0) +@Composable +fun TooltipOpenCase() { + Box(Modifier.width(180.dp).height(100.dp)) { + SampleButton("Save") + Popup(offset = IntOffset(0, 112)) { + val c = SampleTheme.colors + Box( + Modifier + .background(c.text, RoundedCornerShape(6.dp)) + .border(1.dp, c.border, RoundedCornerShape(6.dp)) + .padding(horizontal = 8.dp, vertical = 4.dp), + ) { + BasicText("Save changes (Ctrl+S)", style = SampleTheme.body.copy(color = c.canvas)) + } + } + } +} + +/** + * The buttons on a desktop-width window: the `desktop` viewport's size class is `wide`, so + * the host pins the wide type scale; with a mouse (`fine`) the buttons are shorter than with + * a finger. + */ +@VCase("ds.button.desktop", viewport = ["desktop"], pointer = ["fine", "touch"]) +@Composable +fun DesktopButtonsCase() { + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + SampleButton("Cancel", ButtonKind.Secondary) + SampleButton("Save") + } +} diff --git a/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/SampleTheme.kt b/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/SampleTheme.kt index df3f6e1..76a00f9 100644 --- a/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/SampleTheme.kt +++ b/samples/compose-desktop/src/main/kotlin/dev/vcase/sample/SampleTheme.kt @@ -11,7 +11,7 @@ import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.platform.Font import androidx.compose.ui.unit.sp -/** A tiny design system: two palettes, one font, a touch / fine pointer switch. */ +/** A tiny design system: two palettes, one font, a touch / fine pointer switch, a compact / wide scale. */ @Immutable data class SampleColors( val canvas: Color, @@ -50,8 +50,12 @@ val DarkColors = enum class SamplePointer { Touch, Fine } +/** The layout mode an app picks from its window width: wide windows get a larger type scale. */ +enum class SampleScale { Compact, Wide } + val LocalSampleColors = staticCompositionLocalOf { LightColors } val LocalSamplePointer = staticCompositionLocalOf { SamplePointer.Touch } +val LocalSampleScale = staticCompositionLocalOf { SampleScale.Compact } object SampleFonts { private fun bytes(name: String): ByteArray = @@ -72,20 +76,32 @@ object SampleFonts { object SampleTheme { val colors: SampleColors @Composable get() = LocalSampleColors.current val pointer: SamplePointer @Composable get() = LocalSamplePointer.current + val scale: SampleScale @Composable get() = LocalSampleScale.current - val body: TextStyle @Composable get() = TextStyle(fontFamily = SampleFonts.family, fontSize = 14.sp, color = colors.text) - val title: TextStyle @Composable get() = TextStyle(fontFamily = SampleFonts.family, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.text) + val body: TextStyle + @Composable get() = + TextStyle(fontFamily = SampleFonts.family, fontSize = if (scale == SampleScale.Wide) 16.sp else 14.sp, color = colors.text) + val title: TextStyle + @Composable get() = + TextStyle( + fontFamily = SampleFonts.family, + fontSize = if (scale == SampleScale.Wide) 22.sp else 18.sp, + fontWeight = FontWeight.Bold, + color = colors.text, + ) } @Composable fun SampleTheme( dark: Boolean, pointer: SamplePointer = SamplePointer.Touch, + scale: SampleScale = SampleScale.Compact, content: @Composable () -> Unit, ) { CompositionLocalProvider( LocalSampleColors provides if (dark) DarkColors else LightColors, LocalSamplePointer provides pointer, + LocalSampleScale provides scale, content = content, ) } diff --git a/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/RecordVerifyTest.kt b/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/RecordVerifyTest.kt index bec8d85..063050f 100644 --- a/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/RecordVerifyTest.kt +++ b/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/RecordVerifyTest.kt @@ -29,7 +29,9 @@ class RecordVerifyTest { assertTrue(recorded.ok, recorded.describe()) val stems = recorded.summary!!.results.map { it.variant.fileStem }.toSet() // 4 button (2 themes x 2 pointers) + 2 badge + 4 card (2 themes x 2 font scales) + 4 screen (2 x 2 viewports) - assertEquals(14, stems.size, stems.toString()) + // + 2 wide toolbar + 2 tooltip + 4 desktop button (2 themes x 2 pointers) + assertEquals(22, stems.size, stems.toString()) + assertTrue("ds.button.desktop@dark,desktop,fine" in stems) assertTrue("ds.button.variants@dark,phone,fine" in stems) assertTrue("ds.card.default@light,phone,fs1.3" in stems) assertTrue("screen.inbox.empty@dark,wide" in stems) @@ -73,4 +75,31 @@ class RecordVerifyTest { val badge = ImageIO.read(File(dir, "ds.badge.counts@light,phone.png")) assertTrue(badge.width < 400 && badge.height < 200, "${badge.width}x${badge.height}") } + + @Test + fun captureSettings() { + val root = kotlin.io.path.createTempDirectory("vcase-sample").toFile() + val r = + runVCases( + SampleVCaseHost, + VCaseDesktopConfig( + packages = listOf("dev.vcase.sample"), + mode = VCaseMode.Record, + goldensDir = File(root, "g"), + outputDir = File(root, "o"), + manifestFile = null, + filter = listOf("ds.toolbar.wide", "ds.button.desktop"), + ), + ) + assertTrue(r.ok, r.describe()) + val dir = File(root, "g/desktop-skiko") + // maxWidth = 720: 600dp of toolbar + 2 x 16dp of canvas, past the 360dp phone bound. + val toolbar = ImageIO.read(File(dir, "ds.toolbar.wide@light,phone.png")) + assertEquals(1264, toolbar.width) + assertTrue(r.summary!!.results.all { it.meta!!.warnings.isEmpty() }, r.summary!!.results.map { it.meta!!.warnings }.toString()) + // With a mouse the controls are shorter than with a finger. + val desktop = ImageIO.read(File(dir, "ds.button.desktop@light,desktop,fine.png")) + val desktopTouch = ImageIO.read(File(dir, "ds.button.desktop@light,desktop,touch.png")) + assertTrue(desktopTouch.height > desktop.height, "touch ${desktopTouch.height} vs fine ${desktop.height}") + } } diff --git a/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/SampleVCaseHost.kt b/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/SampleVCaseHost.kt index 266b461..2df6104 100644 --- a/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/SampleVCaseHost.kt +++ b/samples/compose-desktop/src/test/kotlin/dev/vcase/sample/SampleVCaseHost.kt @@ -7,6 +7,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import dev.vcase.VCasePointer +import dev.vcase.VCaseSizeClass import dev.vcase.compose.desktop.VCaseHost import dev.vcase.core.ManifestCase import dev.vcase.core.ManifestDefaults @@ -22,8 +23,14 @@ object SampleVCaseHost : VCaseHost { override val defaults = ManifestDefaults( theme = listOf("light", "dark"), - // `wide` is opt-in: only cases that list it (screens) are captured at it. - viewport = listOf(ManifestViewport("phone", 360, 640, 2f), ManifestViewport("wide", 960, 600, 1f, optIn = true)), + // `wide` and `desktop` are opt-in: only cases that list them are captured at them. + // `desktop` declares the wide size class, which the host maps to the wide type scale. + viewport = + listOf( + ManifestViewport("phone", 360, 640, 2f), + ManifestViewport("wide", 960, 600, 1f, optIn = true), + ManifestViewport("desktop", 1280, 800, 2f, optIn = true, sizeClass = VCaseSizeClass.WIDE), + ), locale = listOf("en"), pointer = listOf("touch"), ) @@ -52,7 +59,9 @@ object SampleVCaseHost : VCaseHost { content: @Composable () -> Unit, ) { val pointer = if (variant.axes.pointer == VCasePointer.Fine) SamplePointer.Fine else SamplePointer.Touch - SampleTheme(dark = variant.axes.theme == "dark", pointer = pointer) { + // The layout mode comes from the viewport's size class, never from the capture size. + val scale = if (variant.axes.viewport.sizeClass == VCaseSizeClass.WIDE) SampleScale.Wide else SampleScale.Compact + SampleTheme(dark = variant.axes.theme == "dark", pointer = pointer, scale = scale) { if (variant.case.kind == ManifestCase.KIND_SCREEN) { content() } else { diff --git a/samples/compose-desktop/vcase.manifest.json b/samples/compose-desktop/vcase.manifest.json index 4ec17d5..849a47e 100644 --- a/samples/compose-desktop/vcase.manifest.json +++ b/samples/compose-desktop/vcase.manifest.json @@ -19,6 +19,14 @@ "h": 600, "density": 1.0, "optIn": true + }, + { + "name": "desktop", + "w": 1280, + "h": 800, + "density": 2.0, + "optIn": true, + "sizeClass": "wide" } ], "locale": [ @@ -38,6 +46,23 @@ "parity": [], "divergences": [] }, + { + "id": "ds.button.desktop", + "kind": "component", + "source": "samples/compose-desktop/src/main/kotlin/dev/vcase/sample/CaptureCases.kt:65", + "fixture": null, + "axes": { + "viewport": [ + "desktop" + ], + "pointer": [ + "fine", + "touch" + ] + }, + "parity": [], + "divergences": [] + }, { "id": "ds.button.variants", "kind": "component", @@ -68,6 +93,31 @@ "parity": [], "divergences": [] }, + { + "id": "ds.toolbar.wide", + "kind": "component", + "source": "samples/compose-desktop/src/main/kotlin/dev/vcase/sample/CaptureCases.kt:28", + "fixture": null, + "axes": {}, + "parity": [], + "divergences": [], + "capture": { + "maxWidth": 720 + } + }, + { + "id": "ds.tooltip.open", + "kind": "component", + "source": "samples/compose-desktop/src/main/kotlin/dev/vcase/sample/CaptureCases.kt:41", + "fixture": null, + "axes": {}, + "parity": [], + "divergences": [], + "capture": { + "settleFrames": 2, + "frameIntervalMs": 0 + } + }, { "id": "screen.inbox.empty", "kind": "screen", diff --git a/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCase.kt b/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCase.kt index 6f6fa1f..6ac8325 100644 --- a/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCase.kt +++ b/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCase.kt @@ -35,6 +35,19 @@ package dev.vcase * @property divergences decided differences from other platforms. * @property needsDevice the case can only be rendered on a device or emulator * (gestures, keyboard, system sheets); JVM adapters skip it. + * @property maxWidth bound in dp of a [VCaseKind.Component] capture's width, for content wider + * than the host's bound (a wide gallery); `0` = the host's bound (by default the viewport + * width). Content reaching the bound is cut there and gets a warning. + * @property maxHeight bound in dp of a [VCaseKind.Component] capture's height; `0` = the + * host's bound (by default 4x the viewport height). + * @property settleFrames frames rendered before the captured one, e.g. `2` for a popup or + * tooltip that lays itself out a frame late; `-1` = the host's `settleFrames`. Applies to the + * capture pass; a component's size is measured as the host measures it. + * @property frameIntervalMs fixed time step between rendered frames: frame `i` renders at + * `i * frameIntervalMs` ms. `0` renders every frame at time 0, so state settles but + * animations never start (what `ImageComposeScene.render()` with no time does); a positive + * step lets time-driven animations run, e.g. `settleFrames = 20, frameIntervalMs = 16` for + * a 300 ms fade. `-1` = the host's `frameTimeNanos`. */ @MustBeDocumented @Target(AnnotationTarget.FUNCTION) @@ -52,6 +65,10 @@ public annotation class VCase( val formerly: Array = [], val divergences: Array = [], val needsDevice: Boolean = false, + val maxWidth: Int = 0, + val maxHeight: Int = 0, + val settleFrames: Int = -1, + val frameIntervalMs: Int = -1, ) /** What a case captures; decides the capture size. */ diff --git a/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCaseAxes.kt b/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCaseAxes.kt index 9d31f9e..a0248d1 100644 --- a/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCaseAxes.kt +++ b/vcase-annotations/src/commonMain/kotlin/dev/vcase/VCaseAxes.kt @@ -20,6 +20,16 @@ public object VCaseTheme { public const val DARK: String = "dark" } +/** + * Conventional viewport size classes ([VCaseViewport.sizeClass]): the layout mode an app picks + * from its window width (phone vs desktop type scale, control sizes). Projects may use any + * other names (e.g. Material's `compact` / `medium` / `expanded`). + */ +public object VCaseSizeClass { + public const val COMPACT: String = "compact" + public const val WIDE: String = "wide" +} + /** Pointer axis values: a finger (large targets, no hover) or a mouse / trackpad. */ public enum class VCasePointer(public val value: String) { Touch("touch"), @@ -35,12 +45,18 @@ public enum class VCasePointer(public val value: String) { /** * A named viewport: logical size in dp ([width] x [height]) and pixel [density] * (1dp = density px). Declared once in the project defaults, referenced by [name]. + * + * [sizeClass] is the layout mode the host should pin for this viewport (e.g. + * [VCaseSizeClass.WIDE]), or null when the project does not declare one. It lets a host + * render the wide layout without deriving it from the capture size: a component is captured + * at its content size, which says nothing about the window it is designed for. */ public data class VCaseViewport( val name: String, val width: Int, val height: Int, val density: Float, + val sizeClass: String? = null, ) /** One concrete point of the axis space a case is rendered at. */ diff --git a/vcase-annotations/src/commonTest/kotlin/dev/vcase/VCasePointerTest.kt b/vcase-annotations/src/commonTest/kotlin/dev/vcase/VCasePointerTest.kt index deac2c9..93ccd00 100644 --- a/vcase-annotations/src/commonTest/kotlin/dev/vcase/VCasePointerTest.kt +++ b/vcase-annotations/src/commonTest/kotlin/dev/vcase/VCasePointerTest.kt @@ -17,3 +17,11 @@ class VCasePointerTest { assertEquals(listOf("theme", "viewport"), VCaseAxis.ORDER.take(2)) } } + +class VCaseViewportTest { + @Test + fun sizeClassIsOptional() { + assertEquals(null, VCaseViewport("phone", 390, 844, 3f).sizeClass) + assertEquals(VCaseSizeClass.WIDE, VCaseViewport("desktop", 1280, 800, 2f, VCaseSizeClass.WIDE).sizeClass) + } +} diff --git a/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/DesktopRenderer.kt b/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/DesktopRenderer.kt index 5286d06..c905c58 100644 --- a/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/DesktopRenderer.kt +++ b/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/DesktopRenderer.kt @@ -65,8 +65,9 @@ public object DesktopRenderer { Box(modifier) { host.Wrap(variant) { content() } } } } + val frames = Frames.of(host, variant) val size = - when (val policy = host.captureSize(variant)) { + when (val policy = Frames.captureSize(host, variant)) { CaptureSize.Viewport -> IntSize(px(vp.width, vp.density), px(vp.height, vp.density)) is CaptureSize.WrapContent -> { val maxW = px(policy.maxWidthDp ?: vp.width, vp.density) @@ -77,7 +78,7 @@ public object DesktopRenderer { Box(Modifier.wrapContentSize(Alignment.TopStart, unbounded = false)) { framed(Modifier.onSizeChanged { measured = it }) } - }.use { scene -> renderFrames(host, scene) } + }.use { scene -> frames.render(scene, frames.measureSettle) } check(measured.width > 0 && measured.height > 0) { "${variant.fileStem} rendered nothing" } if (measured.width >= maxW) warnings += "content reaches the max width ($maxW px)" if (measured.height >= maxH) warnings += "content reaches the max height ($maxH px)" @@ -88,17 +89,64 @@ public object DesktopRenderer { return ImageComposeScene(width = size.width, height = size.height, density = density) { framed(Modifier) }.use { scene -> - val image = renderFrames(host, scene) + val image = frames.render(scene, frames.captureSettle) image.encodeToData(EncodedImageFormat.PNG)?.bytes ?: error("PNG encode failed for ${variant.fileStem}") } } - private fun renderFrames( - host: VCaseHost, - scene: ImageComposeScene, - ): org.jetbrains.skia.Image { - repeat(host.settleFrames) { scene.render(host.frameTimeNanos(it)) } - return scene.render(host.frameTimeNanos(host.settleFrames)) + /** + * Frame plan of one variant. The measure pass (pass 1 of a wrap-content capture) renders the + * host's [VCaseHost.settleFrames]; the capture pass renders the case's `settleFrames` when it + * sets one, else the host's. Frame times come from the case's `frameIntervalMs` when it sets + * one, else from [VCaseHost.frameTimeNanos]. A case that sets neither renders exactly as + * before per-case settings existed. + */ + internal class Frames( + val measureSettle: Int, + val captureSettle: Int, + private val time: (Int) -> Long, + ) { + /** Frame times of a pass with [settle] settle frames: the settle frames, then the captured one. */ + fun times(settle: Int): List = (0..settle).map(time) + + fun render( + scene: ImageComposeScene, + settle: Int, + ): org.jetbrains.skia.Image { + repeat(settle) { scene.render(time(it)) } + return scene.render(time(settle)) + } + + companion object { + fun of( + host: VCaseHost, + variant: VCaseVariant, + ): Frames { + val capture = variant.case.capture + return Frames( + measureSettle = host.settleFrames, + captureSettle = capture?.settleFrames ?: host.settleFrames, + time = { i -> capture?.frameTimeNanos(i) ?: host.frameTimeNanos(i) }, + ) + } + + /** The host's policy with the case's `maxWidth` / `maxHeight` in place of its bounds. */ + fun captureSize( + host: VCaseHost, + variant: VCaseVariant, + ): CaptureSize { + val policy = host.captureSize(variant) + val capture = variant.case.capture ?: return policy + return when (policy) { + CaptureSize.Viewport -> policy + is CaptureSize.WrapContent -> + policy.copy( + maxWidthDp = capture.maxWidth ?: policy.maxWidthDp, + maxHeightDp = capture.maxHeight ?: policy.maxHeightDp, + ) + } + } + } } private fun px( diff --git a/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseHost.kt b/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseHost.kt index 534fd6a..3945ba3 100644 --- a/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseHost.kt +++ b/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseHost.kt @@ -24,19 +24,28 @@ public interface VCaseHost { /** Renderer id, also the golden subdirectory. Change it when the rendering stack changes. */ public val renderer: String get() = RENDERER - /** Frames rendered before the captured one (popups lay themselves out a frame late). */ + /** + * Frames rendered before the captured one (popups lay themselves out a frame late). A case's + * `@VCase(settleFrames = ...)` replaces it for that case's capture pass; the measure pass of + * a wrap-content capture always renders this many. + */ public val settleFrames: Int get() = 0 /** * Frame time of frame [index] (0 = first). Every frame time is fixed, so animations and * `withFrameNanos` clocks are deterministic; the default steps 16 ms per frame from 0. + * A case's `@VCase(frameIntervalMs = ...)` replaces it for that case. */ public fun frameTimeNanos(index: Int): Long = index * 16_000_000L /** Hash of the fonts the host loads, written to capture metadata; null if not tracked. */ public val fontsHash: String? get() = null - /** How big the capture is; default: components at content size, screens at the viewport. */ + /** + * How big the capture is; default: components at content size, screens at the viewport. + * A case's `@VCase(maxWidth = ..., maxHeight = ...)` replaces the [CaptureSize.WrapContent] + * bounds returned here. + */ public fun captureSize(variant: VCaseVariant): CaptureSize = if (variant.case.kind == ManifestCase.KIND_SCREEN) CaptureSize.Viewport else CaptureSize.WrapContent() @@ -46,7 +55,11 @@ public interface VCaseHost { /** Called after rendering a variant (also after a failure). */ public fun afterCapture(variant: VCaseVariant) {} - /** Wraps every case: theme for the axis values, background, freeze settings. */ + /** + * Wraps every case: theme for the axis values, background, freeze settings. Pin the + * layout mode from `variant.axes.viewport.sizeClass` (e.g. a wide type scale) and the input + * mode from `variant.axes.pointer`, not from the capture size. + */ @Composable public fun Wrap( variant: VCaseVariant, diff --git a/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseScanner.kt b/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseScanner.kt index 6ebf2e6..551d996 100644 --- a/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseScanner.kt +++ b/vcase-compose-desktop/src/main/kotlin/dev/vcase/compose/desktop/VCaseScanner.kt @@ -5,6 +5,7 @@ import dev.vcase.VCase import dev.vcase.VCaseAxis import dev.vcase.VCaseKind import dev.vcase.core.AxisExpansion +import dev.vcase.core.ManifestCapture import dev.vcase.core.ManifestCase import dev.vcase.core.ManifestDefaults import dev.vcase.core.ManifestDivergence @@ -101,9 +102,19 @@ public object VCaseScanner { }, formerly = a.formerly.toList(), needsDevice = a.needsDevice, + capture = captureOf(a), ) } + /** The annotation's capture settings; its "use the host's" sentinels (0, -1) become null. */ + internal fun captureOf(a: VCase): ManifestCapture? = + ManifestCapture( + maxWidth = a.maxWidth.takeIf { it != 0 }, + maxHeight = a.maxHeight.takeIf { it != 0 }, + settleFrames = a.settleFrames.takeIf { it != -1 }, + frameIntervalMs = a.frameIntervalMs.takeIf { it != -1 }, + ).takeUnless { it.isEmpty } + private fun annotationOf(p: ComposablePreview): VCase { val cls = Class.forName(p.declaringClass, false, Thread.currentThread().contextClassLoader ?: VCase::class.java.classLoader) return cls.declaredMethods.firstNotNullOfOrNull { m -> m.takeIf { it.name == p.methodName }?.getAnnotation(VCase::class.java) } diff --git a/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/RunVCasesTest.kt b/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/RunVCasesTest.kt index 64dc2c4..1bde5e7 100644 --- a/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/RunVCasesTest.kt +++ b/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/RunVCasesTest.kt @@ -5,7 +5,10 @@ import androidx.compose.foundation.layout.Box import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color +import dev.vcase.core.AxisExpansion import dev.vcase.core.ImageCompare +import dev.vcase.core.ManifestCapture +import dev.vcase.core.ManifestCase import dev.vcase.core.ManifestDefaults import dev.vcase.core.ManifestViewport import dev.vcase.core.VCaseJson @@ -25,7 +28,7 @@ object TestHost : VCaseHost { override val defaults = ManifestDefaults( theme = listOf("light", "dark"), - viewport = listOf(ManifestViewport("tiny", 20, 12, 2f)), + viewport = listOf(ManifestViewport("tiny", 20, 12, 2f), ManifestViewport("tiny-wide", 20, 12, 2f, optIn = true, sizeClass = "wide")), locale = listOf("en"), pointer = listOf("touch"), ) @@ -45,7 +48,21 @@ class RunVCasesTest { @Test fun scanFindsCustomAnnotationIncludingPrivateFunctions() { val cases = VCaseScanner.scan(pkg, "src/test/kotlin") - assertEquals(listOf("test.device.only", "test.screen.full", "test.square.plain", "test.square.pointer"), cases.map { it.entry.id }) + assertEquals( + listOf( + "test.bar.bounded", + "test.bar.wide", + "test.device.only", + "test.frames.clock", + "test.frames.first", + "test.frames.still", + "test.screen.full", + "test.square.plain", + "test.square.pointer", + "test.square.size-class", + ), + cases.map { it.entry.id }, + ) val plain = cases.first { it.entry.id == "test.square.plain" }.entry assertTrue(plain.source.startsWith("src/test/kotlin/dev/vcase/compose/desktop/cases/TestCases.kt:"), plain.source) assertEquals(listOf("web:test.square.plain"), plain.parity) @@ -102,6 +119,73 @@ class RunVCasesTest { assertTrue(File(root, "out/report/index.html").readText().contains("test.square.plain@dark,tiny")) } + @Test + fun scanReadsCaptureSettings() { + val cases = VCaseScanner.scan(pkg).associate { it.entry.id to it.entry } + assertEquals(null, cases.getValue("test.square.plain").capture) + assertEquals(null, cases.getValue("test.frames.first").capture) + assertEquals(ManifestCapture(maxWidth = 40), cases.getValue("test.bar.wide").capture) + assertEquals(ManifestCapture(settleFrames = 3, frameIntervalMs = 0), cases.getValue("test.frames.still").capture) + assertEquals(ManifestCapture(settleFrames = 3, frameIntervalMs = 100), cases.getValue("test.frames.clock").capture) + } + + @Test + fun framePlan() { + val defaults = TestHost.defaults + fun variant(capture: ManifestCapture?) = AxisExpansion.expand(ManifestCase(id = "ds.a.b", source = "x", capture = capture), defaults).first() + // Nothing set: the host's frames, as before. + val plain = DesktopRenderer.Frames.of(TestHost, variant(null)) + assertEquals(listOf(0L), plain.times(plain.captureSettle)) + val still = DesktopRenderer.Frames.of(TestHost, variant(ManifestCapture(settleFrames = 2, frameIntervalMs = 0))) + assertEquals(0, still.measureSettle) + assertEquals(listOf(0L, 0L, 0L), still.times(still.captureSettle)) + val stepped = DesktopRenderer.Frames.of(TestHost, variant(ManifestCapture(settleFrames = 2))) + assertEquals(listOf(0L, 16_000_000L, 32_000_000L), stepped.times(stepped.captureSettle)) + // The case's bounds replace the host's; unset ones keep it. + assertEquals(CaptureSize.WrapContent(1600, null), DesktopRenderer.Frames.captureSize(TestHost, variant(ManifestCapture(maxWidth = 1600)))) + assertEquals(CaptureSize.WrapContent(), DesktopRenderer.Frames.captureSize(TestHost, variant(null))) + } + + @Test + fun captureSettingsRender() { + val root = kotlin.io.path.createTempDirectory("vcase-desktop").toFile() + val r = + runVCases( + TestHost, + VCaseDesktopConfig( + packages = pkg, + mode = VCaseMode.Record, + goldensDir = File(root, "g"), + outputDir = File(root, "o"), + manifestFile = null, + filter = listOf("test.bar.*", "test.frames.*", "test.square.size-class"), + ), + ) + assertTrue(r.ok, r.describe()) + val dir = File(root, "g/desktop-skiko") + fun png(stem: String) = ImageIO.read(File(dir, "$stem.png")) + + // maxWidth: the whole 30dp bar; without it the capture stops at the 20dp viewport. + assertEquals(60 to 4, png("test.bar.wide@light,tiny").let { it.width to it.height }) + assertEquals(40, png("test.bar.bounded@light,tiny").width) + val warned = r.summary!!.results.first { it.variant.fileStem == "test.bar.bounded@light,tiny" }.meta!!.warnings + assertTrue(warned.any { "max width" in it }, warned.toString()) + + val red = 0xFFFF0000.toInt() + val blue = 0xFF0000FF.toInt() + fun probe(stem: String) = png(stem).let { it.getRGB(1, 1) to it.getRGB(5, 1) } + // One frame at time 0: neither square has seen frames. + assertEquals(red to red, probe("test.frames.first@light,tiny")) + // Three settle frames at time 0: frames arrived, the clock stayed at 0. + assertEquals(blue to red, probe("test.frames.still@light,tiny")) + // Three settle frames 100 ms apart: the clock moved. + assertEquals(blue to blue, probe("test.frames.clock@light,tiny")) + + // The size class reaches the case; the pointer axis names the file. + assertEquals(6, png("test.square.size-class@light,tiny,fine").width) + assertEquals(12, png("test.square.size-class@light,tiny-wide,fine").width) + } + @Test fun manifestDriftFailsVerify() { val root = kotlin.io.path.createTempDirectory("vcase-desktop").toFile() diff --git a/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/cases/CaptureCases.kt b/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/cases/CaptureCases.kt new file mode 100644 index 0000000..cce3d02 --- /dev/null +++ b/vcase-compose-desktop/src/test/kotlin/dev/vcase/compose/desktop/cases/CaptureCases.kt @@ -0,0 +1,85 @@ +package dev.vcase.compose.desktop.cases + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.size +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableLongStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.withFrameNanos +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.unit.dp +import dev.vcase.VCase +import dev.vcase.VCaseSizeClass +import dev.vcase.compose.desktop.LocalVCaseVariant + +// Cases for the per-case capture settings: a bound wider than the viewport, settle frames and +// the frame clock, and a viewport size class. + +/** 30dp wide: more than the 20dp `tiny` viewport, inside its own 40dp bound. */ +@VCase("test.bar.wide", theme = ["light"], maxWidth = 40) +@Composable +fun WideBar() { + Box(Modifier.size(30.dp, 2.dp).background(Color.Red)) +} + +/** The same bar on the default bound: cut at the viewport width. */ +@VCase("test.bar.bounded", theme = ["light"]) +@Composable +fun BoundedBar() { + Box(Modifier.size(30.dp, 2.dp).background(Color.Red)) +} + +/** + * Two 2dp squares: the left one turns blue once two frames have reached the content, the right + * one once a frame at 100 ms or later has. + */ +@Composable +private fun FrameProbe() { + var frames by remember { mutableIntStateOf(0) } + var lastNanos by remember { mutableLongStateOf(0L) } + LaunchedEffect(Unit) { + while (true) { + withFrameNanos { + frames++ + lastNanos = it + } + } + } + Row { + Box(Modifier.size(2.dp).background(if (frames >= 2) Color.Blue else Color.Red)) + Box(Modifier.size(2.dp).background(if (lastNanos >= 100_000_000L) Color.Blue else Color.Red)) + } +} + +@VCase("test.frames.first", theme = ["light"]) +@Composable +fun FramesFirst() { + FrameProbe() +} + +@VCase("test.frames.still", theme = ["light"], settleFrames = 3, frameIntervalMs = 0) +@Composable +fun FramesStill() { + FrameProbe() +} + +@VCase("test.frames.clock", theme = ["light"], settleFrames = 3, frameIntervalMs = 100) +@Composable +fun FramesClock() { + FrameProbe() +} + +/** 6dp on a wide viewport, 3dp otherwise. */ +@VCase("test.square.size-class", theme = ["light"], viewport = ["tiny", "tiny-wide"], pointer = ["fine"]) +@Composable +fun SizeClassSquare() { + val wide = LocalVCaseVariant.current?.axes?.viewport?.sizeClass == VCaseSizeClass.WIDE + Box(Modifier.size(if (wide) 6.dp else 3.dp).background(Color.Blue)) +} diff --git a/vcase-core/src/main/kotlin/dev/vcase/core/Axes.kt b/vcase-core/src/main/kotlin/dev/vcase/core/Axes.kt index 89cf566..254c9f8 100644 --- a/vcase-core/src/main/kotlin/dev/vcase/core/Axes.kt +++ b/vcase-core/src/main/kotlin/dev/vcase/core/Axes.kt @@ -55,7 +55,7 @@ public object AxisExpansion { val viewports = (case.axes[VCaseAxis.VIEWPORT] ?: defaults.defaultViewports().map { it.name }).map { name -> val v = defaults.viewport(name) ?: throw IllegalArgumentException("${case.id}: unknown viewport '$name'") - VCaseViewport(v.name, v.w, v.h, v.density) + VCaseViewport(v.name, v.w, v.h, v.density, v.sizeClass) } val locales = case.axes[VCaseAxis.LOCALE] ?: defaults.locale val pointers = diff --git a/vcase-core/src/main/kotlin/dev/vcase/core/Manifest.kt b/vcase-core/src/main/kotlin/dev/vcase/core/Manifest.kt index 579f2b9..8a9b980 100644 --- a/vcase-core/src/main/kotlin/dev/vcase/core/Manifest.kt +++ b/vcase-core/src/main/kotlin/dev/vcase/core/Manifest.kt @@ -51,6 +51,10 @@ public data class ManifestDefaults( * the default expansion unless [optIn] is set: then only cases that name it use it * (e.g. `wide` for screens only). [optIn] is an addition to the design-doc schema and is * omitted from the JSON while false. + * + * [sizeClass] is the layout mode the host pins for this viewport (`compact`, `wide`, ...; + * see `VCaseSizeClass`), handed to the host as `variant.axes.viewport.sizeClass`. Omitted + * from the JSON while null. */ @OptIn(ExperimentalSerializationApi::class) @Serializable @@ -60,6 +64,7 @@ public data class ManifestViewport( val h: Int, val density: Float, @EncodeDefault(EncodeDefault.Mode.NEVER) val optIn: Boolean = false, + @EncodeDefault(EncodeDefault.Mode.NEVER) val sizeClass: String? = null, ) @OptIn(ExperimentalSerializationApi::class) @@ -77,6 +82,8 @@ public data class ManifestCase( val divergences: List = emptyList(), @EncodeDefault(EncodeDefault.Mode.NEVER) val formerly: List = emptyList(), @EncodeDefault(EncodeDefault.Mode.NEVER) val needsDevice: Boolean = false, + /** Per-case capture settings; omitted from the JSON while the case uses the host's. */ + @EncodeDefault(EncodeDefault.Mode.NEVER) val capture: ManifestCapture? = null, ) { public companion object { public const val KIND_COMPONENT: String = "component" @@ -84,6 +91,29 @@ public data class ManifestCase( } } +/** + * How one case is captured, where it differs from the host. Every field is optional (null = + * the host's value) and omitted from the JSON while null; a case that sets none has no + * `capture` object at all. + */ +@OptIn(ExperimentalSerializationApi::class) +@Serializable +public data class ManifestCapture( + /** Bound in dp of a component capture's width (content wider than the host's bound). */ + @EncodeDefault(EncodeDefault.Mode.NEVER) val maxWidth: Int? = null, + /** Bound in dp of a component capture's height. */ + @EncodeDefault(EncodeDefault.Mode.NEVER) val maxHeight: Int? = null, + /** Frames rendered before the captured one. */ + @EncodeDefault(EncodeDefault.Mode.NEVER) val settleFrames: Int? = null, + /** Frame `i` renders at `i * frameIntervalMs` ms; 0 = every frame at time 0. */ + @EncodeDefault(EncodeDefault.Mode.NEVER) val frameIntervalMs: Int? = null, +) { + public val isEmpty: Boolean get() = maxWidth == null && maxHeight == null && settleFrames == null && frameIntervalMs == null + + /** Frame time of frame [index] in nanoseconds, or null when the host decides. */ + public fun frameTimeNanos(index: Int): Long? = frameIntervalMs?.let { index.toLong() * it * 1_000_000L } +} + @OptIn(ExperimentalSerializationApi::class) @Serializable public data class ManifestDivergence( diff --git a/vcase-core/src/main/kotlin/dev/vcase/core/ManifestDiff.kt b/vcase-core/src/main/kotlin/dev/vcase/core/ManifestDiff.kt index 8cbec06..665ff54 100644 --- a/vcase-core/src/main/kotlin/dev/vcase/core/ManifestDiff.kt +++ b/vcase-core/src/main/kotlin/dev/vcase/core/ManifestDiff.kt @@ -64,6 +64,7 @@ public data class ManifestDiff( if (a.divergences != b.divergences) add("divergences") if (a.formerly != b.formerly) add("formerly") if (a.needsDevice != b.needsDevice) add("needsDevice") + if (a.capture != b.capture) add("capture") } if (fields.isNotEmpty()) { changed[id] = fields diff --git a/vcase-core/src/main/kotlin/dev/vcase/core/ManifestValidation.kt b/vcase-core/src/main/kotlin/dev/vcase/core/ManifestValidation.kt index 9087d41..6ce1823 100644 --- a/vcase-core/src/main/kotlin/dev/vcase/core/ManifestValidation.kt +++ b/vcase-core/src/main/kotlin/dev/vcase/core/ManifestValidation.kt @@ -13,6 +13,7 @@ public object ManifestValidation { if (d.pointer.isEmpty()) out += "defaults.pointer is empty" d.viewport.groupBy { it.name }.filterValues { it.size > 1 }.keys.forEach { out += "viewport '$it' declared twice" } d.viewport.filter { it.w <= 0 || it.h <= 0 || it.density <= 0f }.forEach { out += "viewport '${it.name}' must have positive w, h, density" } + d.viewport.filter { it.sizeClass != null && it.sizeClass.isBlank() }.forEach { out += "viewport '${it.name}': sizeClass is blank (omit it instead)" } manifest.cases.groupBy { it.id }.filterValues { it.size > 1 }.forEach { (id, list) -> out += "id '$id' declared ${list.size} times: ${list.joinToString { it.source }}" @@ -34,11 +35,27 @@ public object ManifestValidation { } if (dv.why.isBlank()) out += "${case.id}: divergence with '${dv.with}' needs a why" } + case.capture?.let { out += captureProblems(case, it) } runCatching { AxisExpansion.expand(case, d) }.onFailure { out += it.message ?: it.toString() } } return out } + private fun captureProblems( + case: ManifestCase, + c: ManifestCapture, + ): List = + buildList { + if (c.isEmpty) add("${case.id}: capture is empty (omit it instead)") + c.maxWidth?.let { if (it <= 0) add("${case.id}: capture.maxWidth must be positive, is $it") } + c.maxHeight?.let { if (it <= 0) add("${case.id}: capture.maxHeight must be positive, is $it") } + c.settleFrames?.let { if (it < 0) add("${case.id}: capture.settleFrames must be 0 or more, is $it") } + c.frameIntervalMs?.let { if (it < 0) add("${case.id}: capture.frameIntervalMs must be 0 or more, is $it") } + if (case.kind == ManifestCase.KIND_SCREEN && (c.maxWidth != null || c.maxHeight != null)) { + add("${case.id}: maxWidth / maxHeight bound a component's content size; a screen is captured at its viewport") + } + } + public fun requireValid(manifest: VCaseManifest) { val problems = problems(manifest) require(problems.isEmpty()) { "invalid vcase manifest:\n" + problems.joinToString("\n") { " - $it" } } diff --git a/vcase-core/src/test/kotlin/dev/vcase/core/CaseCaptureTest.kt b/vcase-core/src/test/kotlin/dev/vcase/core/CaseCaptureTest.kt new file mode 100644 index 0000000..9b05c0e --- /dev/null +++ b/vcase-core/src/test/kotlin/dev/vcase/core/CaseCaptureTest.kt @@ -0,0 +1,69 @@ +package dev.vcase.core + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +/** Per-case capture settings (`capture`) and viewport size classes: optional, absent while unset. */ +class CaseCaptureTest { + private val wide = ManifestViewport("wide", 1200, 2400, 2f, optIn = true, sizeClass = "wide") + private val defaults = DEFAULTS.copy(viewport = DEFAULTS.viewport + wide) + + @Test + fun unsetSettingsAreNotWritten() { + val text = VCaseJson.encode(VCaseManifest(project = "p", defaults = DEFAULTS, cases = listOf(case("ds.a.b")))) + assertFalse("capture" in text, text) + assertFalse("sizeClass" in text, text) + } + + @Test + fun captureAndSizeClassRoundTrip() { + val c = case("ds.a.b", mapOf("viewport" to listOf("wide"))).copy(capture = ManifestCapture(maxWidth = 1600, settleFrames = 2, frameIntervalMs = 0)) + val m = VCaseManifest(project = "p", defaults = defaults, cases = listOf(c)) + val text = VCaseJson.encode(m) + assertTrue("\"sizeClass\": \"wide\"" in text, text) + assertTrue("\"maxWidth\": 1600" in text && "\"settleFrames\": 2" in text && "\"frameIntervalMs\": 0" in text, text) + assertFalse("maxHeight" in text, text) + assertEquals(m, VCaseJson.decodeManifest(text)) + assertTrue(ManifestValidation.problems(m).isEmpty(), ManifestValidation.problems(m).toString()) + } + + @Test + fun sizeClassReachesTheVariant() { + val v = AxisExpansion.expand(case("ds.a.b", mapOf("viewport" to listOf("phone", "wide"))), defaults) + assertEquals(listOf(null, "wide"), v.filter { it.axes.theme == "light" }.map { it.axes.viewport.sizeClass }) + // The size class is not an axis of its own: names and metadata are unchanged. + assertEquals(listOf("light,phone", "light,wide", "dark,phone", "dark,wide"), v.map { it.name }) + assertFalse("sizeClass" in v[1].axisMap()) + } + + @Test + fun frameTimes() { + assertEquals(listOf(0L, 0L, 0L), (0..2).map { ManifestCapture(frameIntervalMs = 0).frameTimeNanos(it) }) + assertEquals(listOf(0L, 16_000_000L, 32_000_000L), (0..2).map { ManifestCapture(frameIntervalMs = 16).frameTimeNanos(it) }) + assertEquals(null, ManifestCapture(settleFrames = 2).frameTimeNanos(1)) + } + + @Test + fun validationOfCaptureSettings() { + fun problems(vararg cases: ManifestCase) = ManifestValidation.problems(VCaseManifest(project = "p", defaults = defaults, cases = cases.toList())) + assertEquals(1, problems(case("ds.a.b").copy(capture = ManifestCapture())).size) + assertEquals(1, problems(case("ds.a.b").copy(capture = ManifestCapture(maxWidth = 0))).size) + assertEquals(1, problems(case("ds.a.b").copy(capture = ManifestCapture(maxHeight = -5))).size) + assertEquals(1, problems(case("ds.a.b").copy(capture = ManifestCapture(settleFrames = -1))).size) + assertEquals(1, problems(case("ds.a.b").copy(capture = ManifestCapture(frameIntervalMs = -1))).size) + assertEquals(1, problems(case("screen.a.b").copy(kind = ManifestCase.KIND_SCREEN, capture = ManifestCapture(maxWidth = 1600))).size) + assertTrue(problems(case("screen.a.b").copy(kind = ManifestCase.KIND_SCREEN, capture = ManifestCapture(settleFrames = 2))).isEmpty()) + val blank = ManifestValidation.problems(VCaseManifest(project = "p", defaults = DEFAULTS.copy(viewport = DEFAULTS.viewport + wide.copy(sizeClass = " ")), cases = emptyList())) + assertEquals(1, blank.size, blank.toString()) + } + + @Test + fun changedCaptureIsAManifestChange() { + val a = VCaseManifest(project = "p", defaults = DEFAULTS, cases = listOf(case("ds.a.b"))) + val b = a.copy(cases = listOf(case("ds.a.b").copy(capture = ManifestCapture(settleFrames = 2)))) + assertEquals(mapOf("ds.a.b" to listOf("capture")), ManifestDiff.between(a, b).changed) + assertEquals(listOf("defaults"), ManifestDiff.between(a, a.copy(defaults = defaults)).header) + } +}