From 1591625089ea924f28bcadc3cffd5aefa7ac15eb Mon Sep 17 00:00:00 2001 From: Dwiki Riyadi Date: Tue, 10 Nov 2026 10:53:39 +0700 Subject: [PATCH] docs: a real usage site (#89) docs/usage was a single "not released yet" page. It is now a documentation site: getting started (installation, a quick start on the sample list screen), how the layers fit together, one page per module, guides (testing, a production setup, paging with Camouflage), a changelog, an FAQ and links, with offline search. Every sample is real code. A `// sample: #` block is copied from a compiled or analyzed file in the libraries by scripts/sync_samples.py, which also fails on a block that has drifted. The language switch now drives every Kotlin/Dart code group (the scaffold's LangTabs ignored it), and the home page language menu is no longer clipped: both fixes are Camouflage's (srctool/camouflage#69). Closes srctool/sinew-kotlin#89 Co-Authored-By: Claude Sonnet 5.5 --- docs/usage/README.md | 16 + docs/usage/docs/concepts/_category_.json | 4 + .../docs/concepts/how-it-fits-together.mdx | 48 ++ .../docs/getting-started/_category_.json | 4 + .../docs/getting-started/installation.mdx | 88 +++ .../docs/getting-started/quick-start.mdx | 170 ++++++ docs/usage/docs/guides/_category_.json | 4 + .../docs/guides/paging-with-camouflage.mdx | 96 +++ docs/usage/docs/guides/production-setup.mdx | 88 +++ docs/usage/docs/guides/testing.mdx | 82 +++ docs/usage/docs/index.md | 17 - docs/usage/docs/index.mdx | 45 ++ docs/usage/docs/modules/_category_.json | 4 + docs/usage/docs/modules/camouflage.mdx | 55 ++ docs/usage/docs/modules/devtools.mdx | 53 ++ docs/usage/docs/modules/exception.mdx | 113 ++++ docs/usage/docs/modules/index.mdx | 25 + docs/usage/docs/modules/l10n.mdx | 38 ++ docs/usage/docs/modules/models.mdx | 117 ++++ docs/usage/docs/modules/network.mdx | 94 +++ docs/usage/docs/modules/paging.mdx | 64 ++ docs/usage/docs/modules/presentation.mdx | 77 +++ docs/usage/docs/modules/security.mdx | 78 +++ docs/usage/docs/modules/storage.mdx | 65 +++ docs/usage/docs/modules/testing.mdx | 18 + docs/usage/docs/resources/_category_.json | 4 + docs/usage/docs/resources/changelog.mdx | 18 + docs/usage/docs/resources/faq.mdx | 39 ++ docs/usage/docs/resources/links.mdx | 16 + docs/usage/docusaurus.config.ts | 21 +- docs/usage/package-lock.json | 545 ++++++++++++++++++ docs/usage/package.json | 1 + docs/usage/scripts/sync_samples.py | 72 +++ .../src/components/LangContent/index.tsx | 3 +- docs/usage/src/components/LangTabs/index.tsx | 95 +-- .../src/components/LanguageSwitcher/index.tsx | 3 +- docs/usage/src/pages/index.module.css | 5 +- docs/usage/src/theme/MDXComponents.tsx | 3 +- 38 files changed, 2221 insertions(+), 67 deletions(-) create mode 100644 docs/usage/docs/concepts/_category_.json create mode 100644 docs/usage/docs/concepts/how-it-fits-together.mdx create mode 100644 docs/usage/docs/getting-started/_category_.json create mode 100644 docs/usage/docs/getting-started/installation.mdx create mode 100644 docs/usage/docs/getting-started/quick-start.mdx create mode 100644 docs/usage/docs/guides/_category_.json create mode 100644 docs/usage/docs/guides/paging-with-camouflage.mdx create mode 100644 docs/usage/docs/guides/production-setup.mdx create mode 100644 docs/usage/docs/guides/testing.mdx delete mode 100644 docs/usage/docs/index.md create mode 100644 docs/usage/docs/index.mdx create mode 100644 docs/usage/docs/modules/_category_.json create mode 100644 docs/usage/docs/modules/camouflage.mdx create mode 100644 docs/usage/docs/modules/devtools.mdx create mode 100644 docs/usage/docs/modules/exception.mdx create mode 100644 docs/usage/docs/modules/index.mdx create mode 100644 docs/usage/docs/modules/l10n.mdx create mode 100644 docs/usage/docs/modules/models.mdx create mode 100644 docs/usage/docs/modules/network.mdx create mode 100644 docs/usage/docs/modules/paging.mdx create mode 100644 docs/usage/docs/modules/presentation.mdx create mode 100644 docs/usage/docs/modules/security.mdx create mode 100644 docs/usage/docs/modules/storage.mdx create mode 100644 docs/usage/docs/modules/testing.mdx create mode 100644 docs/usage/docs/resources/_category_.json create mode 100644 docs/usage/docs/resources/changelog.mdx create mode 100644 docs/usage/docs/resources/faq.mdx create mode 100644 docs/usage/docs/resources/links.mdx create mode 100644 docs/usage/scripts/sync_samples.py diff --git a/docs/usage/README.md b/docs/usage/README.md index d360636..4e28d3d 100644 --- a/docs/usage/README.md +++ b/docs/usage/README.md @@ -9,3 +9,19 @@ npm run build ``` The Contributing link goes to the contributor site (docs/internal), set with `SINEW_INTERNAL_URL` (default `http://localhost:3000`). This site's own address is `SINEW_USAGE_URL` (default `http://localhost:3001`). + +## Code samples + +Every sample on the site is real code. A fenced block whose first line is `// sample: #` is a copy of a region (between `// region ` and `// endregion` lines) of a file in `kotlin-lib/` or `dart-lib/`: + +- Kotlin samples live in `kotlin-lib/sample/docs`, a module CI compiles, whose tests CI runs, and in the sample app. +- Dart samples live in the example app and in each package's `example/`, which the analyzer covers. + +```bash +python3 docs/usage/scripts/sync_samples.py # rewrites every block from its source +python3 docs/usage/scripts/sync_samples.py --check # exits 1 when a block differs from its source +``` + +Change a sample in its library, run the script, and commit the result. Run `--check` before a release: it fails on a block that no longer matches. + +The pages' structure and prose are plain MDX in `docs/`; the language switch drives every `` group. diff --git a/docs/usage/docs/concepts/_category_.json b/docs/usage/docs/concepts/_category_.json new file mode 100644 index 0000000..1d3167d --- /dev/null +++ b/docs/usage/docs/concepts/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Concepts", + "position": 3 +} diff --git a/docs/usage/docs/concepts/how-it-fits-together.mdx b/docs/usage/docs/concepts/how-it-fits-together.mdx new file mode 100644 index 0000000..c30cb06 --- /dev/null +++ b/docs/usage/docs/concepts/how-it-fits-together.mdx @@ -0,0 +1,48 @@ +--- +title: How it fits together +sidebar_label: How it fits together +--- + +# How it fits together + +## The layers + +A screen's work flows through four layers. Each one has a short code that ends up in every failure, so a support report points at the exact call. + +```mermaid +flowchart TB + Page["Page (renders state, sends events)"] --> VM["View model or notifier (VM)"] + VM --> UC["Use case (UC)"] + UC --> Repo["Repository (R)"] + Repo --> Api["API or database"] + Api -. "Remote or Entity" .-> Repo + Repo -. "Domain, in a Result" .-> UC + UC -. "Result" .-> VM + VM -. "state and effects" .-> Page +``` + +- The **repository** talks to the API or the database. It maps what it gets (`Remote`, `Entity`) to a **domain** model. +- Everything returns a `Result`: a `Success` that carries the backend's message, or a typed `Failure`. +- The **view model** turns a `Result` into **state** (what the page renders) and **effects** (one-time reactions). + +## A failure is translated once + +Where a call can fail, a **guard** wraps it (`processApiCall`, `processStorageCall`, `processCall`). It turns whatever was thrown into a typed `SinewException`, once, with the code of that exact place: `module-layer-function-type`, for example `ORD-R-load-DF`. Layers above only pass it along. + +A failure keeps its text as data: a message key with arguments, or the backend's own text. The page renders it, every time it builds, in the current language, so a language switch updates an error already on screen. + +## State and effects + +State is what the page renders. Effects are one-time reactions, such as a snackbar or a navigation, and are never state, so a rebuild can't repeat them. An effect is delivered once, to one listener, and held until there is one. + +## Models stay apart + +A `Domain` model is what the app needs, in business language. A `Remote` is what the backend sends, shaped like its JSON, and an `Entity` is what is stored on the device. A backend that renames a field touches one file, the `Remote`, and nothing above it. + +## What Sinew leaves to you + +Sinew ships the mechanism, and your app ships the configuration: the base URL, the paths, the models, the strings, the screens. It never assumes a backend's JSON keys. + +## Next + +[Modules](/docs/modules) has one page per module, with its API and its edge cases. diff --git a/docs/usage/docs/getting-started/_category_.json b/docs/usage/docs/getting-started/_category_.json new file mode 100644 index 0000000..fd94d1f --- /dev/null +++ b/docs/usage/docs/getting-started/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Getting started", + "position": 2 +} diff --git a/docs/usage/docs/getting-started/installation.mdx b/docs/usage/docs/getting-started/installation.mdx new file mode 100644 index 0000000..fdd773e --- /dev/null +++ b/docs/usage/docs/getting-started/installation.mdx @@ -0,0 +1,88 @@ +--- +title: Installation +sidebar_label: Installation +--- + +# Installation + +Sinew is a set of small packages. Add the ones you need; every one is released at the same version. + +## Requirements + +| | Kotlin | Dart | +|---|---|---| +| Language | Kotlin 2.4, JDK 17 | Dart 3.13 | +| Platforms | Android (`minSdk` 24), iOS, JVM desktop, wasm | Android, iOS, web, macOS, Windows, Linux | +| Tools | Xcode for iOS | Flutter 3.47, and CMake for `sinew_security` | + +## Add the packages + + + + +Add the BOM once, then the modules you need, with no versions: + +```kotlin +dependencies { + implementation(platform("com.srctool.sinew:sinew-bom:1.0.0")) + implementation("com.srctool.sinew:sinew-models") + implementation("com.srctool.sinew:sinew-exception") + implementation("com.srctool.sinew:sinew-network") + implementation("com.srctool.sinew:sinew-paging") + implementation("com.srctool.sinew:sinew-viewmodel") + testImplementation("com.srctool.sinew:sinew-testing") +} +``` + +In a Kotlin Multiplatform module, put the same lines in the `commonMain` dependencies. `sinew-testing` belongs in tests only. + + + + +```sh +flutter pub add sinew_models sinew_exception sinew_network sinew_paging sinew_riverpod +flutter pub add --dev sinew_testing +``` + +`sinew_models`, `sinew_exception`, `sinew_paging` and `sinew_presentation` are plain Dart and also work in a Dart-only project (`dart pub add`). `sinew_testing` belongs in `dev_dependencies` only. + + + + +:::note[Sinew's own dependency on Camouflage] + +Only `sinew-camouflage` (`sinew_camouflage`) depends on [Camouflage](https://github.com/srctool/camouflage). Leave it out and you never see Camouflage. + +::: + +## Developer tools: one artifact per build + +Devtools never reach a production build. The app chooses, per build: + + + + +On Android, each variant is given one artifact, and a new variant has to choose: + +```kotlin +// sample: kotlin-lib/sample/androidApp/build.gradle.kts#devtools-variants +"productionDebugImplementation"(projects.sinewDevtoolsUi) +"stagingImplementation"(projects.sinewDevtoolsUi) +"productionReleaseImplementation"(projects.sinewDevtoolsNoop) +``` + +On iOS, desktop and web, the convention is a Gradle property that picks the artifact (the sample uses `-Psinew.devtools=true` for the real one, and the no-op without it), so a build that forgets it fails safe. + + + + +There is no separate artifact: both packages are in `pubspec.yaml`, and a `const` removes them from a production build. Build a staging release with `--dart-define=SINEW_FLAVOR=staging`; a production build, or one with no define, has none. See [the production guide](/docs/guides/production-setup). + + + + +## Platform setup + +- **`sinew_security` on Flutter** compiles BoringSSL for `webcrypto`, so every machine that builds the app needs **CMake** on its `PATH`. The first build per platform takes a minute or two longer. +- **Biometrics** need a little native setup on each platform: see [Security](/docs/modules/security). +- **Secure storage** on macOS needs the Keychain Sharing entitlement. diff --git a/docs/usage/docs/getting-started/quick-start.mdx b/docs/usage/docs/getting-started/quick-start.mdx new file mode 100644 index 0000000..e483cb5 --- /dev/null +++ b/docs/usage/docs/getting-started/quick-start.mdx @@ -0,0 +1,170 @@ +--- +title: Quick start +sidebar_label: Quick start +--- + +# Quick start + +A list that loads its first page, loads more at the end, shows a retry when a page fails, and refreshes. This is the sample app, which runs on every platform: its backend is in memory, and its second page fails once, so you see every state. + +The page sends **events** (it opened, the list neared its end, retry was tapped); a pure function turns each event into the **work** to run; the work updates the **state**. The page only renders state. + +## 1. The view model + + + + +```kotlin +// sample: kotlin-lib/sample/shared/src/commonMain/kotlin/com/srctool/sinew/sample/OrderListViewModel.kt#view-model +class OrderListViewModel(backend: OrderBackend) : + EventActionViewModel(OrderListState()) { + private val pager = Pager.offset(itemKey = { it.id }) { page, _ -> backend.orders(page) } + + override fun mapEventToAction(event: OrderListEvent): LoadOrders? = when (event) { + OrderListEvent.Opened -> LoadOrders(LoadType.Initial) // the pager runs Initial once per query + OrderListEvent.EndReached -> if (currentState.orders.canLoadMore) LoadOrders(LoadType.More) else null + OrderListEvent.RetryTapped -> LoadOrders(currentState.orders.retryType) + OrderListEvent.Refreshed -> LoadOrders(LoadType.Refresh) + } + + override suspend fun onAction(action: LoadOrders) { + pager.load(action.type, currentState.orders) { next -> setState { copy(orders = next) } } + } +} +``` + + + + +```dart +// sample: dart-lib/example/lib/orders/order_list_notifier.dart#notifier +/// Turns the page's events into loads, on Sinew's Riverpod mixins. +class OrderList extends Notifier + with + StateEffectNotifier, + EventActionNotifier { + late final Pager _pager = Pager.offset( + (page, _) => ref.read(orderBackendProvider).orders(page), + itemKey: (order) => order.id, + ); + + @override + OrderListState build() => const OrderListState(); + + @override + LoadOrders? mapEventToAction(OrderListEvent event) => switch (event) { + // The pager runs initial once per query. + OrderListOpened() => const LoadOrders(LoadType.initial), + OrderListEndReached() => + state.orders.canLoadMore ? const LoadOrders(LoadType.more) : null, + OrderListRetryTapped() => LoadOrders(state.orders.retryType), + OrderListRefreshed() => const LoadOrders(LoadType.refresh), + }; + + @override + Future onAction(LoadOrders action) => _pager.load( + action.type, + state.orders, + update: (next) => setState((_) => OrderListState(orders: next)), + ); +} +``` + + + + +- `Pager.offset` holds the paging rules: the first page loads once per query, `More` only starts when there is a next page, and a refresh replaces whatever is running. +- `mapEventToAction` is **pure**: it reads the state and returns the work, or `null` for none right now. Every "should this run" decision is in one testable function. +- `PagingState` stays set after a load, so retry knows what to repeat (`retryType`). + +## 2. The screen + + + + +```kotlin +// sample: kotlin-lib/sample/shared/src/commonMain/kotlin/com/srctool/sinew/sample/OrderListScreen.kt#screen +@Composable +fun OrderListScreen(viewModel: OrderListViewModel) { + val state by viewModel.state.collectAsState() + LaunchedEffect(viewModel) { viewModel.onEvent(OrderListEvent.Opened) } + Column(Modifier.fillMaxSize().background(Camouflage.colors.surface).safeDrawingPadding()) { + CamoButton("Refresh", onClick = { viewModel.onEvent(OrderListEvent.Refreshed) }, modifier = Modifier.padding(8.dp)) + CamoPagedList( + state = state.orders.toCamo(), + itemKey = { it.id }, + onLoadMore = { viewModel.onEvent(OrderListEvent.EndReached) }, + onRetry = { viewModel.onEvent(OrderListEvent.RetryTapped) }, + onRefresh = { viewModel.onEvent(OrderListEvent.Refreshed) }, + item = { order, _ -> CamoListItem(order.title, supporting = order.status) }, + modifier = Modifier.weight(1f).testTag("orders"), + ) + } +} +``` + + + + +```dart +// sample: dart-lib/example/lib/orders/order_list_screen.dart#screen +Widget build(BuildContext context) { + final state = ref.watch(orderListProvider); + return ColoredBox( + color: Camouflage.colorsOf(context).surface, + child: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: CamoButton( + text: 'Refresh', + onPressed: () => _onEvent(const OrderListRefreshed()), + ), + ), + Expanded( + child: CamoPagedList( + state: state.orders.toCamoOf(context), + itemKey: (order) => order.id, + onLoadMore: () => _onEvent(const OrderListEndReached()), + onRetry: () => _onEvent(const OrderListRetryTapped()), + onRefresh: () async => _onEvent(const OrderListRefreshed()), + itemBuilder: (context, order, _) => CamoListItem( + headline: order.title, + supporting: order.status, + ), + ), + ), + ], + ), + ), + ); +} +``` + + + + +`toCamo` (`toCamoOf` on Flutter) turns the paging state into what Camouflage's `CamoPagedList` shows: the skeleton, the items, load more, retry, refresh and the end of the list. See [paging with Camouflage](/docs/guides/paging-with-camouflage). + +## Run it + + + + +```sh +./gradlew :sample:shared:run # desktop +./gradlew :sample:androidApp:installStagingDebug # Android +``` + + + + +```sh +cd example +flutter run +``` + + + diff --git a/docs/usage/docs/guides/_category_.json b/docs/usage/docs/guides/_category_.json new file mode 100644 index 0000000..951513b --- /dev/null +++ b/docs/usage/docs/guides/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Guides", + "position": 5 +} diff --git a/docs/usage/docs/guides/paging-with-camouflage.mdx b/docs/usage/docs/guides/paging-with-camouflage.mdx new file mode 100644 index 0000000..6d0da67 --- /dev/null +++ b/docs/usage/docs/guides/paging-with-camouflage.mdx @@ -0,0 +1,96 @@ +--- +title: Paging with Camouflage +sidebar_label: Paging with Camouflage +sidebar_position: 3 +--- + +# Paging with Camouflage + +[Camouflage](https://github.com/srctool/camouflage) is the component library that Sinew's paging was designed to meet. `CamoPagedList` shows a list with every state of a paged load; `sinew-camouflage` maps Sinew's `PagingState` to it. + +## The mapping + +| `PagingState` | The list shows | +|---|---| +| loading the first page (`Initial`) | a skeleton, with no items | +| loading a refresh (`Refresh`) | a skeleton: a refresh drops the items | +| loading the next page (`More`) | the items so far, and the next page loading | +| done, with a next page | the items | +| done, with no next page | the items, and the end of the list | +| failed on the next page | the items so far, and a next-page error with retry | +| failed on the first page or a refresh | the error with retry, and no items | + +## Wire it + + + + +```kotlin +// sample: kotlin-lib/sample/shared/src/commonMain/kotlin/com/srctool/sinew/sample/OrderListScreen.kt#screen +@Composable +fun OrderListScreen(viewModel: OrderListViewModel) { + val state by viewModel.state.collectAsState() + LaunchedEffect(viewModel) { viewModel.onEvent(OrderListEvent.Opened) } + Column(Modifier.fillMaxSize().background(Camouflage.colors.surface).safeDrawingPadding()) { + CamoButton("Refresh", onClick = { viewModel.onEvent(OrderListEvent.Refreshed) }, modifier = Modifier.padding(8.dp)) + CamoPagedList( + state = state.orders.toCamo(), + itemKey = { it.id }, + onLoadMore = { viewModel.onEvent(OrderListEvent.EndReached) }, + onRetry = { viewModel.onEvent(OrderListEvent.RetryTapped) }, + onRefresh = { viewModel.onEvent(OrderListEvent.Refreshed) }, + item = { order, _ -> CamoListItem(order.title, supporting = order.status) }, + modifier = Modifier.weight(1f).testTag("orders"), + ) + } +} +``` + + + + +```dart +// sample: dart-lib/example/lib/orders/order_list_screen.dart#screen +Widget build(BuildContext context) { + final state = ref.watch(orderListProvider); + return ColoredBox( + color: Camouflage.colorsOf(context).surface, + child: SafeArea( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.all(8), + child: CamoButton( + text: 'Refresh', + onPressed: () => _onEvent(const OrderListRefreshed()), + ), + ), + Expanded( + child: CamoPagedList( + state: state.orders.toCamoOf(context), + itemKey: (order) => order.id, + onLoadMore: () => _onEvent(const OrderListEndReached()), + onRetry: () => _onEvent(const OrderListRetryTapped()), + onRefresh: () async => _onEvent(const OrderListRefreshed()), + itemBuilder: (context, order, _) => CamoListItem( + headline: order.title, + supporting: order.status, + ), + ), + ), + ], + ), + ), + ); +} +``` + + + + +## Good to know + +- The error text is rendered while you build the UI, with the current language: a language switch updates it. +- Without a localizer, a local message falls back to English. +- This is the only place Sinew touches Camouflage. If you use another component library, map `PagingState` to it the same way: `canLoadMore`, `retryType` and the view state carry everything you need. diff --git a/docs/usage/docs/guides/production-setup.mdx b/docs/usage/docs/guides/production-setup.mdx new file mode 100644 index 0000000..d434194 --- /dev/null +++ b/docs/usage/docs/guides/production-setup.mdx @@ -0,0 +1,88 @@ +--- +title: A production setup +sidebar_label: A production setup +sidebar_position: 2 +--- + +# A production setup + +Developer tools are for staging and debug builds. This guide shows how a build chooses, and how to prove a production build has no devtools code. + +## Choose per build + + + + +On Android, give each variant one artifact: + +```kotlin +// sample: kotlin-lib/sample/androidApp/build.gradle.kts#devtools-variants +"productionDebugImplementation"(projects.sinewDevtoolsUi) +"stagingImplementation"(projects.sinewDevtoolsUi) +"productionReleaseImplementation"(projects.sinewDevtoolsNoop) +``` + +Then wrap the app in the platform entry point, never in shared code: + +```kotlin +// sample: kotlin-lib/sample/shared/src/jvmMain/kotlin/com/srctool/sinew/sample/Main.kt#devtools-entry +fun main() = application { + Window(onCloseRequest = ::exitApplication, title = "Sinew") { + SinewDevTools(ribbon = BuildRibbon("Sinew sample")) { SampleApp() } // sinew.devtools picks real or no-op + } +} +``` + +The no-op artifact has the same API with nothing behind it, so this code compiles against both, and `SinewDevTools` only calls its content. + + + + +Put every entry point behind `DevToolsGate.enabled`, a `const`: + +```dart +// sample: dart-lib/example/lib/main.dart#devtools-entry +void main() { + DevToolsGate.assertMatchesFlavor(); + const app = ProviderScope(child: SinewExampleApp()); + runApp( + DevToolsGate.enabled + ? const SinewDevTools(ribbon: BuildRibbon('Sinew example'), child: app) + : app, + ); +} +``` + +| Build | `enabled` | +|---|---| +| debug, any flavor | `true` | +| release or profile, a non-production `SINEW_FLAVOR` | `true` | +| release or profile, `SINEW_FLAVOR=production` | `false` | +| release or profile, no `SINEW_FLAVOR` | `false`: a forgotten define fails safe | + +Build with `--dart-define=SINEW_FLAVOR=staging`. `assertMatchesFlavor` throws at startup if the define names another flavor than the one being run. + + + + +## Prove it + +Sinew's own CI does this for its sample and example, and you can do the same for your app: + + + + +Build the production outputs and search them for `com.srctool.sinew.devtools` names. Anything the no-op doesn't declare is real devtools code. Sinew's `checkDevToolsGating` task does this for the APK, the desktop jar, the wasm bundle and the iOS framework, and checks the real-devtools builds the other way, so a search that can't see devtools code fails instead of passing. + + + + +`sinew_devtools_ui` contains one unique constant string, a marker. Build the production release and profile variants and search the compiled output (`libapp.so`, `App.framework`, `main.dart.js`, `main.dart.wasm`) for it. If it is there, devtools code survived. A staging build is checked the opposite way: the marker must be there. Sinew's `tool/devtools_gating.sh` does this. + + + + +## Good to know + +- Redaction hides secrets before anything is stored, but devtools are still not for production: the gate is the guarantee, redaction is the second line. +- A tester's replay of a request that hid a secret is not offered, and a non-GET replay asks first. diff --git a/docs/usage/docs/guides/testing.mdx b/docs/usage/docs/guides/testing.mdx new file mode 100644 index 0000000..c44054f --- /dev/null +++ b/docs/usage/docs/guides/testing.mdx @@ -0,0 +1,82 @@ +--- +title: Testing with Sinew +sidebar_label: Testing with Sinew +sidebar_position: 1 +--- + +# Testing with Sinew + +`sinew-testing` / `sinew_testing` has a fake for every Sinew interface. These tests run on the JVM or the Dart VM with no device, no network and no platform plugin. + +## Test a call against a mock backend + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/test/kotlin/com/srctool/sinew/docs/Testing.kt#mock-http +@Test +fun ordersLoad() = runTest { + val http = mockHttp { + on(HttpMethod.Get, "/v1/orders").respond(200, """{"data":{"id":7,"title":"Two coffees"}}""") + } + http.client.get("orders") + assertEquals("/v1/orders", http.requests.single().url.encodedPath) +} +``` + + + + +```dart +test('orders load', () async { + final http = mockHttp((routes) => routes + .on('GET', '/v1/orders').respond(200, body: fixture('orders_page.json'))); + final result = await OrderRepository(OrderApi(http.dio)).page(1); + expect(http.requests.single.uri.path, '/v1/orders'); +}); +``` + + + + +A route answers with its responses in order, repeating the last one. A request no route matches fails the test and names it. The mock engine runs on the test's clock on Kotlin, so a delay is virtual time and the client's deadlines fire as they would. + +## Make storage and tokens fail + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/test/kotlin/com/srctool/sinew/docs/Testing.kt#fakes +@Test +fun aFailedReadIsAStorageFailure() = runTest { + val prefs = FakeKeyValueStore() + prefs.failNextRead() // the next read throws, once + val tokens = FakeTokenSource() // counts refreshes and rotates the token + assertEquals("token-1", tokens.accessToken()) +} +``` + + + + +```dart +final prefs = FakeKeyValueStore(); +prefs.failNextRead(); // the next read throws, once +final tokens = FakeTokenSource(); // counts refreshes and rotates the token +``` + + + + +The fakes fail the way the real ones fail, so through `processStorageCall` a scripted failure becomes `StorageReadException`, `StorageWriteException` or `StorageFullException`. + +## Test every state of a list + +`ControlledFetch` holds a pager's calls open until the test answers them, by index, in call order. A call whose coroutine was cancelled (a superseded load) is recorded as cancelled, and `assertAllCompleted` fails the test if one was left pending. + +## Good to know + +- A fake cipher stores a readable `enc(...)` form with no cryptography. It is for code that only stores and loads values; crypto tests use the real cipher. +- `sinew-testing` appears only in test configurations, checked by the dependency-graph check. diff --git a/docs/usage/docs/index.md b/docs/usage/docs/index.md deleted file mode 100644 index d095d03..0000000 --- a/docs/usage/docs/index.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: Using Sinew -sidebar_label: Introduction -slug: / ---- - -# Using Sinew - -Sinew is a plug-and-play app architecture for Kotlin Multiplatform and Flutter. It ships the plumbing every app rewrites (response mapping, results, a coded and localized error model, paging, presentation base classes, an HTTP client with token refresh, secure storage, and developer tools) as small packages you add one by one. Sinew ships the mechanism; your app ships the configuration. - -These docs are for developers **using** Sinew in an app: adding the packages, wiring them, and building a screen on them. - -:::info[Not released yet] - -Sinew has no published release yet. The guides here (installation, wiring, your first paged list) are written with the first release, 1.0, when the API they show is real. - -::: diff --git a/docs/usage/docs/index.mdx b/docs/usage/docs/index.mdx new file mode 100644 index 0000000..d462c09 --- /dev/null +++ b/docs/usage/docs/index.mdx @@ -0,0 +1,45 @@ +--- +title: Using Sinew +sidebar_label: Using Sinew +sidebar_position: 1 +--- + +# Using Sinew + +Sinew is a plug-and-play app architecture for **Kotlin Multiplatform** and **Flutter**. It ships the plumbing every app rewrites (response mapping, results, a coded and localized error model, paging, presentation base classes, an HTTP client with token refresh, secure storage and developer tools) as small packages you add one by one. Sinew ships the mechanism; your app ships the configuration. + +These docs are for developers **using** Sinew in an app: adding the packages, wiring them, and building a screen on them. Every sample has a Kotlin and a Dart version; the language switch in the sidebar changes them all. + +:::info[1.0 is being released] + +The first release, 1.0.0, is in preparation. The snippets here use `1.0.0`; until it is on Maven Central and pub.dev, build from source. The API they show is the one being released. + +::: + +## Start here + +| | | +|---|---| +| [Installation](/docs/getting-started/installation) | Add the BOM or the packages, and choose devtools per build | +| [Quick start](/docs/getting-started/quick-start) | A list that pages, with its loading, error and retry states | +| [How it fits together](/docs/concepts/how-it-fits-together) | The layers, and why a failure is translated once | +| [Modules](/docs/modules) | One page per module: what it holds and how to use it | +| [Guides](/docs/guides/testing) | Testing, a production setup, and paging with Camouflage | + +## What is in the box + +| Module | For | +|---|---| +| [Models](/docs/modules/models) | `Domain`, `Remote`, `Entity`, envelopes, `Result`, `ViewState` | +| [Exception](/docs/modules/exception) | Typed failures with codes, guards, a crash reporter | +| [L10n](/docs/modules/l10n) | The failures' messages in English and Indonesian | +| [Paging](/docs/modules/paging) | `Pager`, `PagingState`, `LoadType` | +| [Presentation](/docs/modules/presentation) | State and one-time effects, with a view model or a notifier | +| [Network](/docs/modules/network) | An HTTP client with auth, token refresh, retry and polling | +| [Security](/docs/modules/security) | Field encryption and a biometric vault | +| [Storage](/docs/modules/storage) | Preferences and secrets that fail with typed errors | +| [Testing](/docs/modules/testing) | A fake for every interface | +| [Camouflage](/docs/modules/camouflage) | Paging state for Camouflage's `CamoPagedList` | +| [DevTools](/docs/modules/devtools) | An in-app inspector that never reaches production | + +Every module is released at one version, so any set of them fits together. diff --git a/docs/usage/docs/modules/_category_.json b/docs/usage/docs/modules/_category_.json new file mode 100644 index 0000000..ebd0045 --- /dev/null +++ b/docs/usage/docs/modules/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Modules", + "position": 4 +} diff --git a/docs/usage/docs/modules/camouflage.mdx b/docs/usage/docs/modules/camouflage.mdx new file mode 100644 index 0000000..0db0154 --- /dev/null +++ b/docs/usage/docs/modules/camouflage.mdx @@ -0,0 +1,55 @@ +--- +title: Camouflage +sidebar_label: Camouflage +sidebar_position: 10 +--- + +# Camouflage + +`sinew-camouflage` / `sinew_camouflage`: the glue between Sinew's paging and [Camouflage](https://github.com/srctool/camouflage), the component library. + +One call turns a `PagingState` into what `CamoPagedList` shows: the skeleton, the items, load more, retry, refresh and the end of the list. It is the only Sinew module that depends on Camouflage. + + + + +```kotlin +CamoPagedList( + state = state.orders.toCamo(), + itemKey = { it.id }, + onLoadMore = { viewModel.onEvent(OrderListEvent.EndReached) }, + onRetry = { viewModel.onEvent(OrderListEvent.RetryTapped) }, + onRefresh = { viewModel.onEvent(OrderListEvent.Refreshed) }, + item = { order, _ -> CamoListItem(order.title, supporting = order.status) }, +) +``` + +`toCamo()` uses Sinew's localizer for the current language. `toCamo(localizer)` takes your own. + + + + +```dart +CamoPagedList( + state: state.orders.toCamoOf(context), + itemKey: (order) => order.id, + onLoadMore: () => onEvent(const OrderListEndReached()), + onRetry: () => onEvent(const OrderListRetryTapped()), + onRefresh: () async => onEvent(const OrderListRefreshed()), + itemBuilder: (context, order, _) => CamoListItem( + headline: order.title, + supporting: order.status, + ), +) +``` + +`toCamoOf(context)` uses Sinew's localizer for the context's locale. `toCamo(localizer)` takes your own. + + + + +## Good to know + +- Only a next-page load or failure keeps the items. A refresh drops them, so the list shows its skeleton. +- An error's text is rendered when you build the UI, so it follows the current language. +- `sinew-camouflage` declares the Camouflage version range it was tested with, so an app can't silently combine incompatible versions. diff --git a/docs/usage/docs/modules/devtools.mdx b/docs/usage/docs/modules/devtools.mdx new file mode 100644 index 0000000..82115cd --- /dev/null +++ b/docs/usage/docs/modules/devtools.mdx @@ -0,0 +1,53 @@ +--- +title: DevTools +sidebar_label: DevTools +sidebar_position: 11 +--- + +# DevTools + +`sinew-devtools`, `sinew-devtools-ui` and `sinew-devtools-noop` on Kotlin; `sinew_devtools` and `sinew_devtools_ui` on Flutter. + +What a tester needs to see and break the app: every request and exception recorded with its secrets already hidden, faults that force a status or drop a connection, and a host that can be switched. **A production build contains none of it.** + +## What it holds + +- **Network Monitor**, with Copy, Copy as cURL and Replay, and an **Exception Log**, both redacted and bounded in memory. +- **Redaction**: tokens, passwords and one-time codes in headers, URLs and bodies are hidden before anything is stored. You can extend the rules; you can't remove the defaults. +- **Fault injection** and an **API host** switch, applied inside the auth layer, so a forced 401 runs the real refresh. +- Inspectors for your key-value and secure stores (secrets masked, never copyable), and **your own sections**. + +## Add it to the app + + + + +```kotlin +// sample: kotlin-lib/sample/shared/src/jvmMain/kotlin/com/srctool/sinew/sample/Main.kt#devtools-entry +fun main() = application { + Window(onCloseRequest = ::exitApplication, title = "Sinew") { + SinewDevTools(ribbon = BuildRibbon("Sinew sample")) { SampleApp() } // sinew.devtools picks real or no-op + } +} +``` + + + + +```dart +// sample: dart-lib/example/lib/main.dart#devtools-entry +void main() { + DevToolsGate.assertMatchesFlavor(); + const app = ProviderScope(child: SinewExampleApp()); + runApp( + DevToolsGate.enabled + ? const SinewDevTools(ribbon: BuildRibbon('Sinew example'), child: app) + : app, + ); +} +``` + + + + +See [the production guide](/docs/guides/production-setup) for how a production build stays clean, and how to prove it. diff --git a/docs/usage/docs/modules/exception.mdx b/docs/usage/docs/modules/exception.mdx new file mode 100644 index 0000000..c6f9ba2 --- /dev/null +++ b/docs/usage/docs/modules/exception.mdx @@ -0,0 +1,113 @@ +--- +title: Exception +sidebar_label: Exception +sidebar_position: 2 +--- + +# Exception + +`sinew-exception` / `sinew_exception`: a coded error model. + +## What it holds + +- Built-in types for connectivity, HTTP statuses, parsing, storage and polling: `NoInternetConnectionException`, `ValidationException`, `UnauthorizedException`, `NotFoundException`, `ServerException`, `ParseException`, `StorageFullException` and more. Each has a short **type code**. +- `processCall` and `processUseCase`: guards that turn whatever a block throws into a `Result`. +- `ExceptionHandler`: one rule in a guard's list, "is this a timeout?" and "make this exception for this call". +- `CrashReporter`: where bugs (unexpected and parse failures) are reported. +- `Localizer` and `displayMessage`: the text a page shows. + +## Guard a call + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Errors.kt#guard +suspend fun loadOrder(api: OrderApi): Result = processCall( + module = "ORD", + function = "load", + layer = ExceptionLayer.Repository, + handlers = listOf( + ExceptionHandler( + matches = { it is SerializationException }, + transform = { ParseException("ORD", ExceptionLayer.Repository, "load", cause = it) }, + ), + ), +) { api.order(7) } +``` + + + + +```dart +// sample: dart-lib/packages/sinew_exception/example/main.dart#guard +// A guard turns whatever a call throws into a typed failure, once, where it +// happened. The handlers say which errors mean what for this layer. +final result = await processCall( + 'ORD', + 'load', + ExceptionLayer.repository, + [ + ExceptionHandler( + (error) => error is FormatException, + (error) => + const ParseException('ORD', ExceptionLayer.repository, 'load'), + ), + ], + loadOrder, +); +``` + + + + +A `SinewException` from a lower layer passes through unchanged. Anything else goes to the first matching handler, or becomes an `UnexpectedException`. Unexpected and parse failures are reported. On Kotlin, cancellation is never a failure: it propagates. + +## Show an error + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Errors.kt#display +fun errorText(error: SinewException, localizer: Localizer?): String = error.displayMessage(localizer) +``` + + + + +```dart +Text(error.displayMessage(localizer)); +``` + + + + +The text is server text unchanged, or a local message key resolved by the `Localizer`, falling back to English (never the raw key). The code always ends the text, for example `You're offline. (ORD-R-load-NIC)`. + +## Report bugs + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Errors.kt#crash-reporter +fun installReporter() { + CrashReporter.install(CrashReporter { error -> println("reported ${error.code}") }) +} +``` + + + + +```dart +CrashReporter.install(MyReporter()); // once, at the composition root +``` + + + + +## Good to know + +- The codes and the `sinew.` key prefix are reserved. Your own exceptions use other codes and keys. +- Validation field messages are shown beside their fields, without a code. diff --git a/docs/usage/docs/modules/index.mdx b/docs/usage/docs/modules/index.mdx new file mode 100644 index 0000000..ad9020f --- /dev/null +++ b/docs/usage/docs/modules/index.mdx @@ -0,0 +1,25 @@ +--- +title: Modules +sidebar_label: Modules +sidebar_position: 0 +--- + +# Modules + +One page per module. Each one says what it holds, shows it in use in Kotlin and Dart, and lists what to know before relying on it. + +| Module | Kotlin | Dart | +|---|---|---| +| [Models](/docs/modules/models) | `sinew-models` | `sinew_models` | +| [Exception](/docs/modules/exception) | `sinew-exception` | `sinew_exception` | +| [L10n](/docs/modules/l10n) | `sinew-l10n` | `sinew_l10n` | +| [Paging](/docs/modules/paging) | `sinew-paging` | `sinew_paging` | +| [Presentation](/docs/modules/presentation) | `sinew-presentation`, `sinew-viewmodel` | `sinew_presentation`, `sinew_riverpod` | +| [Network](/docs/modules/network) | `sinew-network` | `sinew_network`, `sinew_riverpod_providers` | +| [Security](/docs/modules/security) | `sinew-security` | `sinew_security` | +| [Storage](/docs/modules/storage) | `sinew-storage` | `sinew_storage` | +| [Testing](/docs/modules/testing) | `sinew-testing` | `sinew_testing` | +| [Camouflage](/docs/modules/camouflage) | `sinew-camouflage` | `sinew_camouflage` | +| [DevTools](/docs/modules/devtools) | `sinew-devtools`, `sinew-devtools-ui`, `sinew-devtools-noop` | `sinew_devtools`, `sinew_devtools_ui` | + +The API reference is attached to each [Kotlin release](https://github.com/srctool/sinew-kotlin/releases) and built by pub.dev for each Dart package. diff --git a/docs/usage/docs/modules/l10n.mdx b/docs/usage/docs/modules/l10n.mdx new file mode 100644 index 0000000..710c3ab --- /dev/null +++ b/docs/usage/docs/modules/l10n.mdx @@ -0,0 +1,38 @@ +--- +title: L10n +sidebar_label: L10n +sidebar_position: 3 +--- + +# L10n + +`sinew-l10n` / `sinew_l10n`: English and Indonesian for the messages of Sinew's own failures. + +Every failure has a message key and an English fallback. This module translates those keys, so an error shown in the app follows the app's language. + + + + +The strings are Compose resources, in the module. Resolve a failure's key with a `Localizer` that reads them, and pass it to `displayMessage`; your own strings can answer first. + + + + +```dart +MaterialApp( + localizationsDelegates: SinewLocalizations.localizationsDelegates, + supportedLocales: SinewLocalizations.supportedLocales, + home: const Home(), +); + +// in a build method +final localizer = SinewLocalizer.of(context); +Text(error.displayMessage(localizer)); +``` + +Pass `appStrings:` to `SinewLocalizer.of` to translate your own error keys through the same localizer. + + + + +A key with no translation resolves to `null`, and the English fallback shows. diff --git a/docs/usage/docs/modules/models.mdx b/docs/usage/docs/modules/models.mdx new file mode 100644 index 0000000..f6bb594 --- /dev/null +++ b/docs/usage/docs/modules/models.mdx @@ -0,0 +1,117 @@ +--- +title: Models +sidebar_label: Models +sidebar_position: 1 +--- + +# Models + +`sinew-models` / `sinew_models`: the shapes every Sinew app shares. + +## What it holds + +- `Domain`, `Remote` and `Entity`, kept apart so a backend that renames a field touches one file. +- Envelope bases (`ObjectEnvelope`, `ListEnvelope`, `PagedEnvelope`, `VoidEnvelope`) that map any backend's body to one domain shape, and report a failure inside a 2xx body. +- `Result`: a `Success` with the backend's message, or a typed `Failure`. +- `ViewState`: `Loading`, `Done` and `Failed`, where `Loading` and `Failed` can keep the previous data. +- `PagingDomain` and `PagingMetaDomain`: one page shape for every backend. + +## Map a body to the domain + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Models.kt#models +/** What the app needs, in business language. */ +data class Order(val id: Int, val title: String) : Domain + +/** What the backend sends, shaped like its JSON. */ +@Serializable +class OrderRemote(val id: Int, val title: String) : Remote() { + override fun toDomain() = Order(id, title) +} + +/** A response body: one order under `data`. */ +@Serializable +class OrderEnvelope(override val data: OrderRemote? = null) : ObjectEnvelope() +``` + + + + +```dart +// sample: dart-lib/packages/sinew_models/example/main.dart#models +/// What the app needs, in business language. +final class Order extends Domain { + const Order(this.id, this.title); + + final int id; + final String title; + + @override + List get props => [id, title]; + + @override + String toString() => 'Order($id, $title)'; +} + +/// What the backend sends, shaped like its JSON. +final class OrderRemote extends Remote { + const OrderRemote(this.id, this.title); + + final int id; + final String title; + + @override + Order toDomain() => Order(id, title); +} + +/// A response body: one order under `data`. +final class OrderEnvelope extends ObjectEnvelope { + const OrderEnvelope(this.data); + + @override + final OrderRemote? data; +} +``` + + + + +Sinew assumes no JSON keys: your envelope subclass declares its backend's fields. An object envelope's `toDomain` fails with a parse error when its `data` is absent; a list envelope maps an absent list to an empty one. + +## Read a `Result` + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Models.kt#result +fun describe(result: Result): String = result.fold( + onSuccess = { order -> "Loaded ${order.title}" }, + onFailure = { error -> "Failed: ${error.code}" }, +) +``` + + + + +```dart +// sample: dart-lib/packages/sinew_models/example/main.dart#result +// A Result is a success or a failure, never both: read it with `when`. +final text = result.when( + success: (order, message) => 'Loaded $order', + failure: (error, stackTrace) => 'Failed: ${error.code}', +); +print(text); +``` + + + + +## Good to know + +- `ViewState` keeps no success message: a one-time reaction is an **effect**, never state. +- A `Failed` state keeps the exception, never pre-rendered text, so a language switch re-renders it. +- On Kotlin, a generic envelope (`PagedResponse`) needs a serializer for its domain type argument, though the domain is never parsed: declare one with `DomainNotParsed`. diff --git a/docs/usage/docs/modules/network.mdx b/docs/usage/docs/modules/network.mdx new file mode 100644 index 0000000..eb9f5cc --- /dev/null +++ b/docs/usage/docs/modules/network.mdx @@ -0,0 +1,94 @@ +--- +title: Network +sidebar_label: Network +sidebar_position: 6 +--- + +# Network + +`sinew-network` / `sinew_network`: an HTTP client that handles what every app rewrites. + +## What it holds + +- `SinewHttp`: a client (Ktor on Kotlin, Dio on Flutter) with timeouts by method, JSON and language headers, auth, error bodies and logging, from one `SinewConfig`. Use the preset, or add only the pieces you need to your own client. +- The auth layer: the token goes only to `baseUrl`'s host, outside the anonymous paths, with a **single** refresh for any number of concurrent 401s. +- `processApiCall` and `processOptionalApiCall`: map an envelope to a `Result`, and every status to a typed exception. +- `retryWithBackoff` and `poll`, `NetworkChecker`, and certificate pinning. + +## Create the client + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Network.kt#client +fun ordersClient(tokenSource: TokenSource): HttpClient { + val config = SinewConfig( + baseUrl = "https://api.example.com/v1/", + locale = { "en" }, + anonymousPaths = setOf("/auth/login"), + ) + return SinewHttp.client(config, tokenSource) +} +``` + + + + +```dart +final config = SinewConfig( + baseUrl: 'https://api.example.com/v1', + locale: () => 'en', + anonymousPaths: {'/auth/login'}, +); +final dio = SinewHttp.dio(config, tokenSource); +``` + + + + +`locale` and the default headers are read on every request, so a language switch or a new device id applies to the next request without rebuilding the client. + +## Call an API + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Network.kt#api-call +// Paths are relative to baseUrl, and every failure comes back as a typed SinewException. +suspend fun cancel(client: HttpClient, id: String): Result = + processApiCall("ORD", "CANCEL") { client.post("orders/$id/cancel").body() } +``` + + + + +```dart +Future> cancel(String id) => + processApiCall('ORD', 'CANCEL', () => api.cancel(id)); +``` + + + + +## How a status becomes an exception + +| Response | Becomes | +|---|---| +| a request, connect or socket timeout | `RequestTimeOutException` | +| no connection, DNS failure, connection refused or reset | `NoInternetConnectionException` | +| 400 or 422 with field errors | `ValidationException` | +| 401, 403, 404, 409 | `UnauthorizedException`, `ForbiddenException`, `NotFoundException`, `ConflictException` | +| 429 | `RateLimitedException`, with the `Retry-After` wait | +| 503, 504 / any other 5xx | `ServiceUnavailableException` / `ServerException` | +| any other status, with a readable message / without | `ApiErrorException` / `UndefinedErrorResponseException` | +| JSON that doesn't fit the model, or an envelope with no payload | `ParseException`, reported | + +A readable error-body message becomes the exception's server text; otherwise its type's local message is used. A TLS or certificate failure matches nothing and becomes a reported `UnexpectedException`: a security event, never "offline". + +## Good to know + +- API classes use paths **relative** to `baseUrl` (`get("orders")`): a leading `/` would replace its own path. +- On sign-out, reset the auth layer and clear the token source, so nothing carries into the next session. +- On Flutter with Riverpod, `sinew_riverpod_providers` provides the configured client, the token source and the stores, so you override only what differs. diff --git a/docs/usage/docs/modules/paging.mdx b/docs/usage/docs/modules/paging.mdx new file mode 100644 index 0000000..ffc8e15 --- /dev/null +++ b/docs/usage/docs/modules/paging.mdx @@ -0,0 +1,64 @@ +--- +title: Paging +sidebar_label: Paging +sidebar_position: 4 +--- + +# Paging + +`sinew-paging` / `sinew_paging`: the paging rules in one place. + +A list needs the same rules in every screen: load the first page once per query, load more only when there is a next page, retry the load that failed, and let a refresh replace what is running. `Pager` holds those rules and holds no UI state: it reads the current state and writes the next one. + +## What it holds + +- Four strategies for four backends: `Pager.offset`, `Pager.offsetByTotal`, `Pager.cursor` and `Pager.lastItem`. +- `PagingState` with `canLoadMore` and `retryType`, so the UI never decides "may I load more" itself. +- `LoadType`: `Initial`, `Refresh` and `More`. It stays set after a load, so the UI can tell a first-page failure from a next-page failure. + +## Load every page + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Paging.kt#pager +suspend fun loadAll(fetch: suspend (page: Int, query: String) -> Result>): List { + val pager = Pager.offset(itemKey = { it.id }, fetch = fetch) + var state = PagingState() + + pager.load(LoadType.Initial, state) { state = it } + while (state.canLoadMore) pager.load(LoadType.More, state) { state = it } + return state.view.dataOrNull?.items.orEmpty() +} +``` + + + + +```dart +// sample: dart-lib/packages/sinew_paging/example/main.dart#pager +final pager = Pager.offset(fetch); +var state = const PagingState(); + +// The pager reads the current state and writes the next one through `update`. +await pager.load(LoadType.initial, state, update: (next) => state = next); +print('first page: ${state.view.dataOrNull?.items}'); + +while (state.canLoadMore) { + await pager.load(LoadType.more, state, update: (next) => state = next); +} +print('all pages: ${state.view.dataOrNull?.items}'); +``` + + + + +In a real page, the `update` callback writes the state your view model or notifier owns, as in the [quick start](/docs/getting-started/quick-start). + +## Good to know + +- `Initial` runs at most once per query. A new search is an `Initial` with the new query. +- A newer load, or a refresh, supersedes whatever is running; a stale result is dropped. +- A refresh drops the items, so the list shows its skeleton. +- A local list pages the same way: see `pagedQuery` in [Storage](/docs/modules/storage). diff --git a/docs/usage/docs/modules/presentation.mdx b/docs/usage/docs/modules/presentation.mdx new file mode 100644 index 0000000..0bd5957 --- /dev/null +++ b/docs/usage/docs/modules/presentation.mdx @@ -0,0 +1,77 @@ +--- +title: Presentation +sidebar_label: Presentation +sidebar_position: 5 +--- + +# Presentation + +`sinew-presentation` and `sinew-viewmodel` on Kotlin; `sinew_presentation` and `sinew_riverpod` on Flutter. + +A page has **state** (what it renders) and **effects** (one-time reactions), and effects are never state. `sinew-presentation` holds the pattern with no framework; the other module adapts it to a view model or a notifier. + +## What it holds + +- `StateEffectHandler`: a page with one intent. `setState`, `emitEffect`, and a stream of each. +- `EventActionHandler`: a page with several intents. The page sends events, a pure `mapEventToAction` decides the work, and `onAction` does it. +- On Kotlin, `StateEffectViewModel` and `EventActionViewModel` are the same on an AndroidX `ViewModel`, which survives rotation. On Flutter, `StateEffectNotifier` and `EventActionNotifier` are mixins on a Riverpod `Notifier`. + +## A page with one intent + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Presentation.kt#counter +data class CounterState(val count: Int = 0) + +/** A one-time reaction: never state, so a rebuild can't repeat it. */ +data object ReachedTen + +class CounterViewModel : StateEffectViewModel(CounterState()) { + fun increment() { + setState { copy(count = count + 1) } + if (state.value.count == 10) emitEffect(ReachedTen) + } +} +``` + + + + +```dart +// sample: dart-lib/packages/sinew_presentation/example/main.dart#counter +/// The state a page renders. +final class CounterState { + const CounterState(this.count); + + final int count; +} + +/// A one-time reaction: never state, so a rebuild can't repeat it. +final class ReachedTen { + const ReachedTen(); +} + +/// A page with one intent: state in, state and effects out. +final class Counter extends StateEffectHandler { + Counter() : super(const CounterState(0)); + + void increment() { + setState((state) => CounterState(state.count + 1)); + if (state.count == 10) emitEffect(const ReachedTen()); + } +} +``` + + + + +For a page with several intents, see the event and action version in the [quick start](/docs/getting-started/quick-start). + +## Good to know + +- `mapEventToAction` is pure: it reads state and returns the work, or `null` for none right now. Work that must not overlap is guarded there, by reading state. +- `onAction` isn't awaited by `onEvent`, so actions may run concurrently. A throw in it is a bug and reaches the platform's error handler. +- Clearing a view model, or disposing a provider, closes the effects. Late work then changes nothing. +- On Flutter, `useOnOpened` sends "the page opened" once, after the first build, and `useEffects` listens to effects while the page is mounted. diff --git a/docs/usage/docs/modules/security.mdx b/docs/usage/docs/modules/security.mdx new file mode 100644 index 0000000..f8f7452 --- /dev/null +++ b/docs/usage/docs/modules/security.mdx @@ -0,0 +1,78 @@ +--- +title: Security +sidebar_label: Security +sidebar_position: 7 +--- + +# Security + +`sinew-security` / `sinew_security`: field encryption and a biometric vault, on vetted crypto on every platform. + +Sinew never invents a cipher. Values are AES-256-GCM from vetted libraries (Tink, CryptoKit, Web Crypto, BoringSSL), with a fresh nonce for every value, and one layout on every platform. + +## Encrypt a field + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Storage.kt#cipher +suspend fun sealAndOpen(platform: PlatformContext): String { + val cipher = FieldCipher.create(platform) + val sealed = cipher.encrypt("Alice", context = "customer:42") + return cipher.decrypt(sealed, context = "customer:42") +} +``` + + + + +```dart +final cipher = await FieldCipher.create(); +final sealed = await cipher.encrypt('Alice', context: 'customer:42'); +final plain = await cipher.decrypt(sealed, context: 'customer:42'); +``` + + + + +The `context` is bound to the value as associated data, so a value copied to another field doesn't decrypt. `rotateKey` adds a key, and old values still decrypt. + +## Unlock with a biometric + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Storage.kt#vault +suspend fun offerBiometrics(platform: PlatformContext, refreshToken: String) { + val vault = BiometricVault.create(platform) + if (vault.availability() == BiometricAvailability.Available) { + vault.store(refreshToken, reason = "Sign in with biometrics next time") + } + println(vault.unlock(reason = "Sign in")) +} +``` + + + + +```dart +final vault = BiometricVault.create(); +if (await vault.availability() == BiometricAvailability.available) { + await vault.store(refreshToken, reason: 'Sign in with biometrics next time'); +} +final unlocked = await vault.unlock(reason: 'Sign in'); +``` + + + + +A secret is released only by a real biometric match. Why it wasn't (cancelled, locked out, invalidated by a new enrollment) is a user outcome, not an error. + +## Platform setup + +- **Android:** the resumed activity must be a `FragmentActivity` (`FlutterFragmentActivity` on Flutter), since `BiometricPrompt` needs one; without it the vault reports that biometrics are unavailable. Exclude the shared-preferences files that hold the cipher's keyset and the vault's ciphertext from cloud backup and device transfer: a restored value can't be decrypted on a new device anyway. +- **iOS:** `NSFaceIDUsageDescription` in `Info.plist`. +- **Desktop and web:** the vault is unavailable, and `availability` says so. +- **Flutter:** `sinew_security` builds BoringSSL, so every machine that builds the app needs CMake. On macOS, add the Keychain Sharing entitlement. diff --git a/docs/usage/docs/modules/storage.mdx b/docs/usage/docs/modules/storage.mdx new file mode 100644 index 0000000..4894c30 --- /dev/null +++ b/docs/usage/docs/modules/storage.mdx @@ -0,0 +1,65 @@ +--- +title: Storage +sidebar_label: Storage +sidebar_position: 8 +--- + +# Storage + +`sinew-storage` / `sinew_storage`: local storage with the same error model as the network. + +A corrupted file, a full disk or an unreadable value becomes a typed exception instead of a crash, and a reinstall starts with an empty secure store. + +## What it holds + +- `KeyValueStore`: plain preferences, namespaced by name. Never tokens or personal data. +- `SecureStore`: small secrets, encrypted with `FieldCipher`. A value that can't be decrypted reads as absent, and is deleted. +- `processStorageCall`: the guard that makes storage failures typed. +- `pagedQuery`: a local list that pages like a remote one. + +## Use the stores + + + + +```kotlin +// sample: kotlin-lib/sample/docs/src/main/kotlin/com/srctool/sinew/docs/Storage.kt#stores +suspend fun remember(platform: PlatformContext, refreshToken: String) { + val prefs = KeyValueStore.create(platform, name = "orders") + prefs.setString("theme", "dark") + val theme = prefs.getString("theme") // null when missing or written as another type + + val secrets = SecureStore.create(platform) + secrets.write("refreshToken", refreshToken) + println("theme: $theme, token stored: ${secrets.read("refreshToken") != null}") +} +``` + + + + +```dart +final prefs = KeyValueStore.create(name: 'orders'); +await prefs.setString('theme', 'dark'); +final theme = await prefs.getString('theme'); // null when missing or of another type + +final secrets = await SecureStore.create(); +await secrets.write('refreshToken', token); +``` + + + + +## Failures + +| Failure | Becomes | +|---|---| +| a corrupted file, an undecryptable value | `LocalStorageCorruptionException` | +| the device is out of space | `StorageFullException` | +| any other storage error | `StorageReadException` or `StorageWriteException` | + +## Good to know + +- A value read as another type than it was written is absent, as is a missing one. +- On sign-out, call `clearUserData` on the `SecureStore`. +- A reinstall starts empty on every platform: the values go with the app, even where the key survives (the iOS Keychain). diff --git a/docs/usage/docs/modules/testing.mdx b/docs/usage/docs/modules/testing.mdx new file mode 100644 index 0000000..1a99719 --- /dev/null +++ b/docs/usage/docs/modules/testing.mdx @@ -0,0 +1,18 @@ +--- +title: Testing +sidebar_label: Testing +sidebar_position: 9 +--- + +# Testing + +`sinew-testing` / `sinew_testing`: a fake for every Sinew interface, so a test runs without a device, a network or a platform plugin, and fails the way the real thing fails. Add it to **tests only**; the dependency check fails any other use. + +## What it holds + +- `mockHttp`: a real Sinew client on a mock engine, with routes and recorded requests. +- `ControlledFetch`: answer a pager's calls by hand, to test loading, retry and refresh in order. +- `FakeKeyValueStore`, `FakeSecureStore`, `FakeFieldCipher`, `FakeBiometricVault`, `FakeTokenSource`, `FakeRefreshTokenStore`, `FakeNetworkChecker`, `FakeLocalizer`. +- `RecordingCrashReporter` and a recording HTTP logger, to assert what was reported or logged. + +See [the testing guide](/docs/guides/testing) for them in use. diff --git a/docs/usage/docs/resources/_category_.json b/docs/usage/docs/resources/_category_.json new file mode 100644 index 0000000..c4e3616 --- /dev/null +++ b/docs/usage/docs/resources/_category_.json @@ -0,0 +1,4 @@ +{ + "label": "Resources", + "position": 6 +} diff --git a/docs/usage/docs/resources/changelog.mdx b/docs/usage/docs/resources/changelog.mdx new file mode 100644 index 0000000..29dda5d --- /dev/null +++ b/docs/usage/docs/resources/changelog.mdx @@ -0,0 +1,18 @@ +--- +title: Changelog +sidebar_label: Changelog +sidebar_position: 1 +--- + +# Changelog + +Every module is released at one version, so one changelog covers a release. Until 1.0.0 is out, the changes are in each repository's changelog: + +- [Sinew for Kotlin](https://github.com/srctool/sinew-kotlin/blob/main/CHANGELOG.md) +- [Sinew for Dart and Flutter](https://github.com/srctool/sinew-dart/blob/main/CHANGELOG.md) + +:::info[Versioning] + +Sinew follows semantic versioning. A mistake in a released version is never deleted: it gets a patch release. + +::: diff --git a/docs/usage/docs/resources/faq.mdx b/docs/usage/docs/resources/faq.mdx new file mode 100644 index 0000000..5faf8db --- /dev/null +++ b/docs/usage/docs/resources/faq.mdx @@ -0,0 +1,39 @@ +--- +title: FAQ +sidebar_label: FAQ +sidebar_position: 2 +--- + +# FAQ + +## Do I need Camouflage? + +No. Only `sinew-camouflage` / `sinew_camouflage` depends on it. Every other module works with any UI. + +## Can I use Sinew without Riverpod? + +Yes. `sinew_presentation` is plain Dart, and `sinew_riverpod` is the adapter. On Kotlin, `sinew-viewmodel` adapts the same pattern to AndroidX view models. + +## Does the devtools code reach my production app? + +No. On Android, the production release variant depends on the no-op artifact. On Flutter, a `const` gate removes it from the build. See [a production setup](/docs/guides/production-setup). + +## What backend JSON does Sinew expect? + +None. Sinew assumes no keys: your envelope subclass declares its backend's fields, and fills two optional hooks (a failure inside a 2xx body, and a success message) when the backend has them. + +## Which Android version is the minimum? + +`minSdk` 24 for the Kotlin modules. + +## Can I add my own errors? + +Yes. Subclass the base exception with a code and a message that don't start with Sinew's reserved prefixes, and a guard passes it through unchanged. + +## Why does `sinew_security` need CMake? + +Its cipher uses BoringSSL, compiled from source by Dart's native-assets build. Every machine that builds the app needs CMake on its `PATH`. + +## Where is the API reference? + +On Kotlin, attached to each [GitHub release](https://github.com/srctool/sinew-kotlin/releases). On Flutter, pub.dev builds it for each package. diff --git a/docs/usage/docs/resources/links.mdx b/docs/usage/docs/resources/links.mdx new file mode 100644 index 0000000..e7ea62a --- /dev/null +++ b/docs/usage/docs/resources/links.mdx @@ -0,0 +1,16 @@ +--- +title: Links +sidebar_label: Links +sidebar_position: 3 +--- + +# Links + +| | | +|---|---| +| Sinew for Kotlin | [github.com/srctool/sinew-kotlin](https://github.com/srctool/sinew-kotlin) | +| Sinew for Dart and Flutter | [github.com/srctool/sinew-dart](https://github.com/srctool/sinew-dart) | +| The umbrella repository | [github.com/srctool/sinew](https://github.com/srctool/sinew) | +| Design and decisions | the [Guide](https://sinew-dev.srctool.com/guide) | +| Camouflage, the UI library | [github.com/srctool/camouflage](https://github.com/srctool/camouflage) | +| Report a problem | [the Kotlin issues](https://github.com/srctool/sinew-kotlin/issues) and [the Dart issues](https://github.com/srctool/sinew-dart/issues) | diff --git a/docs/usage/docusaurus.config.ts b/docs/usage/docusaurus.config.ts index 52c69c2..baae420 100644 --- a/docs/usage/docusaurus.config.ts +++ b/docs/usage/docusaurus.config.ts @@ -37,7 +37,20 @@ const config: Config = { markdown: { mermaid: true, }, - themes: ['@docusaurus/theme-mermaid'], + themes: [ + '@docusaurus/theme-mermaid', + [ + '@easyops-cn/docusaurus-search-local', + { + // Search runs in the browser over an index built at build time; no service to run. + hashed: true, + indexBlog: false, + docsRouteBasePath: '/docs', + highlightSearchTermsOnTargetPage: true, + explicitSearchResultPath: true, + }, + ], + ], i18n: { defaultLocale: 'en', @@ -96,7 +109,11 @@ const config: Config = { links: [ { title: 'Docs', - items: [{label: 'Introduction', to: '/docs'}], + items: [ + {label: 'Introduction', to: '/docs'}, + {label: 'Quick start', to: '/docs/getting-started/quick-start'}, + {label: 'Modules', to: '/docs/modules'}, + ], }, { title: 'Platform', diff --git a/docs/usage/package-lock.json b/docs/usage/package-lock.json index a3ffee2..bbce903 100644 --- a/docs/usage/package-lock.json +++ b/docs/usage/package-lock.json @@ -11,6 +11,7 @@ "@docusaurus/core": "3.10.2", "@docusaurus/preset-classic": "3.10.2", "@docusaurus/theme-mermaid": "3.10.2", + "@easyops-cn/docusaurus-search-local": "^0.55.3", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", @@ -4207,6 +4208,156 @@ "node": ">=20.0" } }, + "node_modules/@easyops-cn/autocomplete.js": { + "version": "0.38.1", + "resolved": "https://registry.npmjs.org/@easyops-cn/autocomplete.js/-/autocomplete.js-0.38.1.tgz", + "integrity": "sha512-drg76jS6syilOUmVNkyo1c7ZEBPcPuK+aJA7AksM5ZIIbV57DMHCywiCr+uHyv8BE5jUTU98j/H7gVrkHrWW3Q==", + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "immediate": "^3.2.3" + } + }, + "node_modules/@easyops-cn/docusaurus-search-local": { + "version": "0.55.3", + "resolved": "https://registry.npmjs.org/@easyops-cn/docusaurus-search-local/-/docusaurus-search-local-0.55.3.tgz", + "integrity": "sha512-PlMKmxuonvZ1C+/zJS1hJaF1xaxD1TsUvOMzpP6DdQMtZqmTaYjcLGM12ePzl0m1rp3AgfTBeDbFNHQhwnH/dA==", + "license": "MIT", + "dependencies": { + "@docusaurus/plugin-content-docs": "^2 || ^3", + "@docusaurus/theme-translations": "^2 || ^3", + "@docusaurus/utils": "^2 || ^3", + "@docusaurus/utils-common": "^2 || ^3", + "@docusaurus/utils-validation": "^2 || ^3", + "@easyops-cn/autocomplete.js": "^0.38.1", + "@node-rs/jieba": "^1.6.0", + "cheerio": "^1.0.0", + "clsx": "^2.1.1", + "comlink": "^4.4.2", + "debug": "^4.2.0", + "fs-extra": "^10.0.0", + "klaw-sync": "^6.0.0", + "lunr": "^2.3.9", + "lunr-languages": "^1.4.0", + "mark.js": "^8.11.1", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=12" + }, + "peerDependencies": { + "@docusaurus/theme-common": "^2 || ^3", + "open-ask-ai": "^0.7.3", + "react": "^16.14.0 || ^17 || ^18 || ^19", + "react-dom": "^16.14.0 || 17 || ^18 || ^19" + }, + "peerDependenciesMeta": { + "open-ask-ai": { + "optional": true + } + } + }, + "node_modules/@easyops-cn/docusaurus-search-local/node_modules/cheerio": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.2.0.tgz", + "integrity": "sha512-WDrybc/gKFpTYQutKIK6UvfcuxijIZfMfXaYm8NMsPQxSYvf+13fXUJ4rztGGbJcBQ/GF55gvrZ0Bc0bj/mqvg==", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "encoding-sniffer": "^0.2.1", + "htmlparser2": "^10.1.0", + "parse5": "^7.3.0", + "parse5-htmlparser2-tree-adapter": "^7.1.0", + "parse5-parser-stream": "^7.1.2", + "undici": "^7.19.0", + "whatwg-mimetype": "^4.0.0" + }, + "engines": { + "node": ">=20.18.1" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/@easyops-cn/docusaurus-search-local/node_modules/entities": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", + "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/@easyops-cn/docusaurus-search-local/node_modules/fs-extra": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", + "integrity": "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@easyops-cn/docusaurus-search-local/node_modules/htmlparser2": { + "version": "10.1.0", + "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz", + "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.2.2", + "entities": "^7.0.1" + } + }, + "node_modules/@emnapi/core": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", + "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", + "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@hapi/hoek": { "version": "9.3.0", "resolved": "https://registry.npmjs.org/@hapi/hoek/-/hoek-9.3.0.tgz", @@ -4508,6 +4659,18 @@ "node": ">=22.12.0" } }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", + "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.4.3", + "@emnapi/runtime": "^1.4.3", + "@tybys/wasm-util": "^0.10.0" + } + }, "node_modules/@noble/hashes": { "version": "1.8.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", @@ -4520,6 +4683,259 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/@node-rs/jieba": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba/-/jieba-1.10.4.tgz", + "integrity": "sha512-GvDgi8MnBiyWd6tksojej8anIx18244NmIOc1ovEw8WKNUejcccLfyu8vj66LWSuoZuKILVtNsOy4jvg3aoxIw==", + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "optionalDependencies": { + "@node-rs/jieba-android-arm-eabi": "1.10.4", + "@node-rs/jieba-android-arm64": "1.10.4", + "@node-rs/jieba-darwin-arm64": "1.10.4", + "@node-rs/jieba-darwin-x64": "1.10.4", + "@node-rs/jieba-freebsd-x64": "1.10.4", + "@node-rs/jieba-linux-arm-gnueabihf": "1.10.4", + "@node-rs/jieba-linux-arm64-gnu": "1.10.4", + "@node-rs/jieba-linux-arm64-musl": "1.10.4", + "@node-rs/jieba-linux-x64-gnu": "1.10.4", + "@node-rs/jieba-linux-x64-musl": "1.10.4", + "@node-rs/jieba-wasm32-wasi": "1.10.4", + "@node-rs/jieba-win32-arm64-msvc": "1.10.4", + "@node-rs/jieba-win32-ia32-msvc": "1.10.4", + "@node-rs/jieba-win32-x64-msvc": "1.10.4" + } + }, + "node_modules/@node-rs/jieba-android-arm-eabi": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-android-arm-eabi/-/jieba-android-arm-eabi-1.10.4.tgz", + "integrity": "sha512-MhyvW5N3Fwcp385d0rxbCWH42kqDBatQTyP8XbnYbju2+0BO/eTeCCLYj7Agws4pwxn2LtdldXRSKavT7WdzNA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-android-arm64": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-android-arm64/-/jieba-android-arm64-1.10.4.tgz", + "integrity": "sha512-XyDwq5+rQ+Tk55A+FGi6PtJbzf974oqnpyCcCPzwU3QVXJCa2Rr4Lci+fx8oOpU4plT3GuD+chXMYLsXipMgJA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-darwin-arm64": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-darwin-arm64/-/jieba-darwin-arm64-1.10.4.tgz", + "integrity": "sha512-G++RYEJ2jo0rxF9626KUy90wp06TRUjAsvY/BrIzEOX/ingQYV/HjwQzNPRR1P1o32a6/U8RGo7zEBhfdybL6w==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-darwin-x64": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-darwin-x64/-/jieba-darwin-x64-1.10.4.tgz", + "integrity": "sha512-MmDNeOb2TXIZCPyWCi2upQnZpPjAxw5ZGEj6R8kNsPXVFALHIKMa6ZZ15LCOkSTsKXVC17j2t4h+hSuyYb6qfQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-freebsd-x64": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-freebsd-x64/-/jieba-freebsd-x64-1.10.4.tgz", + "integrity": "sha512-/x7aVQ8nqUWhpXU92RZqd333cq639i/olNpd9Z5hdlyyV5/B65LLy+Je2B2bfs62PVVm5QXRpeBcZqaHelp/bg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-linux-arm-gnueabihf": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-linux-arm-gnueabihf/-/jieba-linux-arm-gnueabihf-1.10.4.tgz", + "integrity": "sha512-crd2M35oJBRLkoESs0O6QO3BBbhpv+tqXuKsqhIG94B1d02RVxtRIvSDwO33QurxqSdvN9IeSnVpHbDGkuXm3g==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-linux-arm64-gnu": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-linux-arm64-gnu/-/jieba-linux-arm64-gnu-1.10.4.tgz", + "integrity": "sha512-omIzNX1psUzPcsdnUhGU6oHeOaTCuCjUgOA/v/DGkvWC1jLcnfXe4vdYbtXMh4XOCuIgS1UCcvZEc8vQLXFbXQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-linux-arm64-musl": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-linux-arm64-musl/-/jieba-linux-arm64-musl-1.10.4.tgz", + "integrity": "sha512-Y/tiJ1+HeS5nnmLbZOE+66LbsPOHZ/PUckAYVeLlQfpygLEpLYdlh0aPpS5uiaWMjAXYZYdFkpZHhxDmSLpwpw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-linux-x64-gnu": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-linux-x64-gnu/-/jieba-linux-x64-gnu-1.10.4.tgz", + "integrity": "sha512-WZO8ykRJpWGE9MHuZpy1lu3nJluPoeB+fIJJn5CWZ9YTVhNDWoCF4i/7nxz1ntulINYGQ8VVuCU9LD86Mek97g==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-linux-x64-musl": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-linux-x64-musl/-/jieba-linux-x64-musl-1.10.4.tgz", + "integrity": "sha512-uBBD4S1rGKcgCyAk6VCKatEVQb6EDD5I40v/DxODi5CuZVCANi9m5oee/MQbAoaX7RydA2f0OSCE9/tcwXEwUg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-wasm32-wasi": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-wasm32-wasi/-/jieba-wasm32-wasi-1.10.4.tgz", + "integrity": "sha512-Y2umiKHjuIJy0uulNDz9SDYHdfq5Hmy7jY5nORO99B4pySKkcrMjpeVrmWXJLIsEKLJwcCXHxz8tjwU5/uhz0A==", + "cpu": [ + "wasm32" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^0.2.3" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@node-rs/jieba-win32-arm64-msvc": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-win32-arm64-msvc/-/jieba-win32-arm64-msvc-1.10.4.tgz", + "integrity": "sha512-nwMtViFm4hjqhz1it/juQnxpXgqlGltCuWJ02bw70YUDMDlbyTy3grCJPpQQpueeETcALUnTxda8pZuVrLRcBA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-win32-ia32-msvc": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-win32-ia32-msvc/-/jieba-win32-ia32-msvc-1.10.4.tgz", + "integrity": "sha512-DCAvLx7Z+W4z5oKS+7vUowAJr0uw9JBw8x1Y23Xs/xMA4Em+OOSiaF5/tCJqZUCJ8uC4QeImmgDFiBqGNwxlyA==", + "cpu": [ + "ia32" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@node-rs/jieba-win32-x64-msvc": { + "version": "1.10.4", + "resolved": "https://registry.npmjs.org/@node-rs/jieba-win32-x64-msvc/-/jieba-win32-x64-msvc-1.10.4.tgz", + "integrity": "sha512-+sqemSfS1jjb+Tt7InNbNzrRh1Ua3vProVvC4BZRPg010/leCbGFFiQHpzcPRfpxAXZrzG5Y0YBTsPzN/I4yHQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, "node_modules/@nodelib/fs.scandir": { "version": "2.1.5", "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", @@ -5108,6 +5524,16 @@ "node": ">=14.16" } }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -7010,6 +7436,12 @@ "node": ">=10" } }, + "node_modules/comlink": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/comlink/-/comlink-4.4.2.tgz", + "integrity": "sha512-OxGdvBmJuNKSCMO4NTl1L47VRp6xn2wG4F/2hYzB6tiCb709otOxtEYCSvK80PtjODfXXZu8ds+Nw5kVCjqd2g==", + "license": "Apache-2.0" + }, "node_modules/comma-separated-tokens": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz", @@ -8781,6 +9213,31 @@ "node": ">= 0.8" } }, + "node_modules/encoding-sniffer": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz", + "integrity": "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==", + "license": "MIT", + "dependencies": { + "iconv-lite": "^0.6.3", + "whatwg-encoding": "^3.1.1" + }, + "funding": { + "url": "https://github.com/fb55/encoding-sniffer?sponsor=1" + } + }, + "node_modules/encoding-sniffer/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/enhanced-resolve": { "version": "5.26.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", @@ -10390,6 +10847,12 @@ "node": ">=18" } }, + "node_modules/immediate": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.3.0.tgz", + "integrity": "sha512-HR7EVodfFUdQCTIeySw+WDRFJlPcLOJbXfwwZ7Oom6tjsvZ3bOkCDJHehQC3nxJrv7+f9XecwazynjU8e4Vw3Q==", + "license": "MIT" + }, "node_modules/import-fresh": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", @@ -11035,6 +11498,15 @@ "node": ">=0.10.0" } }, + "node_modules/klaw-sync": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/klaw-sync/-/klaw-sync-6.0.0.tgz", + "integrity": "sha512-nIeuVSzdCCs6TDPTqI8w1Yre34sSq7AkZ4B3sfOBbI2CgVSB4Du4aLQijFU2+lhAFCwt9+42Hel6lQNIv6AntQ==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.1.11" + } + }, "node_modules/kleur": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz", @@ -11213,6 +11685,24 @@ "yallist": "^3.0.2" } }, + "node_modules/lunr": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/lunr/-/lunr-2.3.9.tgz", + "integrity": "sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==", + "license": "MIT" + }, + "node_modules/lunr-languages": { + "version": "1.24.0", + "resolved": "https://registry.npmjs.org/lunr-languages/-/lunr-languages-1.24.0.tgz", + "integrity": "sha512-8Eqin9QVaFzC2IMhYmZWlIn3bwPx9DDrpAoYhcr0JnP5NP1Ih3Sli4tso1Dcc1vTmKnXGxnTzi8NxJLASNu/fQ==", + "license": "MPL-1.1" + }, + "node_modules/mark.js": { + "version": "8.11.1", + "resolved": "https://registry.npmjs.org/mark.js/-/mark.js-8.11.1.tgz", + "integrity": "sha512-1I+1qpDt4idfgLQG+BNWmrqku+7/2bi5nLf4YwF8y8zXvmfiTBY3PV3ZibfrjBueCByROpuBjLLFCajqkgYoLQ==", + "license": "MIT" + }, "node_modules/markdown-extensions": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/markdown-extensions/-/markdown-extensions-2.0.0.tgz", @@ -14421,6 +14911,18 @@ "url": "https://github.com/inikulin/parse5?sponsor=1" } }, + "node_modules/parse5-parser-stream": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz", + "integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==", + "license": "MIT", + "dependencies": { + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, "node_modules/parse5/node_modules/entities": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", @@ -18309,6 +18811,15 @@ "node": ">=14.17" } }, + "node_modules/undici": { + "version": "7.30.2", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.2.tgz", + "integrity": "sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==", + "license": "MIT", + "engines": { + "node": ">=20.18.1" + } + }, "node_modules/undici-types": { "version": "7.12.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.12.0.tgz", @@ -19158,6 +19669,40 @@ "node": ">=0.8.0" } }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", + "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", + "deprecated": "Use @exodus/bytes instead for a more spec-conformant and faster implementation", + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/docs/usage/package.json b/docs/usage/package.json index 57d9e2f..0582323 100644 --- a/docs/usage/package.json +++ b/docs/usage/package.json @@ -18,6 +18,7 @@ "@docusaurus/core": "3.10.2", "@docusaurus/preset-classic": "3.10.2", "@docusaurus/theme-mermaid": "3.10.2", + "@easyops-cn/docusaurus-search-local": "^0.55.3", "@mdx-js/react": "^3.0.0", "clsx": "^2.0.0", "prism-react-renderer": "^2.3.0", diff --git a/docs/usage/scripts/sync_samples.py b/docs/usage/scripts/sync_samples.py new file mode 100644 index 0000000..cda79a9 --- /dev/null +++ b/docs/usage/scripts/sync_samples.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Copies code samples from the libraries into the usage docs, and checks they haven't drifted. + +A fenced code block in `docs/usage/docs/**/*.mdx` whose first line is + + // sample: # + +is a copy of a region of a source file in this repository (the path is relative to the repository root, so it names a +file in `kotlin-lib/` or `dart-lib/`). The region sits between `// region ` and `// endregion` lines in that +file, and the block holds its lines with the common indentation removed. + +The Kotlin samples live in `kotlin-lib/sample/docs`, a module CI compiles (and whose tests CI runs), and in the sample +app; the Dart ones live in the example app and in each package's `example/`. So a sample that no longer compiles fails +the library's build, and one that changed fails here. + + python3 docs/usage/scripts/sync_samples.py # rewrites every block from its source + python3 docs/usage/scripts/sync_samples.py --check # exits 1 when a block differs from its source +""" +import re +import sys +import textwrap +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +DOCS = ROOT / 'docs' / 'usage' / 'docs' +BLOCK = re.compile(r'^(?P`{3,})(?P[a-z]*)[^\n]*\n(?P// sample: (?P[^#\n]+)#(?P[\w-]+))\n(?P.*?)^(?P=fence)[ \t]*$', + re.S | re.M) + + +def region(path: Path, name: str) -> str: + lines = path.read_text().split('\n') + start = next((i for i, l in enumerate(lines) if re.search(rf'//\s*region {re.escape(name)}\s*$', l)), None) + if start is None: + raise SystemExit(f'{path.relative_to(ROOT)}: no "// region {name}"') + end = next((i for i in range(start + 1, len(lines)) if re.search(r'//\s*endregion\s*$', lines[i])), None) + if end is None: + raise SystemExit(f'{path.relative_to(ROOT)}: "// region {name}" is never closed') + body = textwrap.dedent('\n'.join(lines[start + 1:end])).strip('\n') + return '\n'.join(l.rstrip() for l in body.split('\n')) + + +def main(check: bool) -> int: + stale = [] + count = 0 + for page in sorted(DOCS.rglob('*.mdx')) + sorted(DOCS.rglob('*.md')): + text = page.read_text() + + def fill(m): + nonlocal count + count += 1 + source = ROOT / m['path'] + if not source.exists(): + raise SystemExit(f'{page.relative_to(ROOT)}: sample file not found: {m["path"]}') + fresh = region(source, m['name']) + if m['body'].rstrip('\n') != fresh: + stale.append(f'{page.relative_to(ROOT)}: {m["path"]}#{m["name"]}') + return f'{m["fence"]}{m["lang"]}\n{m["marker"]}\n{fresh}\n{m["fence"]}' + + new = BLOCK.sub(fill, text) + if new != text and not check: + page.write_text(new) + if check: + for s in stale: + print('out of date:', s) + print(f'{count} sample blocks checked, {len(stale)} out of date') + return 1 if stale else 0 + print(f'{count} sample blocks synced, {len(stale)} changed') + return 0 + + +if __name__ == '__main__': + sys.exit(main('--check' in sys.argv)) diff --git a/docs/usage/src/components/LangContent/index.tsx b/docs/usage/src/components/LangContent/index.tsx index 412dfa6..a2b36fc 100644 --- a/docs/usage/src/components/LangContent/index.tsx +++ b/docs/usage/src/components/LangContent/index.tsx @@ -7,9 +7,10 @@ import {getPreferredLang, Lang} from '@site/src/components/LanguageSwitcher'; * - Defaults to 'kotlin' during SSR/first render if no preference is saved */ const UseLang: React.FC<{only: Lang; children: React.ReactNode}> = ({only, children}) => { - const [lang, setLang] = useState(getPreferredLang()); + const [lang, setLang] = useState('kotlin'); useEffect(() => { + setLang(getPreferredLang()); const handler = (e: any) => { const next = e?.detail?.lang as Lang | undefined; if (next && next !== lang) setLang(next); diff --git a/docs/usage/src/components/LangTabs/index.tsx b/docs/usage/src/components/LangTabs/index.tsx index 02ebc70..d9978ac 100644 --- a/docs/usage/src/components/LangTabs/index.tsx +++ b/docs/usage/src/components/LangTabs/index.tsx @@ -1,61 +1,68 @@ -import React, {useEffect, useMemo, useState} from 'react'; -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; +import React, {useEffect, useState} from 'react'; import {getPreferredLang, setPreferredLang, Lang} from '../LanguageSwitcher'; -// Wrapper over Docusaurus Tabs that syncs selected tab with global preference +// Kotlin and Dart tabs driven by the site-wide language preference (the sidebar switcher, the home +// page menu and every tab group on the page share it). Docusaurus' own keeps a selection of +// its own and ignores changes to defaultValue, so it can't follow the switcher; this one is +// controlled by the preference instead. +// // Usage in MDX: // -// -// ```kotlin -// // code here -// ``` -// -// -// ```dart -// // code here -// ``` -// +// ```kotlin ... ``` +// ```dart ... ``` // -const LangTabs: React.FC> = ({children, groupId = 'code-lang'}) => { - const [value, setValue] = useState(getPreferredLang()); - // Keep in sync with global preference changes +const LABELS: Record = {kotlin: 'Kotlin', dart: 'Dart'}; + +// A marker component: LangTabs reads its `value` and renders its children for the selected language. +export const TabItem: React.FC> = ({children}) => <>{children}; + +const LangTabs: React.FC = ({children}) => { + // Start from Kotlin on the server and the first client render, then read the saved choice, so the + // markup matches during hydration. + const [lang, setLang] = useState('kotlin'); + useEffect(() => { - const handler = (e: any) => { - const next = e?.detail?.lang as Lang | undefined; - if (next && next !== value) setValue(next); + setLang(getPreferredLang()); + const handler = (e: Event) => { + const next = (e as CustomEvent).detail?.lang as Lang | undefined; + if (next) setLang(next); }; window.addEventListener('sinew:langChange', handler); return () => window.removeEventListener('sinew:langChange', handler); - }, [value]); - - // When user switches tab, persist preference - const onChange = (nextVal: string) => { - const next = (nextVal === 'dart' ? 'dart' : 'kotlin') as Lang; - setValue(next); - setPreferredLang(next); - }; + }, []); - // Ensure we only pass TabItems with our 2 values - const processedChildren = useMemo(() => { - return React.Children.toArray(children).filter(Boolean) as React.ReactElement[]; - }, [children]); + const items = React.Children.toArray(children).filter(Boolean) as React.ReactElement<{value: Lang}>[]; + const available = items.map((item) => item.props.value); + // A group with only one language shows it whatever is selected. + const shown = available.includes(lang) ? lang : available[0]; return ( - onChange(v)} - > - {processedChildren} - +
+
    + {available.map((value) => ( +
  • setPreferredLang(value)} + onKeyDown={(e) => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + setPreferredLang(value); + } + }}> + {LABELS[value]} +
  • + ))} +
