Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs/usage/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: <path>#<region>` is a copy of a region (between `// region <name>` 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 `<LangTabs>` group.
4 changes: 4 additions & 0 deletions docs/usage/docs/concepts/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Concepts",
"position": 3
}
48 changes: 48 additions & 0 deletions docs/usage/docs/concepts/how-it-fits-together.mdx
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 4 additions & 0 deletions docs/usage/docs/getting-started/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Getting started",
"position": 2
}
88 changes: 88 additions & 0 deletions docs/usage/docs/getting-started/installation.mdx
Original file line number Diff line number Diff line change
@@ -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

<LangTabs>
<TabItem value="kotlin">

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.

</TabItem>
<TabItem value="dart">

```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.

</TabItem>
</LangTabs>

:::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:

<LangTabs>
<TabItem value="kotlin">

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.

</TabItem>
<TabItem value="dart">

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).

</TabItem>
</LangTabs>

## 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.
170 changes: 170 additions & 0 deletions docs/usage/docs/getting-started/quick-start.mdx
Original file line number Diff line number Diff line change
@@ -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

<LangTabs>
<TabItem value="kotlin">

```kotlin
// sample: kotlin-lib/sample/shared/src/commonMain/kotlin/com/srctool/sinew/sample/OrderListViewModel.kt#view-model
class OrderListViewModel(backend: OrderBackend) :
EventActionViewModel<OrderListState, OrderListEvent, LoadOrders, Nothing>(OrderListState()) {
private val pager = Pager.offset<Order>(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) } }
}
}
```

</TabItem>
<TabItem value="dart">

```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<OrderListState>
with
StateEffectNotifier<OrderListState, Never>,
EventActionNotifier<OrderListState, OrderListEvent, LoadOrders, Never> {
late final Pager<Order> _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<void> onAction(LoadOrders action) => _pager.load(
action.type,
state.orders,
update: (next) => setState((_) => OrderListState(orders: next)),
);
}
```

</TabItem>
</LangTabs>

- `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

<LangTabs>
<TabItem value="kotlin">

```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"),
)
}
}
```

</TabItem>
<TabItem value="dart">

```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<Order>(
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,
),
),
),
],
),
),
);
}
```

</TabItem>
</LangTabs>

`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

<LangTabs>
<TabItem value="kotlin">

```sh
./gradlew :sample:shared:run # desktop
./gradlew :sample:androidApp:installStagingDebug # Android
```

</TabItem>
<TabItem value="dart">

```sh
cd example
flutter run
```

</TabItem>
</LangTabs>
4 changes: 4 additions & 0 deletions docs/usage/docs/guides/_category_.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"label": "Guides",
"position": 5
}
Loading
Loading