+
+ {items.filter((item) => item.props.value === shown)} +
+
); }; -export {TabItem}; export default LangTabs; diff --git a/docs/usage/src/components/LanguageSwitcher/index.tsx b/docs/usage/src/components/LanguageSwitcher/index.tsx index f47de85..b5fb0a8 100644 --- a/docs/usage/src/components/LanguageSwitcher/index.tsx +++ b/docs/usage/src/components/LanguageSwitcher/index.tsx @@ -110,9 +110,10 @@ const LANG_COLORS: Record = { // A small button group to toggle Kotlin/Dart const LanguageSwitcher: React.FC<{compact?: boolean}> = ({compact = false}) => { - const [lang, setLang] = useState(getInitialLang()); + const [lang, setLang] = useState('kotlin'); useEffect(() => { + setLang(getInitialLang()); // Ensure palette matches current lang on mount and when external changes occur applyPrimaryPaletteForLang(lang); const handler = (e: any) => { diff --git a/docs/usage/src/pages/index.module.css b/docs/usage/src/pages/index.module.css index 0f7db88..8e109d8 100644 --- a/docs/usage/src/pages/index.module.css +++ b/docs/usage/src/pages/index.module.css @@ -7,7 +7,10 @@ padding: 4rem 0; text-align: center; position: relative; - overflow: hidden; + /* The language menu drops below the hero. Infima's .hero sets overflow: hidden, which clipped it, and the + sections below painted over what was left, so the hero lets it out and sits above them. */ + overflow: visible !important; + z-index: 2; } @media screen and (max-width: 996px) { diff --git a/docs/usage/src/theme/MDXComponents.tsx b/docs/usage/src/theme/MDXComponents.tsx index dbcd00a..782c384 100644 --- a/docs/usage/src/theme/MDXComponents.tsx +++ b/docs/usage/src/theme/MDXComponents.tsx @@ -1,7 +1,7 @@ import React from 'react'; import MDXComponents from '@theme-original/MDXComponents'; import {KotlinOnly, DartOnly} from '@site/src/components/LangContent'; -import LangTabs from '@site/src/components/LangTabs'; +import LangTabs, {TabItem} from '@site/src/components/LangTabs'; // Extend the default MDX components so these are available globally in MDX files // This prevents "Expected component X to be defined" errors when an import is missing. @@ -10,4 +10,5 @@ export default { KotlinOnly, DartOnly, LangTabs, + TabItem, } as const;