# Magic Starter documentation > Magic Starter ships pre-built Auth, Profile, Teams and Notifications screens for Magic framework apps, so you stop rebuilding them per project. # Installation Add `magic_starter` to a Magic app, register its dowel commands with `plugin:install`, and let `starter:install` scaffold the config, middleware, models and routes for the features you choose. - [Requirements](#requirements) - [Installing the Package](#installing-the-package) - [Running the Install Command](#running-the-install-command) - [Registering the Service Provider](#registering-the-service-provider) - [Injecting the Config Factory](#injecting-the-config-factory) - [Bootstrapping the Starter](#bootstrapping-the-starter) - [Related Documentation](#related-documentation) ## Requirements The Dart and Flutter floors are inherited from `magic`: a package cannot resolve below its own dependency's floor. | Dependency | Constraint | |:-----------|:-----------| | Dart SDK | `>=3.13.0 <4.0.0` | | Flutter | `>=3.47.0` | | `magic` | `^1.0.0` | | `dowel` | `^1.0.0` | | `magic_notifications` | `^1.0.0` | | `magic_payments` | `^1.0.0` | | `magic_picker` | `^1.0.0` | | `magic_socket` | `^1.0.0` | | `args` | `^2.7.0` | | `path` | `^1.9.1` | | `in_app_review` | `^2.0.12` | | `package_info_plus` | `^10.2.2` | | `web` | `^1.1.2` | The UI is built on `wind_kit` and `material_ui`, which come with `magic`. The app must already be scaffolded by Magic (`lib/config/app.dart` present): run `dart run magic:dowel magic:install` first, see the [Magic installation guide](https://anilcancakir.com/magic/docs/getting-started/installation). The package is the client of `magic-starter-laravel`'s `api/v1` routes: its controllers call them one to one, so the screens need that backend, or one that serves the same routes, to work. ## Installing the Package ```bash flutter pub add magic_starter dart run magic:dowel plugin:install magic_starter --no-bootstrap ``` `plugin:install` registers `MagicStarterDowelProvider` under `.dowel/plugins.json` and injects `MagicStarterServiceProvider` into `lib/config/app.dart`. Without `--no-bootstrap` it also chains `starter:install` as the plugin's bootstrap command. > [!WARNING] > Pass `--no-bootstrap`. The chained run always receives `--non-interactive`, so it asks no questions and writes every feature as `false`. A later `starter:install --features=...` finds the `lib/config/magic_starter.dart` that now exists, does not rewrite it, and exits `1` with the features whose setting differs, instead of reporting success with the features still off. Run `starter:install` yourself, as below. If you already ran the chain, `starter:configure` (or editing `lib/config/magic_starter.dart`) turns on a feature that needs no scaffolding, but not teams: that also needs the `Team` model, the `User` team accessors, the `bootstrap()` team callbacks and `registerMagicStarterTeamRoutes()`, and without them the app throws on startup. For those, commit your changes and re-run `dart run magic:dowel starter:install --features=teams --force`, adding every other feature you want on, since the config is rewritten from that list; `--force` replaces the generated files, including `AppServiceProvider`, and overwrites the translation file. The package has no executable of its own: every command is `dart run magic:dowel starter:`. ## Running the Install Command ```bash dart run magic:dowel starter:install ``` Interactively, the command asks one yes/no question per feature key and defaults every answer to no. For a scripted install pass the keys you want: ```bash dart run magic:dowel starter:install --features=registration,teams,notifications ``` `--features` implies `--non-interactive`; a key you leave out is written as `false`. The accepted keys are the ones in the [feature toggles table](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md#feature-toggles). The command then: 1. **Validates** that `lib/config/app.dart` exists and stops when it does not. 2. **Writes** `lib/config/magic_starter.dart` with your selections, the `EnsureAuthenticated` and `RedirectIfAuthenticated` middleware under `lib/app/middleware/`, `lib/app/models/user.dart` (and `team.dart` when `teams` is on), `lib/resources/views/dashboard_view.dart` and `lib/routes/app.dart`. A file that already exists is skipped, except `lib/routes/app.dart`, which gets the dashboard route group injected instead. 3. **Injects** `MagicStarterServiceProvider` into `lib/config/app.dart`, the config import and `magicStarterConfig` factory into `lib/main.dart` (with a default `primary` palette passed as `windTheme`), the `auth` and `guest` aliases into `lib/app/kernel.dart` and the route registrations into `lib/app/providers/route_service_provider.dart`. 4. **Edits** `lib/app/providers/app_service_provider.dart`: it injects the `MagicStarter.bootstrap(...)` call and a navigation block into an existing file, or writes a full one when the file is missing or `--force` is passed. 5. **Merges** the starter's translation keys into `assets/lang/en.json` and registers that asset in the host `pubspec.yaml`. 6. **Adds** `magic_notifications` to the host `pubspec.yaml` when `notifications` is on, and prints the `notifications:install` command that finishes OneSignal setup. 7. **Runs** `dart format .` on the host project. Every injection is idempotent: a second run does not duplicate a registration. Pass `--force` to overwrite files the command already generated (it also replaces `app_service_provider.dart` instead of injecting into it). `--dry-run` is not a full preview: it stages the file writes without writing them, but the in-place edits of `main.dart`, `kernel.dart`, the route provider, `AppServiceProvider`, the translations and `pubspec.yaml` still run. The other commands (`starter:configure`, `starter:doctor`, `starter:publish`, `starter:uninstall`) are documented in [CLI Commands](https://anilcancakir.com/magic/docs/starter/basics/cli.md). ## Registering the Service Provider The injected section of `lib/config/app.dart` looks like this: ```dart import 'package:magic/magic.dart'; import 'package:magic_starter/magic_starter.dart'; // injected by install final appConfig = { 'app': { 'name': Env.get('APP_NAME', 'My App'), 'providers': [ (app) => RouteServiceProvider(app), (app) => AppServiceProvider(app), (app) => MagicStarterServiceProvider(app), // injected by install ], }, }; ``` `MagicStarterServiceProvider` binds `MagicStarterManager` under the `'magic_starter'` key and defines the `starter.*` Gate abilities; see [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md). ## Injecting the Config Factory The config factory is added to `Magic.init()` in `lib/main.dart`: ```dart import 'package:material_ui/material_ui.dart'; import 'package:magic/magic.dart'; import 'config/app.dart'; import 'config/magic_starter.dart'; // injected by install void main() async { WidgetsFlutterBinding.ensureInitialized(); await Magic.init( configFactories: [ () => appConfig, () => magicStarterConfig, // injected by install ], ); runApp(MagicApplication(title: 'My App')); } ``` The generated `lib/config/magic_starter.dart` and every key in it are described in [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md). ## Bootstrapping the Starter Registering the provider is not enough. The starter also needs four host-owned things: how to build your user model, how to log out, which locales to offer and, when `teams` is on, how to read and switch teams. `MagicStarter.bootstrap()` registers them in one call from `AppServiceProvider.boot()`; the installer writes it for you. ```dart class AppServiceProvider extends ServiceProvider { AppServiceProvider(super.app); @override void register() {} @override Future boot() async { MagicStarter.bootstrap( userFactory: (data) => User.fromMap(data), onLogout: () async { await Auth.logout(); MagicRoute.to('/auth/login'); }, locales: { 'en': 'English', 'tr': 'Türkçe', }, ); } } ``` That is the complete setup for a teamless app. With `magic_starter.features.teams` on, pass the three team callbacks as well: ```dart MagicStarter.bootstrap( userFactory: (data) => User.fromMap(data), onLogout: () async => Auth.logout(), locales: { 'en': 'English', 'tr': 'Türkçe', }, currentTeam: () => User.current.currentTeam?.toMagicStarterTeam(), allTeams: () => User.current.allTeams.map((t) => t.toMagicStarterTeam()).toList(), onSwitch: (id) => MagicStarter.switchTeam('$id'), ); ``` The team callbacks are a group: pass all three or none. | Situation | Result | |:----------|:-------| | Teams off, team callbacks omitted | Valid. No team resolver is registered and no team UI renders. | | Teams on, all three callbacks passed | Valid. The team selector, team switching and team settings work. | | Teams on, team callbacks omitted | Throws a `StateError` naming the missing call and the config flag. | | Only some of the three callbacks passed | Throws an `ArgumentError`; the manager is left untouched. | `bootstrap()` also takes the optional `onLogin` and `onGuestClaimed` callbacks, described in [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#login-callback). The individual setters (`useUserModel()`, `useLogout()`, `useLocaleOptions()`, `useTeamResolver()`) stay public. Call one after `bootstrap()` to replace what it registered, for example to register the team resolver once your own team store is warm: ```dart MagicStarter.useTeamResolver( currentTeam: () => TeamStore.instance.current?.toMagicStarterTeam(), allTeams: () => TeamStore.instance.all, onSwitch: (id) => TeamStore.instance.switchTo(id), ); ``` > [!WARNING] > Do not skip `userFactory`. Without it the starter falls back to its own `MagicStarterAuthUser`, so every screen keeps rendering while silently reading the wrong user model. `bootstrap()` makes that omission impossible: the parameter is required. `bootstrap()` covers the identity contract only. The optional presentation setters (`useNavigation()`, `useTheme()`, `useWindTheme()`, `useHeader()`, `useSocialAuth()` and the per-surface theme setters) stay separate and are called alongside it. ## Related Documentation - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): feature toggles, route prefixes and identity modes. - [CLI Commands](https://anilcancakir.com/magic/docs/starter/basics/cli.md): every `starter:*` command and flag. - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): the registrations `AppServiceProvider.boot()` makes. - [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md): overriding a screen. - [Magic installation guide](https://anilcancakir.com/magic/docs/getting-started/installation): scaffolding the host app. --- # Configuration The `magic_starter` config file turns features on, sets the route prefixes and carries the billing, push, handoff and legal keys, read at runtime through `MagicStarterConfig`. - [Introduction](#introduction) - [The Config File](#config-file) - [Feature Toggles](#feature-toggles) - [Route Customisation](#route-customization) - [Billing](#billing) - [The push external id](#push-external-id) - [Auth Identity Modes](#auth-identity-modes) - [Locale & Timezone Defaults](#locale-timezone-defaults) - [Accessing Values](#accessing-values) - [Related Documentation](#related-documentation) ## Introduction The plugin is configured by one Dart file in your app, `lib/config/magic_starter.dart`, which `starter:install` generates from the features you chose. Every feature defaults to `false` (an absent key reads `false`, and the template `starter:publish --tag=config` copies on a host without the file writes every feature `false` too, see [CLI](https://anilcancakir.com/magic/docs/starter/basics/cli.md#publish-tags)): a toggle decides whether its routes are registered, its views are put in the view registry and its UI shows. ```bash dart run magic:dowel starter:install ``` To flip toggles later, edit the file, or run `dart run magic:dowel starter:configure` for the toggles it has a flag for; see [CLI Commands](https://anilcancakir.com/magic/docs/starter/basics/cli.md). ## The Config File The file exports one top-level getter that returns a nested `Map`: ```dart Map get magicStarterConfig => { 'magic_starter': { 'features': { 'teams': false, 'registration': false, 'extended_profile': false, 'profile_photos': false, 'social_login': false, 'two_factor': false, 'sessions': false, 'phone_otp': false, 'newsletter': false, 'notifications': false, 'email_verification': false, 'guest_auth': false, 'timezones': false, 'billing': false, 'support': false, 'support_csat': false, 'support_feedback': false, 'support_attachments': false, 'support_client_context': false, 'support_chat': false, 'store_review': false, 'releases': false, 'app_update': false, 'handoff': false, }, 'auth': { 'email': true, 'phone': false, }, 'defaults': { 'locale': 'en', 'timezone': 'UTC', }, 'localization': { 'apply_user_locale': true, }, 'supported_locales': [ 'en', 'tr', ], 'routes': { 'home': '/', 'login': '/auth/login', 'auth_prefix': '/auth', 'teams_prefix': '/teams', 'profile_prefix': '/settings', 'notifications_prefix': '/notifications', 'billing': '/teams/billing', }, 'billing': { 'web_origin': null, 'billable': 'user', }, 'notifications': { 'external_id_prefix': 'user_', }, 'handoff': { 'confirm_without_session': true, 'signed_out_route': null, }, 'legal': { 'terms_url': null, 'privacy_url': null, }, 'account': { 'deletion_url': null, }, }, }; ``` Register it with `Magic.init()` next to your other config factories (the installer does this for you): ```dart await Magic.init( configFactories: [ () => appConfig, () => magicStarterConfig, ], ); ``` Every key under `'magic_starter'` is readable with `Config.get('magic_starter.')` using dot notation. The support and store review screens read further keys, listed in [Support](https://anilcancakir.com/magic/docs/starter/basics/support.md). ## Feature Toggles Each toggle controls whether routes are registered, views are put in the registry and UI sections render. | Key | Default | Description | |:----|:--------|:------------| | `teams` | `false` | Team creation, management, member invitations and team switching. Needs a team resolver, see [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md#bootstrapping-the-starter). | | `registration` | `false` | The registration screen and route. | | `extended_profile` | `false` | Additional profile fields (phone, timezone, language) and the Language settings page. | | `profile_photos` | `false` | Profile photo upload and removal in the profile settings. | | `social_login` | `false` | Provider buttons on the login and register screens, the Connected accounts settings page and the provider option of the identity-confirmation dialog. Needs a bridge registered with `MagicStarter.useSocialAuth(...)`, see [Social Login](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#social-login); the flag alone renders nothing. | | `two_factor` | `false` | Two-factor setup, the challenge screen and recovery codes. | | `sessions` | `false` | The browser sessions list with revoke. | | `phone_otp` | `false` | The phone-based one-time code flow (send, verify). | | `newsletter` | `false` | The newsletter subscribe toggle in the settings. | | `notifications` | `false` | The in-app notification list, unread badge and preferences screen, and the push identity this package declares. | | `email_verification` | `false` | The email verification page and resend flow. | | `guest_auth` | `false` | The login screen's "Continue as guest" button, plus the listeners that record a guest sign-in and claim that guest's data when an account signs in. It adds no routes or screens. | | `timezones` | `false` | The Timezone settings page with debounced async search. | | `billing` | `false` | The `teams.billing` view; see [Billing](#billing). | | `support` | `false` | The support desk (`/support`, `/support/new`, `/support/:id`). The host registers the routes with `registerMagicStarterSupportRoutes()`; see [Support](https://anilcancakir.com/magic/docs/starter/basics/support.md). | | `support_csat` | `false` | A thumbs rating under a resolved conversation. | | `support_feedback` | `false` | The feedback card and the `/support/feedback` page. | | `support_attachments` | `false` | Image and PDF attachments on a message. | | `support_client_context` | `false` | App version, platform and locale sent with a new conversation. | | `support_chat` | `false` | The chat launcher and its floating panel. Needs `support`. | | `store_review` | `false` | The native store review prompt. | | `releases` | `false` | The "What's new" changelog page (`/settings/changelog`) and the version caption, read from the backend's `GET releases`. Needs `Features::releases()` on `magic-starter-laravel`; see [Releases](https://anilcancakir.com/magic/docs/starter/basics/releases.md). | | `app_update` | `false` | `MagicStarterAppUpdateBanner` in the app layout: Reload when a new web deploy appears in `version.json`, Update when the store has a newer build. The store path reads `GET releases`; see [Releases](https://anilcancakir.com/magic/docs/starter/basics/releases.md). | | `handoff` | `false` | The sign-in handoff page `/auth/handoff?code=&next=`: it trades a one-time code for a session, after asking "Sign in as ...?", and opens `next`. See [Sign-in handoff](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#handoff). | The handoff keys sit beside the toggle. `handoff.confirm_without_session` (default `true`) keeps the question when nobody is signed in, which is what stops a link carrying an attacker's own code from signing a visitor in to the attacker's account; `false` only saves the tap. `handoff.signed_out_route` (default `null`, meaning `routes.login`) is where a signed-out visit without a code goes, carrying `?next=`. To enable features, set their values to `true`: ```dart 'features': { 'teams': true, 'registration': true, 'notifications': true, // ... remaining features stay false }, ``` > [!TIP] > A disabled feature registers no route and no view, so asking the view registry for its key (`MagicStarter.view.make('teams.create')`) throws a `StateError`. Check `MagicStarterConfig.hasTeamFeatures()` and its siblings before building a link to a gated page. ## Route Customisation The `routes` block controls the URL paths the starter registers: ```dart 'routes': { 'home': '/', 'login': '/auth/login', 'auth_prefix': '/auth', 'teams_prefix': '/teams', 'profile_prefix': '/settings', 'notifications_prefix': '/notifications', 'billing': '/teams/billing', }, ``` | Key | Default | Description | |:----|:--------|:------------| | `home` | `'/'` | Where a successful sign-in lands (unless an intended URL or a `next` path says otherwise) and where `RedirectIfAuthenticated` sends a signed-in visitor. | | `login` | `'/auth/login'` | Where `EnsureAuthenticated` sends a signed-out visitor. | | `auth_prefix` | `'/auth'` | Prefix of the auth routes (login, register, forgot and reset password, two-factor challenge, OTP, verify email, handoff). | | `teams_prefix` | `'/teams'` | Prefix of the team routes (create, settings). | | `profile_prefix` | `'/settings'` | Prefix of the settings hub and its sub-pages. | | `notifications_prefix` | `'/notifications'` | The notifications list page. | | `billing` | `'/teams/billing'` | The billing page, also where the upgrade prompts send the user. | `MagicStarterConfig` also builds the paths that depend on a prefix: ```dart MagicStarterConfig.teamCreateRoute(); // '/teams/create' MagicStarterConfig.teamSettingsRoute(); // '/teams/settings' MagicStarterConfig.profileRoute(); // '/settings/profile' MagicStarterConfig.settingsHubRoute(); // '/settings' MagicStarterConfig.notificationsRoute(); // '/notifications' MagicStarterConfig.notificationPreferencesRoute(); // '/settings/notifications' MagicStarterConfig.twoFactorChallengeRoute(); // '/auth/two-factor-challenge' MagicStarterConfig.handoffRoute(); // '/auth/handoff' ``` Changing a prefix updates every path built from it: setting `profile_prefix` to `'/account'` makes `profileRoute()` return `'/account/profile'` and `notificationPreferencesRoute()` return `'/account/notifications'`. ## Billing The `billing` feature gates the `teams.billing` view, which sells subscriptions through [`magic_payments`](https://pub.dev/packages/magic_payments). It has its own toggle rather than hanging on `teams`: a subscription is bought by whoever holds the account, so an app with no team features can still sell one. ```dart 'features': { 'billing': true, }, 'routes': { 'billing': '/teams/billing', }, 'billing': { 'web_origin': 'https://app.example.com', 'billable': 'user', }, ``` | Key | Default | Description | |:----|:--------|:------------| | `billing.web_origin` | `null` | The host app's own web origin, with no trailing slash. Required once billing is on; read on the web rail only. | | `billing.billable` | `'user'` | What a store purchase is billed to: `'user'` or `'team'`. It must match `magic-starter-laravel`'s `billable` key. Any other value throws a `StateError`. | > [!WARNING] > `billing.web_origin` carries no default on purpose. The billing view builds Stripe's `successUrl`, `cancelUrl` and the portal `returnUrl` by concatenating this origin with a path, and Stripe requires absolute urls. Left unset or empty, the screen hides the web checkout button rather than build a relative url, and the portal still opens, without a return url. Set to a relative value, the checkout reaches Stripe, which refuses it; the resulting `BillingException` is logged rather than shown, so the customer sees a button that does nothing. `dart run magic:dowel starter:doctor` reports the missing key. A store purchase on iOS or Android never reads `web_origin`. See [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md) for what `billable` changes. ## The push external id With the `notifications` feature on, this package declares who the device is subscribed as every time a session begins, and releases it on every sign-out, including the ones no call site performs (account deletion, and a session that simply expires). You wire nothing. What it declares is the prefix below followed by the authenticated user's id: ```dart 'notifications': { 'external_id_prefix': 'user_', }, ``` > [!WARNING] > This has to match what your backend addresses. `magic-starter-laravel`'s `HasNotifications` composes `user_`, so the default is correct against that backend, and changing one side alone means the server sends to an id no device carries. Nothing fails visibly when they disagree: the notification is accepted and delivered to nobody, and only a zero-recipient report on the server says so. > > A blank value resolves to `user_` rather than to no prefix, and surrounding whitespace is trimmed, because OneSignal rejects a bare numeric external id outright and the PHP side normalises the same way. Emptying this key does not switch the prefix off; it restores the default. Change it when one OneSignal app serves more than one kind of subject, and change the backend with it. On the backend the key is `onesignal.external_id_prefix` in `config/magic-starter.php`. `dart run magic:dowel starter:doctor` prints the prefix this config resolves to, so the two sides can be read against each other: ```text Push external id prefix: user_ (default, key not set) Push external id prefix: user_ (blank, using default) Push external id prefix: operator- ``` The first two resolve to the same prefix and are not the same situation: the second means the value you wrote is being discarded, which "key not set" would hide. It is printed rather than checked, and never fails: any prefix is valid as long as the backend uses the same one, and nothing inside this repository can see the other side. `--verbose` adds the key name and the backend key to compare it against. The value comes from the config file text, so an app that writes the key at runtime through `Config.set` is not covered (the command boots nothing and has no container to ask), and a whole-line `//` comment above the live key is skipped. ## Auth Identity Modes The `auth` block controls which identity fields the login and registration forms show: ```dart 'auth': { 'email': true, 'phone': false, }, ``` | `email` | `phone` | Result | |:--------|:--------|:-------| | `true` | `false` | Email only (default). | | `false` | `true` | Phone only. | | `true` | `true` | Both fields are offered; the payload carries every non-empty identity field and the backend decides which one identifies the account. | Read the modes at runtime: ```dart final emailEnabled = MagicStarterConfig.emailIdentity(); final phoneEnabled = MagicStarterConfig.phoneIdentity(); ``` ## Locale & Timezone Defaults ```dart 'defaults': { 'locale': 'en', 'timezone': 'UTC', }, 'localization': { 'apply_user_locale': true, }, 'supported_locales': [ 'en', 'tr', ], ``` | Key | Default | Description | |:----|:--------|:------------| | `defaults.locale` | `'en'` | The language a release note or campaign falls back to when the backend sent none in the reader's own. | | `defaults.timezone` | `'UTC'` | Read through `MagicStarterConfig.defaultTimezone()`; no screen in the package consumes it. | | `localization.apply_user_locale` | `true` | Whether a signed-in user's saved `locale` attribute is applied to the running app automatically, on sign-in and on restore. Set `false` to own locale switching yourself. See [Locale Application](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#locale-application). | | `supported_locales` | `['en', 'tr']` | Read through `MagicStarterConfig.supportedLocales()`; no screen in the package consumes it. The language picker lists `MagicStarter.localeOptions`, which comes from `useLocaleOptions()` or, without it, from magic's own `Lang.supportedLocales`. | The `legal` block carries optional links shown on the registration screen and the billing page: ```dart 'legal': { 'terms_url': 'https://example.com/terms', 'privacy_url': 'https://example.com/privacy', }, ``` Both default to `null`, and a blank string reads as unset. `MagicStarterConfig.hasLegalLinks()` says whether at least one is set. The `account` block names where a card-billed subscription is cancelled and the account deleted: ```dart 'account': { 'deletion_url': 'https://app.example.com/account', }, ``` A refused account deletion offers that page as its one action; with `null` (the default), or a blank string, it offers none. ## Accessing Values `MagicStarterConfig` carries the defaults and the types, so prefer it to raw `Config.get()`: ```dart // Feature checks final teamsEnabled = MagicStarterConfig.hasTeamFeatures(); final registrationEnabled = MagicStarterConfig.hasRegistrationFeatures(); final twoFactorEnabled = MagicStarterConfig.hasTwoFactorFeatures(); // Route paths final loginPath = MagicStarterConfig.loginRoute(); final profilePath = MagicStarterConfig.profileRoute(); // Identity, defaults and legal links final emailAuth = MagicStarterConfig.emailIdentity(); final locale = MagicStarterConfig.defaultLocale(); final termsUrl = MagicStarterConfig.termsUrl(); ``` For dynamic access, or when you need the raw value, use dot notation: ```dart final teamsEnabled = Config.get('magic_starter.features.teams', false); final authPrefix = Config.get('magic_starter.routes.auth_prefix', '/auth'); final termsUrl = Config.get('magic_starter.legal.terms_url', null); ``` ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md): running the installer and bootstrapping the starter. - [CLI Commands](https://anilcancakir.com/magic/docs/starter/basics/cli.md): `starter:configure` and `starter:doctor`. - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): the identity modes, social login and handoff in use. - [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md): the team resolver and the billable subject. - [Support](https://anilcancakir.com/magic/docs/starter/basics/support.md): the support and store review keys. - [Releases](https://anilcancakir.com/magic/docs/starter/basics/releases.md): the changelog page and the update banner. --- # Authentication The feature-gated sign-in surface of the starter: login, registration, password reset, email verification, two-factor, social, phone OTP, guest and handoff, and the controllers behind them. - [Introduction](#introduction) - [Login Flow](#login-flow) - [Registration](#registration) - [Forgot Password](#forgot-password) - [Verify Email](#verify-email) - [Landing After Sign-In](#next) - [Sign-In Handoff](#handoff) - [Reset Password](#reset-password) - [Two-Factor Authentication](#two-factor-authentication) - [Two-Factor Challenge](#two-factor-challenge) - [Enabling Two-Factor](#enabling-two-factor) - [Recovery Codes](#recovery-codes) - [Social Login](#social-login) - [The MagicStarterSocialAuth Contract](#the-magicstartersocialauth-contract) - [OTP Flow](#otp-flow) - [Sending an OTP](#sending-an-otp) - [Verifying an OTP](#verifying-an-otp) - [Guest Sessions](#guest-sessions) - [Guest Claim](#guest-claim) - [Logout](#logout) - [Before-Logout Hooks](#before-logout-hooks) - [Onboarding Steps](#onboarding-steps) - [Identity Modes](#identity-modes) - [Feature Gates](#feature-gates) - [Controllers](#controllers) - [Views](#views) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction The authentication module is built on the Magic framework and driven by opt-in configuration flags. It covers login, registration, password reset, email verification, two-factor authentication, social login, phone OTP, guest authentication and sign-in handoff. These controllers split the responsibilities (the handoff controller is covered under [Sign-In Handoff](#handoff)): | Controller | Scope | |-----------|-------| | `MagicStarterAuthController` | Login, register, forgot/reset password, email verification, social sign-in, two-factor challenge, logout | | `MagicStarterGuestAuthController` | Device-ID-based guest login | | `MagicStarterOtpController` | Phone OTP send and verify | Every controller follows the Magic singleton pattern (`static T get instance => Magic.findOrPut(T.new)`) and mixes in `NavigatesRoutes` and `CompletesSignIn`; the auth, guest and OTP controllers add `MagicStateMixin` and `ValidatesRequests`. > [!NOTE] > All auth routes are registered under the configurable prefix `MagicStarterConfig.authPrefix()` (default `/auth`). Guest-facing routes use `GuestLayout`; post-login routes use `AppLayout`. ## Login Flow Call `MagicStarterAuthController.instance.doLogin()` with the user's credentials. The controller builds the identity payload based on the active [identity mode](#identity-modes), sends `POST /auth/login`, and handles the response: ```dart await MagicStarterAuthController.instance.doLogin( email: form['email'], phone: form['phone'], password: form['password'], rememberMe: form.value('remember_me'), ); ``` `rememberMe` is sent as `remember_me`. `anilcancakir/magic-starter-laravel` reads it from 1.0.0; up to 0.0.64 (published as `fluttersdk/magic-starter-laravel`) ignores it, so the "remember me" checkbox changes nothing there. On 1.0.0 the checkbox changes the token lifetime only once the backend sets `MAGIC_STARTER_REMEMBER_ME_EXPIRATION` (`remember_me_expiration_minutes`, in minutes). That setting and `MAGIC_STARTER_TOKEN_EXPIRATION` both default to `null`: a remembered sign-in then gets the ordinary lifetime, and when both are `null` the token does not expire unless `sanctum.expiration` says so. The login flow has three possible outcomes: 1. **Success**: the controller hands the body to `CompletesSignIn.completeSignIn()`, the one path every token takes (password, social, two-factor challenge, OTP and guest): it extracts `token` and `user` from the nested `data` key, calls `Auth.login()`, shows the `social.deletion_cancelled` toast when `data.deletion_cancelled` is `true` (a sign-in during the grace period of a scheduled account deletion cancels it), sets success state, and calls `navigateHome()`. That is the intended url a bounced deep link recorded, read once through `MagicRouter.pullIntendedUrl()`, and `MagicStarterConfig.homeRoute()` only as the fallback when nothing was recorded or the recorded value is not an in-app path. An intent belongs to the session that asked for it: `MagicStarterServiceProvider` listens to `Auth.stateNotifier` and discards it whenever the state goes to signed-out, so it never reaches the next person on the device. That covers the sign-out a user asks for, the account deletion, and the one the app performs on its own when a token refresh fails, since all three go through the same notifier. No host wiring is needed; the provider boots in every starter app. 2. **Two-factor required**: the controller detects the challenge flag and navigates to `MagicStarterConfig.twoFactorChallengeRoute()` with the encrypted token as a query parameter. No login occurs yet. 3. **Failure**: `handleApiError()` sets the error state with a localised fallback message. > [!IMPORTANT] > Two-factor detection checks **both** `response['two_factor']` and `response['data']['two_factor']`. Some backends nest the flag differently, and the controller handles both variants. A `_isSubmitting` guard prevents double-submit: concurrent calls to `doLogin()` are silently discarded. The login, register, forgot-password and reset-password views hint their fields (`username`/`email`, `password`, `newPassword`, `telephoneNumber`) so a password manager or the OS keychain can fill them. The login, register and reset-password forms sit in an `AutofillGroup` that cancels on dispose, and the login and register forms stay mounted while the request is in flight; the context is committed (`TextInput.finishAutofillContext(shouldSave: true)`) only after an email and password sign-in or a registration has logged a session in and is about to navigate (`completeSignIn(saveCredentials: true)`), so a failed attempt, a provider or one-time-code sign-in, and a background guest session are never offered for saving. `Auth.login()` dispatches magic's `AuthLogin` event, which `MagicStarterServiceProvider` listens for to call the host's `MagicStarter.useLogin()` hook (see [Login Callback](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#login-callback)), unawaited and logged on failure. It fires for every sign-in path this package ships: password (above), [two-factor challenge](#two-factor-challenge), [social login](#social-login), guest login (`MagicStarterGuestAuthController.doGuestLogin()`) and [OTP verification](#verifying-an-otp), and never for a cold-boot restore of a stored session. ## Registration `doRegister()` collects `name`, `email`/`phone` (per identity mode), `password`, and `password_confirmation`: ```dart await MagicStarterAuthController.instance.doRegister( name: form['name'], email: form['email'], phone: form['phone'], password: form['password'], passwordConfirmation: form['password_confirmation'], subscribeNewsletter: form.value('subscribe_newsletter'), ); ``` When the `newsletter` feature is active and `subscribeNewsletter` is `true`, the payload includes `subscribe_newsletter: true`. The response determines the post-registration flow: - **Auto-login**: when the server returns `token` + `user` in `data`, the controller calls `Auth.login()` and navigates home. - **Email verification required**: when no credentials are returned, the controller navigates to the login page so the user can verify their email first. > [!TIP] > Registration is gated by `MagicStarterConfig.hasRegistrationFeatures()`. When disabled, the registration route is not registered and the view is inaccessible. ## Forgot Password Sends a password reset link via `POST /auth/forgot-password`: ```dart await MagicStarterAuthController.instance.doForgotPassword( email: form['email'], ); ``` On success, the controller sets success state. The view should display a confirmation message. No navigation occurs; the user stays on the same page. ## Verify Email Registered with `magic_starter.features.email_verification`. The verification mail of `magic-starter-laravel` opens `/auth/verify-email?id=...&hash=...&expires=...&signature=...`. `MagicStarterVerifyEmailView` reads the four query parameters once in `didChangeDependencies` and calls `doVerifyEmail`, which replays them as `GET /email/verify/{id}/{hash}?expires=...&signature=...`; the API's `signed` middleware checks them against its own host. On success a signed-in user is restored so `email_verified_at` lands, and the page offers Continue (home) or Back to Sign In. Any refusal (a bad or expired signature, a changed address), and any link whose `id` is not key-shaped or whose `hash` is not a sha1, shows `magic_starter.email_verification.verify_failed`; the malformed link is never sent. A reader signed in as a different user sees `verify_success_other` instead of the second-person copy. The route sits outside the `guest` group: the link is opened signed in as often as signed out, and `guest` would send a signed-in reader home before the link was replayed. ## Landing After Sign-In (`?next=`) `MagicStarterLoginView` and `MagicStarterRegisterView` read a `next` query once when they open. A valid in-app path becomes the router's intended url (`MagicRouter.setIntendedUrl`), so the sign-in or sign-up that follows from that screen (password, social, two-factor, OTP, registration) lands there through `navigateHome()`. Without `next`, or with one that is not valid, the screens record nothing and leave an intent `EnsureAuthenticated` recorded alone. A valid `next` has exactly one leading `/` (`//host` is another origin), at most 512 characters, no backslash, no whitespace, separator or other `\p{C}` character (controls, format characters such as U+202E, private use, unassigned), the same rule as the backend's `SameAppPath`, no `..` path segment (percent-encoded included). Anything else is ignored silently. ## Sign-In Handoff Registered with `magic_starter.features.handoff`. Another surface that has already authenticated the visitor (a landing page, a mail) asks `magic-starter-laravel` for a one-time code (`POST auth/handoff`, authenticated) and opens the app at `/auth/handoff?code=&next=`, on the web or through a Universal Link or App Link that resolves to the same route. No bearer token travels in a url. `MagicStarterHandoffView` reads `code` and `next` once and calls `MagicStarterHandoffController.handOff`: 1. **With a code**, the controller posts it to `POST auth/handoff/exchange`. The answer is a login answer plus `data.next`, held in memory only. - The page asks "Sign in as ?" with Continue and Cancel before anything changes, with or without an open session. Without one the question is what stops a login CSRF: a link carrying an attacker's own code would otherwise sign the visitor in to the attacker's account. `handoff.confirm_without_session` (default `true`) is the one knob: an app may set it to `false` to skip that tap when no session is open; over an open session the page always asks. - Continue signs any open session out through `MagicStarterAuthController.logout()` (before-logout hooks included), records `data.next` (validated like `?next=`; the query `next` is ignored once a code is exchanged, since it is not bound to the code) as the intended url and concludes through `completeSignIn`, so a two-factor answer opens the challenge and its success lands on `next` too. - Cancel goes home with an open session untouched, or to the sign-in screen without one. The exchange already minted a token on the server (and cancelled a scheduled account deletion), so a declined answer, one dropped by leaving the page, and one that lands after the page closed are revoked with `POST auth/logout` presenting that token on the same bare driver: best effort, never logged, never touching the open session. A two-factor answer carries no token and revokes nothing. - A refused code (the backend's one 422 shape, `code: handoff_expired`), a transport failure or an answer that is neither a session nor a challenge changes nothing: home over a session, the sign-in screen without one, with one toast (`magic_starter.handoff.expired`) that never tells which of those it was. 2. **Without a code** but with a valid `next`: signed in, the visitor goes to `next`; signed out, to `handoff.signed_out_route` (default `routes.login`) carrying `?next=`, which the login and register screens honour. 3. **With neither**: home when signed in, the sign-in screen otherwise. The route sits outside the `guest` group and carries no `auth` middleware: a visitor with an open session has to reach the confirmation. The exchange goes out on a bare `DioNetworkDriver` with the `Http` facade driver's origin, timeout and default headers but none of its interceptors, so magic's `AuthInterceptor` neither attaches the open session's bearer nor answers a 401 with its refresh-or-logout path, and no devtools recorder keeps the answer, which carries the new token. The code, the token and the handed email are never logged; the email (or name) appears only on the confirmation. An app overrides the page through the registry key `auth.handoff`. The code stays in the browser history entry of `/auth/handoff?code=...`. It is single use, but removing it from history is the app's job; the starter does not rewrite the address bar. A web host should also send `` so the code never rides a same-origin `Referer` into a server log. The exchange mints its token before the visitor confirms. A visitor who closes the tab on "Sign in as ...?" leaves that token alive until it is revoked by hand, because the page can only revoke on Cancel or when it is left through the app. ## Reset Password Completes the password reset using the token from the email link, `/auth/reset-password?token=...&email=...`. Both values are query parameters, not path segments. The view reads them once in `didChangeDependencies` through `MagicRouter.instance.queryParameterOf(context, ...)`, which answers for the page the view sits in; `initState` cannot read route state, and the static `queryParameter()` answers for whichever page was built last: ```dart @override void didChangeDependencies() { super.didChangeDependencies(); if (_token != null) return; _token = MagicRouter.instance.queryParameterOf(context, 'token') ?? ''; _email = MagicRouter.instance.queryParameterOf(context, 'email') ?? ''; } await MagicStarterAuthController.instance.doResetPassword( token: _token!, email: _email!, password: form['password'], passwordConfirmation: form['password_confirmation'], ); ``` On success, the controller sets success state. The view should display a confirmation and provide a link back to login. ## Two-Factor Authentication Two-factor authentication spans two contexts: **challenging** (during login) and **managing** (in profile settings). ### Two-Factor Challenge When `doLogin()` detects a two-factor requirement, it navigates to the challenge view with the encrypted `two_factor_token`. The user enters either a TOTP code from their authenticator app or a recovery code: ```dart await MagicStarterAuthController.instance.doTwoFactorChallenge( twoFactorToken: token, code: form['code'], // TOTP from authenticator // OR recoveryCode: form['recovery_code'], // One-time recovery code ); ``` Exactly one of `code` or `recoveryCode` must be provided; the controller asserts this invariant in debug builds. On success, the flow completes the same as a normal login: `Auth.login()` followed by navigation to home. ### Enabling Two-Factor Enabling 2FA is a multi-step process managed by `MagicStarterProfileController`: 1. **Enable**: `doEnableTwoFactor(proof:)` calls `POST /two-factor-authentication`. Returns a map containing `secret`, `qr_url`, `qr_svg`, and `recovery_codes`. 2. **Confirm**: `doConfirmTwoFactor(code:)` calls `POST /two-factor-authentication/confirm` with the TOTP code from the authenticator app. 3. **Disable**: `doDisableTwoFactor(proof:)` uses Laravel method spoofing (`{'_method': 'DELETE'}`) via `Http.post()`. > [!NOTE] > The `isTwoFactorEnabled` getter reads `two_factor_enabled` from the authenticated user model. Use it to conditionally render the enable/disable UI. ### Recovery Codes Recovery codes can be viewed and regenerated via `MagicStarterProfileController`: ```dart // View existing codes (requires a step-up proof) final codes = await controller.getRecoveryCodes(proof: proof); // Regenerate codes (requires a step-up proof) final newCodes = await controller.doRegenerateRecoveryCodes(proof: proof); ``` Both methods call endpoints under `/two-factor-recovery-codes`. Like enabling and disabling 2FA, they take a `proof` map: `{'password': ...}` for an account with a password, `{'code': ...}` or `{'confirmation_token': ...}` for one without, `{}` for a guest. See [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md) for how the starter produces one. ## Social Login Social login is feature-gated via `magic_starter.features.social_login`. The starter owns the screens (the "Continue with" buttons on login and register, the [Connected accounts](https://anilcancakir.com/magic/docs/starter/basics/connected-accounts.md) page, the identity-confirmation dialog) and what a sign-in concludes (a session, a two-factor challenge, a cancelled deletion). The provider SDKs and the backend calls belong to a **bridge** the app registers, so this package depends on no social login package. ```dart MagicStarter.useSocialAuth(AppSocialAuth()); ``` While a bridge is registered and the feature is on, login and register render one button per provider the bridge offers, and the Connected accounts page is reachable from the settings hub. Without a bridge the buttons and the hub row are absent: the feature flag alone renders nothing. The page's route is registered on the feature alone, since the bridge is set after the routes are. `magic_social_auth` installs the bridge for you: `social:install` publishes `lib/app/providers/social_auth_starter_service_provider.dart`, which implements the contract below over `SocialAuth` and calls `MagicStarter.useSocialAuth`. See its [installation guide](https://anilcancakir.com/magic/docs/social_auth/getting-started/installation). ### The MagicStarterSocialAuth Contract ```dart abstract class MagicStarterSocialAuth { List providers(); // in display order: google, apple, ... String label(String provider); // 'Google' Widget icon(String provider); Future> signIn(String provider); Future> Function()> beginConnect( String provider, Map proof, ); Future confirm(String provider); // the confirmation token Future signOut(); } ``` | Method | Contract | |---|---| | `signIn(provider)` | Answers the backend's body untouched: a session (`{data: {user, token}}`, plus `data.deletion_cancelled` when the sign-in cancelled a scheduled deletion) or a challenge (`{two_factor: true, two_factor_token}`). Called synchronously from the user's tap, with no `await` before it, so a web implementation can still open its popup. A newer call supersedes a pending one. | | `beginConnect(provider, proof)` | Starts linking a provider to the signed-in account and answers the call that finishes it. `proof` is minted fresh for every call and empty for a guest. Whatever needs the network before the provider opens (a link ticket) happens here, so the returned call opens the provider before its first `await`: on the web the starter runs it from a fresh user tap, elsewhere at once. It answers `{data: {provider, email}}`. | | `confirm(provider)` | Re-authenticates the signed-in user with a linked provider and answers the confirmation token the backend issued. | | `signOut()` | Signs out of every provider SDK that keeps a session of its own. The starter does not call it; the bridge `social:install` publishes signs Google out itself whenever `Auth.stateNotifier` goes to signed-out, and a bridge of your own has to do the same. | Every failure surfaces as a `MagicStarterSocialException(code:, message:, cancelled:)`. `cancelled` marks the user backing out, which the starter shows nothing for. Otherwise the starter shows the `social.` sentence (`social_email_taken`, `flow_expired`, `step_up_required`, ...) and falls back to `message`. ### What a Social Sign-In Does `MagicStarterAuthController.doSocialSignIn(provider)` calls the bridge before anything is awaited, then concludes through the same `completeSignIn` as every other sign-in: a two-factor answer opens the challenge, a session logs in and goes home, and `deletion_cancelled` shows the "Account deletion cancelled" toast. A cancelled flow shows nothing; a pending flow does not block a new tap. > [!IMPORTANT] > Provider sign-out is the bridge's job. The Google SDK keeps its own session, so a bridge of your own has to sign it out on every transition to signed-out (listen to `Auth.stateNotifier`), or the next sign-in skips the account picker. The published bridge does this. ### Language Keys The screens read a `social.*` group (`continue_with`, `connect`, `disconnect`, `connected_accounts`, `confirm_identity`, `confirm_with`, `step_up_required`, `deletion_cancelled`, `deletion_scheduled`, and one sentence per backend refusal code), `profile.set_password`, `profile.set_password_description`, `profile.password_set`, `profile.password_set_failed` and `magic_starter.titles.connected_accounts`. A fresh `starter:install` writes them to `assets/lang/en.json`; an existing app adds them from `assets/stubs/install/en.stub`. ## OTP Flow The phone OTP flow is a two-step process managed by `MagicStarterOtpController`. It is gated by the `phone_otp` feature flag alone: the route and the registry key exist only while `magic_starter.features.phone_otp` is on. ### Sending an OTP Step 1 collects the phone number and sends the OTP via `POST /auth/otp/send`: ```dart await MagicStarterOtpController.instance.sendOtp( phone: '+905301234567', // E.164 format ); ``` On success, the controller transitions from `OtpStep.phoneInput` to `OtpStep.codeInput` and stores the phone number internally for step 2. ### Verifying an OTP Step 2 verifies the 6-digit code via `POST /auth/otp/verify`: ```dart await MagicStarterOtpController.instance.verifyOtp( phone: controller.phoneNumber ?? '', code: form['code'], ); ``` On success, the controller calls `Auth.login()` with the returned token and navigates home. Call `controller.resetToPhoneInput()` to restart the flow. > [!NOTE] > The `OtpStep` enum drives the view state. Check `controller.step` to determine which input (phone or code) to display. ## Guest Sessions `MagicStarterGuestAuthController` signs a visitor in as a guest with `POST /auth/guest`, sending a device id it keeps in `Vault` under `guest_device_id`, so the backend recognises a returning guest. Two entry points share the request: - `doGuestLogin()` is the login screen's "Continue as guest": it opens the session, then goes home. - `openGuestSession()` opens one in the background and leaves the viewer where they are, for a host that needs a session before anyone asks for one. It resolves `true` when a session exists afterwards and `false` when none could be opened (the reason is in the controller's error state); it never throws. ```dart final bool hasSession = await MagicStarterGuestAuthController.instance.openGuestSession(); ``` A session already held is kept and no request goes out: a guest's, because a second `POST /auth/guest` revokes every token that guest holds, and an account's, signed in or only stored, because a guest never replaces an account. Concurrent callers share the request in flight and its result; once it settles, the next call tries again. ## Guest Claim With `guest_auth` on, what a guest accumulated moves to the account they sign in to next. `MagicStarterGuestClaim` runs the flow, and `MagicStarterServiceProvider` wires it to magic's auth events: 1. **Guest sign-in** (`AuthLogin` for a user whose `is_guest` is `true`): the guest's bearer token and user id are written to `Vault` under `MagicStarterGuestClaim.tokenKey` (`guest_claim_token`) and `MagicStarterGuestClaim.userKey` (`guest_claim_user`). The write is local and awaited. 2. **Sign-in or restore of a real account** (`AuthLogin` for a non-guest, or `AuthRestored`): `claimIfPending()` runs unawaited, so it never holds up `Auth.login` or a cold-boot `Magic.init`. When the recorded id equals the signed-in id (registration promoted the guest row in place), the record is dropped with no request. Otherwise it posts `POST /auth/guest/claim` with `{'guest_token': }` and `Authorization: Bearer `. A 2xx settles as `claimed`, a 404 (the backend has no claim route) or a 422 settles as `refused`, and either drops the record; anything else keeps it for the next sign-in or restore. 3. **Sign-out** (`AuthLogout`): `MagicStarterGuestClaim.forget()` deletes the record before `Auth.logout()` returns, so the next person to sign in on the device cannot claim the previous viewer's rows. It also ends the session a claim in flight belongs to: that claim's answer is dropped, it settles as `none`, it never touches a guest recorded after it, and the next sign-in starts its own claim. Every outcome but `GuestClaimOutcome.none` reaches `MagicStarter.useGuestClaimed()` (see [Guest Claim Callback](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#guest-claim-callback)). An app that needs its own ordering after the claim (a refetch that must see the moved rows, say) calls it directly: ```dart final GuestClaimOutcome outcome = await MagicStarterGuestClaim.instance.claimIfPending(); ``` A claim already in flight hands every caller in the same session the same future, so this never posts the token twice. The claim does not ride the `Http` facade. Its body is the guest's live bearer token, and the facade's driver is the one `magic_devtools` records request bodies from in debug and profile builds. It goes out on a bare `DioNetworkDriver` built from `network.drivers.api` (`base_url`, `timeout`, `headers`) with no interceptors. That driver sends no magic `User-Agent`: `NetworkServiceProvider` adds that header only to the facade driver, so set one in `network.drivers.api.headers` if the backend needs it on this request. ## Logout There are two sign-out paths a user can take, and both end in `Auth.logout()`: - `MagicStarterAuthController.instance.logout()`: runs the before-logout hooks, stops notification polling and the push identity (when the `notifications` feature is on), calls `Auth.logout()`, then navigates to `MagicStarterConfig.loginRoute()`. - The profile dropdown's sign-out item: calls your `MagicStarter.useLogout()` callback when one is registered, after running the before-logout hooks, and the controller path above otherwise. The hooks run once either way. ### Before-Logout Hooks Some work needs the session token and has to happen before it is dropped: releasing this device's push registration on your backend, revoking a server-side session, signing out of a social SDK. Register it once, from a service provider `boot()`: ```dart MagicStarter.beforeLogout(() => SocialAuth.signOut()); ``` The contract: - Hooks run in registration order, **before** a custom `useLogout()` callback and **before** `Auth.logout()`, on both paths above. - Each hook is isolated: a throw is logged with `Log.error` and the next hook runs. - Each hook is bounded to five seconds (`MagicStarterManager.beforeLogoutTimeout`); a dead network cannot trap somebody who asked to leave. - Registering the same hook twice keeps one copy. - A sign-out button of your own calls `await MagicStarter.manager.runBeforeLogoutHooks()` before its own `Auth.logout()`. When the `magic_notifications` package is bound and its push-state reporting is configured (`notifications.push_state.report_path`), `MagicStarterServiceProvider` registers `Notify.pushState.release` as a default hook, so the backend stops treating this device as reachable for the person who just left it. Nothing to wire. It also registers a hook that revokes the token on the server, `POST /auth/logout` with the still-valid bearer, so a sign-out ends the session on the backend rather than only forgetting the token on the device. It runs after the push release, sends nothing when no token is held, and logs a refused or failed request without holding up the sign-out. A hook you register after `MagicStarterServiceProvider` boots runs after the revoke, on a dead token. > [!WARNING] > Hooks do not run for a sign-out the app performs on its own. Magic's `AuthInterceptor` calls `Auth.logout()` when a token refresh fails, and by then the token is already dead: an authenticated hook could only answer `401`. Server-side state that must not outlive a session (a push-device row, for one) needs its own expiry on the backend. ## Onboarding Steps `MagicStarterOnboarding` is a one-time gate for first-run steps (a locale confirmation, a feature tour, a welcome banner): each step is shown once per device and never again. Each step persists under its own `Vault` key (`onboarding__done`), and every loaded step is mirrored in memory so a synchronous `build` can read it. Load the steps your app cares about once, after `Magic.init()`, then read and flip them from the screens that own them: ```dart await MagicStarterOnboarding.load(['locale', 'tour']); if (!MagicStarterOnboarding.isCompleted('tour')) { // Show the tour, then: await MagicStarterOnboarding.markCompleted('tour'); } ``` | Member | Purpose | |--------|---------| | `load(steps)` | Reads every step's flag from `Vault`. A missing key, or a `Vault` read that fails (logged as a warning), reads as not completed. | | `isCompleted(step)` | Whether the step was resolved on this device. Synchronous. | | `markCompleted(step)` | Flips the flag in memory at once and persists it. | | `vaultKeyFor(step)` | The `Vault` key a step persists under. | The flags are per device, not per account: they survive sign-out and a sign-in as someone else. ## Identity Modes The starter supports three identity modes configured via `magic_starter.auth.email` and `magic_starter.auth.phone`: | `auth.email` | `auth.phone` | Mode | Behaviour | |:-------------|:-------------|:-----|:----------| | `true` | `false` | Email-only (default) | Only `email` field is sent in the payload | | `false` | `true` | Phone-only | Only `phone` field is sent in the payload | | `true` | `true` | Both | Every non-empty field is sent | The private `_applyIdentityToPayload()` helper centralises this logic across login and registration. In "both" mode, every non-empty identity field is included, so the backend receives whatever the form collected and decides which one identifies the account. ```dart // Config for phone-only mode Config.set('magic_starter.auth.email', false); Config.set('magic_starter.auth.phone', true); ``` > [!IMPORTANT] > `doLogin()` sets the `auth.login_failed` error and returns before any request when both `email` and `phone` are empty, and sets a `validation.required` error when `password` is empty. Registration has no such early return: with no identity in email-only mode it sends `email: ''` and leaves the refusal to the backend. ## Feature Gates Authentication features are controlled by these configuration toggles. All default to `false`. | Config Key | Gate Method | Affects | |-----------|------------|---------| | `magic_starter.features.registration` | `hasRegistrationFeatures()` | Register view and route | | `magic_starter.features.social_login` | `hasSocialLoginFeatures()` | Social login buttons on login/register, the Connected accounts page and its settings row (all need a bridge from `MagicStarter.useSocialAuth`), and the "Confirm with a provider" option of the identity-confirmation dialog | | `magic_starter.features.two_factor` | `hasTwoFactorFeatures()` | 2FA enable/disable in profile, challenge route | | `magic_starter.features.guest_auth` | `hasGuestAuthFeatures()` | Guest login flow | | `magic_starter.features.phone_otp` | `hasPhoneOtpFeatures()` | Phone OTP send/verify | | `magic_starter.features.newsletter` | `hasNewsletterFeatures()` | Newsletter checkbox on registration | | `magic_starter.features.email_verification` | `hasEmailVerificationFeatures()` | Email verification flow | | `magic_starter.features.handoff` | `hasHandoffFeatures()` | Sign-in handoff route and view | | `magic_starter.auth.email` | `emailIdentity()` | Email field in login/register (default `true`) | | `magic_starter.auth.phone` | `phoneIdentity()` | Phone field in login/register (default `false`) | > [!TIP] > A feature that is disabled registers no route, so navigating to its path hits the router's not-found handling: magic logs `Route not found` and nothing opens. A few view keys are registered only while their feature is on (`auth.verify_email`, `auth.two_factor_challenge`, `auth.handoff`, `auth.otp_verify` and the settings pages that mirror a toggle), and `MagicStarter.view.make` throws a `StateError` for one of them when the feature is off. `auth.login`, `auth.register`, `auth.forgot_password` and `auth.reset_password` are always registered; only their routes follow the toggles. Check the config before navigating programmatically. ## Controllers | Controller | Singleton | Key Methods | |-----------|----------|-------------| | `MagicStarterAuthController` | `.instance` | `doLogin()`, `doRegister()`, `doForgotPassword()`, `doResetPassword()`, `doTwoFactorChallenge()`, `logout()` | | `MagicStarterGuestAuthController` | `.instance` | `doGuestLogin()`, `openGuestSession()`, `isGuestUser`, `getStoredDeviceId()` | | `MagicStarterOtpController` | `.instance` | `sendOtp()`, `verifyOtp()`, `resetToPhoneInput()`, `step`, `phoneNumber` | | `MagicStarterHandoffController` | `.instance` | `handOff()`, `confirm()`, `cancel()`, `forget()`, `isConfirming`, `confirmingAs` | All controllers use the `NavigatesRoutes` mixin for safe navigation. Never call `context.go()` directly in a controller: the navigator context may not be mounted. The mixin checks `MagicRouter.instance.navigatorKey.currentContext` and no-ops when unavailable. After successful login or registration, `Auth.login()` stores the token and user model. Call `Auth.restore()` when you need to refresh the user model from the backend (e.g., after profile updates). ## Views All views extend `MagicStatefulView` and are registered in the view registry with string keys: | Registry Key | View | Layout | |-------------|------|--------| | `auth.login` | `MagicStarterLoginView` | `layout.guest` | | `auth.register` | `MagicStarterRegisterView` | `layout.guest` | | `auth.forgot_password` | `MagicStarterForgotPasswordView` | `layout.guest` | | `auth.reset_password` | `MagicStarterResetPasswordView` | `layout.guest` | | `auth.verify_email` | `MagicStarterVerifyEmailView` | `layout.guest` | | `auth.two_factor_challenge` | `MagicStarterTwoFactorChallengeView` | `layout.guest` | | `auth.otp_verify` | `MagicStarterOtpVerifyView` | `layout.guest` | | `auth.handoff` | `MagicStarterHandoffView` | `layout.guest` | Views are instantiated through the registry (`MagicStarter.view.make('auth.login')`) and wrapped in the appropriate layout (`MagicStarter.view.makeLayout('layout.guest', child: view)`). The host app can override any view by registering a custom builder under the same key. Views carry no business logic: async operations, state management and navigation decisions live in the controllers. ### Names for a screen reader The icon-only controls on the auth screens read their names from the catalogue: `common.toggle_theme` for the theme toggle at the top of the auth card, and `auth.show_password` or `auth.hide_password` for the eye on a password field (the register, reset password and password settings screens and the password confirmation dialog carry it too). The eye names the action its next tap performs, so the label flips with the field. The install stub ships the three keys; an app installed before `auth.show_password` and `auth.hide_password` gets the English names (`Show password`, `Hide password`, `Toggle theme`) rather than the raw keys until it adds them to its own language files. ## Gotchas | Mistake | Fix | |:--------|:----| | Passing `password:` to `doEnableTwoFactor`, `doDisableTwoFactor`, `getRecoveryCodes` or `doRegenerateRecoveryCodes` | They take `proof:` (`{password}`, `{code}`, `{confirmation_token}` or `{}` for a guest); the screens get one from [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md). | | Concluding a sign-in by hand with `Auth.login()` | Every token (password, social, two-factor challenge, OTP, guest) goes through `CompletesSignIn.completeSignIn`, which also handles the two-factor answer and `deletion_cancelled`. | | Enabling `social_login` and expecting buttons | The buttons and the Connected accounts page render only after `MagicStarter.useSocialAuth(bridge)`; the flag alone renders nothing. | | Checking only `response['two_factor']` for a challenge | `completeSignIn` reads both `response['two_factor']` and `response['data']['two_factor']`; a controller of your own has to do the same. | | Calling `context.go()` from a controller | Use `navigateTo(path)` from the `NavigatesRoutes` mixin; the navigator may not be mounted. | | Expecting an authenticated before-logout hook to run after a failed token refresh | Hooks run on the two sign-out paths of the starter only. When `AuthInterceptor` signs out after a refresh failure the token is already dead; give server-side state its own expiry. | ## Related Documentation - [Identity Confirmation](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md): the step-up proof the two-factor and session calls take. - [Connected Accounts](https://anilcancakir.com/magic/docs/starter/basics/connected-accounts.md): linking and unlinking providers. - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): two-factor management, sessions and account deletion. - [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md): team switching after sign-in. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature flags and identity keys. - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): `useLogin`, `useLogout` and `beforeLogout` callbacks. - [Middleware](https://anilcancakir.com/magic/docs/starter/basics/middleware.md): the `auth` and `guest` route guards. --- # Confirming Identity How the starter asks an account to prove who it is again before a sensitive action, and which proof each kind of account gives. - [Introduction](#introduction) - [Which Proof an Account Gives](#which-proof-an-account-gives) - [Gated Controller Methods](#gated-controller-methods) - [The Step-Up Dialog](#the-step-up-dialog) - [Refusals](#refusals) - [Helpers](#helpers) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction A few actions are sensitive enough that the backend asks the caller to prove who they are again: turning two-factor on or off, viewing or regenerating recovery codes, revoking a browser session, deleting the account, linking a provider and setting a first password. An account with a password types it. An account created through a provider has none, so the backend takes a different proof. ## Which Proof an Account Gives | Account | Proof | Request fields | |:--------|:------|:---------------| | Has a password | The password, in a password dialog | `password` | | No password, not a guest | A step-up dialog (below) | `code`, or `confirmation_token` | | Guest (`is_guest`, no password) | None: the backend lets it through and no dialog is shown | none | `has_password` and `is_guest` come from the user resource. A proof is **minted per call and never kept**: a confirmation token is single use, so a retry asks again. The proof reaches the controller as a `Map` that is spread into the request body. ## Gated Controller Methods These methods on `MagicStarterProfileController` take `proof:`, not `password:`. Where the route is a `DELETE`, the controller sends a `POST` with `_method: DELETE` in the body (Laravel method spoofing) and the proof fields beside it: | Method | Request | |:-------|:--------| | `doEnableTwoFactor(proof:)` | `POST /two-factor-authentication` | | `doDisableTwoFactor(proof:)` | `POST /two-factor-authentication` with `_method: DELETE` | | `getRecoveryCodes(proof:)` | `POST /two-factor-recovery-codes/show` | | `doRegenerateRecoveryCodes(proof:)` | `POST /two-factor-recovery-codes` | | `doRevokeSession(tokenId:, proof:)` | `POST /sessions/{token}` with `_method: DELETE` | | `doRevokeOtherSessions(proof:)` | `POST /sessions/other` with `_method: DELETE` | | `doDeleteAccount(proof:)` | `POST /user` with `_method: DELETE` (schedules the deletion) | | `doSetPassword(password:, passwordConfirmation:, proof:)` | `POST /user/password/set` (see [Set a Password](https://anilcancakir.com/magic/docs/starter/basics/set-password.md)) | Connecting a provider carries the same proof through `beginSocialConnect(provider, proof:)` to the bridge's `beginConnect`. To pass a password account's proof by hand, use `{'password': password}`. ## The Step-Up Dialog `MagicStarterStepUpDialog` asks a password-less account for what it can send: - **A code field**, when two-factor is confirmed on the account (`two_factor_enabled`): a TOTP code, sent as `code`. - **One "Confirm with " button per linked provider** (an entry of `social_accounts` with `revoked_at` null that the bridge also offers): it re-authenticates through `MagicStarterSocialAuth.confirm(provider)` and sends the resulting token as `confirmation_token`. A provider row asks the bridge again on every tap. - With neither, only the `social.step_up_required` sentence ("Please confirm your identity to continue."). It opens proactively for a password-less account. A refusal keeps it open and shows the error inline so the user can retry with a fresh proof. When the backend answers 422 `step_up_required`, its `accepts` list (`code`, `confirmation_token`) narrows the dialog to the proofs the server takes; `MagicStarterProfileController.stepUpAccepts` exposes it and is cleared with the errors. The web rule applies here too: the bridge's `confirm` is called before anything is awaited in the tap, so the provider popup opens. Cancel stays available while a provider confirm is pending, since on the web a closed popup only fails after a long timeout; a token that arrives after the dialog closed is discarded. ## Refusals Gated calls report a refusal by its `code`, never by its message: | Code | Shown as | |:-----|:---------| | `step_up_required` | `social.step_up_required`; the dialog narrows to `accepts`. | | `password_already_set`, `password_not_set` | The cached user was stale: it is restored first, and the page rebuilds with the other password form. | | `last_login_method` | `social.last_login_method`. | | `owns_shared_teams`, `team_has_active_subscription`, `subscription_active` | Their own `social.*` sentences (account deletion refused). | | anything else | The standard API error handling with the call's fallback sentence. | ## Helpers The starter's screens use two helpers from `lib/src/support/confirms_identity.dart`. The package barrel exports them, along with `MagicStarterStepUpDialog`, so a host that overrides a registry view can confirm a password-less account the same way. | Helper | Does | |:-------|:-----| | `confirmIdentity(context, {variant, title, description, accepts, attempt})` | Picks the proof by the rules above and answers it as request fields, or `null` when the user cancels. With `attempt`, each proof is handed to it before the dialog closes: a returned error string is shown inline and the dialog stays open for the next, fresh proof. | | `confirmAndRun(context, controller, {action, variant, title, description})` | Confirms identity, then runs a gated `action(proof)` inside the dialog, so a refusal is shown inline and the user retries without reopening it. The dialog stays open only while the server refuses the proof itself (`step_up_required`, or a field error on `password`, `code` or `confirmation_token`); any other refusal closes it and leaves the controller's error on the page. Resolves to `true` when the action succeeded, `false` when the user cancelled or the action was refused for another reason. | ```dart final success = await confirmAndRun( context, controller, title: trans('profile.set_password'), action: (proof) => controller.doDeleteAccount(proof: proof), ); ``` ## Gotchas | Mistake | Fix | |:--------|:----| | Keeping a proof between attempts | A proof is minted per call and a confirmation token is single use; ask again on every retry. | | Showing a dialog to a guest | `confirmIdentity` answers `{}` for a guest (no password, `is_guest`) without a dialog; the backend lets it through. | | Switching on a refusal's message | Read its `code` (`step_up_required`, `last_login_method`, ...); the message is localised and not stable. | | Calling the provider bridge's `confirm` after an `await` on the web | The popup is blocked. The step-up dialog calls `confirm` before anything is awaited in the tap; a bridge of your own must open the provider in that same call. | | Passing `password:` to a gated method | They take `proof:`; use `{'password': value}` for a password account or let `confirmIdentity` produce it. | | Treating `has_password` as present on every backend | `MagicStarterAuthUser.hasPassword` defaults to `true` when the field is missing, so a backend that never sends it shows the password dialog. | ## Related Documentation - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#social-login): the social bridge contract and `confirm`. - [Connected Accounts](https://anilcancakir.com/magic/docs/starter/basics/connected-accounts.md): the page that asks for a proof before it links a provider. - [Set a Password](https://anilcancakir.com/magic/docs/starter/basics/set-password.md): the first-password form for a provider account. - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): two-factor, sessions and account deletion, the gated screens. - [Social Auth Flows](https://anilcancakir.com/magic/docs/social_auth/basics/flows): how the bridge's `confirm` and `beginConnect` run. --- # Connected Accounts The settings sub-page where a signed-in user links a social provider to the account they already have, or removes a link. - [Introduction](#introduction) - [Requirements](#requirements) - [The Page](#the-page) - [Connecting a Provider](#connecting-a-provider) - [Disconnecting a Provider](#disconnecting-a-provider) - [Controller Methods](#controller-methods) - [User Data](#user-data) - [Overriding the Page](#overriding-the-page) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction The providers listed are the ones the registered bridge offers; the `magic_social_auth` bridge covers Google, Apple, GitHub and Microsoft. The page is drilled into from the Security group of the Settings hub and stacked over it. ## Requirements The route exists while `magic_starter.features.social_login` is `true`. It is registered on the feature alone: the app's bridge is set by a provider that boots after the one that registers routes, so the route cannot wait for it. The hub row additionally needs a bridge registered with `MagicStarter.useSocialAuth(...)` (see [Social Login](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#social-login)); a page opened without one lists no provider. The route is `MagicStarterConfig.settingsConnectedAccountsRoute()`, `/security/connected-accounts` (`/settings/security/connected-accounts` by default), titled `magic_starter.titles.connected_accounts`. The view registry key is `settings.security.connected_accounts`. The backend is `magic-starter-laravel` with its social login feature on. The starter itself sends `DELETE /user/social-accounts/{provider}` when a link is removed; `POST /user/social-accounts/link-ticket`, which starts a connect, is sent by the bridge inside `beginConnect`. ## The Page One row per provider the bridge offers (`MagicStarterSocialAuth.providers()`), with the provider's icon and label. | State | Row shows | Action | |:------|:----------|:-------| | Linked (an entry in `social_accounts` with `revoked_at` null) | The address the provider was linked with (`email_at_link`) | **Disconnect** | | Not linked | Nothing more | **Connect** | A link the provider revoked (`revoked_at` set) is treated as not linked: it no longer counts as a way to sign in. A refusal appears as a sentence above the list. ## Connecting a Provider A linked identity is a new way into the account, so **Connect** confirms the user's identity first. 1. [`confirmIdentity`](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md) asks for the proof the account can give (the password, a TOTP code or a provider confirmation; none for a guest). The proof is minted for this attempt only. 2. `MagicStarterProfileController.beginSocialConnect(provider, proof:)` asks the bridge to begin: the network half (the backend link ticket) happens here, and it answers the call that opens the provider. 3. On iOS and Android the provider opens at once. **On the web the page shows a "Continue with " button instead**, because a popup opened after the awaits behind steps 1 and 2 is blocked as not user-initiated; the user's tap runs the opener. 4. `doConnectSocialAccount(opener)` runs the opener, then `Auth.restore()` so the new link shows. Every retry starts over at step 1: a new proof, a new link ticket, a new PKCE pair. A cancelled flow shows nothing. A refusal shows its `social.` sentence: `social_email_taken`, `social_account_taken` (the provider account is already linked to another user, or the caller already holds another account of that provider), `step_up_required`, `flow_expired`. ## Disconnecting a Provider **Disconnect** calls `doDisconnectSocialAccount(provider)`, which sends `DELETE /user/social-accounts/{provider}` and restores the user. No proof is asked. The last way to sign in cannot be removed. For an account with no password and at most one active link, the page disables **Disconnect** as a courtesy and swaps the footer for the `social.last_login_method` sentence. The backend holds that line whatever the page shows (422 `last_login_method`), and the refusal is read by its `code`. Set a password first (see [Set a Password](https://anilcancakir.com/magic/docs/starter/basics/set-password.md)) or link another provider. ## Controller Methods On `MagicStarterProfileController`: | Method | Does | |:-------|:-----| | `doDisconnectSocialAccount(provider)` | `DELETE /user/social-accounts/{provider}`, then `Auth.restore()`. Returns `true` on success. | | `beginSocialConnect(provider, {proof})` | Asks the bridge to begin a connect; answers the opener, or `null` when the bridge refused or the user backed out. | | `doConnectSocialAccount(opener)` | Runs the opener, then `Auth.restore()`. Calls the opener before anything is awaited, so call it straight from a tap on the web. | ## User Data `MagicStarterAuthUser` carries what the page reads: | Getter | Source | Meaning | |:-------|:-------|:--------| | `hasPassword` | `has_password` | Whether the account can sign in with a password. `true` when a backend that predates social login does not send the field. | | `isGuest` | `is_guest` | A device-bound guest account. | | `socialAccounts` | `social_accounts` | Linked identities: `provider`, `email_at_link`, `created_at`, `revoked_at`. | | `deletionScheduledAt` | `deletion_scheduled_at` | When a scheduled account deletion runs, or `null`. | ## Overriding the Page Replace the view through the registry like any other starter screen: ```dart MagicStarter.view.register( 'settings.security.connected_accounts', () => const MyConnectedAccountsView(), ); ``` ## Gotchas | Mistake | Fix | |:--------|:----| | Enabling `social_login` and expecting providers to appear | The page lists what `MagicStarter.socialAuth.providers()` returns; without a registered bridge it lists none, and the Settings hub row is absent. | | Calling the opener from `doConnectSocialAccount` after an `await` on the web | The popup is blocked as not user-initiated. The page shows "Continue with " and runs the opener from that tap; a custom view must do the same. | | Reusing a proof or link ticket for a retry | Each attempt starts at `confirmIdentity`: a new proof, a new link ticket, a new PKCE pair. | | Relying on the disabled **Disconnect** button as the guard | It is a courtesy. The backend refuses the last sign-in method with 422 `last_login_method`; read the refusal's `code`. | | Assuming `has_password` is always sent | `hasPassword` defaults to `true` when the field is missing, so the last-method check only fires on a backend that sends `has_password: false`. | | Registering the view only when a bridge exists | The route and registry key are registered on the feature flag alone, so the bridge may be set later, from a provider that boots after the routes. | ## Related Documentation - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#social-login): the `MagicStarterSocialAuth` bridge contract. - [Identity Confirmation](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md): the proof a connect asks for. - [Set a Password](https://anilcancakir.com/magic/docs/starter/basics/set-password.md): the first-password form for a provider account. - [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md): overriding the page. - [Social Auth Flows](https://anilcancakir.com/magic/docs/social_auth/basics/flows): the connect flow on the bridge side. --- # Set a Password How the Security password page lets an account created through a provider set its first password, and what the backend refuses. - [Introduction](#introduction) - [The Page](#the-page) - [doSetPassword](#dosetpassword) - [Refusals](#refusals) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction An account created through a provider has no password (`has_password` is `false`), so there is nothing to change. The Security password page becomes **Set password** for it, and the user can then also sign in with email and password. The page is `settings.security.password`, reached from the Security group of the settings hub (see [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md)). ## The Page `MagicStarterPasswordView` reads `has_password` from `Auth.user()` on every build: | `has_password` | Page | |:---------------|:-----| | `true`, or absent (a backend that predates social login) | The change form: current, new and confirm password, `doUpdatePassword`. | | `false` | **Set password**: new and confirm password only, with the `profile.set_password_description` footer. | Submitting the set form confirms the user's identity first (see [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md)): a first password is a new way into the account, so a password-less account steps up with a TOTP `code` or a `confirmation_token`, and a guest passes without a dialog. The dialog stays open while the backend refuses the proof, so the user retries with a fresh one. On success the user is restored, which flips `has_password` and with it the page from set to change. ## doSetPassword ```dart final success = await MagicStarterProfileController.instance.doSetPassword( password: form.get('password'), passwordConfirmation: form.get('password_confirmation'), proof: proof, ); ``` It sends `POST /user/password/set` with `password`, `password_confirmation` and the spread `proof`. The backend applies the same rules as a password change (at least 8 characters with letters, numbers and mixed case, confirmed). On success the controller calls `Auth.restore()`, shows the `profile.password_set` toast and sets success state; on a refusal it shows the refusal's own sentence or the `profile.password_set_failed` fallback. `magic-starter-laravel` registers `POST /user/password/set` only with its `socialLogin` feature on. With it off the route does not exist and the call fails as any other 404. ## Refusals The controller reads a refusal by its `code`: | Code | Meaning | Client behaviour | |:-----|:--------|:-----------------| | `password_already_set` (422) | The account already has a password. | The user is restored; the page rebuilds with the change form. | | `step_up_required` (422) | The proof was missing or spent. | The step-up dialog narrows to the proofs in `accepts` and stays open. | The mirror case: `PUT /user/password` on a password-less account answers 422 `password_not_set`, the user is restored, and the page rebuilds with the set form. ## Gotchas | Mistake | Fix | |:--------|:----| | Calling `doSetPassword` without a `proof` | `proof` is required. Produce it with `confirmIdentity`, or let the page do it through `confirmAndRun`. | | Showing the change form to a password-less account | Read `has_password` from `Auth.user()` (absent means `true`); the controller restores the user on `password_not_set` so the page can correct itself. | | Switching on the set flow with the backend's social login off | The set route is registered only with the backend's `socialLogin` feature; enable both sides. | | Matching a refusal by its message | Read the `code` (`password_already_set`, `step_up_required`); the sentence is translated. | ## Related Documentation - [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md): how the `proof` is produced. - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): the settings hub and the change-password flow. - [Connected Accounts](https://anilcancakir.com/magic/docs/starter/basics/connected-accounts.md): linking and unlinking providers. - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): sign-in and social login. --- # Profile The settings hub and the sub-pages behind it, where a signed-in user edits their profile, security and preferences through `MagicStarterProfileController`. - [Basic Usage](#basic-usage) - [Quick Reference](#quick-reference) - [Profile Photo](#profile-photo) - [Profile Information](#profile-information) - [Changing a Password](#changing-a-password) - [Email Verification](#email-verification) - [Sessions](#sessions) - [Timezone and Language](#timezone-and-language) - [Newsletter](#newsletter) - [Delete Account](#delete-account) - [Two-Factor](#two-factor) - [Gate Abilities](#gate-abilities) - [Overriding a Page](#overriding-a-page) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage Register the routes from your route provider, beside the other starter routes: ```dart registerMagicStarterAuthRoutes(); registerMagicStarterProfileRoutes(); ``` The hub opens at `MagicStarterConfig.settingsHubRoute()`, which is `magic_starter.routes.profile_prefix` (default `/settings`). Every sub-page is pushed (`.stacked()`) so the back gesture returns to the hub, and the whole group sits behind the `auth` middleware alias inside the `layout.app` shell. The pages call the controller for you. A page of your own calls it the same way: ```dart final controller = MagicStarterProfileController.instance; final saved = await controller.withoutNotifying( () => controller.doUpdateProfile(name: 'Alice', email: 'alice@example.com'), ); ``` Every `do*` method answers `bool` (a few two-factor reads answer a map or a list, or `null` on failure), refuses to start while another write is in flight, and keeps its refusal on the controller for the view to show. ## Quick Reference | Page | Route | View key | Shown when | |:-----|:------|:---------|:-----------| | Hub | `settingsHubRoute()` | `settings.hub` | Always | | Profile | `profileRoute()` | `profile.profile` | Always | | Appearance | `settingsAppearanceRoute()` | `settings.appearance` | Always | | Password | `settingsPasswordRoute()` | `settings.security.password` | Gate `starter.update-password` | | Language | `settingsLanguageRoute()` | `settings.language` | `extended_profile` | | Timezone | `settingsTimezoneRoute()` | `settings.timezone` | `timezones` | | Newsletter | `settingsNewsletterRoute()` | `settings.newsletter` | `newsletter` and Gate `starter.manage-newsletter` | | What's new | `settingsChangelogRoute()` | `settings.changelog` | `releases` (see [Releases](https://anilcancakir.com/magic/docs/starter/basics/releases.md)) | | Two-factor | `settingsTwoFactorRoute()` | `settings.security.two_factor` | `two_factor` and Gate `starter.manage-two-factor` | | Sessions | `settingsSessionsRoute()` | `settings.security.sessions` | `sessions` | | Connected accounts | `settingsConnectedAccountsRoute()` | `settings.security.connected_accounts` | `social_login` and a bridge from `MagicStarter.useSocialAuth` (see [Connected Accounts](https://anilcancakir.com/magic/docs/starter/basics/connected-accounts.md)) | All the route helpers hang off `MagicStarterConfig` and follow `profile_prefix`. A disabled feature registers neither its route nor its default view. ## Profile Photo Gated by `magic_starter.features.profile_photos` and the Gate `starter.update-profile-photo`. The Profile page shows the section. ```dart final uploaded = await MagicStarterProfileController.instance.doUpdateProfilePhoto( file: magicFile, ); final removed = await MagicStarterProfileController.instance.doDeleteProfilePhoto(); ``` Upload is a multipart `POST /user/profile-photo` with the file under the `photo` key; removal is `DELETE /user/profile-photo`. Both call `Auth.restore()` on success, so `profile_photo_url` on the user model is fresh. `magic-starter-laravel` serves these routes only with its `profilePhotos` feature on. ## Profile Information `doUpdateProfile()` sends `PUT /user/profile`. `name` and `email` are required arguments; `phone`, `timezone` and `language` are sent only when non-empty, and `language` travels as the `locale` key: ```dart final success = await controller.withoutNotifying( () => controller.doUpdateProfile( name: form.get('name'), email: form.get('email'), phone: form.get('phone'), language: form.get('language'), ), ); ``` `withoutNotifying()` suppresses `notifyListeners()` for the duration of the action, so a form that already shows its own loading state through `MagicFormData.process()` does not rebuild the whole page. On success the controller calls `Auth.restore()`, shows a toast and, when `language` is present, hands it to `MagicStarterManager.applyLocale()`, which switches the app's locale after the current frame. `MagicStarterServiceProvider` also applies a signed-in user's saved `locale` on every sign-in and restore, gated by `magic_starter.localization.apply_user_locale` (default `true`); see [Locale Application](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#locale-application). Both go through `applyLocale()`, so one save issues one `Lang.setLocale()` call. The Profile page carries name and email (email behind the Gate `starter.update-email`) and, with `extended_profile`, a phone field behind `starter.update-phone`. ## Changing a Password ```dart final success = await controller.doUpdatePassword( currentPassword: form.get('current_password'), password: form.get('password'), passwordConfirmation: form.get('password_confirmation'), ); ``` This sends `PUT /user/password` with `current_password`, `password` and `password_confirmation`. It does not call `Auth.restore()`: the user model does not change. An account created through a provider has no password (`has_password` is `false`): the backend answers `PUT /user/password` with 422 `password_not_set`, and the page shows the **Set password** form instead. See [Set a Password](https://anilcancakir.com/magic/docs/starter/basics/set-password.md). ## Email Verification Gated by `magic_starter.features.email_verification` and the Gate `starter.verify-email`. The Profile page shows a banner with a resend button while the email is unverified, and a verified badge afterwards. ```dart await MagicStarterProfileController.instance.sendEmailVerification(); final verified = MagicStarterProfileController.instance.isEmailVerified; ``` `sendEmailVerification()` posts to `/email/verification-notification` and toasts on success. `isEmailVerified` reads `email_verified_at` from `Auth.user()` and is `true` only for a non-empty string. The mailed link is handled by the backend and the app's verify-email view; call `Auth.restore()` to pull the new status. ## Sessions Gated by `magic_starter.features.sessions`. The Sessions page lists the account's tokens (device, IP address, location and a "current device" badge) from `GET /sessions`: ```dart final sessions = await controller.getSessions(); ``` `getSessions()` answers `null` when the feature is off or the read fails. Revoking is gated by the Gate `starter.logout-sessions` and needs a step-up `proof`: ```dart final revoked = await controller.doRevokeSession(tokenId: session['id'].toString(), proof: proof); final others = await controller.doRevokeOtherSessions(proof: proof); ``` Both go out as `POST` with `{'_method': 'DELETE', ...proof}` to `/sessions/{id}` and `/sessions/other`; the backend route is `DELETE`. `proof` is `{'password': ...}`, `{'code': ...}`, `{'confirmation_token': ...}` or `{}` for a guest; [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md) covers how the right one is produced for the signed-in account. ## Timezone and Language Each is its own sub-page and saves through `doUpdateProfile()`, carrying the user's current `name` and `email` so the save does not blank them. The Timezone page (`timezones` feature) uses `MagicStarterTimezoneSelect`, a searchable dropdown over `GET /timezones?search=&per_page=&page=`. It debounces the search, pages through the endpoint on scroll and keeps the current value in the list. Entries without an `identifier` and a `label` are dropped. The backend serves the route only with its own `timezones` feature on. The Language page (`extended_profile` feature) selects from `MagicStarter.localeOptions`. Without an override the list is the app's supported locales (`Lang.supportedLocales`) with native language names; register your own with `MagicStarter.useLocaleOptions({'en': 'English', 'tr': 'Türkçe'})`. ## Newsletter Gated by `magic_starter.features.newsletter` and the Gate `starter.manage-newsletter`. `MagicStarterNewsletterController` keeps the subscription apart from the profile controller: ```dart await MagicStarterNewsletterController.instance.getNewsletterStatus(); await MagicStarterNewsletterController.instance.updateNewsletterSubscription(subscribe: true); ``` These call `GET /user/newsletter` and `PUT /user/newsletter`. `MagicStarter.useNewsletterLabel('Subscribe to our updates')` sets the label of the newsletter checkbox on the register view (with `newsletter` on); the profile newsletter section does not read it. ## Delete Account Account deletion lives on the Sessions page. It asks first whether the account goes after the grace period or now, then confirms identity, then calls the controller: ```dart final proof = await confirmIdentity(context); if (proof == null) return; // the user cancelled final success = await MagicStarterProfileController.instance.doDeleteAccount( proof: proof, immediately: false, // true purges now instead of after the grace period ); ``` The controller sends `POST /user` with `{'_method': 'DELETE', ...proof}` and, for the second choice, `'immediately': true`. The backend answers `202`: by default it schedules the deletion, revokes every token and purges after a grace period, and a sign-in within it cancels the deletion (the next sign-in shows an "Account deletion cancelled" toast; the user carries `deletion_scheduled_at`). With `immediately` it purges at once. Either way the controller toasts the server's sentence, calls `Auth.logout()` and navigates to the login page. A refusal keeps the user signed in and shows its own sentence, read by `code`: `owns_shared_teams`, `team_has_active_subscription`, `subscription_active`, `step_up_required`, or a wrong password. A subscription refusal can carry one action that clears it: the store's subscription screen for a store plan, or the page at `magic_starter.account.deletion_url` for a card plan (without that key the sentence stands alone). ## Two-Factor Enabling, confirming, disabling and recovery codes run through the same controller (`doEnableTwoFactor`, `doConfirmTwoFactor`, `doDisableTwoFactor`, `getRecoveryCodes`, `doRegenerateRecoveryCodes`), on the Two-factor page. `controller.isTwoFactorEnabled` reads `two_factor_enabled` from the user. See [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#two-factor-authentication). ## Gate Abilities `MagicStarterServiceProvider` defines these abilities, all denying a guest. Feature flags decide whether a feature exists; the abilities decide whether this user sees it. Re-define one with `Gate.define` after the provider boots to change the rule. | Ability | Controls | |:--------|:---------| | `starter.update-profile-photo` | The photo section | | `starter.update-email` | The email field | | `starter.update-phone` | The phone field | | `starter.update-password` | The Password row and page | | `starter.verify-email` | The verification banner | | `starter.manage-two-factor` | The Two-factor row | | `starter.manage-newsletter` | The Newsletter row | | `starter.logout-sessions` | The revoke buttons on Sessions | | `starter.delete-account` | The delete section; a guest is denied and sees an upgrade prompt instead | ## Overriding a Page Replace any page through the view registry, and add content around the hub and the Profile page with their `header` and `footer` slots: ```dart MagicStarter.view.register('settings.security.password', () => const MyPasswordView()); MagicStarter.view.slot('settings.hub', 'footer', (context) => const MyAboutSection()); ``` `MagicStarterSettingsAccountGroup`, `MagicStarterSettingsSecurityGroup` and `MagicStarterSettingsPreferencesGroup` are the hub's sections, each with its own gating; a host that registers its own `settings.hub` composes them instead of copying the rows. ## Gotchas | Mistake | Fix | |:--------|:----| | Expecting a single long profile page under `profile.settings` | The default is the hub and its sub-pages. `profile.settings` is a publishable view that no default registers, and `MagicStarterProfileController.profile()` throws a `StateError` until you register it. | | Calling `doUpdateProfile` with only a timezone or a language | `name` and `email` are required. Carry them from `Auth.user()`, as the Timezone and Language pages do. | | Passing `password:` to `doRevokeSession`, `doRevokeOtherSessions` or `doDeleteAccount` | They take `proof:`. Produce it with `confirmIdentity`. | | Turning on `extended_profile` and expecting a Timezone row | The row needs the `timezones` flag. `extended_profile` adds the Language row and the phone field. | | Reading `language` in the backend's profile payload | The client sends it as `locale`. | | Showing the photo section with `profile_photos` off on the backend | `magic-starter-laravel` registers the photo routes only with its own feature on; turn on both sides. | ## Related Documentation - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): sign-in, two-factor and guest sessions. - [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md): the `proof` the gated methods take. - [Set a Password](https://anilcancakir.com/magic/docs/starter/basics/set-password.md): the first password of a social-only account. - [Connected Accounts](https://anilcancakir.com/magic/docs/starter/basics/connected-accounts.md): linking and unlinking providers. - [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md): team creation and switching. - [Releases](https://anilcancakir.com/magic/docs/starter/basics/releases.md): the What's new page. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the view registry and the app shell. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature flags and route keys. --- # Session Scope How a controller that caches one user's (or one team's) data is reset when the signed-in identity changes, using magic's `SessionScoped` contract and the identity key this package declares. - [Introduction](#introduction) - [The Leak](#the-leak) - [The Contract](#the-contract) - [Clear Before You Refetch](#clear-before-you-refetch) - [Wiring the Sync](#wiring-the-sync) - [The Identity Key](#the-identity-key) - [Why Logout Does Not Reset](#why-logout-does-not-reset) - [Error Isolation](#error-isolation) - [Testing](#testing) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction Any controller that caches data belonging to one signed-in user, or to one of that user's teams, has to be told when that user changes. Magic core ships the two pieces: the `SessionScoped` contract, which a controller (or a repository) implements to declare "my rows belong to exactly one session", and `SessionScope`, which watches `Auth.stateNotifier` and resets every scoped holder whenever the authenticated identity changes. This package's part is the identity: `MagicStarterServiceProvider` sets `SessionScope.identity` to `:` in `register()`, so a team switch by the same user counts as a change. Attaching stays your app's call (see [Wiring the Sync](#wiring-the-sync)). > [!IMPORTANT] > This is a privacy guard, not a freshness nicety. Without it, a logout followed by a login as a different user leaves the previous user's rows on screen. On a team-scoped product that is a cross-tenant data exposure. ## The Leak Magic resolves controllers as type-keyed singletons: `Magic.findOrPut(ProjectController.new)` returns the same instance for the whole process lifetime. The initial fetch usually lives in `onInit()`, and `MagicStatefulViewState` only calls it while the controller has not been initialised yet, so `onInit()` runs once per instance lifetime, not once per mount. Follow the consequence through: 1. User A signs in, opens the projects screen. `ProjectController.onInit()` fetches A's projects. 2. A signs out. The controller instance survives: nothing disposes it, and its rows are still in memory. 3. User B signs in on the same device and opens the projects screen. The controller is already initialised, so `onInit()` does not run and no fetch happens. 4. B is looking at A's projects until the app is restarted. The same happens without a logout: a team switch changes which rows the API returns, while every cached controller keeps the old team's data. ## The Contract Implement magic's `SessionScoped` on every controller that caches session-scoped data. A repository or any other non-controller holder implements it too and registers itself with `SessionScope.register(holder)` (and `SessionScope.unregister(holder)` on dispose); controllers are found in `Magic.controllers` without registration. ```dart import 'package:magic/magic.dart'; class ProjectController extends MagicController with MagicStateMixin> implements SessionScoped { static ProjectController get instance => Magic.findOrPut(ProjectController.new); final List projects = []; @override Future onInit() async { super.onInit(); await loadProjects(); } @override Future resetForSession() async { // 1. Publish the cleared state BEFORE the refetch. projects.clear(); setLoading(); // 2. Refetch for whoever is authenticated now. await loadProjects(); } } ``` `resetForSession()` is the only member of the contract. It is called on login and on team switch, and it is expected to drop every cached row, publish that cleared state, and then refetch. ## Clear Before You Refetch `resetForSession()` is destructive on purpose, and the clear must land before the refetch is attempted. An ordinary `reload()` is deliberately non-destructive: when a refresh fails, keeping the last-known-good rows is right, because a five-second network blip should not blank a dashboard the user is reading. Across an identity change that behaviour is exactly wrong, since the rows on screen belong to the previous session: | | Ordinary `reload()` | `resetForSession()` | |:--|:--------------------|:--------------------| | Refetch succeeds | New rows | New rows | | Refetch fails | Previous rows stay (same user, stale data) | Must be empty (the previous rows belong to another session) | So the order inside `resetForSession()` is load-bearing: ```dart @override Future resetForSession() async { projects.clear(); // 1. Drop the previous session's rows. setLoading(); // 2. Publish it, so the UI is empty even if step 3 throws. await loadProjects(); // 3. Only now go to the network. } ``` > [!WARNING] > Do not write `resetForSession()` as a plain `await reload()`, and do not clear inside a `try` whose `catch` restores the old rows. A failed refetch must leave an empty screen, never a populated one. ## Wiring the Sync Attach `SessionScope` once, from your app's service provider `boot()`, after `MagicStarterServiceProvider` has booted and as the last `Auth.stateNotifier` listener you add. The starter never attaches it for you: ```dart import 'package:magic/magic.dart'; import 'package:magic_starter/magic_starter.dart'; class AppServiceProvider extends ServiceProvider { AppServiceProvider(super.app); @override void register() {} @override Future boot() async { MagicStarter.useUserModel((data) => User.fromMap(data)); // MagicStarter.useTeamResolver(...) goes here, see Teams. // Register last: notification polling, realtime subscriptions and locale // should already point at the new session before its data is refetched. SessionScope.attach(); } } ``` `attach()` subscribes to `Auth.stateNotifier` and records the identity the app boots with. It resets nothing at boot: no view has resolved a controller yet, so there is nothing cached to clear, and the first real change is the first one that resets. | Member | Purpose | |:-------|:--------| | `SessionScope.attach()` | Subscribe to auth state changes. Idempotent; a second call while attached is a no-op. | | `SessionScope.detach()` | Unsubscribe and forget the recorded identity. Mainly for tests. | | `SessionScope.isAttached` | Whether a subscription is active. | | `SessionScope.register(holder)` / `unregister(holder)` | Add or remove a non-controller holder. | | `SessionScope.identity` | The identity resolver. This package sets it in `register()`; see below. | ## The Identity Key The sync compares a string key, not object identity. Magic's default is the user id alone; `MagicStarterServiceProvider` replaces it in `register()` with a two-leg key: ``` : ``` | Leg | Source | Reads `null` when | |:----|:-------|:------------------| | `userId` | `Auth.id()` | Never while `Auth.check()` is true | | `teamId` | `MagicStarter.currentTeamId()`, the team resolver's current team id as a string | Teams are disabled, or no team resolver is registered | Two legs, because a team-scoped API scopes its endpoints to the current team and not just to the user: switching teams changes every response body while `Auth.id()` stays put. Reading the team through the starter's own [team resolver](https://anilcancakir.com/magic/docs/starter/basics/teams.md#team-resolver) keeps this package independent of your `User` model. The whole key is `null` when, and only when, nobody is signed in (`Auth.check()` is the discriminator). Two rules follow: - An unchanged key is a no-op. `Auth.stateNotifier` also bumps on a plain session restore, and without this check every incidental bump would stampede a fresh wave of refetches. - Only a change to a non-null key resets. Team switching triggers the sync for free: `MagicStarter.switchTeam()` goes through `MagicStarterTeamController.switchTeam()`, which applies the fresh user the switch answer carries (falling back to `Auth.restore()` only when the answer carries none) and bumps `Auth.stateNotifier` either way. If you implement your own switch path, apply the answer's user directly rather than always calling `Auth.restore()`, which re-applies the cached user, still on the previous team. An app that needs a different key (an organisation leg, say) sets `SessionScope.identity` in its own provider's `boot()`, after this one. ## Why Logout Does Not Reset On logout the key goes from `1:10` to `null`, and nothing is reset. There is no identity to refetch for: a reset on logout would clear every controller and then fire a wave of requests from the login screen, where the token is already gone, so they could only come back `401`. The stale rows sit unreachable in memory behind the auth guard, and the next login resets them before any authenticated view renders, because `Auth.login` bumps `Auth.stateNotifier` before it returns to the code that navigates. The key is still recorded on logout (as `null`), which is what makes signing back in as the same user count as a change (`null` to `1:10`) and refetch. ## Error Isolation Each `resetForSession()` is fired independently: `Auth.stateNotifier` listeners are synchronous, so the sync does not await them, and each future carries its own error guard. One controller throwing does not stop the others, and the failure is logged rather than swallowed: ``` [SessionScope] session reset failed: ``` Handle your own failures the way any other reload does (`setError()`, a fallback message). A throw that escapes leaves that one controller cleared and unrefetched: safe, but an empty screen with no explanation. ## Testing `SessionScope` holds process-wide statics that neither `MagicApp.reset()` nor `Magic.flush()` clears, so call `detach()` in both `setUp` and `tearDown`. `detach()` keeps the identity resolver, so a test that boots the starter provider restores the one it found: ```dart setUp(() { MagicApp.reset(); Magic.flush(); // bind 'log', 'auth' and 'magic_starter', register the team resolver... SessionScope.detach(); }); tearDown(() => SessionScope.detach()); test('drops the previous tenant rows when another user logs in', () async { await Auth.login({'token': 'a'}, userA); SessionScope.attach(); final controller = Magic.put(ProjectController()); controller.projects.addAll(projectsOfA); await Auth.login({'token': 'b'}, userB); await pumpEventQueue(); expect(controller.projects, isNot(contains(projectsOfA.first))); }); ``` `detach()` unsubscribes from the exact notifier instance it subscribed to. That matters in tests: `Auth.stateNotifier` resolves through the container, so rebinding the guard hands back a different notifier. ## Gotchas | Mistake | Fix | |:--------|:----| | Expecting the starter to attach the sync | It only declares the identity in `register()`. Call `SessionScope.attach()` yourself, last in your provider's `boot()`. | | Writing `resetForSession()` as `await reload()` | Clear the rows and publish the cleared state first, then refetch. A failed refetch must leave an empty screen. | | Switching teams through your own path with `Auth.restore()` | Apply the switch answer's user directly, as `MagicStarterTeamController.switchTeam()` does, or the identity flips late. | | Caching rows in a repository | A non-controller holder is not found automatically: implement `SessionScoped` and call `SessionScope.register(holder)`. | | Leaving `SessionScope` attached between tests | Call `SessionScope.detach()` in `setUp` and `tearDown`. | ## Related Documentation - [State Management](https://anilcancakir.com/magic/docs/starter/guides/state-management.md): `MagicController`, `MagicStateMixin` and the singleton accessor pattern this contract sits on. - [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md): the team resolver that supplies the second leg of the identity key. - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): `Auth.stateNotifier`, login, logout and session restore. - [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md): where `attach()` belongs in the boot sequence. --- # Teams Create teams, switch between them, invite members and manage team settings through `MagicStarterTeamController`, with a team resolver that bridges your own team model to the starter. - [Basic Usage](#basic-usage) - [Team Resolver](#team-resolver) - [Creating Teams](#creating-teams) - [Team Switching](#team-switching) - [Billing](#billing) - [The Billable Subject](#the-billable-subject) - [Price Format](#price-format) - [Free Trials](#free-trials) - [Changing a Web Plan](#changing-a-web-plan) - [Campaigns](#campaigns) - [Invitations](#invitations) - [Sending Invitations](#sending-invitations) - [Accepting Invitations](#accepting-invitations) - [Cancelling Invitations](#cancelling-invitations) - [Team Settings](#team-settings) - [Updating the Team Name](#updating-the-team-name) - [Managing Members](#managing-members) - [Controller](#controller) - [Overriding a View](#overriding-a-view) - [MSTeamSelector](#msteamselector) - [MagicStarterTeam](#magicstarterteam) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage Turn the feature on in `lib/config/magic_starter.dart`, register the routes from your route provider and register a team resolver (see [Team Resolver](#team-resolver)): ```dart 'features': { 'teams': true, }, ``` ```dart registerMagicStarterAuthRoutes(); registerMagicStarterTeamRoutes(); ``` With `teams` off, `registerMagicStarterTeamRoutes()` is a no-op and the default team views are not registered. The routes sit under `MagicStarterConfig.teamsPrefix()` (`magic_starter.routes.teams_prefix`, default `/teams`), behind the `auth` middleware alias, inside the `layout.app` shell. | Registry key | View | Route | |:-------------|:-----|:------| | `teams.create` | `MagicStarterTeamCreateView` | `MagicStarterConfig.teamCreateRoute()` (`/teams/create`) | | `teams.settings` | `MagicStarterTeamSettingsView` | `MagicStarterConfig.teamSettingsRoute()` (`/teams/settings`) | | `teams.invitation_accept` | `MagicStarterTeamInvitationAcceptView` | `/invitations/:token/accept` | | `teams.billing` | `MagicStarterBillingView` | Registered by the `billing` feature alone, with no route of its own: your route provider points `MagicStarterConfig.billingRoute()` (`/teams/billing`) at `MagicStarter.view.make('teams.billing')` | Create and settings are pushed (`.stacked()`), so the back gesture returns to the team switcher. Invitation acceptance is an arrival from an email link, so it is not stacked. The backend side is `magic-starter-laravel`'s `teams` feature; turn on both. ## Team Resolver The team resolver is the bridge between your application's team model and the starter. Register it during app boot with `MagicStarter.useTeamResolver()`: ```dart MagicStarter.useTeamResolver( currentTeam: () => User.current.currentTeam?.toMagicStarterTeam(), allTeams: () => User.current.allTeams .map((t) => t.toMagicStarterTeam()) .toList(), onSwitch: (id) => MagicStarter.switchTeam('$id'), ); ``` | Callback | Return type | Purpose | |:---------|:------------|:--------| | `currentTeam` | `MagicStarterTeam?` | The user's active team | | `allTeams` | `List` | Every team the user belongs to | | `onSwitch` | `Future` | Called when the user picks a different team | The starter reads these callbacks to fill the team selector, show the active team name and handle switching. Register the resolver in your service provider's `boot()`, before any team UI renders. `MagicStarter.bootstrap()` takes the same three callbacks and throws a `StateError` when `teams` is on and none are passed (an `ArgumentError` when only some are). ## Creating Teams ```dart final success = await MagicStarterTeamController.instance.doCreate( name: form.get('name'), ); ``` The controller sends `POST /teams` with the team name. With the new team's `id` it then sends `PUT /user/current-team`, stores the id in `currentTeamId.value` and applies the user that answer carries (falling back to `Auth.restore()`), so the sidebar names the new team. A toast confirms the creation. ## Team Switching Switch the active team with `MagicStarter.switchTeam()`, which answers whether the backend accepted it: ```dart if (!await MagicStarter.switchTeam(teamId)) return; MagicRoute.to('/projects/$projectId'); ``` It goes through `MagicStarterTeamController.instance.switchTeam()`, which sends `PUT /user/current-team` with the target `team_id` and, on success, updates `currentTeamId.value` and applies the signed-in user the switch answers with, so the session is on the new team before the future completes. An answer without that user (an empty `data`, a team record) falls back to `Auth.restore()`. In an app that never calls `SessionScope.attach()`, the switch also resets every `SessionScoped` controller registered with `Magic` (see [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md)). A refused switch answers `false` and leaves the session on the team it was on, so a caller that navigates after a switch must check the answer first. On success it also re-identifies the store rail as the paying subject (`StoreIdentitySync.syncNow()` from `magic_payments`), so a purchase made after the switch is not attributed to the team that was left. A build without a store rail (web, desktop) identifies nothing, and a refused switch identifies nothing. Pass `MagicStarter.switchTeam` as the resolver's `onSwitch` so the team selector gets the same behaviour. `MagicStarter.currentTeamId()` answers the active team's id as a string (`null` without a resolver or an active team), so an int id from your model and a string id from a link or a push payload compare equal. ## Billing The billing screen (`teams.billing`, with the `billing` feature) sells plans through `magic_payments`: Stripe on the web, the store on mobile. It needs `magic_starter.billing.web_origin`, an absolute url, for the web rail. Unset or empty, the screen hides the web checkout button; a relative value reaches Stripe, which refuses it, and the error is only logged. ### The Billable Subject `magic_starter.billing.billable` names what a store purchase is billed to, and it mirrors `magic-starter-laravel`'s key of the same name. The two must agree: | Value | The store rail is identified as | |:------|:--------------------------------| | `'user'` (default) | `Auth.id()` | | `'team'` | The active team id | ```dart 'billing': { 'web_origin': 'https://app.example.com', 'billable': 'team', }, ``` `MagicStarterServiceProvider` reads it in `register()` and sets `StoreIdentitySync.billableId`; any other value throws a `StateError` there and stops `Magic.init`, because a typo that fell back to `'user'` would bind every purchase to the wrong subject. Identifying on login and restore as well stays your call: add `StoreIdentitySync.attach()` to your provider's `boot()`. ### Price Format Every web price the billing screen shows reads the producer's `display` string, such as `379.00 TRY`, which carries no separator and no symbol. An app that writes money its own way registers a `MagicStarterPriceFormat` on the controller: ```dart Magic.put( MagicStarterBillingController( usageCopy: usageCopy, formatNumber: Number.format, formatPrice: (MagicStarterWebPrice price) => switch (price.currency) { 'TRY' => '${Number.format(price.amountMinor / 100)} TL', _ => price.display, }, ), ); ``` `MagicStarterWebPrice` carries `amountMinor` (in the currency's minor unit), `currency` (the ISO 4217 code) and `display`. Return `price.display` for any currency the app does not format itself. `usageCopy` is your own `MagicStarterUsageCopy`; the controller takes required collaborators, so it is registered with `Magic.put` rather than `findOrPut`. ### Free Trials The billing screen shows a trial and a store introductory offer without further setup, provided the backend's catalogue rows carry `trial_days` per product. `MagicStarterProduct.trialDays` is the free days a purchase of that product starts with, and `0` for none. The backend answers it for the signed-in caller, so `0` also means a trial already used. `MagicStarterBillingController.trialEnd` is the date a running trial ends (`null` unless the plan status is `trialing`); a store trial has no `trial_ends_at`, so it falls back to the entitlement's current period end. | Where | What it shows | |:------|:--------------| | Current plan card | A "Trial" badge beside the plan name, and one line in place of the renewal line saying when the trial ends and what is billed after it (or that it will not renew once cancelled) | | Web plan card | For a product with `trialDays` above zero, "Free for :period. Card required, then :price per :cycle." above the call to action, which reads "Start free trial". Web build only | | Store plan card | "Free for :intro_period, then :price per :period" for a free introductory offer, only when the store says this customer is eligible (`StoreProductOffer.introEligible`) | The translator has no plural API, so each count is chosen in Dart: a count of one reads the `_one` key and any other count the `_other` key. A store introductory period is read from its ISO 8601 form when it is one whole unit (`P14D`, `P2W`, `P1M`, `P1Y`); anything else (`P1Y2M`) states no offer and keeps the plain line. ### Changing a Web Plan A team that already holds a web (Stripe) subscription changes tier or cycle by moving that subscription, never by buying a second one: `magic-starter-laravel` refuses a checkout with a 409 `subscription_exists` while one still grants. `MagicStarterBillingController.holdsWebSubscription` is `true` once the entitlement names `BillingProvider.stripe` with a plan status that still grants (`trialing`, `active`, `pastDue`, `grace`), and while it is, a tap on another paid tier opens a confirmation instead of a checkout. On confirm the screen calls `WebBillingService.swap(productKey:)` (`POST /billing/swap`), re-reads the payment method and the invoices, and polls the entitlement with `awaitEntitlementChange(before)`, because the backend answers the swap before Stripe's webhook writes the new tier. A team with no web subscription still goes through the hosted checkout, and the move to the free tier still opens the billing portal. The confirmation states what the backend does with the money: | Move | The sentence | |:-----|:-------------| | During a running trial | Nothing is charged until the trial ends | | A higher tier, or a held tier the catalogue cannot rank | The card on file is charged the prorated difference now | | A lower tier on another cycle | The new billing period is billed at once, less the unused time on the current plan | | A lower tier on the same cycle | The change applies now and the unused time is credited to the next invoice | An upgrade the card declines, or one the bank asks to confirm with 3D Secure, is refused with a 402, which `magic_payments` reports as `BillingErrorCode.paymentDeclined` and `paymentRequiresAction`; the toast says the plan has not changed and why. ### Campaigns A staff-run, time-boxed offer on `magic-starter-laravel` (`GET /billing/campaign`) reaches a floor-tier team owner on the web rail as an app-wide banner and a tag on the plan cards it discounts. The backend answers `{"data": null}` unless the caller is the audience, so nothing here decides who qualifies; the client only declines to ask when it could not act on the offer. `MagicStarterBillingController.loadCampaign()` reads the offer. It is separate from `load()` and asks only when the `billing` feature is on and `canPurchaseViaWeb` holds (a web rail, no store managing the subscription, not a known non-owner). The answer lives on the controller as `campaign`, a `MagicStarterCampaign` (`id`, `startsAt`, `endsAt`, `products`, `discount`, and `headlineFor(languageCode)` and `bodyFor(languageCode)`, which pick the app locale, then `magic_starter.defaults.locale`, then any copy the backend sent). A team switch or a sign-in clears it and the mounted banner asks again. The backend answers 404 when its `campaigns` feature is off, which is read as no campaign and logs nothing; any other failed read is logged as a warning. | Where | What it shows | |:------|:--------------| | `MagicStarterCampaignBanner` | The headline and body above every page, a "See plans" action to `MagicStarterConfig.billingRoute()` and a "Dismiss" action. `MagicStarterAppLayout` mounts it when `billing` is on; a host that maps `layout.app` to its own layout places it itself. It hides itself once `endsAt` has passed | | Plan card | For a card whose product at the selected billing cycle is in the campaign, a "Limited offer" tag and the discount under the card's price. The tag follows the cycle toggle, and a fixed-amount discount tags only a card priced in the campaign's own currency or one the coupon lists in `currency_options`. The billing screen reads the campaign itself, so a host without the banner still gets the tag | "Dismiss" stores the campaign id in the `Vault` under `MagicStarterCampaignBanner.dismissalKey()`, which is `dismissedCampaignKey` plus the signed-in account's id, so a second account on the same device does not inherit the first one's dismissal. The next campaign has a new id and shows again. A fixed-sum discount passes through the app's `MagicStarterPriceFormat` when one is registered; otherwise it is written the producer's way (`5.00 USD`), which assumes a currency with two decimals. The package ships English copy only. The headline and body come from the backend per language; the labels are keys under `magic_starter.billing` in `assets/stubs/install/en.stub`, and an app that published its own `en.json` adds new keys by hand. ## Invitations ### Sending Invitations Invite a member to the current team by email and role: ```dart final success = await MagicStarterTeamController.instance.doInvite( email: 'colleague@example.com', role: 'member', ); ``` The controller sends `POST /teams/{teamId}/invitations` and refreshes the lists with `loadMembersAndInvitations()` on success. The team id is `activeTeamId`: the explicit `currentTeamId.value`, else the resolver's `currentTeam()`. With neither, the controller sets an error and returns `false`. The shipped settings view offers the roles `member` and `admin`. ### Accepting Invitations Accept an invitation with the token from the invitation URL: ```dart final success = await MagicStarterTeamController.instance.doAcceptInvitation( token: invitationToken, ); ``` This sends `POST /invitations/{token}/accept` and, on success, calls `Auth.restore()` so the user model includes the new team. The accept view (`teams.invitation_accept`) reads the token from its own route once, in `didChangeDependencies`, because route state cannot be read in `initState`: ```dart _token ??= MagicRouter.instance.pathParameterOf(context, 'token'); ``` The static `pathParameter()` would answer for whichever page was built last, which across layout shells is not always this one. ### Cancelling Invitations Cancel a pending invitation (a team admin action): ```dart final success = await MagicStarterTeamController.instance.cancelInvitation( invitationId, ); ``` This sends `DELETE /teams/{teamId}/invitations/{invitationId}`. ## Team Settings ### Updating the Team Name ```dart final success = await MagicStarterTeamController.instance.doUpdate( name: form.get('name'), ); ``` This sends `PUT /teams/{teamId}` and calls `Auth.restore()` on success. ### Managing Members ```dart await MagicStarterTeamController.instance.loadMembersAndInvitations(); ``` This fires `GET /teams/{teamId}/members` and `GET /teams/{teamId}/invitations` together and stores the results in the `members` and `invitations` notifiers. A newer read for another team supersedes an older one, so a slow answer never lands on the wrong team's screen. ```dart final removed = await MagicStarterTeamController.instance.removeMember(memberId); ``` This sends `DELETE /teams/{teamId}/members/{memberId}` and updates the local `members` list. ## Controller `MagicStarterTeamController.instance` is the singleton. It implements `SessionScoped`: a login or a team switch drops its members and invitations and re-points `currentTeamId` at the resolver's current team. | Member | Type | Purpose | |:-------|:-----|:--------| | `currentTeamId` | `ValueNotifier` | An explicitly set team id; overrides the resolver | | `members` | `ValueNotifier>>` | The current team's members | | `invitations` | `ValueNotifier>>` | Pending invitations | | `activeTeamId` | `dynamic` | `currentTeamId.value`, else the resolver's `currentTeam()` id | | `activeTeamName` | `String?` | The name matching `activeTeamId`, from the resolver | Use `ValueListenableBuilder` on `members` and `invitations` for fine-grained rebuilds. The controller's `dispose()` disposes all three notifiers, so dispose it in test `tearDown()`. ## Overriding a View Every team screen resolves through the view registry, so a host replaces one by registering a builder under the same key: ```dart MagicStarter.view.register('teams.settings', () => const MyTeamSettingsView()); ``` ## MSTeamSelector A dropdown built from the resolver's callbacks. It lists the user's teams and calls `onSwitch` when the selection changes: ```dart const MSTeamSelector() ``` Pass `compact: true` for an icon-only trigger. It renders nothing without a registered resolver or with an empty `allTeams()`. The shipped app layout places it in the sidebar; a host layout places it where it wants. ## MagicStarterTeam A lightweight team DTO (`id`, `name`, `photoUrl`, `isPersonalTeam`) that bridges your app's team model with the starter. `MagicStarterTeam.fromMap()` normalises a backend map, including a `personal_team` that arrives as `true` or `1`. Give your own model a conversion: ```dart extension on Team { MagicStarterTeam toMagicStarterTeam() { return MagicStarterTeam( id: id, name: name, photoUrl: profilePhotoUrl, isPersonalTeam: personalTeam, ); } } ``` ## Gotchas | Mistake | Fix | |:--------|:----| | Enabling `teams` without a team resolver | Register `MagicStarter.useTeamResolver()`, or pass the callbacks to `MagicStarter.bootstrap()`. The selector and the current team name read it. | | Navigating after `switchTeam` without reading the answer | A refused switch answers `false` and leaves the session on the old team; check it first. | | Calling `Auth.restore()` in your own switch path | Apply the switch answer's user directly, as the controller does, or the session identity flips late. | | Setting `billable: 'team'` on one side only | `magic_starter.billing.billable` and the backend key of the same name must agree. Any value other than `'user'` or `'team'` refuses the boot. | | Forgetting `billing.web_origin`, or setting a relative one | Set an absolute url. Without one the web checkout button is hidden; a relative one makes Stripe refuse the checkout and the error is only logged. | | Expecting `members` and `invitations` to refill after a team switch | The controller refetches them only while a settings screen is mounted. Call `loadMembersAndInvitations()` from your own screen. | ## Related Documentation - [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md): what resets when the team changes. - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): the settings hub and account pages. - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): sign-in and `Auth.restore()`. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the view registry and the app shell. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the `teams` and `billing` flags and keys. --- # Notifications How the starter mounts the `magic_notifications` screens and bell, runs the polling lifecycle, and declares the push identity of a signed-in device. - [Introduction](#introduction) - [Real-Time Polling](#real-time-polling) - [Push Identity](#push-identity) - [Notification List](#notification-list) - [Notification Preferences](#notification-preferences) - [Notification Dropdown](#notification-dropdown) - [Notification Type Icons](#notification-type-icons) - [Overriding a Screen](#overriding-a-screen) - [Feature Gate](#feature-gate) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction The notification UI belongs to the `magic_notifications` package, which provides `NotificationsListView`, `NotificationPreferencesView`, `NotificationPreferencesController` and `NotificationDropdown`. This package ships none of them. What stays here is what a notifications package cannot know on its own: `registerMagicStarterNotificationRoutes()` owns the paths (`MagicStarterConfig.notificationsRoute()` and `MagicStarterConfig.notificationPreferencesRoute()`, `/notifications` and `/settings/notifications` by default), mounts them inside the authenticated `layout.app` shell behind the `auth` middleware, and wraps the package's screens in this package's own page geometry (`MSPageContainer`) so they read like every other page in the app rather than spreading full-bleed. `MagicStarterAppLayout` owns the polling lifecycle and renders the bell, and `MagicStarterServiceProvider` declares the push identity. The feature is opt-in behind `magic_starter.features.notifications`. When it is on, the layout starts polling and renders the bell; the routes resolve through `Notify.view`, not `MagicStarter.view`. ## Real-Time Polling Notification polling is managed by `MagicStarterAppLayout`. When the authenticated layout mounts and the notifications feature is on, it calls `Notify.startPolling()`, which fetches notifications at a regular interval. Polling stops when the layout is disposed: ```dart @override void initState() { super.initState(); if (MagicStarterConfig.hasNotificationFeatures()) { Notify.startPolling(); } } @override void dispose() { if (MagicStarterConfig.hasNotificationFeatures()) { Notify.stopPolling(); } super.dispose(); } ``` `Notify.startPolling()` is idempotent: calling it again has no effect. It also triggers an immediate fetch so the UI has data without waiting for the first interval tick. The layout wraps both calls in a `try`/`catch` so a test environment where Magic is not fully initialised does not fail; your own test teardown should still call `Notify.stopPolling()` with a silent catch to avoid a timer leak. ## Push Identity `magic_notifications` declares no push identity of its own; the starter does. `MagicStarterServiceProvider` listens to `Auth.stateNotifier` and, on every bump while the notifications feature is on, calls `Notify.initializePush('')`. That covers a password, social, two-factor, OTP or guest sign-in and the restore of a stored session at launch. The call is safe to repeat: the manager returns early when the intent is unchanged. - **Prefix.** `magic_starter.notifications.external_id_prefix`, default `user_`; a blank value reads as the default. The backend must produce the same string: `onesignal.external_id_prefix` in `config/magic-starter.php` (`MAGIC_STARTER_EXTERNAL_ID_PREFIX`). A mismatch is accepted by OneSignal and delivered to nobody. `starter:doctor` prints the prefix it finds in the config. - **Guests.** A guest session is declared as nobody: it releases any identity instead of subscribing a throwaway id. - **Sign-out.** Any transition to signed-out releases the identity, including account deletion and the sign-out `AuthInterceptor` performs after a failed token refresh. `MagicStarterAuthController.logout()` also calls `Notify.logoutPush()` and `Notify.stopPolling()` first. - **Push state.** When the notifications package is bound and `notifications.push_state.report_path` is configured, the provider registers `Notify.pushState.release` as a before-logout hook (see [Before-Logout Hooks](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#before-logout-hooks)). ## Notification List `NotificationsListView` (from `magic_notifications`) is a full-page view that lists notifications with server-side pagination. It supports mark-as-read, mark-all-as-read, delete, and navigation to the notification's action URL. `registerMagicStarterNotificationRoutes()` registers it on `Notify.view` under `'notifications.list'`, wrapped in this package's page container, and the route renders that key at `MagicStarterConfig.notificationsRoute()`: ```dart MagicRoute.page( MagicStarterConfig.notificationsRoute(), () => Notify.view.make('notifications.list'), ).title('magic_starter.titles.notifications').stacked(); ``` ### Deleting a notification The mount supplies the view's `onDelete`, which is what makes the per-row delete control render at all: `NotificationsListView` draws it only when that callback is non-null. It does not hand the callback straight to `Notify.deleteNotification`. A delete is destructive, irreversible and one tap away in a scrollable list, so the mount asks first, through this package's own `MSConfirmDialog`: - The dialog is shown against `MagicRouter.instance.navigatorKey.currentContext`, because neither the view registry nor `onDelete` provides a `BuildContext`. A null context refuses rather than deleting: nobody could have been asked. - `MSConfirmDialog` is used rather than `Magic.confirm` so the dialog follows `MagicStarter.manager.modalTheme` and the host's dark mode. - Copy comes from `notifications.delete_confirm_title`, `notifications.delete_confirm_message`, `common.delete` and `common.cancel`. All four ship in `assets/stubs/install/en.stub`, so an app scaffolded by `starter:install` has them; an app with a hand-written catalogue needs them added, or the dialog renders the raw keys. To take the confirmation out, or to change what it asks, register your own screen for `'notifications.list'` and pass whatever `onDelete` you want. That registration wins (see [Overriding a Screen](#overriding-a-screen)). Each notification item resolves its icon through the notification type icon slot (see [Notification Type Icons](#notification-type-icons)). A tapped notification is marked as read and the user is sent to its `actionUrl`. ## Notification Preferences `NotificationPreferencesView` (from `magic_notifications`) shows a type-by-channel preference matrix fetched from the backend. Each notification type (for example "Monitor Down") lists its channels (email, in-app, push) as toggle switches. `registerMagicStarterNotificationRoutes()` registers it under `'notifications.preferences'`, passing what the notifications package cannot know: where "back" goes in this app, and the host page geometry. ```dart Notify.view.register( 'notifications.preferences', () => NotificationPreferencesView( backRoute: MagicStarterConfig.settingsHubRoute(), contentClassName: geometry, headerBuilder: _pageHeader, ), ); ``` Both mounts pass `headerBuilder`, which draws each screen's header as an `MSPageHeader` inside the screen's own scroll view, so both pages follow [host-owned page chrome](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#host-page-chrome) like every other starter page: under `MagicStarter.useHostPageChrome` the inbox reports its title and keeps only its mark-all-as-read action, and the preferences report the settings hub as their back fallback. A screen you register yourself draws its own header unless you pass a `headerBuilder` too. The matrix structure returned by the API: ```json { "monitor_down": { "label": "Monitor Down", "channels": { "mail": { "enabled": true, "locked": false }, "database": { "enabled": true, "locked": true }, "push": { "enabled": false, "locked": false } } } } ``` Locked channels display a lock icon and their toggle is disabled; the backend enforces that certain channels cannot be turned off. > [!NOTE] > Preference updates are optimistic. The toggle flips immediately and a `PUT /notification-preferences` request is sent; on failure the matrix reverts to its pre-update snapshot. That state lives in `magic_notifications`'s `NotificationPreferencesController`; this package carries no controller for it. The screen also opens with a bulk card above the matrix, one switch per channel applying to every type at once, backed by the batch shape `PUT /notification-preferences` with `{preferences: [{type, channel, is_enabled}, ...]}`. `magic-starter-laravel` accepts that shape; a hand-rolled endpoint that only takes the single shape answers 422 and the card does nothing. The notification screens read five `notifications.*` keys that no package supplies: `bulk_title` and `bulk_description` head the bulk card, `delete` names the list row's delete glyph for a screen reader, `delete_failed` is shown when the server refuses a delete, and `channel_sms` labels the SMS row. All five ship in `assets/stubs/install/en.stub`, so an app scaffolded by `starter:install` has them; an app with a hand-written catalogue adds them, or each renders as its own key. ## Notification Dropdown `NotificationDropdown` (from `magic_notifications`) is a standalone widget, not a view: a bell icon with a live unread badge, built on a `StreamBuilder>`. `MagicStarterAppLayout` mounts it with these callbacks: ```dart NotificationDropdown( notificationStream: Notify.notifications(), onMarkAsRead: (id) => Notify.markAsRead(id), onMarkAllAsRead: () => Notify.markAllAsRead(), onNotificationTap: (notification) => MagicRoute.to(notification.actionUrl ?? '/'), onViewAll: () => MagicRoute.to(MagicStarterConfig.notificationsRoute()), ) ``` The layout also passes the trigger, icon, panel and badge classNames from `MagicStarter.manager.layoutTheme`; a null one keeps the widget's own default. The dropdown is rendered in the layout's header and sidebar through the `_buildNotificationBell()` helper, and only when `MagicStarterConfig.hasNotificationFeatures()` is `true`. | State | Display | |:------|:--------| | Loading | Bell icon with no badge, spinner in the dropdown body | | Error | Bell icon with no badge, error icon in the dropdown body | | Empty | Bell icon with no badge, "No notifications" empty state | | Unread > 0 | Bell icon with red badge (`9+` overflow), notification list | A tapped notification is marked as read and `onNotificationTap` fires; the dropdown closes after the tap. > [!TIP] > The dropdown uses `WPopover` for overlay positioning. It aligns to `PopoverAlignment.bottomRight` by default and constrains its height to 400 logical pixels. ## Notification Type Icons What a notification type looks like is `magic_notifications`'s own slot, and it answers the same question for the list screen and the bell at once: ```dart import 'package:magic_notifications/magic_notifications.dart'; Notify.view.slot( NotificationViewRegistry.typeIconSlotView, 'monitor_down', (context) => WIcon(Icons.error_outline, className: 'text-lg text-red-500'), ); ``` Register the slot name `'default'` to answer for every type you did not name individually: ```dart Notify.view.slot( NotificationViewRegistry.typeIconSlotView, 'default', (context) => WIcon(Icons.info_outline, className: 'text-lg text-blue-500'), ); ``` Both the list view and the dropdown read `Notify.view.buildTypeIcon(type, context)`, which checks the type's own slot first and falls back to `'default'`, so one registration answers for both surfaces. ## Overriding a Screen To swap either screen, register on `Notify.view`, not `MagicStarter.view`: ```dart Notify.view.register( 'notifications.list', () => const MyCustomNotificationsListView(), ); ``` **The order does not matter.** `registerMagicStarterNotificationRoutes()` installs its own wrapped screens only when nobody has chosen one for that key (`Notify.view.hasOverride`), so a host registration wins whether it runs before or after the routes are mapped. The check is `hasOverride`, not `has`: reading `Notify.view` seeds `magic_notifications`' own two defaults into the registry, so `has(key)` is already true before anybody has decided anything, and gating on it would make this package skip every time and never apply the page geometry. The two calls can land in different files (the installer injects the route registration into `route_service_provider.dart`, while your `Notify.view` work usually sits in `AppServiceProvider`), and which boots first depends on the host's provider list, which is why the order is made not to matter. The registry has the same shape as `MagicStarter.view` (`register` / `has` / `make` / `slot` / `buildSlot` / `clear`). ## Feature Gate All notification functionality is gated behind `MagicStarterConfig.hasNotificationFeatures()`. Enable it in your configuration: ```dart Config.set('magic_starter.features.notifications', true); ``` When it is off: - The notification routes are not registered (`registerMagicStarterNotificationRoutes()` returns at once). - The bell does not render in the app layout. - Polling never starts. - No push identity is declared. > [!TIP] > The install command can enable it: `dart run magic:dowel starter:install --features=notifications`. That adds `magic_notifications` to your `pubspec.yaml` and prints the follow-up `dart run magic:dowel notifications:install --app-id=`; it does not run the OneSignal installer for you, because the app id is yours. ## Gotchas | Mistake | Fix | |:--------|:----| | Changing `magic_starter.notifications.external_id_prefix` on one side only | Change the backend's `onesignal.external_id_prefix` (`MAGIC_STARTER_EXTERNAL_ID_PREFIX`) with it. OneSignal accepts the mismatch and delivers to nobody; `starter:doctor` shows the prefix the app declares. | | Using a custom prefix while reporting push state | `magic_notifications` reads its own `notifications.push_state.external_id_prefix` (default `user_`) and reports only when the intent is ``; set both keys to the same value. | | Registering your own screen on `MagicStarter.view` | The notification routes resolve through `Notify.view`; register `'notifications.list'` or `'notifications.preferences'` there. | | Gating an override on `Notify.view.has(key)` | Reading `Notify.view` seeds the package defaults, so `has` is always true. Use `hasOverride`. | | A hand-written language catalogue missing the notification keys | The delete confirmation and the bulk card render raw keys. Add the `notifications.*` and `common.delete` entries from `assets/stubs/install/en.stub`. | | Expecting authenticated work in a before-logout hook after a refresh failure | Hooks do not run for the sign-out `AuthInterceptor` performs; the starter still releases the push identity, but server-side rows need their own expiry. | ## Related Documentation - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#before-logout-hooks): sign-out and the before-logout hooks. - [Components](https://anilcancakir.com/magic/docs/starter/basics/components.md): `MSConfirmDialog`, `MSPageHeader` and the page container the screens are wrapped in. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the app layout that owns polling and the bell. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature flag and the prefix key. - [Channels](https://anilcancakir.com/magic/docs/notifications/basics/channels): the notification channels. - [Preferences](https://anilcancakir.com/magic/docs/notifications/basics/preferences): the preference model behind the matrix. --- # Support The support desk: screens, a chat popup and optional ratings, attachments and feedback that let a signed-in customer write to your team and follow the answer inside the app. - [Introduction](#introduction) - [Enabling the Desk](#enabling-the-desk) - [Screens](#screens) - [Chat Popup](#chat-popup) - [The AI Desk](#the-ai-desk) - [Knowledge Base Articles](#knowledge-base-articles) - [Topics](#topics) - [Live Updates](#live-updates) - [Contact Sales](#contact-sales) - [Rating a Resolved Conversation](#rating-a-resolved-conversation) - [Attachments](#attachments) - [Client Info](#client-info) - [Page Context](#page-context) - [The Feedback Card](#the-feedback-card) - [Store Review](#store-review) - [Overriding a Screen](#overriding-a-screen) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction The desk is the client of `magic-starter-laravel`'s support API (`support/conversations`), which scopes every conversation to the user who opened it: a teammate asking for someone else's thread gets the same 404 as a missing one. Staff answer from the backend's admin panel; nothing on this side reads or writes another user's conversation. ## Enabling the Desk Turn the feature on in `lib/config/magic_starter.dart`: ```dart 'features': { 'support': true, }, ``` Then register the routes from your route provider, beside the other starter routes: ```dart registerMagicStarterAuthRoutes(); registerMagicStarterProfileRoutes(); registerMagicStarterTeamRoutes(); registerMagicStarterSupportRoutes(); ``` The profile dropdown shows its Support item whenever the feature is on, so a host that enables the feature without registering the routes ships a menu item that leads nowhere. A host that draws its own account menu instead of `MSUserProfileDropdown` adds its own entry pointing at `MagicStarterConfig.supportRoute()`. The backend has to enable the same feature (`Features::support()` in `config/magic-starter.php`); with it off the endpoints do not exist and the screens show their error state. The screens below need `magic-starter-laravel` with the AI desk columns (`topic`, `awaiting_ai`, `last_message` and the paginated list). Further flags build on it. All default to `false`. `support_csat`, `support_feedback`, `support_attachments` and `support_client_context` need the backend to turn on the feature of the same name (`Features::supportCsat()`, `supportFeedback()`, `supportAttachments()`, `supportClientContext()`) because they call routes and fields it adds; `support_chat` and `store_review` are client only: ```dart 'features': { 'support': true, 'support_csat': true, 'support_feedback': true, 'support_attachments': true, 'support_client_context': true, 'support_chat': true, 'store_review': true, }, ``` | Flag | Adds | |:-----|:-----| | `support_csat` | A thumbs rating under a resolved thread | | `support_feedback` | `MagicStarterFeedbackCard`, a "Send feedback" page and menu item | | `support_attachments` | Image and PDF files on a new conversation and on a reply, and in the thread | | `support_client_context` | Client info (app version, platform, locale) on a new conversation | | `support_chat` | `MagicStarterSupportChatLauncher`, a button with an unread badge that opens a floating chat panel at the bottom right of the screen. Needs `support` | | `store_review` | The native review prompt and a "Rate us" menu item (client only; the backend has no counterpart) | `starter:install --features=support` adds `registerMagicStarterSupportRoutes();` to `route_service_provider.dart`, `starter:uninstall` removes it, and `starter:doctor` warns when the feature is on and the call is missing. ## Screens | Path | View key | What it shows | |:-----|:---------|:--------------| | `/support` | `support.index` | The user's conversations in an Open and a Resolved tab, newest activity first. Each row shows the sender and a preview of the last message, a status badge and an unread dot when staff or the AI wrote since the last read. A "Load more" button reads the next page (20 a page); a refresh rereads every page already loaded, so the poll never collapses them, and the Resolved tab offers "Load more" instead of an empty claim while pages remain | | `/support/new` | `support.create` | Topic chips and a message with a character counter, posted with source `in_app`. A "How it works" card sits beside the form on a wide screen and collapses to one line above it on a phone | | `/support/:id` | `support.thread` | Chat bubbles by who wrote them, activity lines for handoffs, and a composer docked at the bottom | `/support/new` and `/support/:id` are pushed (`.stacked()`), so the back gesture returns to the list. Opening a thread that has an unread reply sends a seen receipt and clears the dot; a thread with nothing unread sends none. All the screens share one `MagicStarterSupportController`. A thread read that answers after the reader has already opened another thread is dropped, so a slow response never puts one conversation's messages under another's composer. A page of the list that answers after the list was reloaded is dropped the same way, and a row already held is not added twice when new activity moves it between two reads. ## Chat Popup With `support_chat` on (and `support`), a host can mount `MagicStarterSupportChatLauncher` in its shell: a button with an unread count that opens a floating panel with the customer's conversations, one thread or the new-conversation form. Place it once in the shell, such as a sidebar; the panel does not depend on where the button sits: ```dart class AppSidebar extends StatelessWidget { const AppSidebar({super.key}); @override Widget build(BuildContext context) { return WDiv( className: 'flex flex-col gap-1', children: [ const MagicStarterSupportChatLauncher( className: 'flex flex-row items-center gap-3 px-3 py-2 rounded-lg text-sm text-fg', ), ], ); } } ``` The launcher renders nothing unless the flag and `support` are on and a signed-in, non-guest user is present; signing out closes the panel. Mount it once per app: a second launcher would open a second panel. The props are `className` (the trigger's classes; null is a full-width sidebar row; a value replaces the default trigger classes rather than adding to them, so give it a full class list including `flex flex-row`, or the icon stacks above the label), `width` (400) and `height` (520), and `margin` (16), the gap the panel keeps from the screen edges. The panel floats at the bottom right of the screen, like a chat widget, wherever the launcher sits. It is non-modal: a tap outside does not close it and the page stays interactive. It stays on screen: it is clamped to the safe area, and its height gives way to the keyboard. Escape closes it; opening moves focus into the panel and closing returns it to the launcher. The header has back, the title, "open full page" (closes the panel and goes to `/support`) and close. An empty conversation list opens the new-conversation form. ### Sharing state with the pages The popup and the `/support` pages run side by side without conflict. `MagicStarterSupportSync` owns the one 30 second poll, the one broadcast listener and one refetch after a reconnect for every open surface, and a closed launcher holds no poll. The controller keeps a thread per conversation id, so the popup and a page can show different threads, and a write locks per surface (`'page'` for the pages, `'chat'` for the panel): a reply on the page and a new conversation in the popup run together, a second tap on the same surface is refused. A host that replaces `support.chat_panel` takes over the shared-refresh `retain()` and `release()`, the thread watch and the seen receipt. Limit: validation errors and write errors (`getError`, `writeError`) are still held once on the controller, not per surface, so an error one surface raised is visible to the other while both are open. The knowledge-base suggestions on the create form are shared the same way: there is one list, and `forgetArticleSuggestions` runs when a create form mounts, so opening the panel's form clears the suggestions of the form on the page. On native macOS the Escape key inside the composer may be consumed by the text field before it reaches the panel; the web is unaffected. The copy lives under `magic_starter.support.chat.*`. The package ships English only: a host adds the keys to each catalogue it ships, and an app with a published `en.json` merges them from `assets/stubs/install/en.stub`. On a layout with no room for the launcher, the `/support` routes remain the way in. ## The AI Desk When the backend has an AI responder bound, a verified customer's conversation starts with the AI answering. The screens read three fields the backend computes and never guess at them: | Field | Meaning | What the screen shows | |:------|:--------|:----------------------| | `awaiting_ai` | Pending, and the newest customer message has no AI answer yet | An "AI answering" pill, a typing bubble in the thread and the line "Our AI answers right away and hands off to the team when needed" above the composer | | `waiting_on_team` | Open and waiting on a person | A "Team answering" pill and the line "Our team usually replies within a few hours" above the composer | | neither | Answered, or finished | The plain "Open" badge, or the "Resolved" pill | "AI answering", "Team answering" and "Resolved" are soft tinted pills with a leading dot (`bg-ai-soft`, `bg-warning-soft`, `bg-success-soft`); the assistant's bubble carries a 2px `border-ai` left edge. A customer message sent on a `pending` conversation flips the local copy to `awaiting_ai` at once, so the typing bubble shows before the next refetch. `pending` and `snoozed` are the desk's own bookkeeping and read as open. A message from the assistant carries `sender_type` `ai` and its name; it renders on the left with a sparkle avatar on `bg-ai-soft` and a chip under the bubble, a teammate shows their first name and photo or initials, and the customer sits on the right. A message with `kind` `activity` (the handoff line, a status change) renders as a centred divider line, not a bubble. If the AI has been pending for 45 seconds, counted from when the screen first saw it pending, the typing bubble gives way to "This is taking longer than usual. If the AI cannot answer, our team will take over." The backend's sweeper hands the turn to staff after a few minutes, so a stranded thread does not stay in the typing state. The composer sits in the page scaffold's `footer`, above the keyboard. On web and desktop Enter sends and Shift+Enter breaks the line (a pending IME composition keeps Enter); on a phone Enter breaks the line and the round send button sends. A write the backend refuses for a reason other than validation shows under the field as `writeError`. ## Knowledge Base Articles When the backend runs `magic-starter-laravel` with `support.articles.enabled`, the create form and AI answers point the customer at its public knowledge-base articles: - **While writing.** Once the new-conversation message has 12 characters and typing has paused for 600 ms, the form asks `GET support/articles?search=&locale=` (the message cut to 200 characters, the app's language code) and shows up to three articles, question and excerpt, under a "These may help" label above Start conversation. A slower earlier answer never replaces a newer one, falling under 12 characters clears them, and a failed or switched-off (404) lookup shows nothing. - **Under an AI answer.** An AI message parses `articles` (`slug`, `question`, `url`), and its bubble shows one `MagicStarterSupportArticleCard` per article. No other sender's message renders them. A tap opens the article's `url`, the public FAQ page of its language anchored on the article, with `Launch.url`; a url the system cannot open shows `article_open_error`, and an article without a `url` is plain text. The labels are `magic_starter.support.articles_label` and `magic_starter.support.article_open_error`: add both to every locale the app ships, since the translator merges no fallback. ## Topics A new conversation is filed under a topic. The chips come from `magic_starter.support.topics` (read by `MagicStarterConfig.supportTopics()`), which defaults to `billing`, `technical`, `account`, `sales` and `other`. The keys are wire values the backend validates against its own `support.topics`, so a topic added here has to exist there as well. A chip's label is `magic_starter.support.topic.`, and a topic a host added without translating it shows its key. ```dart 'support': { 'topics': ['billing', 'technical', 'other'], }, ``` The backend derives the subject from the first line of the message (the topic is shown beside it as a tag), so the create form asks for none; `createConversation` still accepts an optional `subject`. The counter under the message field reads `magic_starter.support.message_max_length` (`MagicStarterConfig.supportMessageMaxLength()`, default 2000). It is display only: set it to the backend's `support.message_max_length`, which is what refuses a longer message. On a phone the thread hides the bottom navigation, like a chat screen: `registerMagicStarterSupportRoutes()` registers it in the app shell (`MagicStarterLayoutIds.app`) with the page wrapped in `MagicStarterHideBottomNav`, so the bar slides away with the page and moving between support pages never rebuilds the layout. The list and the create page keep it. ## Live Updates The list and the thread refetch when the backend broadcasts `support.conversation.updated` on the private channel `App.Models.User.{id}`. They subscribe through `BroadcastListeners` from `magic_socket` (see [Listeners](https://anilcancakir.com/magic/docs/socket/basics/listeners)), which the notification bell shares, so neither listener replaces the other. With no broadcast connection configured, or while the socket is down, both screens poll every 30 seconds instead. ## Contact Sales With the support feature on, the billing screen's custom tier ("Contact sales") opens a conversation with source `contact_sales` and the subject `Contact sales: `, then lands on its thread. It names no topic: the backend files a Contact sales conversation under `sales`. With the feature off the button keeps its toast. A refusal toasts the backend's message and stays on the billing screen. ## Rating a Resolved Conversation With `support_csat` on, a resolved thread ends with "How did we do?": a thumbs up or down and an optional comment (1000 characters at most), posted to `support/conversations/{id}/rating`. The block shows when the backend reports `can_rate`, or when the conversation already carries a `rating`, which the customer can then change: the backend overwrites it for as long as the conversation stays resolved. A down rating alerts staff on the backend, once per resolution. `MagicStarterSupportController.rate()` does the write and a refusal lands in `getError('rating')`. ## Attachments With `support_attachments` on, the create form and the thread composer get an "Attach files" button, and a message that has files may have no text. A bubble lists its files: an image shows as a thumbnail that opens full size, a PDF as a row that opens in the system viewer. The files go up in the same request as the message. As soon as one is attached the request is `multipart/form-data` with one part per file (`attachments[0]` to `attachments[2]`); without a file it stays JSON. The controller refuses a pick the backend would refuse before it uploads it, from these keys: ```dart 'support': { 'attachments': { 'max_files': 3, 'max_bytes': 5 * 1024 * 1024, 'extensions': ['jpg', 'jpeg', 'png', 'webp', 'pdf'], }, }, ``` The defaults match the backend's `support.attachments` (`max_files`, `max_kb`, `types`); a host that changes one changes the other, since the backend enforces its own. An image is read with the bearer token (`MagicStarterSupportController.attachmentHeaders()`), because the file endpoint answers to the token alone. A PDF asks for a 60 second signed url (`attachmentLink()`) and hands it to the system viewer. ## Client Info With `support_client_context` on, a new conversation carries the device and app details the customer did not type (`MagicStarterSupportClientContext.collect()`), sent as `client_context[...]`: `app_version`, `build_number`, `platform`, `os_version`, `locale` and `timezone`. Each value is cut to 120 characters, and a value the device cannot tell is left out. ## Page Context A customer chatting from a monitor page should not have to describe it. `MagicStarter.usePageContext` registers a provider that answers which things the current screen is about, as `MagicStarterSupportPageRef`s: a `kind` and an `id`, a typed pointer and never free text. The package knows no kinds of its own; you choose them, and the backend allows only the kinds it is configured with. ```dart MagicStarter.usePageContext(() { final id = MagicRouter.instance.routerConfig.state.pathParameters['monitor']; return [ if (id != null) MagicStarterSupportPageRef(kind: 'monitor', id: id), ]; }); ``` Read the top route through `routerConfig.state`. A page opened from a list is pushed, and `MagicRouter.instance.pathParameter` and the router's `currentConfiguration` keep naming the page underneath it. The provider is asked when a message is sent, for a new conversation and for every reply, so it answers for the screen behind the Send button, and the references travel as `page_context`. At most three are kept, in order, duplicates dropped, and `kind` and `id` are cut to 64 characters; one with an empty value is left out. The key is omitted when there are none. The full `/support` pages send nothing as long as your provider returns nothing for those routes, while the chat panel, which floats over another screen, sends that screen's references. A provider that throws is logged as a warning and the message goes without references. Registering again replaces the provider, and there is no feature flag: a registered provider is the opt-in. ## The Feedback Card With `support_feedback` on, `MagicStarterFeedbackCard` asks "How likely are you to recommend us?" on a 0 to 10 scale with an optional comment (2000 characters at most). Place it yourself, on the screen where a customer finishes something: ```dart const MagicStarterFeedbackCard() ``` It renders nothing until the backend says the account is due (`GET support/feedback`, which the backend paces by account age and time since the last answer), and nothing for a guest or a signed-out visitor. "Not now" records a dismissal, which paces it like an answer. A score the backend counts as low opens, or continues, a conversation, and the thanks line then links to it. The backend never lets the AI desk answer that conversation. The same form is the "Send feedback" page (`/support/feedback`, view key `support.feedback`) behind a profile menu item. That page and `MagicStarterFeedbackCard(onDemand: true)` skip the eligibility read and the dismissal. A guest or an account with an unverified email is not offered the menu item, since the backend refuses it. ## Store Review With `store_review` on, the app can ask for the native store review sheet and offer a "Rate us" link. Ask for the review yourself, at a moment that went well (a first check passed, a tenth incident resolved): ```dart await MagicStarterStoreReview.maybeRequest(); ``` `maybeRequest()` stays quiet unless every rule holds: - never on the web; - never for a guest or a signed-out user; - never in the first 7 days of an account (`magic_starter.store_review.min_account_days`); - at most once per 120 days on this device (`magic_starter.store_review.interval_days`, remembered in the `Vault`); - never in a run where the feedback card was shown, so a customer is not asked a question and then asked for a review in the same session; With `support_feedback` on, the call first waits for the card's eligibility read (shared with the card) and stays quiet when the card is due, even if the card has not rendered yet; - never from a button. The platforms decide whether a sheet appears and say nothing back, so a button wired to it would sometimes do nothing. Call it from your own milestone. It answers whether the platform was asked, not whether a sheet showed. "Rate us" in the profile menu is the button instead: it calls `MagicStarterStoreReview.openStoreListing()`, which opens the store page and has no quota. It shows on Android, and on iOS and macOS once the App Store id is set: ```dart 'store_review': { 'app_store_id': '1234567890', 'min_account_days': 7, 'interval_days': 120, }, ``` Android finds its listing from the package name. The feature uses the `in_app_review` package; the client info uses `package_info_plus` for the version and build number. Both come with `magic_starter`, and a host with no other use for them adds nothing. ## Overriding a Screen Each screen resolves through the view registry, so a host replaces one the usual way: ```dart MagicStarter.view.register('support.thread', () => const MySupportThreadView()); ``` `support.feedback` joins `support.index`, `support.create` and `support.thread` when `support_feedback` is on, and `support.chat` (the launcher) and `support.chat_panel` (the floating panel) when `support_chat` is on. Copy lives under `magic_starter.support.*`, `magic_starter.nav.support` and `magic_starter.titles.support*`. A host that published its own `en.json` adds those keys from `assets/stubs/install/en.stub`. ## Gotchas | Mistake | Fix | |:--------|:----| | Enabling `support` without calling `registerMagicStarterSupportRoutes()` | The flag alone mounts no page, and the profile menu still shows its Support item. Call it from your route provider; `starter:doctor` warns when it is missing. | | Turning on `support_csat`, `support_feedback`, `support_attachments` or `support_client_context` on the client only | They call routes and fields the backend adds only with its feature of the same name. Turn on both sides. | | Mounting `MagicStarterSupportChatLauncher` more than once | A second launcher opens a second panel. Mount it once in the shell. | | Passing a `className` to the launcher that only tweaks the default | A value replaces the default trigger classes. Give it a full list, including `flex flex-row`. | | Adding a topic in `magic_starter.support.topics` the backend does not know | The keys are wire values the backend validates against its own `support.topics`. Add it on both sides. | | Calling `MagicStarterStoreReview.maybeRequest()` from a button | The platform decides whether a sheet appears and says nothing back. Call it from a milestone; use "Rate us" (`openStoreListing()`) for a button. | ## Related Documentation - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): the settings hub and the profile menu that carries the Support item. - [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md): the billing screen whose "Contact sales" opens a conversation. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the view registry the screens resolve through. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature flags and the `support` keys. - [Listeners](https://anilcancakir.com/magic/docs/socket/basics/listeners): the broadcast listeners the live updates share. --- # Middleware The two route guards the starter ships, `EnsureAuthenticated` and `RedirectIfAuthenticated`, and the `auth` and `guest` aliases its route groups expect. - [Introduction](#introduction) - [Registering the Aliases](#registering-the-aliases) - [EnsureAuthenticated](#ensureauthenticated) - [RedirectIfAuthenticated](#redirectifauthenticated) - [Which Routes Expect Which Alias](#which-routes-expect-which-alias) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction `EnsureAuthenticated` blocks a signed-out visitor from a protected route, and `RedirectIfAuthenticated` blocks a signed-in visitor from a guest-only page such as the login form. Both extend `MagicMiddleware` and override `redirectTarget`, so the redirect resolves inside the router's `redirect` callback before any page builds; the destination view mounts exactly once instead of building the gated page and then remounting. ## Registering the Aliases Register them once in your app's `Kernel`, using the exact alias names `'auth'` and `'guest'` that the starter's own route groups reference: ```dart import 'package:magic/magic.dart'; import 'package:magic_starter/magic_starter.dart'; void registerMiddleware() { Kernel.registerAll({ 'auth': () => EnsureAuthenticated(), 'guest': () => RedirectIfAuthenticated(), }); } ``` Call `registerMiddleware()` once from your bootstrap, before the router builds its routes. `starter:install` does this for you in `lib/app/kernel.dart`, with copies of the two classes it scaffolds into `lib/app/middleware/` (see [Gotchas](#gotchas)). ## EnsureAuthenticated Redirects an unauthenticated visitor to `MagicStarterConfig.loginRoute()`. It leaves the login route itself alone so the redirect can never loop: `go_router` raises past five successive redirects. Before it redirects, it records the location it bounced as the router's intended url (`MagicRouter.setIntendedUrl`), so a successful sign-in lands there through `navigateHome()`. Nothing is recorded for the login route or for the guest-only auth pages (register, forgot and reset password, two-factor challenge, OTP). The location carries no query string, so a recorded intent loses a `?token=...` the original link had. ```dart MagicRoute.group( middleware: ['auth'], routes: () { // protected routes }, ); ``` ## RedirectIfAuthenticated Redirects an already authenticated visitor to `MagicStarterConfig.homeRoute()`. It leaves the home route itself alone for the same reason: a signed-in visitor landing back on home must not be redirected to home again. A guest session (`is_guest: true`) is exempt and stays on the auth pages, because login and registration are where a guest becomes an account. ```dart MagicRoute.group( middleware: ['guest'], routes: () { // auth pages: login, register, forgot/reset password }, ); ``` ## Which Routes Expect Which Alias The starter's own route groups assume these aliases are registered: | Route group | Alias | File | |:------------|:------|:-----| | Auth (login, register, forgot/reset password, two-factor challenge, OTP) | `guest` | `lib/src/routes/auth_routes.dart` | | Profile / settings | `auth` | `lib/src/routes/profile_routes.dart` | | Teams | `auth` | `lib/src/routes/team_routes.dart` | | Notifications | `auth` | `lib/src/routes/notification_routes.dart` | | Support | `auth` | `lib/src/routes/support_routes.dart` | The email verification and sign-in handoff routes sit outside both groups on purpose: a visitor may open those links signed in or signed out (see [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#verify-email)). If a route names an alias that was never registered, the router throws a `StateError` naming the route and the alias when it builds, which surfaces from `Magic.init`. ## Gotchas | Mistake | Fix | |:--------|:----| | Forgetting to register `auth` or `guest` | The router refuses to build with a `StateError` that names each route and the missing alias. Register both before the router builds. | | Assuming the installed Kernel uses the package classes | `starter:install` writes `lib/app/middleware/ensure_authenticated.dart` and `redirect_if_authenticated.dart` and registers those. They are plain `handle`-based copies: they redirect after the build, do not record an intended url and do not exempt a guest session. Delete them and register the package classes to get the behaviour on this page. | | Using a different alias name | The starter's route groups look up `auth` and `guest` literally; any other name leaves them unregistered. | | Expecting the intended url to keep a query string | `redirectTarget` receives the matched location without its query, so a `?token=...` is lost. | | Putting the guest guard on the verify-email or handoff route | Those routes are deliberately outside `guest`: a signed-in reader would be sent home before the link was replayed. | ## Related Documentation - [Authentication](https://anilcancakir.com/magic/docs/starter/basics/authentication.md): `Auth.check()`, login, logout and the routes these guards protect. - [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md): what resets when `Auth.stateNotifier` changes identity. - [CLI Commands](https://anilcancakir.com/magic/docs/starter/basics/cli.md): what `starter:install` scaffolds and registers. --- # Views and Layouts How a page-level view binds to its controller, how the app and guest shells wrap it, and how a host replaces any screen or shell through the view registry. - [Introduction](#introduction) - [Quick Reference](#quick-reference) - [MagicStatefulView](#magicstatefulview) - [View Lifecycle](#view-lifecycle) - [State Rendering](#state-rendering) - [Form Handling](#form-handling) - [AppLayout](#applayout) - [Where the sidebar starts, and where it grows labels](#where-the-sidebar-starts-and-where-it-grows-labels) - [Letting the viewer collapse the sidebar](#letting-the-viewer-collapse-the-sidebar) - [A focus ring for a keyboard or a remote](#a-focus-ring-for-a-keyboard-or-a-remote) - [A live count on a destination](#a-live-count-on-a-destination) - [The box the route child is handed](#the-box-the-route-child-is-handed) - [Hiding the bottom nav on a page](#hiding-the-bottom-nav-on-a-page) - [An immersive route](#an-immersive-route) - [GuestLayout](#guestlayout) - [Page Chrome](#page-chrome) - [Wind UI System](#wind-ui-system) - [Dark Mode](#dark-mode) - [View Registry](#view-registry) - [Layout Registry](#layout-registry) - [Overriding the App Shell](#overriding-the-app-shell) - [Feature-Gated Rendering](#feature-gated-rendering) - [Zero Business Logic](#zero-business-logic) - [Reusable Widgets](#reusable-widgets) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction The view layer separates rendering from state: views render, controllers hold state and business logic. Every page-level view extends `MagicStatefulView`, which binds the view to its controller singleton and provides lifecycle hooks. Two layout shells wrap the views: `MagicStarterAppLayout` for authenticated pages and `MagicStarterGuestLayout` for auth pages. The views are built with Wind widgets (`WDiv`, `WText`, `WButton` and the rest); `Icons` is the only Material import. All views and layouts are registered by string key in a registry, so every screen is overridable by the host app. ## Quick Reference Replace a view or a layout by registering a builder under its key, in your own provider's `boot()`: ```dart MagicStarter.view.register('auth.login', () => const MyLoginView()); MagicStarter.view.registerLayout('layout.app', (child) => MyAppShell(child: child)); ``` | View keys | Registered when | |:----------|:----------------| | `auth.login`, `auth.register`, `auth.forgot_password`, `auth.reset_password` | Always | | `auth.verify_email` | `email_verification` | | `auth.two_factor_challenge` | `two_factor` | | `auth.otp_verify` | `phone_otp` | | `auth.handoff` | `handoff` | | `settings.hub`, `profile.profile`, `settings.appearance`, `settings.security.password` | Always | | `settings.language` | `extended_profile` | | `settings.timezone` | `timezones` | | `settings.newsletter` | `newsletter` | | `settings.changelog` | `releases` | | `settings.security.two_factor` | `two_factor` | | `settings.security.sessions` | `sessions` | | `settings.security.connected_accounts` | `social_login` | | `teams.create`, `teams.settings`, `teams.invitation_accept` | `teams` | | `teams.billing` | `billing` | | `support.index`, `support.create`, `support.thread` | `support` | | `support.feedback` | `support` and `support_feedback` | | `support.chat`, `support.chat_panel` | `support` and `support_chat` | | Layout keys | Layout | |:------------|:-------| | `layout.app` | The authenticated shell with sidebar and navigation | | `layout.guest` | The centred shell for auth pages | `profile.settings` is a long single-page profile view the package can publish (`starter:publish`) but no default registers. `notifications.list` and `notifications.preferences` are not on `MagicStarter.view` either: those screens belong to `magic_notifications` and live on its own `Notify.view`; see [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md). ## MagicStatefulView Page-level views extend `MagicStatefulView` with a state class that extends `MagicStatefulViewState`: ```dart class ProjectsView extends MagicStatefulView { const ProjectsView({super.key}); @override State createState() => _ProjectsViewState(); } class _ProjectsViewState extends MagicStatefulViewState { @override void onInit() { controller.clearErrors(); controller.setEmpty(); } @override Widget build(BuildContext context) { return controller.renderState( (_) => _buildList(), onEmpty: _buildList(), onError: (message) => _buildList(errorMessage: message), ); } } ``` The base class gives you the controller singleton as `controller`, plus the `onInit()` and `onClose()` hooks. Only full-page views that need a controller binding use it; components such as `MSUserProfileDropdown` extend `StatelessWidget` or `StatefulWidget` directly. ## View Lifecycle `onInit()` runs once when the state is initialised: clear errors, set the initial state or trigger a fetch. `onClose()` runs when the state is disposed: dispose form data and local notifiers. ```dart @override void onClose() => form.dispose(); ``` A view with several forms disposes every `MagicFormData` in `onClose()`, and field names must not collide across forms in the same view. A view that runs while its route is being built should not notify: the profile and team controllers expose `resetQuietly()` for that. ## State Rendering `controller.renderState()` picks a builder from the controller's `MagicStateMixin` state. The first positional argument builds the success state (it receives the state value): | Parameter | When | Typical use | |:----------|:-----|:------------| | `onLoading` | A request is in flight | A skeleton | | `onEmpty` | No data loaded yet | The empty form or a placeholder | | `onError` | The controller called `setError()` | The form with an error banner | Read `controller.isLoading` at the top of a build method to disable a submit button: ```dart WButton( onTap: controller.isLoading ? null : _submit, className: 'w-full py-3 rounded-lg bg-primary text-white', child: WText(controller.isLoading ? trans('common.loading') : trans('auth.login')), ) ``` ## Form Handling Forms are `MagicFormData` instances with empty-string defaults for text fields and typed defaults for the rest: ```dart late final form = MagicFormData( { 'email': '', 'password': '', 'remember_me': false, }, controller: controller, ); ``` Read a text field with `form.get('email')` and a typed one with `form.value('remember_me')`. Render fields with `WFormInput`, bound to the form's field controller: ```dart WFormInput( label: trans('attributes.email'), controller: form['email'], type: InputType.email, validator: rules([Required(), Email()], field: 'email'), ) ``` Validate, then hand the values to the controller: ```dart Future _submit() async { if (!form.validate()) return; await controller.doLogin( email: form.get('email'), password: form.get('password'), rememberMe: form.value('remember_me'), ); } ``` Read route values a controller call needs (a reset token, say) in the view's `didChangeDependencies` through `MagicRouter.instance.queryParameterOf(context, 'token')` or `pathParameterOf(context, ...)`, which answer for the page the view sits in. ## AppLayout `MagicStarterAppLayout` is the authenticated shell: a sidebar with brand, team selector, navigation and user menu on a wide screen, and a header, drawer and bottom navigation on a narrow one. The `MagicStarterManager` constructor registers it under `layout.app` as a default. It starts notification polling when it mounts (with notifications on, through `Notify.startPolling()`), mounts the update and campaign banners when their features are on, and rebuilds on `Auth.stateNotifier` and on the static `MagicStarterAppLayout.refreshNotifier`. Nothing in the package bumps that notifier, since the layout already rebuilds on `Auth.stateNotifier`; only a host that needs an extra rebuild increments its `value`. Customise it before the layout first paints, ideally in `AppServiceProvider.boot()`: ```dart // Replace the mobile header. MagicStarter.useHeader((context, isDesktop) { return MyCustomHeader(showMenuButton: !isDesktop); }); // Navigation destinations. MagicStarter.useNavigation( mainItems: [ MagicStarterNavItem( icon: Icons.dashboard_outlined, labelKey: 'nav.dashboard', path: '/', ), ], ); // A widget between the navigation items and the user menu. MagicStarter.useSidebarFooter((context) => MyVersionBadge()); // Colours and brand. MagicStarter.useNavigationTheme( MagicStarterNavigationTheme( activeItemClassName: 'active:text-amber-500 active:bg-amber-500/10 dark:active:text-amber-400 dark:active:bg-amber-400/10', brandBuilder: (context) => Image.asset('assets/logo.png', height: 28), bottomNavActiveClassName: 'active:text-amber-500 dark:active:text-amber-400', avatarClassName: 'bg-amber-500/10 dark:bg-amber-400/10', ), ); ``` `useNavigation` also takes `systemItems`, `bottomItems` and `profileMenuItems`. See [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md) for the themes. ### Theme setters and `useWindTheme` `MagicStarter.useWindTheme(windTheme)` derives the colours of every sub-theme from your Wind palette, and it lands them only on the fields you have not set yourself. So a `useLayoutTheme`, `useNavigationTheme` or other `use*Theme()` call made before it is kept field by field. A setter called after it assigns its whole struct: build that struct from the active theme with `copyWith` (below), or every field it omits, the derived colours included, goes back to its stock default. The rule is per field. A field counts as yours when its current value differs both from its sub-theme's default constructor value and from what the previous `useWindTheme` call derived for it. Your fields are kept; every other field takes the derived value. Two things follow from that: - A second `useWindTheme` with another palette re-skins what the first one derived, and still leaves your fields alone, including a field whose value a palette in between happened to derive too. - A field set to exactly its stock default, or to exactly what the previous `useWindTheme()` derived for it, reads as unset, and the next `useWindTheme()` replaces it; to keep such a value, set a different one, or set it again after `useWindTheme()` with `copyWith`. `useTheme(MagicStarterTheme(...))` is not a merge: it replaces every sub-theme whole. Each setter assigns its whole struct, so `MagicStarterLayoutTheme(navigationBreakpoint: 'sm')` puts every other layout field back on its default, including the sidebar, header and background colours `useWindTheme` derived. A one-field override is `current.copyWith(...)`, which every sub-theme has: ```dart MagicStarter.useLayoutTheme( MagicStarter.layoutTheme.copyWith(navigationBreakpoint: 'sm'), ); MagicStarter.useNavigationTheme( MagicStarter.navigationTheme.copyWith( focusItemClassName: 'focus:ring-2 focus:ring-primary', ), ); ``` `useWindTheme` also derives the drawer and content area backgrounds (`drawerBackground*` and `contentBackground*`) from the `bg-surface` role the sidebar and header use. Those fields are `wColor` keys rather than classNames, so each half of the role (`bg-ink-50`, `dark:bg-[#0E0F11]`) becomes a colour name, or a hex, and a shade; where the role names two backgrounds for one brightness, the last one is read, as Wind paints it. A half that does not resolve, an opacity step or a colour the Wind theme does not carry, keeps the stock key. A colour and its shade count as one field: set either and the pair is yours. ### Where the sidebar starts, and where it grows labels Three fields on `MagicStarterLayoutTheme` decide the shell's shape. The first two are breakpoints, named as keys of the Wind theme's `screens` map (`sm`, `md`, `lg`, `xl`, `2xl` by default) rather than as pixel counts; the third is a width in logical pixels: | Field | Default | What it decides | |:------|:--------|:----------------| | `navigationBreakpoint` | `'lg'` | The breakpoint from which the sidebar replaces the drawer and the bottom bar | | `sidebarExpandedBreakpoint` | `'lg'` | The breakpoint from which the sidebar carries labels beside its icons | | `sidebarCompactWidth` | `80` | The width of the sidebar while it is compact | Between the two breakpoints the sidebar renders compact: icons only, with every text label dropped (the app name, the item labels, the system section's name, and the user's name and email, which falls back to the avatar trigger the mobile header mounts). What a host supplies itself, `brandBuilder` and `sidebarFooterBuilder`, is not reshaped, since only the host knows whether its own widget fits an icon column. A host whose wordmark does not fit sets `MagicStarterNavigationTheme.compactBrandBuilder` to a glyph, and the compact rail shows that instead. A name the Wind theme does not carry throws a `StateError` naming the field and listing the valid keys, because `wScreenIs` answers false for an unknown key and a typo would otherwise pin the shell to its narrow form with nothing to read. The defaults leave the two breakpoints equal, so the compact form never fires until a host lowers one of them: ```dart // An icon rail from 640 px, labels from 1024 px. MagicStarter.useLayoutTheme( const MagicStarterLayoutTheme( navigationBreakpoint: 'sm', sidebarExpandedBreakpoint: 'lg', ), ); ``` Keep `sidebarCompactWidth` at 80 or more: the compact team selector (`mx-3 p-2` around a `w-8` avatar) plus the sidebar's `border-r` overflows a narrower rail. ### Letting the viewer collapse the sidebar | Field | Default | What it decides | |:------|:--------|:----------------| | `sidebarCollapsible` | `false` | Whether a toggle above the user menu collapses the labelled sidebar to its compact form and back | | `sidebarCollapsedByDefault` | `false` | Whether a collapsible sidebar starts compact before the viewer has chosen | The toggle appears only at or above `sidebarExpandedBreakpoint`; below it the sidebar is compact because the window cannot spare `sidebarWidth`. `sidebarCollapsedByDefault` is ignored unless the sidebar is collapsible. The viewer's choice is remembered through Magic's `Cache` under `magic_starter.sidebar_collapsed`, written with a ten year TTL because the cache has no `forever` and its own default would hand the viewer the default back the next morning. A host that binds no cache keeps the choice in memory for the life of the shell, and a remembered choice wins over `sidebarCollapsedByDefault`. The toggle reads `nav.collapse_sidebar` and `nav.expand_sidebar`, both in the install stub; a host with its own language files adds them. ```dart // Icons only until the viewer asks for labels, with a glyph for the rail. MagicStarter.useLayoutTheme( const MagicStarterLayoutTheme( sidebarCollapsible: true, sidebarCollapsedByDefault: true, ), ); MagicStarter.useNavigationTheme( MagicStarterNavigationTheme( brandBuilder: (context) => const MyLogoLockup(), compactBrandBuilder: (context) => const MyLogoGlyph(), ), ); ``` ### A focus ring for a keyboard or a remote `MagicStarterNavigationTheme.focusItemClassName` is applied to every navigation item the shell draws (sidebar, drawer and bottom bar). Each token carries the `focus:` prefix; Wind lights them when the item's `WAnchor` holds primary focus. It defaults to `''`, which is no ring, and an app driven by arrow keys or a television remote wants it set: ```dart MagicStarter.useNavigationTheme( const MagicStarterNavigationTheme( focusItemClassName: 'focus:ring-2 focus:ring-primary focus:ring-offset-2', ), ); ``` ### Names for a screen reader Every control the shell draws has a name in the semantics tree, which is what a screen reader announces and what a semantics-driven test tool finds a control by. A labelled sidebar row, a drawer row and a bottom bar item are named by their label. The compact rail drops the label it draws, so its items carry that label as their name all the same, with a badge's count sentence after it. A sidebar item scrolled out of view stays in the tree, named and flagged hidden, and the list offers the scroll actions that bring it in. The icon-only controls read their names from the catalogue: `nav.open_menu` for the phone header's menu button, `nav.close_menu` for the drawer's close button, `nav.notifications` for the bell (the bell in the sidebar takes the same name), `nav.account_menu` for the avatar that opens the account menu (on the phone header and on the compact rail), and `nav.team_menu` for the compact rail's team switcher, which carries the current team's name as its value. The install stub ships the five keys; an app installed before them gets the English names (`Open menu`, `Close menu`, `Notifications`, `Account menu`, `Team menu`) rather than the raw keys until it adds them to its own language files. What a host supplies names itself: a `triggerBuilder` handed to `MSUserProfileDropdown`, a `brandBuilder`, a `sidebarFooterBuilder` and a `sidebar.team_selector` view. ### A live count on a destination A `MagicStarterNavItem` takes a `badgeCount`, a `ValueListenable`. The shell listens to it, so the host moves the number by updating the notifier and never rebuilds the navigation config: ```dart // Owned by whatever loads the number: a controller, a repository, a stream. final ValueNotifier unticked = ValueNotifier(null); MagicStarter.useNavigation( mainItems: [ MagicStarterNavItem( icon: Icons.shopping_cart_outlined, labelKey: 'nav.shopping', path: '/shopping', badgeCount: unticked, badgeLabelKey: 'nav.shopping_open', ), ], ); unticked.value = 4; // the badge reads 4 unticked.value = 0; // and is gone ``` The badge is hidden while the value is `null` or not above zero, and reads `99+` above 99. The sidebar and the drawer draw it at the trailing edge of the row, the compact rail and the bottom bar on the corner of the icon; the profile menu ignores it. On the compact rail the pill overhangs the icon by 16 px, so a `sidebarCompactWidth` under 52 would cut it. A badge is not colour alone. A screen reader gets a sentence in place of the number, added to the item's own label: `badgeLabelKey` names a catalogue line with both plural forms and a `:count` placeholder, read with the real count even above 99. It defaults to `nav.badge_count`, which the install stub ships (`"One item|:count items"`); name your own key when the number counts something specific: ```json { "nav": { "shopping_open": "One line to buy|:count lines to buy" } } ``` An item holding a notifier is not `const`, so the list that carries it is `final`. Recolour the badge through the navigation theme, with a `dark:` peer on every colour (a semantic alias such as `bg-primary` already carries one): ```dart MagicStarter.useNavigationTheme( const MagicStarterNavigationTheme( badgeClassName: 'bg-primary text-on-primary', ), ); ``` ### The box the route child is handed The shell wraps the route child in one `WDiv`, and two fields on `MagicStarterLayoutTheme` own it: | Field | Default | What it decides | |:------|:--------|:----------------| | `contentClassName` | `'flex-1 min-h-0'` | The content area's own className | | `contentScrollPrimary` | `false` | Whether that area attaches to the ambient `PrimaryScrollController` | The default is a box of bounded height that does not scroll, so each routed page scrolls itself. Every view this package ships already does, through `MSPageScaffold` (which brings its own `SingleChildScrollView(primary: false)`) or, for the invitation card, its own scroll view. A page of your own that is taller than the window needs its own vertical scroll: put it through `MSPageScaffold`, or wrap it: ```dart MagicRoute.page( '/reports', // `primary: false`, as MSPageScaffold does: the page owns its controller. () => const SingleChildScrollView(primary: false, child: ReportsView()), ); ``` > [!WARNING] > Setting `contentClassName` to `'flex-1 overflow-y-auto'` with `contentScrollPrimary: true` makes the shell scroll, and it has a cost. In a go_router shell the route child is the nested Navigator, so a scrolling content box scrolls the Navigator and lays its Overlay out under an unbounded height. A page left under a `.stacked()` route is then never laid out again, and its second rebuild while hidden fails `_debugRelayoutBoundaryAlreadyMarkedNeedsLayout` in debug. The same setting also gives a fill-shaped screen (an `h-full` column that scrolls inside itself) an unbounded height, which it cannot lay out. See [flutter/flutter#193247](https://github.com/flutter/flutter/issues/193247). Set the two fields together: Wind reads `scrollPrimary` only where it builds a scroll view, so beside a non-scrolling className it is inert. Two `primary: true` scrollables in one tree contend for the single controller. ### Hiding the bottom nav on a page Wrap the page, not the route group, in `MagicStarterHideBottomNav`: ```dart MagicRoute.page( '/chat/:id', () => MagicStarterHideBottomNav(child: ChatView()), ).stacked(); ``` The phone's bottom bar collapses in step with that page's transition and returns as it leaves, an iOS back swipe included. The page stays in the same shell as the rest of the app, so nothing is rebuilt on the way in. A page registers once magic's route middleware has mounted it, so the bar starts collapsing a frame or two into the transition. A host layout that draws its own bottom nav joins in with `MagicStarterBottomNavScope` at the layout's root and its nav inside `MagicStarterBottomNavSlot`: ```dart class MyAppShell extends StatelessWidget { const MyAppShell({super.key, required this.child}); final Widget child; @override Widget build(BuildContext context) { return MagicStarterBottomNavScope( child: Column( children: [ Expanded(child: child), MagicStarterBottomNavSlot(child: MyBottomNav()), ], ), ); } } ``` The slot's height is the nav's times how much of it is showing, so the content above grows into the room the bar gives up. Read that fraction with `MagicStarterBottomNavScope.visibilityOf(context)` (`0` to `1`). Place the scope inside the layout, never around it: magic tells shells apart by the layout widget's runtime type. ### An immersive route `MagicStarterHideChrome` drops all of the chrome (sidebar, drawer, header and bottom bar, plus the safe-area inset), so a player, a viewfinder or a map paints the whole window: ```dart MagicRoute.group( layout: (child) => MagicStarterHideChrome( child: MagicStarter.view.makeLayout('layout.app', child: child), ), layoutId: 'app.immersive', routes: () { MagicRoute.page('/player', () => const PlayerView()); }, ); ``` The group needs an id of its own, and a separate id is a separate shell: entering the route builds this layout and leaving it builds the app shell again, so the layout's state (the sidebar's collapsed choice, notification polling, the auth listeners) is rebuilt on each crossing. That suits an immersive route. A page that only wants the bottom bar gone belongs in the app shell under `MagicStarterHideBottomNav`. ## GuestLayout `MagicStarterGuestLayout` is a minimal centred wrapper for authentication pages (login, register, forgot password, reset password). It constrains content to 480 px and provides scrolling. It is registered under `layout.guest`, uses `wColor()` for theme-aware backgrounds, and pads the content with `p-4 lg:p-8`. Guest routes use `RouteTransition.none`, so there is no animation between auth screens. ## Page Chrome The layout shell owns the sidebar, the header and the content box. What is left is page chrome: how wide the content column is, how far it sits from the edges, and where the title goes. `MSPageScaffold` and `MSPageContainer` own that, and every authenticated page goes through one of them. `MSPageScaffold` is the full treatment. Give it a title and a list of sections, and it renders the page surface, its own vertical scroll, the shared content geometry, an `MSPageHeader` and a `gap-6` column for the sections: ```dart MSPageScaffold( title: trans('teams.settings'), subtitle: trans('teams.settings_subtitle'), children: [ MSCard(title: 'General', child: generalForm), MSCard(title: 'Members', child: memberList), ], ) ``` A sub-page adds a back affordance, and a top-level page can put an action next to the title: ```dart MSPageScaffold( title: trans('profile.settings'), backLabel: trans('magic_starter.nav.settings'), backFallback: MagicStarterConfig.settingsHubRoute(), actions: [saveButton], children: [profileForm], ) ``` `MSPageContainer` is the geometry alone: width cap, edge margins, vertical rhythm and a horizontal safe-area guard. Reach for it when the page brings its own header or scrolls its own way, which is the usual shape in a host app: ```dart MSPageContainer( children: [ MSPageHeader(title: 'Monitors', actions: [newMonitorButton]), monitorTable, ], ) ``` Neither component decides the numbers. They read `MagicStarter.manager.pageContainerClassName`, which the host sets once (see [Page Geometry](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#page-geometry)), so a starter account page and a host domain page line up inside the same shell. See [Components](https://anilcancakir.com/magic/docs/starter/basics/components.md) for `MSCard`, `MSPageHeader` and the rest. > [!WARNING] > Do not open a page with its own `WDiv(className: 'p-4 lg:p-6 flex flex-col gap-6')`. It is how pages end up at different widths in the same app. A page that needs to tune one axis passes `className` to `MSPageContainer` instead. ## Wind UI System The views use Wind widgets and Tailwind-style `className` strings: `WDiv` for containers, `WText` for text, `WButton`, `WAnchor`, `WIcon`, `WFormInput`, `WPopover` and so on. For long class lists, use a triple-quoted string: ```dart WDiv( className: ''' rounded-2xl bg-surface border border-color-border shadow-sm p-6 ''', child: content, ) ``` Use Wind widgets in views, not `Container`, `Text` or `ElevatedButton`. `Icons.*` is the one Material reference, for icon data. ## Dark Mode Wind supports the `dark:` prefix. A raw colour token needs its `dark:` peer in the same `className`; a semantic alias such as `bg-primary`, `bg-surface` or `text-fg-muted` already carries one: ```dart WText('Hello', className: 'text-gray-900 dark:text-white') WText('Hello', className: 'text-fg-muted') ``` The profile dropdown toggles the theme with `context.windTheme.toggleTheme()`, and `context.windIsDark` reads the current mode. ## View Registry All views are registered by string key in `MagicStarterViewRegistry`. The host overrides a screen by registering under the same key; the key table is in the [Quick Reference](#quick-reference): ```dart // Override with a custom view. MagicStarter.view.register( 'auth.login', () => const MyCustomLoginView(), ); // Build a view by key. final widget = MagicStarter.view.make('auth.login'); // Inject content into a view that exposes a slot. MagicStarter.view.slot('settings.hub', 'footer', (context) => const MyAboutSection()); ``` `make(key)` throws a `StateError` when the key is not registered, so register views before routes reference them. The registry also answers `has(key)` and `clear()`, and `buildSlot()` is what a view calls to render a slot. Register slots before the view is built. ## Layout Registry Layouts follow the same pattern with a `child` parameter for wrapping content: ```dart // Override with a custom layout. MagicStarter.view.registerLayout( 'layout.app', (child) => MyCustomAppLayout(child: child), ); // Build a layout around content. final widget = MagicStarter.view.makeLayout( 'layout.guest', child: loginView, ); ``` `makeLayout` hands the builder a `child` already wrapped in a route-keyed `KeyedSubtree`, so a replaced layout keeps the remount behaviour the default layouts carry. To test a view in isolation, register a minimal layout: `MagicStarter.view.registerLayout('layout.guest', (child) => child);`. ## Overriding the App Shell Every account, profile, team and settings route renders through the `layout.app` key. The `MagicStarterManager` constructor registers `MagicStarterAppLayout` under it, so a fresh install already renders in a working shell. An app that already has its own navigation chrome does not want starter routes rendering inside a second, different shell on top of its own. Re-register `layout.app` with your own shell and every starter route renders inside it: ```dart MagicStarter.view.registerLayout( 'layout.app', (child) => MyAppShell(child: child), ); ``` Call this from your own `AppServiceProvider`'s `boot()`, alongside `MagicStarter.useNavigation()` or `MagicStarter.useHeader()`. `registerLayout()` always overwrites what is registered under the key, and the default is registered synchronously the first time the `magic_starter` singleton resolves, before your code runs, so your override wins whether you call it first or last in boot. Your own authenticated routes join the same shell. Magic merges route groups into one go_router `ShellRoute` only when they carry the same `layoutId`, so give your group `MagicStarterLayoutIds.app`: ```dart MagicRoute.group( layout: (child) => MagicStarter.view.makeLayout('layout.app', child: child), middleware: ['auth'], layoutId: MagicStarterLayoutIds.app, routes: () { MagicRoute.page('/', () => const DashboardView()); }, ); ``` A group with another id, or none, becomes a second shell, and every crossing between it and the starter's profile, team, notification or support pages rebuilds and re-animates the whole layout. `layout.app` is the only authenticated-shell key the starter resolves: override it in place, do not add a second key. ## Feature-Gated Rendering Use conditional spreads to show or hide UI based on feature flags at build time: ```dart WDiv( className: 'flex flex-col gap-4', children: [ _buildEmailField(), _buildPasswordField(), if (MagicStarterConfig.hasRegistrationFeatures()) WAnchor( onTap: () => MagicRoute.to('${MagicStarterConfig.authPrefix()}/register'), child: WText(trans('auth.register_link'), className: 'text-sm text-primary'), ), if (MagicStarterConfig.hasSocialLoginFeatures() && MagicStarter.socialAuth != null) ...[ const MSSocialDivider(), MagicStarterSocialButtons( socialAuth: MagicStarter.socialAuth!, onSelected: controller.doSocialSignIn, isLoading: controller.isLoading, busyProvider: controller.pendingSocialProvider, ), ], ], ) ``` Feature checks in views are read-only queries against the config. A view never toggles a feature; that is `starter:configure` or a config edit. ## Zero Business Logic A view contains no business logic: - No async work: `_submit()` calls a controller method and returns. - No state decisions: the controller decides what happens after a submit (navigation, error handling). - No HTTP calls: all API communication lives in controllers through `Http.post()`, `Http.get()` and the rest. - No direct navigation: controllers use the `NavigatesRoutes` mixin, and views never call `context.go()`. - Local UI state only: a password visibility toggle, a phone/email switch, a section spinner in a local `ValueNotifier`. ```dart // Correct: the view delegates to the controller. Future _submit() async { if (!form.validate()) return; await controller.doLogin( email: form.get('email'), password: form.get('password'), ); } // Wrong: the view makes the API call. Future _submit() async { final response = await Http.post('/auth/login', data: payload); } ``` ## Reusable Widgets These widgets take plain callbacks and no internal controller, so a host app uses them directly. All are exported from `package:magic_starter/magic_starter.dart`. The `MS` components (`MSCard`, `MSPageHeader`, `MSAvatar` and the rest) are covered in [Components](https://anilcancakir.com/magic/docs/starter/basics/components.md). `MagicStarterConfirmDialog` is a confirmation dialog with variant-driven styling, an alias of `MSConfirmDialog`. It returns `true` when confirmed and `false` when cancelled or dismissed, and shows a loading state while `onConfirm` runs: ```dart final confirmed = await MagicStarterConfirmDialog.show( context, title: trans('teams.remove_member_label'), description: trans('teams.confirm_remove_member'), confirmLabel: trans('teams.remove'), variant: ConfirmDialogVariant.danger, onConfirm: () async { await TeamService.removeMember(memberId); }, ); if (confirmed) _refreshMembers(); ``` `ConfirmDialogVariant` is `primary`, `danger` or `warning`; the button classNames come from `MagicStarter.manager.modalTheme`. `MagicStarterPasswordConfirmDialog` is a password gate. Its `onConfirm` returns `null` on success or an error string to show inline; the dialog stays open on an error and closes with `true` on success. Without an `onConfirm` it closes with `true` as soon as the user confirms. For a gate that picks the right proof for the account, use `confirmIdentity` (see [Confirming Identity](https://anilcancakir.com/magic/docs/starter/basics/identity-confirmation.md)). ```dart final confirmed = await MagicStarterPasswordConfirmDialog.show( context, title: trans('projects.delete_title'), onConfirm: (password) async { // Return null to confirm, or an error string on failure. return await ProjectService.delete(id, password: password); }, ); ``` `MagicStarterTwoFactorModal` is the two-factor setup wizard: the QR code and a code input, then the recovery codes. It resolves `true` once `onConfirm` accepts a code: ```dart final enabled = await MagicStarterTwoFactorModal.show( context, setupData: { 'secret': 'JBSWY3DPEHPK3PXP', // shown for manual entry 'qr_svg': qrSvg, // raw SVG string 'recovery_codes': recoveryCodes, // list of strings }, onConfirm: (code) async { return await TwoFactorService.confirmSetup(code); }, ); ``` The other widgets a host can place: | Widget | What it is | |:-------|:-----------| | `MagicStarterAuthFormCard` | A centred card (480 px) for auth-adjacent screens such as an invitation or onboarding, with a title, a subtitle, an optional error banner and a theme toggle | | `MagicStarterTimezoneSelect` | A searchable timezone dropdown over `GET /timezones`; see [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md#timezone-and-language) | | `MSTeamSelector` | The current-team switcher; needs a registered team resolver (see [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md#msteamselector)) | | `MSUserProfileDropdown` | The avatar menu with user info, profile links, the theme toggle and logout; accepts a custom `triggerBuilder` | | `MSSocialDivider` | The "Or continue with" divider for auth forms | | `MagicStarterHideBottomNav`, `MagicStarterBottomNavScope`, `MagicStarterBottomNavSlot` | Collapse the phone's bottom navigation per page; see [Hiding the bottom nav on a page](#hiding-the-bottom-nav-on-a-page) | | `MagicStarterHideChrome` | Hides the whole shell chrome for an immersive route; see [An immersive route](#an-immersive-route) | | `MagicStarterLayoutIds` | The `layoutId` values of the starter's route groups; `MagicStarterLayoutIds.app` is the one a host's own group must share | The notification bell is not here: it moved to `magic_notifications` as `NotificationDropdown`; see [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md). ## Gotchas | Mistake | Fix | |:--------|:----| | Registering a layout under a new key for your shell | `layout.app` is the only authenticated-shell key the starter resolves. Re-register it. | | Giving your own authenticated group another `layoutId` | Use `MagicStarterLayoutIds.app`, or crossing into a starter page rebuilds the whole layout. | | A page taller than the window that does not scroll | The content box does not scroll by default. Use `MSPageScaffold` or wrap the page in a `SingleChildScrollView(primary: false)`. | | Calling `MagicStarter.view.make(key)` for a key nothing registered | It throws a `StateError`. `profile.settings` is not registered by default, and a key behind a feature flag exists only with the flag on. | | A breakpoint name the Wind theme does not carry in `MagicStarterLayoutTheme` | It throws a `StateError` listing the valid keys. Use `sm`, `md`, `lg`, `xl`, `2xl` or your own `screens` keys. | | Calling `useNavigationTheme()` or `useModalTheme()` after the first paint | Call them in `AppServiceProvider.boot()`, before the layout or a dialog first renders. | ## Related Documentation - [Components](https://anilcancakir.com/magic/docs/starter/basics/components.md): the `MS` design-system components. - [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md): the notification screens on `Notify.view`. - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): the settings hub and its sub-pages. - [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md): the team selector and team views. - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): the themes, locale options and page geometry. - [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md): how the registry is built. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature flags that decide which views register. --- # Design-System Components The `MS`-prefixed Wind components the starter's screens are built from, and the semantic token layer that skins them. - [Introduction](#introduction) - [Semantic Token Layer](#semantic-token-layer) - [MagicStarterTokens](#magicstartertokens) - [Wiring into WindThemeData](#wiring-into-windthemedata) - [Token Reference](#token-reference) - [Atomic Folder Shape](#atomic-folder-shape) - [Component Families](#component-families) - [Form Controls](#form-controls) - [Display and Feedback](#display-and-feedback) - [Selection and Navigation](#selection-and-navigation) - [Overlay](#overlay) - [Composition and App Chrome](#composition-and-app-chrome) - [Import Collisions](#import-collisions) - [design.md.stub](#designmdstub) - [Component Previews](#component-previews) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction Magic Starter ships an atomic design-system component library under `lib/src/ui/components/`. Each component is driven by a recipe that resolves colours through the `MagicStarterTokens` semantic alias layer, so a single brand configuration flows into all built-in screens and every component your host app composes directly. The components are exported from `package:magic_starter/magic_starter.dart`. The families below cover the form, display, navigation, overlay and layout components; the barrel also exports `MSAvatar`, `MSConfirmDialog`, the settings rows (`MSSettingsSection`, `MSSettingsRow`, `MSSettingsNavRow`), `MSUpdateBanner`, `MSUpgradeDialog`, `MSUpgradeNudge` and `MSUsageMeter`. ## Semantic Token Layer ### MagicStarterTokens `MagicStarterTokens` is a `final` class with a `const` map, `defaultAliases`, and two helpers. `defaultAliases` maps semantic class names to light and dark Wind className pairs. Each key is the full class it replaces (`bg-surface`, `text-fg`, `border-color-border`), not a bare role name, because Wind expands an alias only when a whole token matches a key: ```dart final aliases = MagicStarterTokens.defaultAliases; // { // 'bg-surface': 'bg-white dark:bg-gray-950', // 'text-fg': 'text-gray-900 dark:text-gray-50', // 'bg-primary': 'bg-primary-600 dark:bg-primary-500', // 'border-color-border': 'border-gray-200 dark:border-gray-700', // 'bg-destructive': 'bg-red-600 dark:bg-red-500', // ... // } ``` | Helper | Returns | |:-------|:--------| | `MagicStarterTokens.role(theme, token)` | The token itself when the theme defines it (an alias key, or a backing colour in `WindThemeData.colors`); otherwise the default alias or a fallback pair, so a partly configured theme never renders an invisible surface. | | `MagicStarterTokens.readableOn(context, fill:, role:)` | The on-colour class for a fill: the host's own role when it defines one, otherwise `text-white` or `text-gray-950`, whichever has the better contrast against the fill in the current brightness. | ### Wiring into WindThemeData Pass `MagicStarterTokens.defaultAliases` as the `aliases` argument of the `WindThemeData` you give `MagicApplication`, and hand the same theme to `MagicStarter.useWindTheme` so the navigation, modal, form, card, page header, layout, auth and dropdown themes are derived from it: ```dart final windTheme = WindThemeData( colors: {'primary': myBrandColor}, aliases: MagicStarterTokens.defaultAliases, ); MagicApplication( title: 'Acme', windTheme: windTheme, ); // In AppServiceProvider.boot(): MagicStarter.useWindTheme(windTheme); ``` Components that reference a semantic class (`bg-surface`, `text-fg`, `bg-primary`) resolve through this map at render time. Without the aliases wired in, those class names are silently skipped by Wind, so your brand colour and surface tokens do not apply. `useWindTheme` keeps the button and field themes you set, on either side of it; `useTheme` resets them, so call `MagicStarter.useButtonTheme` and `useFieldTheme` after that. ### Token Reference | Alias key | Semantic meaning | Maps to (default) | |:----------|:-----------------|:------------------| | `bg-surface` | Page/card background | `bg-white dark:bg-gray-950` | | `bg-surface-container` | Subtle recessed area | `bg-gray-50 dark:bg-gray-900` | | `bg-surface-container-high` | Elevated container | `bg-gray-100 dark:bg-gray-800` | | `text-fg` | Primary text | `text-gray-900 dark:text-gray-50` | | `text-fg-muted` | Secondary/supporting text | `text-gray-500 dark:text-gray-400` | | `text-fg-disabled` | Disabled state text | `text-gray-300 dark:text-gray-600` | | `bg-primary` | Brand primary fill | `bg-primary-600 dark:bg-primary-500` | | `text-on-primary` | Text on primary fill | `text-white dark:text-white` | | `bg-primary-container` | Tinted primary area | `bg-primary-100 dark:bg-primary-900` | | `bg-accent` | Secondary brand fill | `bg-indigo-600 dark:bg-indigo-500` | | `border-color-border` | Standard border colour | `border-gray-200 dark:border-gray-700` | | `border-color-border-subtle` | Faint separator colour | `border-gray-100 dark:border-gray-800` | | `bg-destructive` | Danger / delete fill | `bg-red-600 dark:bg-red-500` | | `text-on-destructive` | Text on danger fill | `text-white dark:text-white` | | `bg-destructive-container` | Tinted danger area | `bg-red-100 dark:bg-red-900` | | `bg-success` | Positive / confirmed | `bg-green-600 dark:bg-green-500` | | `bg-warning` | Caution / review | `bg-amber-600 dark:bg-amber-500` | | `bg-ai-soft` | Soft container for AI-authored content (replies, summaries) | `bg-violet-100 dark:bg-violet-900` | | `text-ai-soft-foreground` | Text or icon on top of `bg-ai-soft` | `text-violet-700 dark:text-violet-200` | | `border-ai` | Accent edge of AI-authored content | `border-violet-500 dark:border-violet-400` | | `bg-warning-soft` | Soft amber container for a quiet status pill | `bg-amber-100 dark:bg-amber-900` | | `text-warning-soft-foreground` | Text or icon on top of `bg-warning-soft` | `text-amber-800 dark:text-amber-200` | | `bg-success-soft` | Soft green container for a quiet status pill | `bg-green-100 dark:bg-green-900` | | `text-success-soft-foreground` | Text or icon on top of `bg-success-soft` | `text-green-800 dark:text-green-200` | `text-destructive`, `text-primary`, `text-on-success` and `text-on-warning` are not alias keys: `MagicStarterTokens.role` answers them with a fallback pair when the host theme does not define them. The support screens use the AI pair and `border-ai` for the assistant's avatar, its bubble (a 2px left edge) and its chip, and the soft warning and success pairs for the "Team answering" and "Resolved" pills. A host theme that defines the same keys supplies its own map and wins. To override individual roles, spread `defaultAliases` and replace specific keys: ```dart WindThemeData( aliases: { ...MagicStarterTokens.defaultAliases, 'bg-primary': 'bg-indigo-600 dark:bg-indigo-500', 'text-on-primary': 'text-white dark:text-white', }, ) ``` ## Atomic Folder Shape Every component lives in a 4-file atomic folder: ``` lib/src/ui/components// .dart # The widget class (StatelessWidget or StatefulWidget) .recipe.dart # Recipe: resolves className from theme tokens .preview.dart # Standalone preview widget for interactive inspection index.dart # Barrel: re-exports the public API for this component ``` The `.recipe.dart` file holds the recipe: a top-level `WindRecipe` or slot recipe (`badgeRecipe`, `textareaRecipe`), or a function that builds a recipe or a slot-to-className map from a theme or state (`buildButtonRecipe`, `buildInputRecipe`, `buildCardRecipe`, `selectRecipe`). The widget delegates its className derivation to the recipe, so the visual contract is inspectable and testable in isolation. ## Component Families ### Form Controls | Component | Enums / Helpers | Notes | |-----------|----------------|-------| | `MSButton` | `ButtonIntent` (primary/secondary/ghost/destructive), `ButtonSize` (sm/md/lg), `buildButtonRecipe` | Use `ButtonIntent.destructive` for delete / danger actions; `fullWidth: true` fills the parent width (wraps in `SizedBox`, defaults `false`). Shape, the three sizes and the secondary border come from `MagicStarterButtonTheme` (`MagicStarter.useButtonTheme`). Below `lg`, every size keeps its painted size but takes a 44x44 hit area | | `MSInput` | `InputState` (normal/error), `buildInputRecipe` | Pairs with `MSFormField` for label + error display; `fullWidth: true` fills the parent width (defaults `false`). A single-line field is 44px tall below `lg` and 40px from `lg` up (`py-3 lg:py-2.5` over a `leading-5` line); the padding and type of the text, placeholder and value come from `MagicStarterFieldTheme.inputSizeClassName` (`MagicStarter.useFieldTheme`) | | `MSTextarea` | `TextareaState` (normal/error), `textareaRecipe` | Multi-line input, same state model as `MSInput`; `fullWidth: true` fills the parent width (defaults `false`). On iOS a focused field carries a Done toolbar above the keyboard, since a multiline field's Return key inserts a newline and would otherwise leave the keyboard with no way out. One consequence for consumer TESTS: while that toolbar is up it schedules a frame callback every frame, so `pumpAndSettle` under `debugDefaultTargetPlatformOverride = TargetPlatform.iOS` never settles; pump explicitly instead | | `MSCheckbox` | | Boolean toggle; Wind-only, no Material dependency | | `MSSwitch` | | Toggle that wraps `WSwitch` with semantic colours. An optional `label` renders beside the track and is part of the tap target; below `lg` the hit area is at least 44 px tall. Shows a focus ring on keyboard focus | | `MSRadio` | | Single-select option | | `MSSelect` | `selectRecipe` | Dropdown single-select backed by an item list; the trigger is the same height as `MSInput` (44px below `lg`, 40px from `lg` up), and its padding, minimum height and type come from `MagicStarterFieldTheme.selectSizeClassName` | | `MSCombobox` | `comboboxRecipe` | Searchable single-select with filter input; the trigger is the same height as `MSInput` (44px below `lg`, 40px from `lg` up) and shares `MagicStarterFieldTheme.selectSizeClassName` with `MSSelect`. The search field's placeholder defaults to `trans('common.search_placeholder')` | | `MSSwitchRow` | `switchRowRecipe` | An `MSSwitch` with its `label` beside it; the label doubles as the switch's accessibility name | | `MSKeyValueEditor` | `MSKeyValueRow`, `keyValueEditorRecipe` | Controlled editor for an ordered list of key/value pairs (e.g. HTTP headers); every mutation emits a fresh list | | `MSStringValueList` | `StringValueListTone`, `stringValueListRecipe` | Controlled editor for a short list of distinct strings rendered as chips; commits on Enter/IME-done, trims and de-duplicates | ### Display and Feedback | Component | Enums / Helpers | Notes | |-----------|----------------|-------| | `MSBadge` | `BadgeTone` (neutral/primary/accent/success/warning/destructive/outline) | Inline label chip | | `MSTypography` | `TypographyVariant` (h1/h2/h3/body/caption) | Semantic text wrapper | | `MSSkeleton` | `SkeletonShape` (block/text/circle) | Placeholder loading block | | `MSToast` | `ToastVariant` (info/success/warning/error) | Transient feedback banner (the message is `text-sm font-medium`; `messageClassName` is appended after it, so `text-[15px] leading-5 font-normal` sets another body type, with or without an action); presents nothing itself, so the host shows it (through its own `OverlayEntry`) and decides how long it stays. `Magic.toast(String)` cannot carry an action and its overlay ignores pointers, so an action needs the host's own overlay. `actionLabel` and `onAction` (both or neither) add a trailing text action such as Undo: a cell at least 44 px tall and wide at every width (it grows with the label at a large text size), named by `actionLabel` for assistive technology, with a ring inside the toast on keyboard focus. A long message wraps beside it and the action keeps its size; a one line toast is as tall with an action as without | | `MSTooltip` | | Hover/long-press hint bubble | | `MSEmptyState` | | Centred placeholder with optional icon, title, description and action | | `MSErrorState` | | Same slots as `MSEmptyState` with a destructive tone; the retry is whatever `action` widget you pass | | `MSDataTable` | `MSDataColumn`, `dataTable*ClassName` | Header plus rows, with the columns passed in. Two modes: the default renders `rows` eagerly (right for a short, complete list); `MSDataTable.paginated` hands the body to magic's `MagicPaginatedListView` inside a bounded box, so a long collection costs the viewport rather than the result and reaching the tail asks the paginator for its next page. The header stays outside the scrolling body. `bodyHeight` is what bounds it, since a `ListView` needs a bound and `shrinkWrap: true` would build every row anyway. Column labels and `loadingLabel` are ALREADY TRANSLATED strings, not keys: half the callers render a label that is not a key at all (a currency code, a region name) | ### Selection and Navigation | Component | Enums / Helpers | Notes | |-----------|----------------|-------| | `MSSegmentedControl` | `SegmentedControlSize`, `segmentedControlRecipe` | Inline tab switcher; below `lg` each segment is at least 44 px tall to tap, the painted pill unchanged. The pill's padding and type per size and the root's padding come from `MagicStarterFieldTheme` (`segmentedSmClassName`, `segmentedMdClassName`, `segmentedPaddingClassName`); the hit cell is not themed. In a horizontal scroller (the `overflow-x-auto` root override, or your own scroll view that holds nothing but the control) it scrolls the selected segment into view on mount and when `selectedIndex` changes; a page view, a vertical list or a strip with padding or other content around the control is left alone, and the page's vertical scroll never moves | | `MSTabs` | `tabsRecipe` | Full tab bar with content panels | | `MSAccordion` | `MSAccordionItem`, `accordionRecipe` | Collapsible section list | | `MSNavbar` | | Horizontal top navigation bar | | `MSDropdownMenu` | `MSDropdownMenuItem` | Contextual action menu | ### Overlay | Component | Notes | |-----------|-------| | `MSDialog` | Modal dialog shell; reads `MagicStarterModalTheme` tokens. `scrollable: false` hands a body that scrolls itself the bounded height, as on `MSBottomSheet`. With the modal theme's `presentation: MagicStarterModalPresentation.sheet`, `MSDialog.show` opens the same content as a bottom sheet, and the widget draws the sheet panel inside a bottom sheet route | | `MSBottomSheet` | Slide-up sheet; reads `MagicStarterModalTheme` tokens. `MSBottomSheet.show(..., dialogBreakpoint: 'lg')` presents an `MSDialog` from that Wind breakpoint up, with the same title, description, body, footer and `scrollable`, so one call serves a phone and a desktop; the width is read when the call is made. Null (the default) always presents a sheet, and so does the `sheet` presentation, which ignores the breakpoint; the `adaptive` presentation ignores it too and swaps at `MagicStarterModalTheme.dialogBreakpoint` for every call. Built in a dialog route (an overlay route under `adaptive`), the widget draws the dialog shell. `canDismiss` (a `ValueListenable`, read at the gesture) holds a sheet with unsaved input open: while false a drag down is off (the handle stays drawn), and a scrim tap or its semantics dismiss, Back and Escape leave it open and call `onDismissBlocked(sheetContext)`, where the app asks the person and, on a confirmed discard, closes it with `Navigator.of(sheetContext).pop()` (a `pop` skips the guard; the opener's context would pop the wrong navigator, since the sheet sits on the root one); the dialog from `dialogBreakpoint` is held the same way | ### Composition and App Chrome | Component | Notes | |-----------|-------| | `MSFormField` | Label + input + hint + error layout wrapper | | `MSCard` | Surface/inset/elevated variants | | `MSPageHeader` | Full-width responsive header (title, subtitle, leading, actions). Stacked below `sm`, a row above it; `inlineActions` (or `MagicStarterPageHeaderTheme.inlineActions`) makes it a row at every width AND lets a long title shrink instead of overflowing. `size` picks `MSPageHeaderSize.regular`, `.large` (the theme's `largeTitleClassName`, display size on a phone and one step smaller from `lg`) or `.compact` (a 44 pt bar below the top safe area: leading control, centred one-line title, actions, over a translucent fill and a backdrop blur that turn opaque under high contrast). Null follows `MagicStarterPageHeaderTheme.largeTitle`. `className` is appended to the container after the theme's container class, for a page under a bar of its own (`pt-0` or `lg:pt-0` takes the header's top padding off); it styles the regular and the large header, and the compact bar ignores it. Under `MagicStarter.useHostPageChrome`, where the predicate answers true, it draws only its actions and reports its title, subtitle and back control to `MagicStarter.pageChrome` ([host-owned page chrome](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#host-page-chrome)) | | `MSSocialDivider` | "Or continue with" separator for auth forms | | `MSUserProfileDropdown` | Avatar menu with profile links, theme toggle and logout | | `MSTeamSelector` | Current-team switcher; requires a registered team resolver | | `MSPageContainer` | Shared page geometry: width cap, edge margins, vertical rhythm, horizontal safe area. Reads `MagicStarter.manager.pageContainerClassName` | | `MSPageScaffold` | Full page treatment: page surface + own scroll + `MSPageContainer` + `MSPageHeader` + `gap-6` sections column. `footer` docks a widget below the scroll area, outside it, in the same width and edge margins; it clears the bottom safe area and rides above the on-screen keyboard (a chat composer is the use). A docked layout needs a bounded height, as the app shell provides. `scrollController` hands the scroll area to the page, to keep a thread on its newest message. `containerClassName` is appended to the page container after the host's geometry, for a page under a bar of its own (`pt-4` replaces the host's top padding). `headerClassName` is handed to the regular and the large header the same way (`lg:pt-0` takes the header's own top padding off from `lg` up); the compact bar is built without it. `largeTitle: true` (or `MagicStarterPageHeaderTheme.largeTitle`, which also reaches the starter's own pages) renders a large header that collapses into the compact bar pinned over the page once it has scrolled under it, fading in 200 ms (a swap under Reduce Motion). Under host-owned page chrome it builds neither the large title nor the bar | | `MSMasterDetail` | A list and its selected item side by side from `breakpoint` (`lg` by default): `master` in a fixed `w-96` column, `detail` (or `placeholder` while it is null) in the rest. Below the breakpoint it renders `detail ?? master`, which is push navigation when the selection lives in the route. Owns no page geometry or scroll, so it goes inside `MSPageScaffold`; `MSMasterDetail.isSplit(context)` gives a page the same answer for its header | | `MSFormActions` | Cancel/submit footer row for a form; `cancelLabel`/`onCancel` are optional (omitting both renders no cancel button) | | `MSHeaderAction` | Page-header action that collapses to an icon-only glyph below `lg` and a labelled `MSButton` at `lg` and up; `label` becomes the icon form's accessibility label | > [!NOTE] > The bell-icon dropdown is not in this table. It moved to `magic_notifications` as `NotificationDropdown`; see [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md). ## Import Collisions Every component class carries an `MS` prefix (`MSButton`, `MSDialog`, `MSSwitch`, ...), so the barrel's component exports do not collide with `package:material_ui/material_ui.dart` (`Switch`, `Dialog`, ...). Import both without a `hide` clause: ```dart import 'package:material_ui/material_ui.dart'; import 'package:magic_starter/magic_starter.dart'; // No ambiguity: MSSwitch is the component, Switch is Material's. ``` ## design.md.stub `assets/stubs/design.md.stub` is a `DESIGN.md` template covering the colour roles, typography, rounded and spacing scales, and key component entries, with `{{ placeholder }}` tokens for the app name, brand colours and font family. Copy it from the package source into your project root as `DESIGN.md` (a hosted dependency sits in the pub cache; `.dart_tool/package_config.json` lists its `rootUri`), fill in the brand hex values and fonts, then run the core commands: ```bash # Validate your DESIGN.md against the schema dart run magic:dowel design:lint # Generate the Wind theme from your DESIGN.md dart run magic:dowel design:sync ``` `design:sync` writes a Dart file (`lib/config/wind_theme.g.dart` by default, `--output` changes it) with an alias map for `WindThemeData(aliases: ...)` and a brand `primary` colour ramp. Pass that map where this page passes `MagicStarterTokens.defaultAliases`. See [Magic CLI](https://anilcancakir.com/magic/docs/packages/magic-cli) for the command reference. ## Component Previews `package:magic_starter/previews.dart` is a dev-only library, kept out of the runtime barrel. `starterComponentPreviews()` returns one `StarterComponentPreview` record per component: a `label`, a URL-safe `slug` (the component folder name) and a `WidgetBuilder` that renders the component's variants. Feed it to your own preview catalog behind a release guard, so a release build that never reaches the call tree-shakes every preview: ```dart import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; import 'package:magic_starter/previews.dart'; List catalogPreviews() { if (kReleaseMode) return const []; return starterComponentPreviews(); } Widget buildPreview(BuildContext context, String slug) { final StarterComponentPreview preview = catalogPreviews().firstWhere( (StarterComponentPreview entry) => entry.slug == slug, ); return preview.builder(context); } ``` `buildPreview` here throws a `StateError` when `slug` matches no entry. In a release build `catalogPreviews()` is empty, so every call throws; the release guard (a route, a menu entry or a flag that a release build never reaches) is what keeps release builds away from this call. ## Gotchas | Mistake | Fix | |:--------|:----| | Adding a bare role such as `primary` to your `aliases` | Alias keys are full classes (`bg-primary`, `text-fg`, `border-color-border`); Wind expands only a whole token that matches a key. | | Leaving `aliases` out of the `WindThemeData` | The semantic classes are silently skipped and the components lose their colours. Pass `MagicStarterTokens.defaultAliases` or a `design:sync` map. | | Calling `useButtonTheme` or `useFieldTheme` before `useTheme` | `useTheme` resets both, so call them after it. `useWindTheme` keeps a field you set. | | Hardcoding `className: 'py-3 ...'` on an `MSButton` | A caller className is appended after the theme and wins, which breaks a host's button standard; set the shape and sizes through `MagicStarter.useButtonTheme`. | | Calling `Magic.toast()` to show an `MSToast` with an action | `Magic.toast(String)` carries no action and its overlay ignores pointers; show the `MSToast` through your own `OverlayEntry`. | | Putting `Icons.*` inline in a `build()` | Extract it to `static const _icon = Icons.xxx`; Flutter web cannot tree-shake an inline icon. | ## Related Documentation - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the screens these components compose into. - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): the sub-themes (`useTheme`, `useButtonTheme`, `useFieldTheme`) and the page container. - [Wind Theme Adoption](https://anilcancakir.com/magic/docs/starter/guides/wind-theme-adoption.md): moving a host's palette onto the semantic aliases. - [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md): the bell dropdown that lives in `magic_notifications`. --- # CLI Commands The `starter:*` commands that scaffold, configure, diagnose, publish and remove the starter inside a Magic application, run through `dart run magic:dowel`. - [Introduction](#introduction) - [Quick Reference](#quick-reference) - [Install Command](#install-command) - [What It Creates](#what-it-creates) - [What It Injects](#what-it-injects) - [Flags](#install-flags) - [Configure Command](#configure-command) - [Show Current Config](#show-current-config) - [Toggle Features](#toggle-features) - [Non-Interactive Mode](#non-interactive-mode) - [Doctor Command](#doctor-command) - [Health Checks](#health-checks) - [Verbose Mode](#verbose-mode) - [Publish Command](#publish-command) - [Publish Tags](#publish-tags) - [Uninstall Command](#uninstall-command) - [Stub Templates](#stub-templates) - [Testing CLI Commands](#testing-cli-commands) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Introduction The package has no executable of its own. `MagicStarterDowelProvider` contributes its commands to the host app's `dowel` registry, so they run as `dart run magic:dowel starter:`. `dart run magic:dowel plugin:install magic_starter` registers the provider and, unless you pass `--no-bootstrap`, chains `starter:install` as the plugin's bootstrap command. The chain always forwards `--non-interactive`, so it writes every feature as `false` and a later `starter:install --features=...` skips the config file that exists by then: pass `--no-bootstrap` and run `starter:install` yourself (see [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md#installing-the-package)). Each command extends `DowelCommand` (install extends `DowelInstallCommand`), declares a `signature` DSL string for its arguments and flags, and implements `handle(DowelContext ctx)`. Every command resolves the host project root through `FileHelper.findProjectRoot()`. ## Quick Reference | Command | Purpose | |:--------|:--------| | `starter:install` | Scaffolds config, middleware, models, dashboard and routes, and injects the registrations into existing host files. | | `starter:configure` | Turns feature flags on in `lib/config/magic_starter.dart`; `--show` prints the current state. | | `starter:doctor` | Checks the installation; also exposed as the read-only MCP tool `starter_doctor`. | | `starter:publish` | Copies views, layouts, middleware, config or translations into the host for customisation. | | `starter:uninstall` | Removes the files and injections `starter:install` made. | ## Install Command ```bash dart run magic:dowel starter:install ``` The installer validates the host project, asks which features to enable (one yes/no prompt per feature key, unless `--features` or `--non-interactive` is passed), generates files from stubs and injects registrations into existing files. It throws when `lib/config/app.dart` is missing, which means the host has not been scaffolded: run `dart run magic:dowel magic:install` first. ### What It Creates Each file is written only when it does not exist yet, or when `--force` is passed: | File | Purpose | |:-----|:--------| | `lib/config/magic_starter.dart` | Feature toggle configuration with the selected features enabled | | `lib/app/middleware/ensure_authenticated.dart` | Auth guard middleware | | `lib/app/middleware/redirect_if_authenticated.dart` | Guest redirect middleware | | `lib/app/models/user.dart` | User model | | `lib/app/models/team.dart` | Team model (only when `teams` is enabled) | | `lib/resources/views/dashboard_view.dart` | Dashboard view scaffold | | `lib/routes/app.dart` | App routes file with the dashboard inside the authenticated layout | | `lib/app/providers/app_service_provider.dart` | Created from a stub; an existing file is injected into instead, unless `--force` replaces it | | `assets/lang/en.json` | Translation strings, deep-merged into an existing file | ### What It Injects Beyond creating files, the installer modifies existing host files. Each injection checks for its own marker first, so a re-run adds nothing twice: - **`lib/config/app.dart`**: adds `MagicStarterServiceProvider` to the providers list (the `install.yaml` manifest step). - **`lib/main.dart`**: adds the `magicStarterConfig` factory to the config factories, a `WindThemeData` with a `primary` palette passed to `MagicApplication`, and the `config/magic_starter.dart` and `material_ui` imports. - **`lib/app/kernel.dart`**: registers the `auth` (`EnsureAuthenticated`) and `guest` (`RedirectIfAuthenticated`) middleware aliases. - **`lib/app/providers/route_service_provider.dart`**: adds `registerMagicStarterAuthRoutes()` and `registerMagicStarterProfileRoutes()`, plus the team, notification and support route registrations when those features are enabled. - **`lib/app/providers/app_service_provider.dart`**: injects `MagicStarter.bootstrap(...)` (and `MagicStarter.useNavigation(...)`) into `boot()` unless the provider already configures the starter. - **`pubspec.yaml`**: lists `assets/lang/en.json` under `flutter: assets:`, and adds `magic_notifications` when `notifications` is enabled. ```dart // Injected into lib/config/app.dart (app) => MagicStarterServiceProvider(app), // Injected into lib/main.dart () => magicStarterConfig, ``` ### Flags | Flag | Description | |:-----|:------------| | `--force` | Overwrite existing generated files and replace `app_service_provider.dart` instead of injecting into it | | `--dry-run` | Stages the transactional writes (config, middleware, models, dashboard, routes, provider registration) without writing them. The in-place edits of `main.dart`, `kernel.dart`, the route provider, `AppServiceProvider`, the translations and `pubspec.yaml` still run. | | `--non-interactive` | Skip the prompts; every feature stays off unless `--features` names it | | `--no-bootstrap` | Inherited from `DowelInstallCommand`; read by `plugin:install`, which is what chains this command | | `--features` | Comma-separated feature keys; passing it implies `--non-interactive` | ```bash # Interactive installation (prompts for each feature) dart run magic:dowel starter:install # Non-interactive with specific features dart run magic:dowel starter:install --features=teams,notifications,registration # Force overwrite existing files dart run magic:dowel starter:install --force ``` > [!TIP] > With `notifications` enabled the installer does not run the `magic_notifications` installer. It adds the dependency to `pubspec.yaml` and prints `dart run magic:dowel notifications:install --app-id=`, because OneSignal needs an app id only you have. ## Configure Command ```bash dart run magic:dowel starter:configure ``` Updates individual feature flags in `lib/config/magic_starter.dart` without modifying any other file. It exits with an error when that file does not exist. With no flag it prints a warning and changes nothing. ### Show Current Config ```bash dart run magic:dowel starter:configure --show ``` Prints every feature key found in the config file with its status: ``` Current Magic Starter Feature Configuration: Feature Status ------------- -------- teams enabled social_login disabled ... ``` ### Toggle Features ```bash # Enable teams and notifications dart run magic:dowel starter:configure --teams --notifications ``` | CLI Flag | Config Key | |:---------|:-----------| | `--teams` | `teams` | | `--social-login` | `social_login` | | `--two-factor` | `two_factor` | | `--sessions` | `sessions` | | `--phone-otp` | `phone_otp` | | `--newsletter` | `newsletter` | | `--notifications` | `notifications` | | `--email-verification` | `email_verification` | > [!NOTE] > Only flags you pass are touched; the rest stay as they are. The command rewrites the Dart source with a regular expression through `MagicStarterConfigHelper.updateFeature()`. Features without a flag here (registration, billing, support and the rest) are edited in the config file by hand. Each flag is negatable: `--teams` turns the feature on and `--no-teams` turns it off, for example `dart run magic:dowel starter:configure --no-teams`. Flipping a toggle edits the config file and nothing else. A feature that needs scaffolding (teams needs the `Team` model, the `User` team accessors, the `bootstrap()` team callbacks and `registerMagicStarterTeamRoutes()`) gets it only from `starter:install`. ### Non-Interactive Mode The configure command never prompts: it works entirely through flags. That makes it safe for CI pipelines and scripts. ## Doctor Command ```bash dart run magic:dowel starter:doctor ``` Runs independent checks that the starter was installed correctly. It exits with code 0 when every required check passes and code 1 otherwise. The same report is available to agents as the MCP tool `starter_doctor`, which takes an optional `verbose` boolean. ### Health Checks | Check | What It Verifies | |:------|:-----------------| | Magic Framework | `lib/config/app.dart` exists | | Starter Config | `lib/config/magic_starter.dart` exists | | Provider | `MagicStarterServiceProvider` appears in `lib/config/app.dart` | | Config Factory | `magicStarterConfig` appears in `lib/main.dart` | | Middleware | `EnsureAuthenticated` appears in `lib/app/kernel.dart` | | Routes | `registerMagicStarterAuthRoutes` appears in `route_service_provider.dart` | | Facade | `app_service_provider.dart` calls `MagicStarter.bootstrap(` or one of the legacy `useUserModel`, `useLocaleOptions`, `useLogout` setters | | Translations | `assets/lang/en.json` exists | | Billing web origin | Reported and required only when `billing` is enabled: `billing.web_origin` must be set to a non-empty value | Three more lines appear only when relevant and never fail the command: a `Support routes: WARN` line when `support` is enabled but `registerMagicStarterSupportRoutes()` is not called, a `Push external id prefix` line when `notifications` is enabled (the prefix must equal the backend's `onesignal.external_id_prefix`), and a `Published Views` list that marks a published view `WARN` when `AppServiceProvider` does not register it. ``` Magic Framework: OK Starter Config: OK Provider: OK Config Factory: OK Middleware: OK Routes: OK Facade: FAIL Translations: OK Missing Requirements: FAIL MagicStarter facade not configured in app_service_provider.dart 1 check(s) failed. Run `dart run magic:dowel starter:install` to fix. ``` ### Verbose Mode ```bash dart run magic:dowel starter:doctor --verbose ``` Shows the file inspected for each check and the string searched for: ``` Provider: OK File: lib/config/app.dart Contains: MagicStarterServiceProvider ``` ## Publish Command ```bash dart run magic:dowel starter:publish ``` Copies plugin source files into the host application for customisation, the starter's equivalent of Laravel's `vendor:publish`. Without `--tag` it publishes every group. When views or layouts are published, the command registers them in `AppServiceProvider` (`MagicStarter.view.register(...)` and `registerLayout(...)`) so the registry serves your copy. A published view or layout compiles where it lands. Its relative imports are rewritten as it is copied: one that the package barrel covers becomes `import 'package:magic_starter/magic_starter.dart';`, and any other keeps its target through a `package:magic_starter/src/...` URI. A view or layout that has a registry key needs only the barrel; the support screens' helper widgets, published by the unscoped `views` tag, still reach into `src/`, which a host on `flutter_lints` sees as `implementation_imports`. Config, middleware and translations are copied unchanged. The registration imports your copy under a prefix, because `AppServiceProvider` also imports the barrel and the barrel exports the original under the same class name: ```dart import '../../resources/views/starter/auth/magic_starter_login_view.dart' as published; MagicStarter.view.register('auth.login', () => const published.MagicStarterLoginView()); ``` ### Publish Tags ```bash # Publish everything dart run magic:dowel starter:publish # Publish only views dart run magic:dowel starter:publish --tag=views # One module, one view, one layout dart run magic:dowel starter:publish --tag=views:auth dart run magic:dowel starter:publish --tag=views:auth.login dart run magic:dowel starter:publish --tag=layouts:app # Overwrite existing files dart run magic:dowel starter:publish --force ``` | Tag | What It Publishes | |:----|:------------------| | `config` | `lib/config/magic_starter.dart`, copied from the package's template, which writes every feature `false` (`starter:install` writes the features you chose `true`). It matters when the host has no config yet; an existing file is skipped, and `--force` replaces it with this template, which turns every feature off | | `views` | View files to `lib/resources/views/starter/` | | `layouts` | `app` and `guest` layouts to `lib/resources/layouts/starter/` | | `middleware` | Auth middleware files to `lib/app/middleware/` | | `lang` | Translation file to `assets/lang/en.json` | | `all` (default) | All of the above | A `views:` scope is either one registry key (`auth.login`) or a module prefix (`auth`) taken from the command's view map; an unknown scope prints an error. Views with no entry in that map, such as the handoff page, are published only by the unscoped `views` tag. > [!NOTE] > Without `--force`, existing files are skipped with a warning. The command reports the number of published files at the end. > [!NOTE] > A published file is a snapshot of the release that published it. A later release that changes a view or a layout does not reach your copy: read the CHANGELOG entry for the edits it names, or re-publish with `--force` and re-apply your own changes. ## Uninstall Command ```bash dart run magic:dowel starter:uninstall ``` Performs a reverse of the install command. It removes generated files and cleans up injected lines from host config files while keeping user code intact. It lists what it will remove and asks for confirmation first. What it removes: - `lib/config/magic_starter.dart` - The `magic_starter` dependency from `pubspec.yaml` - The `MagicStarterServiceProvider` import and registration from `lib/config/app.dart` - The `magicStarterConfig` import and factory from `lib/main.dart` - The middleware aliases and imports from `lib/app/kernel.dart` - The route imports and registrations from `route_service_provider.dart` ```bash # Skip the confirmation prompt dart run magic:dowel starter:uninstall --force ``` Each removal step is wrapped in error handling, so already-clean projects and partial installations do not crash the command. Afterwards `dart format .` runs automatically. > [!TIP] > The uninstall command does not remove your `AppServiceProvider` integrations, the middleware files or the translation entries. It lists them as manual cleanup once it finishes. ## Stub Templates Generated files are built from stub templates in the `assets/stubs/install/` directory: | Stub | Output | |:-----|:-------| | `magic_starter_config.stub` | `lib/config/magic_starter.dart` | | `ensure_authenticated.stub` | `lib/app/middleware/ensure_authenticated.dart` | | `redirect_if_authenticated.stub` | `lib/app/middleware/redirect_if_authenticated.dart` | | `user.stub` | `lib/app/models/user.dart` | | `team.stub` | `lib/app/models/team.dart` | | `app_service_provider.stub` | `lib/app/providers/app_service_provider.dart` | | `dashboard_view.stub` | `lib/resources/views/dashboard_view.dart` | | `app_routes.stub` | `lib/routes/app.dart` | | `en.stub` | `assets/lang/en.json` | Stub paths are resolved relative to the plugin package at runtime. The installer searches two locations through `getStubSearchPaths()`: the plugin's `assets/stubs` found through `.dart_tool/package_config.json`, then `assets/stubs` under the current directory. > [!NOTE] > Stubs are plain Dart and JSON files with placeholder tokens that the installer replaces based on the selected features. Never hardcode absolute stub paths; resolve them through the package config. ## Testing CLI Commands Commands expose overridable methods so a test can isolate them from the real filesystem: ```dart class TestableInstallCommand extends MagicStarterInstallCommand { final String _testRoot; TestableInstallCommand(this._testRoot); @override String getProjectRoot() => _testRoot; @override List getStubSearchPaths() => [ '$_testRoot/stubs', ]; @override Future runDartFormat(String rootPath) async { return ProcessResult(0, 0, '', ''); // No-op in tests } } ``` | Method | Commands | Purpose | |:-------|:---------|:--------| | `getProjectRoot()` | All | Redirect to a temp directory | | `getStubSearchPaths()` | Install | Point to test stub fixtures | | `resolveManifestPath()` | Install | Point to a test `install.yaml` | | `runDartFormat()` | Install, Uninstall | Skip formatting in tests | | `getPluginSourceDir()` | Publish | Point to a test plugin source | > [!TIP] > The doctor command's check methods (`checkConfigExists()`, `checkProviderRegistered()` and the rest) take a root path, so they are testable without subclassing. ## Gotchas | Mistake | Fix | |:--------|:----| | Running `dart run magic_starter install` | The package has no executable. Every command is `dart run magic:dowel starter:`. | | Running `starter:configure --teams` on a host installed without teams | It only flips `'teams': true` in the config; the `Team` model, the `User` team accessors, the `bootstrap()` team callbacks and the team routes are not written, so the app throws on startup. Commit your changes, then re-run `dart run magic:dowel starter:install --features=teams --force`, adding every other feature you want on, since the config is rewritten from that list. `--force` also replaces `AppServiceProvider` and overwrites the translation file. | | Expecting `starter:configure` to toggle every feature | Only the flags in the table have one. `registration`, `billing`, `support` and the others are edited in the config file. | | Running `starter:install` before the host is scaffolded | It throws when `lib/config/app.dart` is missing. Run `dart run magic:dowel magic:install` first. | | Expecting `--features` to leave the prompts on | Passing `--features` skips them, and every key it does not name is written as `false`. | | Expecting `starter:uninstall` to remove everything | `AppServiceProvider` integrations, middleware files and translation entries stay; it prints them as manual cleanup. | ## Related Documentation - [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md): adding the package and registering the plugin. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature keys the config file carries. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): overriding a screen without publishing it. - [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md): what `MagicStarterServiceProvider` registers. --- # Releases The opt-in `releases` and `app_update` features: a "What's new" page, a build caption and an update banner, all read from the backend's `GET releases` and from the web bundle's `version.json`. - [Basic Usage](#basic-usage) - [The Releases Feed](#the-releases-feed) - [The Changelog Page](#the-changelog-page) - [The Version Caption](#the-version-caption) - [The Update Banner](#the-update-banner) - [Web](#web) - [iOS and Android](#ios-and-android) - [Translations](#translations) - [Gotchas](#gotchas) - [Related Documentation](#related-documentation) ## Basic Usage `releases` adds a "What's new" page, a row for it on the settings hub and a version caption. `app_update` adds a banner that offers the newest build without interrupting the customer. Turn either on, or both, in `lib/config/magic_starter.dart`: ```dart 'features': { 'releases': true, 'app_update': true, }, ``` Both default to `false`. `registerMagicStarterProfileRoutes()` registers the changelog route like every other settings page, so a host that already calls it adds nothing else. Both features read one guest-readable endpoint of `magic-starter-laravel`, `GET releases`. The backend has to enable its `releases` feature (`Features::releases()` in `config/magic-starter.php`) as well: with it off the endpoint answers 404, the changelog page shows its error state and the store banner stays quiet. The client reads no flag from the backend, so the two sides are switched on separately. The web banner does not use the endpoint; it reads `version.json` (see [Web](#web)). ## The Releases Feed The client reads one body, newest release first, capped on the backend by `magic-starter.releases.limit` (default 50): ```json { "data": [ { "version": "1.1.0", "published_at": "2026-10-20T09:00:00.000000Z", "ios_build": 15, "android_build": 15, "items": [ { "type": "new", "text": { "en": "Dark mode", "tr": "Koyu tema" } } ] } ], "meta": { "latest_build": { "ios": 15, "android": 15 } } } ``` An item's `type` is `new`, `improved` or `fixed`; an item with any other type is skipped, so an older app keeps working when the backend learns a new one. The page shows the reader's own language, then `magic_starter.defaults.locale`, then the first entry that is not empty. `published_at`, `ios_build`, `android_build` and both `latest_build` values may be `null`, and `meta` may be missing. `MagicStarterReleasesController` reads it. `readFeed()` is the stateless read the banner uses and answers `null` on any failure (logged as a warning); `fetchReleases()` loads the feed into the controller state for the page. ## The Changelog Page With `releases` on, the settings hub gets a "What's new" row in its Preferences group, and the page opens at `MagicStarterConfig.settingsChangelogRoute()` (`/settings/changelog`, which follows `profile_prefix`). It is pushed (`.stacked()`), so the back gesture returns to the hub. Each release is a card with its version, its date and one line per change, tagged with a New, Improved or Fixed badge. A failed read shows an error state with "Try again", and a feed with no releases shows an empty state. The view key is `settings.changelog`. Replace the page the usual way: ```dart MagicStarter.view.register('settings.changelog', () => const MyChangelogView()); ``` ## The Version Caption `MagicStarterAppVersion` is a one-line caption naming the build the app runs. The settings hub and the changelog page show it when `releases` is on; on the hub it closes the page, below anything a host registers in the hub's `footer` slot. A host that wants it elsewhere places the widget itself: ```dart const MagicStarterAppVersion() ``` The text is the `magic_starter.releases.version_caption` line (`Version :version`), where the version reads `1.0.0 (14)` on iOS and Android, with `14` as the build number, and `1.0.0 · ` on the web. It shows only the version when the build number is empty. Pass `className` to replace the default style (`text-xs text-fg-muted text-center`). The widget renders nothing while the read is pending and when the platform cannot answer. The support conversation's client info reads the same package info, so the caption and the report agree. ## The Update Banner `MagicStarterAppUpdateBanner` is a non-modal strip with a message, one action and "Later". The shipped app layout mounts it when `app_update` is on. A host with its own layout places it by hand, near the top of the content: ```dart const MagicStarterAppUpdateBanner() ``` It checks once after mounting and again whenever the app resumes, at most once per 15 minutes (`MagicStarterAppUpdateBanner.checkInterval`). It never reloads by itself and never opens a dialog. "Later" remembers the offered build in the `Vault` under `magic_starter.app_update.dismissed_build`, so the banner stays hidden for that build and returns only for a newer one. If the write fails, the banner is still hidden for the rest of the session. A check that cannot read a build (no network, a refusal, an unreadable store) logs a warning and leaves the banner as it was. Desktop, debug and profile builds, and an app with `app_update` off, render nothing and start no timer. ## Web On the web the banner compares the build the page is running with the `build_number` in the `version.json` the server serves now. The package fetches that file from the page's own origin, next to `index.html`, not through the `Http` facade (so it carries no base url and no bearer token), with a cache buster and `no-store`. It polls every 15 minutes and on resume, which a browser reports when the tab comes back to the front. A difference is not shown at once. The banner waits 60 seconds from the moment it first sees the new build (`MagicStarterAppUpdateBanner.revealDelay`), so a deploy that is still rolling out does not flash it at every customer. The action is "Reload", which reloads the page. The check needs a build number on both sides, so it stays quiet when `version.json` is missing or carries no `build_number`. Two deploys with the same build number look identical to it. Flutter writes the number it was built with into `version.json`, so give each deploy its own: ```bash flutter build web --release --build-number="$GITHUB_SHA" ``` The running build is read once, at boot (when `app_update` or `releases` is on), and kept for the life of the page: a later first read could already see the next deploy and report it as the one that is loaded. Serving the new bundle after "Reload" is up to your server and CDN; the package configures nothing there. ## iOS and Android On a phone the banner compares the installed build number with `meta.latest_build` from the feed (`ios` or `android`) and shows at once when the store build is higher. It checks on mount and on resume, at most once per 15 minutes; there is no periodic timer. It only looks at release builds installed from the store: the App Store (installer `com.apple`) and Google Play (`com.android.vending`). TestFlight, the simulator, a debug build and a sideload stay quiet for the rest of the session, since a store build would not replace them. "Update" opens the store page: | Platform | Opens | |:---------|:------| | iOS | `https://apps.apple.com/app/id` | | Android | `https://play.google.com/store/apps/details?id=` | iOS needs the App Store id, the same one the store review feature reads (the `store_review` feature itself can stay off): ```dart 'store_review': { 'app_store_id': '1234567890', }, ``` Without it the iOS banner stays hidden and logs a warning. The banner also stays quiet until the backend publishes a release with a build number for the platform; a build that is not a plain number, on either side, is never counted as newer. ## Translations The copy lives under `magic_starter.releases.*`, `magic_starter.app_update.*` and `magic_starter.titles.changelog`. `starter:publish --tag=lang` skips an `assets/lang/en.json` that already exists unless you pass `--force`, so an existing app merges the new keys by hand from `assets/stubs/install/en.stub`. A missing key shows as the key itself. ## Gotchas | Mistake | Fix | |:--------|:----| | Enabling `releases` on the client only | The backend answers 404 until its own `releases` feature is on, and the page shows its error state. | | Expecting the web banner to read the backend | It compares the bundle's build number with `version.json`; only the store banner reads `GET releases`. | | Building every web deploy with the same build number | The banner cannot tell them apart. Pass a distinct `--build-number`. | | Expecting the iOS banner without an App Store id | Set `magic_starter.store_review.app_store_id`; without it the banner stays hidden and logs a warning. | | Testing the store banner from a debug build, TestFlight or a sideload | Only a release build installed from the App Store or Google Play checks. | | Using the banner in a custom layout | The shipped layout mounts it; a host layout places `MagicStarterAppUpdateBanner` itself. | ## Related Documentation - [Profile](https://anilcancakir.com/magic/docs/starter/basics/profile.md): the settings hub that carries the What's new row. - [Support](https://anilcancakir.com/magic/docs/starter/basics/support.md): the conversation client info that shares the build caption. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the view registry and the app shell that mounts the banner. - [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md): the feature flags and the `store_review` keys. --- # MagicStarterManager `MagicStarterManager` is the singleton behind the `MagicStarter` facade: it holds the host's user model, team resolver, navigation, callbacks, sub-themes and the view registry. - [Introduction](#introduction) - [Singleton Pattern](#singleton-pattern) - [Unbound Fallback and Testing](#unbound-fallback-and-testing) - [User Model Registration](#user-model-registration) - [Team Resolver](#team-resolver) - [Navigation Configuration](#navigation-configuration) - [Navigation Theme](#navigation-theme) - [Modal Theme](#modal-theme) - [Sidebar Footer Builder](#sidebar-footer-builder) - [Header Builder](#header-builder) - [Logout Callback](#logout-callback) - [Login Callback](#login-callback) - [Guest Claim Callback](#guest-claim-callback) - [Locale Application](#locale-application) - [Unified Theme](#unified-theme) - [Form Theme](#form-theme) - [Auth Theme](#auth-theme) - [Card Theme](#card-theme) - [Page Header Theme](#page-header-theme) - [Host-owned page chrome](#host-page-chrome) - [Layout Theme](#layout-theme) - [Page Geometry](#page-geometry) - [View Registry Integration](#view-registry-integration) - [Default Views](#default-views) - [MagicStarter Facade](#magicstarter-facade) - [Related Documentation](#related-documentation) ## Introduction The manager is the configuration hub where host apps register custom user models, team resolvers, navigation items, header builders, logout callbacks and view overrides. What a notification type looks like is not one of its seams: that lives on `magic_notifications`'s own `NotificationViewRegistry` (see [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md)). The manager lives at `lib/src/magic_starter_manager.dart`. `MagicStarterServiceProvider` binds it as a container singleton in its register phase. ## Singleton Pattern The manager is bound into the Magic IoC container under the key `'magic_starter'` by the service provider: ```dart app.singleton('magic_starter', () => MagicStarterManager()); ``` All access goes through the `MagicStarter` facade, which resolves the singleton from the container: ```dart static MagicStarterManager get manager { if (Magic.bound('magic_starter')) { return Magic.make('magic_starter'); } // Falls back to a shared default manager instead of throwing. return _fallbackManager ??= MagicStarterManager(); } ``` > [!NOTE] > The constructor calls `registerDefaultViews()`, so the default views and layouts are available as soon as the manager is built. ## Unbound Fallback and Testing Every accessor on the `MagicStarter` facade delegates through `manager`, so any code that reads a theme (for example `MSCard` through `MagicStarter.cardTheme`) would fail when rendered without `MagicStarterServiceProvider` bound, in a standalone widget test or a preview catalogue entry. `MagicStarter.manager` checks `Magic.bound('magic_starter')` first. When unbound it falls back to a shared, lazily created default `MagicStarterManager()`, whose sub-themes all hold `const` defaults, instead of throwing. The fallback also prints a one-time `kDebugMode` warning (`MagicStarterManager not bound; using defaults. Call MagicStarter... to configure.`), so a forgot-to-bind bug in a real app still surfaces during development. A manager bound in the container always wins over the fallback. For tests that need a specific manager configuration (custom theme, team resolver, etc.), bind one explicitly with `setUpMagicStarterForTests()`: ```dart import 'package:magic_starter/magic_starter.dart'; setUp(() { MagicApp.reset(); Magic.flush(); setUpMagicStarterForTests(); // binds a default MagicStarterManager() }); ``` Pass a pre-configured instance to bind it instead: ```dart setUpMagicStarterForTests( manager: MagicStarterManager() ..cardTheme = const MagicStarterCardTheme(surfaceClassName: 'bg-white'), ); ``` `setUpMagicStarterForTests()` is `Magic.singleton('magic_starter', () => manager ?? MagicStarterManager())` in one call. A test that only relies on default theme values can skip binding altogether and use the fallback. In a test that exercises the fallback itself, call `MagicStarter.resetFallbackManagerForTests()` in `setUp`, because `Magic.flush()` does not clear it. ## User Model Registration By default the manager creates `MagicStarterAuthUser` instances from API data. Host apps override this to use their own `Authenticatable` subclass: ```dart MagicStarter.useUserModel((data) => User.fromMap(data)); ``` Internally the manager stores a `UserModelFactory`, a function that takes `Map` and returns `Authenticatable`: ```dart UserModelFactory userFactory = (data) => MagicStarterAuthUser.fromMap(data); ``` The factory is invoked via `MagicStarter.createUser(data)` whenever the plugin needs to hydrate a user model from an API response. > [!TIP] > Register your user model factory in your `AppServiceProvider.boot()`, so all auth flows use the correct model from the start. `MagicStarter.bootstrap()` takes it as a required argument; see [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md#bootstrapping-the-starter). ## Team Resolver The team resolver bridges the plugin's team UI with app-specific team models through three callbacks: ```dart MagicStarter.useTeamResolver( currentTeam: () => User.current.currentTeam?.toMagicStarterTeam(), allTeams: () => User.current.allTeams .map((t) => t.toMagicStarterTeam()) .toList(), onSwitch: (id) => MagicStarter.switchTeam('$id'), ); ``` The callbacks are wrapped in `MagicStarterTeamResolverConfig`: | Callback | Signature | Purpose | |:---------|:----------|:--------| | `currentTeam` | `MagicStarterTeam? Function()` | Returns the active team (null if none) | | `allTeams` | `List Function()` | Returns all teams the user belongs to | | `onSwitch` | `Future Function(dynamic teamId)` | Handles team switching logic | > [!NOTE] > If the `magic_starter.features.teams` config flag is enabled but no team resolver is configured, the service provider logs a warning at boot time, `manager.isReady` returns `false` and `MagicStarter.bootstrap()` throws a `StateError`. `MagicStarter.switchTeam(teamId)` asks the backend to switch and answers whether it accepted; on success it re-identifies the store rail as the paying subject, so a purchase after the switch is not attributed to the team that was left. A refused switch changes nothing. A failure of that re-identification is logged and does not turn the answer into `false`, because the switch already happened. `MagicStarter.currentTeamId()` answers the active team's id as a string, or `null` without a resolver or an active team. ## Navigation Configuration Host apps register navigation items for the authenticated app layout (sidebar, bottom bar and profile dropdown): ```dart MagicStarter.useNavigation( mainItems: [ MagicStarterNavItem( icon: Icons.dashboard, labelKey: 'nav.dashboard', path: '/', ), ], systemItems: [ MagicStarterNavItem( icon: Icons.people_outline, labelKey: 'nav.members', path: '/teams/members', ), ], bottomItems: [ MagicStarterNavItem( icon: Icons.dashboard_outlined, labelKey: 'nav.dashboard', path: '/', ), ], profileMenuItems: [ MagicStarterNavItem( icon: Icons.notifications_outlined, labelKey: 'nav.notifications', path: '/notifications', ), ], ); ``` The items are stored in `MagicStarterNavigationConfig`: | Property | Required | Description | |:---------|:---------|:------------| | `mainItems` | Yes | Primary sidebar/drawer items (Dashboard, Monitors, etc.) | | `systemItems` | No | Secondary items below the main group (Settings, Members) | | `bottomItems` | No | Mobile bottom navigation bar items (subset of main) | | `profileMenuItems` | No | Extra links in the profile dropdown, between "Profile Settings" and logout | Each `MagicStarterNavItem` takes `icon`, `labelKey` and `path`, plus these optional fields: | Property | Default | Description | |:---------|:--------|:------------| | `activeIcon` | `icon` | Icon drawn on the bottom bar while the item is active | | `badgeCount` | `null` | A `ValueListenable` drawn as a count badge on the item; see [A live count on a destination](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md#a-live-count-on-a-destination) | | `badgeLabelKey` | `'nav.badge_count'` | Translation key of the sentence a screen reader gets for the badge | ## Navigation Theme `MagicStarterNavigationTheme` overrides the default `text-primary` tokens used for active nav items, the brand/logo, bottom navigation and user avatar colours, without requiring any view override. ```dart MagicStarter.useNavigationTheme( MagicStarterNavigationTheme( activeItemClassName: 'active:text-amber-500 active:bg-amber-500/10 dark:active:text-amber-400 dark:active:bg-amber-400/10', brandClassName: 'text-lg font-bold text-amber-500 dark:text-amber-400', brandBuilder: (context) => Image.asset('assets/logo.png', height: 28), bottomNavActiveClassName: 'active:text-amber-500 dark:active:text-amber-400', avatarClassName: 'bg-amber-500/10 dark:bg-amber-400/10', avatarTextClassName: 'text-sm font-bold text-amber-600 dark:text-amber-400', dropdownAvatarClassName: 'bg-gradient-to-tr from-amber-500 to-amber-300', dropdownAvatarTextClassName: 'text-sm font-bold text-white', ), ); ``` All fields are optional; an omitted field keeps its default. | Field | Default | Controls | |:------|:--------|:--------| | `activeItemClassName` | `active:text-primary active:bg-primary/10 dark:active:bg-primary/10` | Sidebar/drawer active nav item | | `hoverItemClassName` | `hover:bg-gray-100 dark:hover:bg-gray-800` | Sidebar/drawer hover state | | `brandClassName` | `text-lg font-bold text-primary` | Brand/logo text style (supports gradient tokens) | | `brandBuilder` | `null` | Custom brand widget builder (image, SVG, etc.); overrides `brandClassName` when set | | `compactBrandBuilder` | `null` | Brand builder for the compact, icon-only sidebar; falls back to `brandBuilder` when unset | | `bottomNavActiveClassName` | `active:text-primary` | Bottom nav active icon and label | | `avatarClassName` | `bg-primary/10 dark:bg-primary/10` | Sidebar user menu avatar background | | `avatarTextClassName` | `text-sm font-bold text-primary` | Sidebar user menu avatar initial and placeholder glyph colour | | `dropdownAvatarClassName` | `bg-gradient-to-tr from-primary to-gray-200` | Profile dropdown trigger avatar gradient | | `dropdownAvatarTextClassName` | `text-sm font-bold text-white` | Profile dropdown trigger avatar initial and placeholder glyph colour | Both avatars draw the account's photo when `profile_photo_url` carries one, the first letter of the account's name when it does not, and a person glyph when there is no name to take a letter from: before the session is known, or for an account that never set one. The theme is stored on `MagicStarterManager` as `navigationTheme` and reset to defaults by `manager.reset()`. The active theme is read at widget build time, so `useNavigationTheme()` can be called at any point before the layout is first painted. > [!NOTE] > When `brandBuilder` is set, `brandClassName` is ignored. The builder receives the current `BuildContext` and should return any widget: `Image.asset`, `SvgPicture.asset`, a styled `WText`, etc. ## Modal Theme `MagicStarterModalTheme` overrides the default tokens used for every modal dialog: confirmation dialogs, password prompts and two-factor modals. Works the same way as `NavigationTheme`: register once, all modals pick up the tokens at build time. ```dart MagicStarter.useModalTheme( MagicStarterModalTheme( containerClassName: 'rounded-2xl bg-white dark:bg-gray-900', titleClassName: 'text-lg font-semibold text-gray-900 dark:text-white', descriptionClassName: 'text-sm text-gray-500 dark:text-gray-400', primaryButtonClassName: 'bg-primary hover:bg-primary/90 text-white', dangerButtonClassName: 'bg-red-600 hover:bg-red-700 text-white', warningButtonClassName: 'bg-amber-500 hover:bg-amber-600 text-white', inputClassName: 'rounded-lg border border-gray-300 dark:border-gray-600', maxWidth: 480, ), ); ``` All fields are optional; an omitted field keeps its default. | Field | Default | Controls | |:------|:--------|:--------| | `containerClassName` | Default dialog container | Outer dialog container background, border-radius, border | | `headerClassName` | Default header | Dialog header section (sticky top) | | `bodyClassName` | Default body | Scrollable body section | | `footerClassName` | Default footer | Dialog footer section (sticky bottom) | | `titleClassName` | Default title | Dialog title text style | | `descriptionClassName` | Default description | Dialog description/subtitle text style | | `primaryButtonClassName` | Default primary | Primary action button (confirm, save) | | `secondaryButtonClassName` | Default secondary | Secondary action button (cancel, dismiss) | | `dangerButtonClassName` | Default danger | Danger action button (delete, destroy) | | `warningButtonClassName` | Default warning | Warning action button | | `errorClassName` | Default error | Inline error message text style | | `inputClassName` | Default input | Text input fields inside dialogs | | `maxWidth` | `448.0` | Maximum dialog width in logical pixels (a dialog only) | | `presentation` | `MagicStarterModalPresentation.dialog` | Whether the starter's modals open as a dialog, as a bottom sheet, or as a sheet below `dialogBreakpoint` and a dialog from it (`adaptive`) | | `dialogBreakpoint` | `'lg'` | The `wind_kit` breakpoint `adaptive` swaps to a dialog from; read by `adaptive` only | | `headlessBodyClassName` | `'pt-6'` | Top padding of the body of an `MSBottomSheet` drawn as a dialog with no title and no description (an overlay route under `adaptive`), where the sheet had its drag handle | ### Presentation `presentation: MagicStarterModalPresentation.adaptive` opens every modal the starter opens, and every `MSBottomSheet.show`, as a bottom sheet below `dialogBreakpoint` and as a centred `MSDialog` (at most `maxWidth`) from it: a phone gets the sheet, a desktop window the dialog, from one setting. The screen width is read when a modal opens, so one that is already open keeps its form through a resize; `MSBottomSheet.show(dialogBreakpoint:)` is ignored, and a breakpoint the Wind theme does not carry throws a `StateError` naming `MagicStarterModalTheme.dialogBreakpoint`. Overlay routes (`RouteDefinition.overlay`) follow too: the provider installs a resolver on magic's router (`MagicRoute.useOverlayPresentation`), an `MSBottomSheet` built in a dialog route draws the dialog shell, and under `dialog` or `sheet` an overlay route stays the sheet it has always been. `presentation: MagicStarterModalPresentation.sheet` opens the starter's modals as the same bottom sheet `MSBottomSheet` draws, at every width (the plan upgrade prompt, which opens through magic's `MagicFeedback.showCustomDialog`, stays a dialog): `MSDialog.show`, `MSConfirmDialog.show` (and its `MagicStarterConfirmDialog` alias), `MagicStarterPasswordConfirmDialog.show`, `MagicStarterStepUpDialog.show` and `MagicStarterTwoFactorModal.show`. `MSBottomSheet.show(dialogBreakpoint:)` then ignores its breakpoint and stays a sheet. ```dart MagicStarter.useModalTheme( MagicStarter.modalTheme.copyWith( presentation: MagicStarterModalPresentation.sheet, ), ); ``` - Return values do not change: `true` or `false` from a confirm, the proof map or `null` from the step up. - A sheet is full width on a phone. On a wide screen Flutter's Material 3 default caps it at 640 px; `maxWidth` applies to the dialog only. - The setting is read when a modal opens. An `MSDialog` widget draws the sheet panel when it is built inside a bottom sheet route, and its dialog shell otherwise, so a dialog a host opens with its own `showDialog` keeps the shell. - `useWindTheme()` keeps a modal field set before it, `presentation` included. After it, set the field with `MagicStarter.modalTheme.copyWith(...)`, since a fresh `MagicStarterModalTheme` puts the derived colours it omits back on their defaults. `useTheme()` resets the modal theme, so set it after that. The theme is stored on `MagicStarterManager` as `modalTheme` and reset to defaults by `manager.reset()`. The active theme is read at widget build time, so `useModalTheme()` can be called at any point before a dialog is shown. > [!TIP] > Register your modal theme in `AppServiceProvider.boot()` alongside `useNavigationTheme()`. Both follow the same pattern: register once, and every widget reads the tokens at build time. ## Sidebar Footer Builder Add a custom widget between the navigation items and the user menu in both the desktop sidebar and mobile drawer: ```dart MagicStarter.useSidebarFooter((context) { return MyVersionBadge(); }); ``` The builder receives the current `BuildContext` and should return any widget: a version badge, environment indicator, support link, etc. When `sidebarFooterBuilder` is `null` (the default), no extra content is rendered between navigation and the user menu. ## Header Builder Replace the default app layout header with a custom widget: ```dart MagicStarter.useHeader((context, isDesktop) { return AppHeader(showMenuButton: !isDesktop); }); ``` The builder receives the current `BuildContext` and a `bool isDesktop` flag so the header can adapt between desktop sidebar and mobile drawer layouts. When `headerBuilder` is `null`, the app layout renders its built-in header with the team selector, the notification bell and the user profile dropdown. ## Logout Callback Override the default logout behaviour to add custom cleanup steps: ```dart MagicStarter.useLogout(() async { await Notify.logoutPush(); await SocialAuth.signOut(); await Auth.logout(); MagicRoute.to('/auth/login'); }); ``` When set, the profile dropdown's logout item calls this callback instead of `MagicStarterAuthController.instance.logout()`. This is useful for apps that need to unregister push tokens, sign out of social providers, or perform other cleanup before navigating to the login screen. Work that has to happen while the session token still works belongs in a before-logout hook, which runs ahead of both sign-out paths (the profile dropdown, ahead of a custom `onLogout`, and `MagicStarterAuthController.logout()`, ahead of `Auth.logout()`): ```dart MagicStarter.beforeLogout(() => SocialAuth.signOut()); ``` Hooks run in registration order, each isolated and bounded to five seconds (`MagicStarterManager.beforeLogoutTimeout`); one that throws or times out is logged and the next still runs, because a sign-out the user asked for has to happen whatever a hook's network does. The same hook is not added twice. `MagicStarterServiceProvider` registers its token-revoke hook in `boot()`, so a hook your own provider registers after that runs on a revoked token: list the provider whose hook needs the session token before `MagicStarterServiceProvider` in `providers`. A host with its own sign-out button calls `MagicStarter.manager.runBeforeLogoutHooks()` before its own `Auth.logout()`. A sign-out the app performs on its own, such as magic's `AuthInterceptor` after a failed token refresh, does not run them: the token is already dead. The provider registers two of its own, see [Before-Logout Hooks](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md#before-logout-hooks). ## Login Callback Run custom logic after a fresh sign-in: ```dart MagicStarter.useLogin(() async { await Analytics.identify(Auth.user()); }); ``` `MagicStarterServiceProvider` registers an internal listener on magic's `AuthLogin` event (dispatched at the end of `BaseGuard.startSession`) that calls this callback, unawaited, and logs rather than rethrows on failure. It fires for every fresh sign-in path this package ships (password, two-factor challenge, social, guest, and phone OTP) and deliberately **not** for a cold-boot restore of a stored session or a team switch: both go through `Auth.restore()`, which dispatches `AuthRestored`, and only once an API sync confirms the user (never offline, never on a failed sync, never without a `userEndpoint` configured); neither path ever dispatches `AuthLogin`. When `onLogin` is `null` (the default), nothing runs. ## Guest Claim Callback Run custom logic once a guest claim settles: ```dart MagicStarter.useGuestClaimed((GuestClaimOutcome outcome) async { if (outcome == GuestClaimOutcome.claimed) await Library.refresh(); }); ``` Also accepted as the `onGuestClaimed` argument of `MagicStarter.bootstrap()`. With the `guest_auth` feature on, the provider's `AuthLogin` and `AuthRestored` listeners claim a pending guest record for a non-guest user and call this callback with every outcome but `none` (`claimed`, `refused`, `promoted`), each of which marks the first sign-in to a real account after a guest session on this device. It runs unawaited and a failure is logged, not rethrown; a sign-in and a restore that share one claim call it once. See [Guest Claim](https://anilcancakir.com/magic/docs/starter/basics/authentication.md#guest-claim) for the flow. When `onGuestClaimed` is `null` (the default), nothing runs. ## Locale Application `MagicStarterServiceProvider` also applies a signed-in user's saved `locale` attribute to the running app automatically, so a Turkish account does not land on an English shell until its next cold boot. Configured with `magic_starter.localization.apply_user_locale` (default `true`): ```dart Map get magicStarterConfig => { 'magic_starter': { 'localization': {'apply_user_locale': false}, // opt out // ... }, }; ``` A named static listener on `Auth.stateNotifier`, plus one immediate "once, now" read in `boot()` for the ordinary cold-boot case, reads `Auth.user()?.get('locale')` and hands any non-empty value to `MagicStarterManager.applyLocale()`, the same method a [profile save](https://anilcancakir.com/magic/docs/starter/basics/profile.md) calls once it changed the language. `applyLocale()` holds a single pending target: whichever call reaches it first for a given locale wins, and a same-frame second call for the same target is a no-op, so a profile save (which itself calls `Auth.restore()` and so wakes this listener too) still issues exactly one `Lang.setLocale()` call however long the catalogue load takes. When `Auth.check()` is `false`, the user carries no `locale`, or the toggle is off, nothing happens. ## Unified Theme `MagicStarterTheme` wraps every sub-theme object into a single configuration. Host apps can set the entire visual identity in one call, then selectively override individual sub-themes afterward: ```dart MagicStarter.useTheme( MagicStarterTheme( navigation: MagicStarterNavigationTheme( activeItemClassName: 'active:text-amber-500 active:bg-amber-500/10', ), form: MagicStarterFormTheme( inputClassName: 'rounded-xl border-2 border-zinc-700', ), card: MagicStarterCardTheme( surfaceClassName: 'bg-zinc-50 dark:bg-zinc-900', ), ), ); // Override just one sub-theme after unified set MagicStarter.useAuthTheme( MagicStarterAuthTheme(cardClassName: 'rounded-3xl bg-zinc-900 p-8'), ); ``` The unified theme supports `copyWith()` for partial overrides: ```dart final customTheme = MagicStarter.theme.copyWith( form: MagicStarterFormTheme(inputClassName: 'rounded-xl'), ); MagicStarter.useTheme(customTheme); ``` The manager maintains bidirectional sync: the `theme` getter constructs a `MagicStarterTheme` from the individual fields, while the `theme` setter distributes each sub-theme to its respective field, so `useTheme()` and the individual `use*Theme()` methods work together. Call the unified one first: a later `use*Theme()` replaces only its own sub-theme. | Sub-theme | Class | Facade getter/setter | |:----------|:------|:--------------------| | Navigation | `MagicStarterNavigationTheme` | `useNavigationTheme()` / `navigationTheme` | | Modal | `MagicStarterModalTheme` | `useModalTheme()` / `modalTheme` | | Form | `MagicStarterFormTheme` | `useFormTheme()` / `formTheme` | | Auth | `MagicStarterAuthTheme` | `useAuthTheme()` / `authTheme` | | Card | `MagicStarterCardTheme` | `useCardTheme()` / `cardTheme` | | Page Header | `MagicStarterPageHeaderTheme` | `usePageHeaderTheme()` / `pageHeaderTheme` | | Layout | `MagicStarterLayoutTheme` | `useLayoutTheme()` / `layoutTheme` | | Dropdown | `MagicStarterDropdownTheme` | `useDropdownTheme()` / `dropdownTheme` | | Button | `MagicStarterButtonTheme` | `useButtonTheme()` / `buttonTheme` | | Field | `MagicStarterFieldTheme` | `useFieldTheme()` / `fieldTheme` | All sub-theme classes live in `lib/src/configuration/magic_starter_theme.dart`. ## Form Theme `MagicStarterFormTheme` overrides the class names for form inputs, labels, placeholders, buttons, links, and checkboxes across all auth and profile forms. ```dart MagicStarter.useFormTheme( MagicStarterFormTheme( inputClassName: 'w-full px-4 py-4 rounded-xl bg-zinc-900 border border-zinc-700 text-white', primaryButtonClassName: 'w-full bg-indigo-600 hover:bg-indigo-700 text-white font-semibold', ), ); ``` `useFormTheme()` assigns the whole struct, so every field you leave out goes back to its default, including the ones `useWindTheme()` derived. To change one string and keep the rest, copy the active theme. Every sub-theme has the same `copyWith`: ```dart MagicStarter.useFormTheme( MagicStarter.formTheme.copyWith(inputClassName: 'w-full py-[11px] ...'), ); MagicStarter.useModalTheme( MagicStarter.modalTheme.copyWith(inputClassName: 'w-full py-[11px] ...'), ); ``` ## Auth Theme `MagicStarterAuthTheme` overrides the class names for the auth form card, title, subtitle, error banner, social divider, and link styles on login/register/forgot/reset pages. ```dart MagicStarter.useAuthTheme( MagicStarterAuthTheme( cardClassName: 'rounded-3xl bg-zinc-900 border border-zinc-700 p-8', titleClassName: 'text-3xl font-black text-white text-center', ), ); ``` ## Card Theme `MagicStarterCardTheme` overrides the class names for `MSCard` variant backgrounds, border radius, padding, and title styles. ```dart MagicStarter.useCardTheme( MagicStarterCardTheme( surfaceClassName: 'bg-zinc-900 border border-zinc-700', borderRadius: 'rounded-xl', ), ); ``` ## Page Header Theme `MagicStarterPageHeaderTheme` overrides the class names for the `MSPageHeader` container, title, subtitle, action container and compact bar, plus two layout switches. ```dart MagicStarter.usePageHeaderTheme( MagicStarterPageHeaderTheme( titleClassName: 'text-3xl font-black text-white', ), ); ``` ### `inlineActions`, and the one combination that overflows The header stacks below `sm` and lays out as a row above it. An app that wants a row at EVERY width, so a phone header keeps its action beside the title instead of dropping it under the subtitle, overrides `containerClassName`: ```dart MagicStarter.usePageHeaderTheme( const MagicStarterPageHeaderTheme( containerClassName: 'w-full flex flex-row items-start justify-between gap-3 ...', // Required with the override above, and easy to miss. inlineActions: true, ), ); ``` **Setting the container alone overflows.** `inlineActions` does two things: it selects `containerInlineClassName`, and it gives the title row `flex-1 min-w-0` instead of `sm:flex-1`. Without the second half the title column is `flex-initial`, a loose fit, so a long title takes its intrinsic width and runs past the actions rather than shrinking. `line-clamp-2` on the title does not help, for the same reason `truncate` does not without a constrained box. `MSPageHeader.inlineActions` is `bool?` and defaults to this field, so a single screen can still opt out with `inlineActions: false`. `MSPageScaffold` does not expose the argument, which is why the theme is the only reachable switch for a scaffold consumer. ### Large title `largeTitle: true` makes every `MSPageHeader` a large title and every `MSPageScaffold` collapse it into a compact bar on scroll, the starter's own pages included. A widget argument still wins (`size:` on the header, `largeTitle:` on the scaffold). ```dart MagicStarter.usePageHeaderTheme( const MagicStarterPageHeaderTheme( largeTitle: true, largeTitleClassName: 'text-4xl lg:text-3xl font-bold text-fg', compactBarClassName: 'px-2 bg-white/80 dark:bg-gray-900/80 border-b border-color-border', compactBarOpaqueClassName: 'px-2 bg-surface-container border-b border-color-border', compactTitleClassName: 'text-base font-semibold text-fg truncate', compactBarBlurSigma: 24, ), ); ``` The bar is glass: `compactBarClassName` should be translucent, and `compactBarBlurSigma` blurs what scrolls under it (`0` adds no blur layer). Under high contrast (`MediaQuery.highContrast`, iOS Increase Contrast) it paints `compactBarOpaqueClassName` with no blur. A semantic alias carries no opacity step, so `MagicStarterTheme.fromWind` sets both fills to the opaque `bg-surface-container`; a host after glass passes its own translucent fill. ### Host-owned page chrome `manager.pageChrome` is a `MagicStarterPageChrome`, a `ChangeNotifier` that lives as long as the manager (`reset()` clears it, it does not replace it). A host that draws the page title and back control in its own bar registers a predicate: ```dart MagicStarter.useHostPageChrome((context) => MediaQuery.sizeOf(context).width < 768); ``` Wherever it answers true, `MSPageHeader` draws only its `actions` (right aligned, nothing at all without them, no heading role) and reports a `MagicStarterPageChromeEntry` (`title`, `subtitle`, `backLabel`, `backFallback`, value equality) keyed by its own state; `MSPageScaffold` then builds neither the large title nor the compact bar. The predicate gets a context inside the page and is asked again when its dependencies (the `MediaQuery` it reads) or the header's widget change. A header reports only while its `ModalRoute` is the current one: it withdraws when a route is pushed over it and the moment its own route is popped, before the exit transition ends, and reports again when the page above is popped. So `current` names the top page, and is null when that page has no `MSPageHeader`. A header under no route reports whenever the predicate answers true. Every starter page follows it, the two `magic_notifications` screens included: the starter mounts the inbox and the preferences with a `headerBuilder` that draws their header as an `MSPageHeader` (`lib/src/routes/notification_routes.dart`), so the inbox reports its title and keeps its mark-all-as-read action, and the preferences report the settings hub as their `backFallback`. | Member | Contract | |:-------|:---------| | `hostOwns(context)` | The predicate's answer; `false` while none is registered | | `current` | The entry of the owner whose first report is the most recent; an update keeps its place, so the older of two pages mounted together under an instant swap neither takes over nor clears the newer one when it withdraws | | `report(owner, entry)` / `withdraw(owner)` | Called by the header from `didChangeDependencies`, `didUpdateWidget` and `dispose`, and `withdraw` also when its route is popped; it reports only while its route is current | | listeners | Notified after the frame in which `current` changed, never during a build; a change undone within the frame notifies nobody | The host's bar listens and goes back with the fallback the page reported: ```dart ListenableBuilder(listenable: MagicStarter.pageChrome, builder: (context, _) { final MagicStarterPageChromeEntry? entry = MagicStarter.pageChrome.current; return TopBar(title: entry?.title, onBack: () => MagicRoute.back(fallback: entry?.backFallback)); }); ``` ## Layout Theme `MagicStarterLayoutTheme` overrides `wind_kit` class names and dimensions for the app layout shell: sidebar, header, the content area and its background, drawer background, brand bar, and bottom navigation. It also carries the two breakpoints and the compact width that decide when the sidebar appears and when it renders as an icon rail. ```dart MagicStarter.useLayoutTheme( MagicStarterLayoutTheme( sidebarWidth: 280, sidebarClassName: 'h-full flex flex-col bg-zinc-900 border-r border-zinc-700', contentBackgroundLightColor: 'zinc', contentBackgroundLightShade: 50, ), ); ``` ## Page Geometry `pageContainerClassName` is the `wind_kit` geometry every page in the app shares: the width cap, the horizontal edge margins, and the vertical rhythm. `MSPageContainer` reads it, and `MSPageScaffold` composes `MSPageContainer`, so every page in this package and every page in the host app resolve to the same numbers. ```dart // In AppServiceProvider.boot() MagicStarter.manager.pageContainerClassName = 'max-w-6xl px-4 sm:px-5 lg:px-8 pt-6 sm:pt-8 pb-24'; ``` The geometry belongs to the host, not to this package. Magic Starter's account pages render inside the host's own shell (see [Layout Theme](#layout-theme) and the `layout.app` view key), so a width chosen here is a guess about someone else's layout. Set one geometry and every page, starter-owned or host-owned, lines up by construction. Carry the whole geometry in the one string. A cap that agrees while the padding does not still reads as two different pages. It defaults to `MagicStarterManager.defaultPageContainerClassName` (`max-w-7xl px-4 lg:px-8 pt-6 sm:pt-8 pb-16`), so an app that configures nothing still gets a complete, capped, edge-padded page. > [!NOTE] > The vertical padding matters as much as the cap. The app layout's content region is a bare scroll view with no padding of its own, so a geometry with no `pt-*` glues the page header to the top edge of the viewport. If the host floats anything over its content region (a FAB, for instance), the bottom pad has to clear it. Per-page tuning goes through `MSPageContainer`'s `className`, which is appended after the shared geometry: ```dart MSPageContainer( className: 'pb-0', // This page ends with its own footer bar. child: pageBody, ) ``` ## View Registry Integration The manager holds a private `MagicStarterViewRegistry` instance, exposed via the `view` getter: ```dart final MagicStarterViewRegistry _viewRegistry = MagicStarterViewRegistry(); MagicStarterViewRegistry get view => _viewRegistry; ``` The facade provides a shortcut: `MagicStarter.view` delegates to `manager.view`. All view and layout registration, lookup, and building flows through this single registry instance. > [!TIP] > Register overrides in your `AppServiceProvider.boot()`. `register()` on the registry replaces a key, and `registerDefaultViews()` skips keys that already exist, so an override wins in either order. The registry API is in [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md). ## Default Views `registerDefaultViews()` runs in the constructor and fills the registry with the package's views, layouts and modals. It registers a key only when it is absent, so an override registered earlier is never replaced. A view whose feature is off is not registered: | Key | View | Registered when | |:----|:-----|:----------------| | `auth.login`, `auth.register`, `auth.forgot_password`, `auth.reset_password` | `MagicStarterLoginView`, `MagicStarterRegisterView`, `MagicStarterForgotPasswordView`, `MagicStarterResetPasswordView` | Always | | `auth.verify_email` | `MagicStarterVerifyEmailView` | `hasEmailVerificationFeatures()` | | `auth.two_factor_challenge` | `MagicStarterTwoFactorChallengeView` | `hasTwoFactorFeatures()` | | `auth.handoff` | `MagicStarterHandoffView` | `hasHandoffFeatures()` | | `auth.otp_verify` | `MagicStarterOtpVerifyView` | `hasPhoneOtpFeatures()` | | `settings.hub`, `profile.profile`, `settings.appearance`, `settings.security.password` | `MagicStarterSettingsHubView`, `MagicStarterProfileSubPageView`, `MagicStarterAppearanceView`, `MagicStarterPasswordView` | Always | | `settings.language` | `MagicStarterLanguageView` | `hasExtendedProfileFeatures()` | | `settings.timezone` | `MagicStarterTimezoneView` | `hasTimezoneFeatures()` | | `settings.newsletter` | `MagicStarterNewsletterView` | `hasNewsletterFeatures()` | | `settings.changelog` | `MagicStarterChangelogView` | `hasReleasesFeatures()` | | `settings.security.two_factor` | `MagicStarterTwoFactorView` | `hasTwoFactorFeatures()` | | `settings.security.sessions` | `MagicStarterSessionsView` | `hasSessionsFeatures()` | | `settings.security.connected_accounts` | `MagicStarterConnectedAccountsView` | `hasSocialLoginFeatures()` | | `teams.create`, `teams.settings`, `teams.invitation_accept` | `MagicStarterTeamCreateView`, `MagicStarterTeamSettingsView`, `MagicStarterTeamInvitationAcceptView` | `hasTeamFeatures()` | | `teams.billing` | `MagicStarterBillingView` | `hasBillingFeatures()` | | `support.index`, `support.create`, `support.thread` | `MagicStarterSupportIndexView`, `MagicStarterSupportCreateView`, `MagicStarterSupportThreadView` | `hasSupportFeatures()` | | `support.feedback` | `MagicStarterFeedbackView` | `hasSupportFeatures()` and `hasSupportFeedbackFeatures()` | | `support.chat`, `support.chat_panel` | `MagicStarterSupportChatLauncher`, `MagicStarterSupportChatPanel` | `hasSupportFeatures()` and `hasSupportChatFeatures()` | `notifications.list` and `notifications.preferences` are not among them. Both screens live on `magic_notifications`'s own `Notify.view`, which `registerMagicStarterNotificationRoutes()` re-registers wrapped in this package's page geometry; see [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md). The default layout and modal keys are in [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md). ## MagicStarter Facade `MagicStarter` is a static class (private constructor `MagicStarter._()`) that delegates every call to the manager singleton. It is the API host apps use: | Facade method | Does | |:--------------|:-----| | `MagicStarter.bootstrap(...)` | Registers the identity contract (user factory, logout, locales, optional login and guest-claim callbacks, optional team trio) in one call | | `MagicStarter.useUserModel(factory)` | `manager.userFactory = factory` | | `MagicStarter.createUser(data)` | `manager.userFactory(data)` | | `MagicStarter.useTeamResolver(...)` | `manager.teamResolver = config` | | `MagicStarter.switchTeam(id)`, `MagicStarter.currentTeamId()` | Switch the active team, read its id | | `MagicStarter.useNavigation(...)` | `manager.navigationConfig = config` | | `MagicStarter.useTheme(theme)` | `manager.theme = theme` (sets every sub-theme) | | `MagicStarter.useWindTheme(windTheme)` | `manager.applyWindTheme(windTheme)`: derives the colour-bearing sub-themes from a `WindThemeData` and keeps the fields the host set; see [wind_kit Theme Adoption](https://anilcancakir.com/magic/docs/starter/guides/wind-theme-adoption.md) | | `MagicStarter.useNavigationTheme(theme)` | `manager.navigationTheme = theme` | | `MagicStarter.useModalTheme(theme)` | `manager.modalTheme = theme` | | `MagicStarter.useFormTheme(theme)` | `manager.formTheme = theme` | | `MagicStarter.useAuthTheme(theme)` | `manager.authTheme = theme` | | `MagicStarter.useCardTheme(theme)` | `manager.cardTheme = theme` | | `MagicStarter.usePageHeaderTheme(theme)` | `manager.pageHeaderTheme = theme` | | `MagicStarter.useHostPageChrome(owns)` | `manager.pageChrome.ownsWhen = owns` | | `MagicStarter.pageChrome` | `manager.pageChrome` | | `MagicStarter.useLayoutTheme(theme)` | `manager.layoutTheme = theme` | | `MagicStarter.useDropdownTheme(theme)` | `manager.dropdownTheme = theme` | | `MagicStarter.useButtonTheme(theme)` | `manager.buttonTheme = theme` | | `MagicStarter.useFieldTheme(theme)` | `manager.fieldTheme = theme` | | `MagicStarter.useSidebarFooter(builder)` | `manager.sidebarFooterBuilder = builder` | | `MagicStarter.useHeader(builder)` | `manager.headerBuilder = builder` | | `MagicStarter.useLogout(callback)` | `manager.onLogout = callback` | | `MagicStarter.beforeLogout(hook)` | Adds a before-logout hook | | `MagicStarter.useLogin(callback)` | `manager.onLogin = callback` | | `MagicStarter.useGuestClaimed(callback)` | `manager.onGuestClaimed = callback` | | `MagicStarter.useSocialAuth(socialAuth)` | `manager.socialAuth = socialAuth` | | `MagicStarter.usePageContext(provider)` | `manager.pageContextProvider = provider`: what the customer is looking at, sent with each support message (see [Support](https://anilcancakir.com/magic/docs/starter/basics/support.md)) | | `MagicStarter.useLocaleOptions(locales)` | `manager.localeOptions = options` | | `MagicStarter.useGuestAuthEntry(builder)` | `manager.guestAuthEntryBuilder = builder` (stored only: no starter screen reads it) | | `MagicStarter.useNewsletterLabel(label)` | `manager.newsletterLabel = label` (read by the register view as its newsletter checkbox label, not by the profile newsletter page) | | `MagicStarter.view` | `manager.view` | | `MagicStarter.isReady` | `manager.isReady` | The `reset()` method on the manager restores every property to its default, clears the view registry and registers the default views again. Tests call it in `setUp()` for isolation. ## Related Documentation - [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md): binds the manager and registers the Gate abilities. - [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md): the string-keyed view factory the manager holds. - [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md): `MagicStarter.bootstrap()` in the host's `AppServiceProvider`. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the app shell the layout theme styles. - [Magic service container](https://anilcancakir.com/magic/docs/architecture/service-container): singleton and factory bindings. --- # MagicStarterServiceProvider `MagicStarterServiceProvider` binds the manager, listens to the auth events, defines the profile Gate abilities and wires the sign-in and sign-out side effects the starter owns. - [Two-Phase Bootstrap](#two-phase-bootstrap) - [Register Phase](#register-phase) - [Boot Phase](#boot-phase) - [Teams Feature Warning](#teams-feature-warning) - [Gate Abilities](#gate-abilities) - [Primary Colour Fallback](#primary-color-fallback) - [Auth State Listeners](#auth-state-listeners) - [Before-Logout Hooks](#before-logout-hooks) - [IoC Bindings](#ioc-bindings) - [Related Documentation](#related-documentation) The provider lives at `lib/src/providers/magic_starter_service_provider.dart` and extends `ServiceProvider` from `package:magic/magic.dart`. `starter:install` adds it to the `providers` list in `lib/config/app.dart`. ## Two-Phase Bootstrap Magic calls every provider's `register()` first, then every provider's `boot()` in list order: | Phase | Method | Constraint | |:------|:-------|:-----------| | 1 | `register()` | Sync. Only bind into the container; no other service may be resolved yet. | | 2 | `boot()` | Async. Every provider has registered, so bindings are resolvable. Providers boot one after another in the order of the `providers` list. | ## Register Phase ```dart @override void register() { app.singleton('magic_starter', () => MagicStarterManager()); EventDispatcher.instance.register(AuthRestored, [ () => _ReloadOnAuthRestored(), ]); EventDispatcher.instance.register(AuthLogin, [() => _CallOnLoginHook()]); // ... guest listeners, session identity and store billable, below } ``` 1. **Manager singleton**: binds `MagicStarterManager` under `'magic_starter'`. The container builds it the first time it is resolved, and its constructor calls `registerDefaultViews()`, so the default views, layouts and modals are available from then on. 2. **Auth restored listener**: `_ReloadOnAuthRestored` calls `Magic.reload()` when `AuthRestored` fires with `changed` true, so screens refresh after a write that calls `Auth.restore()` (team rename, invitation accept, profile update). A sync that only confirms the cached user (`changed` false, the usual cold boot) reloads nothing. It also stays out of the way while `MagicStarterHandoffController` holds a sign-in handoff. A team switch does not come through here; it resets team-scoped screens through `SessionScope`. 3. **Auth login listener**: `_CallOnLoginHook` calls the host's `MagicStarter.useLogin()` callback (unawaited, logged on failure) whenever `AuthLogin` fires: every fresh sign-in, never a cold-boot restore. See [Login Callback](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#login-callback). 4. **Guest listeners**, only when `features.guest_auth` is on: on `AuthLogin` a guest sign-in is recorded and any other sign-in claims the recorded guest's data in the background; on `AuthRestored` a pending claim runs; on `AuthLogout` the record is forgotten. See [Guest Claim Callback](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#guest-claim-callback). 5. **Session identity**: sets `SessionScope.identity` to `:` while signed in and `null` otherwise, so a team switch by the same user counts as a change. See [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md). 6. **Store billable**: points `StoreIdentitySync.billableId` at the manager, so the store rail is identified as the user or the team according to `magic_starter.billing.billable`. > [!NOTE] > The manager is built the first time it is resolved. If you want to override views, register them in your `AppServiceProvider.boot()`: `registerDefaultViews()` registers a key only when it is absent, and `register()` on the registry replaces whatever is there. ## Boot Phase `boot()` is `async`. In order, it: 1. warns about a missing team resolver, 2. defines the Gate abilities, 3. schedules the primary colour fallback, 4. installs the modal presentation resolver on magic's router (`MagicRoute.useOverlayPresentation`), so an overlay route follows the modal theme's `presentation`, 5. on the web, primes the app build when `app_update` or `releases` is on, 6. attaches the auth state listeners and the before-logout hooks described below. ### Teams Feature Warning If `magic_starter.features.teams` is on and no team resolver has been registered, the provider logs a warning: ```dart final teamsEnabled = Config.get('magic_starter.features.teams', false) ?? false; if (teamsEnabled && MagicStarter.manager.teamResolver == null) { Log.warning( '[MagicStarter] Teams feature is enabled but no team resolver ' 'is configured. Call MagicStarter.useTeamResolver() in your AppServiceProvider.', ); } ``` `MagicStarter.bootstrap()` throws on the same condition instead of logging, so prefer it; see [Installation](https://anilcancakir.com/magic/docs/starter/getting-started/installation.md#bootstrapping-the-starter). The resolver has to be registered before this provider boots, so list the provider that registers it before `MagicStarterServiceProvider`. ### Gate Abilities The provider defines the abilities that control profile section visibility. Every ability is granted when the user is not a guest (`is_guest != true`). ```dart bool isNotGuest(Model user, [dynamic _]) { return user.get('is_guest') != true; } Gate.define('starter.update-profile-photo', isNotGuest); Gate.define('starter.update-email', isNotGuest); // ... ``` | Ability | Controls | |:--------|:---------| | `starter.update-profile-photo` | Profile photo upload and remove section | | `starter.update-email` | Email field in profile information | | `starter.update-phone` | Phone and country code in the extended profile | | `starter.update-password` | Password change section | | `starter.verify-email` | Email verification banner | | `starter.manage-two-factor` | Two-factor authentication section | | `starter.manage-newsletter` | Newsletter preferences section | | `starter.logout-sessions` | Revoke buttons in browser sessions | | `starter.delete-account` | Account deletion section | `Gate.define()` replaces an ability of the same name, so the last definition wins. To override one, define it after this provider boots, which means listing your own provider after `MagicStarterServiceProvider`: ```dart // In a provider listed after MagicStarterServiceProvider Gate.define('starter.delete-account', (user, [_]) => false); // disable for all ``` > [!WARNING] > A `Gate.define()` for a `starter.*` ability in a provider listed before `MagicStarterServiceProvider` boots first and is then overwritten by the starter's own definition. ### Primary Colour Fallback If the host has not defined a `primary` colour in its Wind theme, the provider registers `indigo` as the fallback. `boot()` runs during `Magic.init()`, before `runApp()` builds the widget tree, so the check is deferred to a post-frame callback: ```dart WidgetsBinding.instance.addPostFrameCallback((_) { final context = MagicRouter.instance.navigatorKey.currentContext; if (context == null) return; final windTheme = WindTheme.of(context); if (!windTheme.data.isValidColor('primary')) { windTheme.updateTheme( colors: {'primary': windTheme.data.colors['indigo']!}, ); } }); ``` The fallback applies only when no `primary` colour exists; if your `WindThemeData.colors` defines one, the callback does nothing. ### Auth State Listeners Three listeners attach to `Auth.stateNotifier`, each once per notifier, so a hot restart does not stack them: | Listener | Does | |:---------|:-----| | Intended URL | On sign-out, clears the intended URL magic's router remembered, so the next sign-in does not land on the previous person's page. | | Push identity | With `features.notifications` on: signed in as a non-guest, declares `` to the push driver (`Notify.initializePush`); signed out, or a guest, releases it. See [The push external id](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md#push-external-id). | | Saved locale | With `localization.apply_user_locale` on, applies the signed-in user's `locale` attribute through `MagicStarterManager.applyLocale()`. See [Locale Application](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#locale-application). | ### Before-Logout Hooks The provider registers two hooks that run before every sign-out the user asks for, while the token still works (see [Logout Callback](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#logout-callback)): 1. **Push device release**, when `magic_notifications` is bound and its push state is configured: `Notify.pushState.release`, which frees the backend's push-state row. 2. **Token revoke**, when an `auth` guard is bound and a token exists: `POST /auth/logout`. A non-success answer is logged as a warning and the token may stay valid until it expires. Both register in `boot()`, in `providers` order, and hooks run in registration order: a hook from a provider listed after this one runs after the revoke, on a revoked token. A hook that throws or runs past five seconds is logged and skipped. A sign-out the app performs on its own, such as magic's `AuthInterceptor` after a failed token refresh, does not run them: the token is already dead. ## IoC Bindings The manager is reachable two ways: ```dart // Via the facade (preferred) final manager = MagicStarter.manager; // Via the container final manager = Magic.make('magic_starter'); ``` Register the provider in the `providers` list of `lib/config/app.dart`, and the config factory in `Magic.init()`: ```dart import 'package:magic_starter/magic_starter.dart'; Map get appConfig => { 'app': { 'providers': [ // ... other providers (app) => MagicStarterServiceProvider(app), ], }, }; ``` The `magic_starter` keys live in their own config file, see [Configuration](https://anilcancakir.com/magic/docs/starter/getting-started/configuration.md). ## Related Documentation - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): the singleton holding every customisation registration. - [View Registry](https://anilcancakir.com/magic/docs/starter/architecture/view-registry.md): the string-keyed view factory behind overridable screens. - [Controllers](https://anilcancakir.com/magic/docs/starter/architecture/controllers.md): the lazy singleton pattern and the starter's own controllers. - [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md): what resets when the identity key changes. - [Magic service providers](https://anilcancakir.com/magic/docs/getting-started/service-providers): the two-phase lifecycle. - [Magic authorization](https://anilcancakir.com/magic/docs/security/authorization): the Gate. --- # Controllers The starter's controllers hold the business logic and async state behind each screen: every view delegates its API calls, state transitions and navigation to a paired controller. - [Introduction](#introduction) - [Lazy Singleton Pattern](#lazy-singleton-pattern) - [MagicController and MagicStateMixin](#magiccontroller-and-magicstatemixin) - [Controller Lifecycle](#controller-lifecycle) - [View Binding](#view-binding) - [Fine-Grained Reactivity](#fine-grained-reactivity) - [Consumer Apps](#consumer-apps) - [Related Documentation](#related-documentation) ## Introduction A view renders state and forwards user input; the controller calls the backend, moves the state machine and navigates. Controllers live in `lib/src/http/controllers/` and are exported from `package:magic_starter/magic_starter.dart`. They share two small mixins from `concerns/`: | Mixin | Provides | |:------|:---------| | `NavigatesRoutes` | `navigateTo(path, {query})` and `navigateHome()`, which are no-ops while no navigator is mounted and send the user to the intended URL or `routes.home` | | `CompletesSignIn` | `completeSignIn(...)`, the one way a sign-in concludes (password, social, two-factor challenge, OTP, guest, handoff), which also announces a cancelled account deletion | Notification preferences state moved with the notification UI: `NotificationPreferencesController` lives in `magic_notifications` and follows the same lazy-singleton shape. ## Lazy Singleton Pattern A controller exposes one static accessor that delegates instantiation to the Magic container: ```dart class MagicStarterAuthController extends MagicController with MagicStateMixin, ValidatesRequests, NavigatesRoutes, CompletesSignIn { static MagicStarterAuthController get instance => Magic.findOrPut(MagicStarterAuthController.new); } ``` `Magic.findOrPut` checks whether a binding for the controller's runtime type exists. On first access it calls the tear-off constructor, stores the result and returns it; every later call returns the cached instance. A controller is created only when first needed and lives as long as the container. | Controller | State mixin | Also | |:-----------|:------------|:-----| | `MagicStarterAuthController` | `MagicStateMixin` | `ValidatesRequests`, `NavigatesRoutes`, `CompletesSignIn` | | `MagicStarterOtpController` | `MagicStateMixin` | `ValidatesRequests`, `NavigatesRoutes`, `CompletesSignIn` | | `MagicStarterGuestAuthController` | `MagicStateMixin` | `ValidatesRequests`, `NavigatesRoutes`, `CompletesSignIn` | | `MagicStarterHandoffController` | none | `NavigatesRoutes`, `CompletesSignIn`, `SessionScoped` | | `MagicStarterProfileController` | `MagicStateMixin` | `ValidatesRequests`, `NavigatesRoutes` | | `MagicStarterNewsletterController` | `MagicStateMixin` | `ValidatesRequests` | | `MagicStarterReleasesController` | `MagicStateMixin` | none | | `MagicStarterTeamController` | `MagicStateMixin` | `ValidatesRequests`, `SessionScoped` | | `MagicStarterSupportController` | none | `ValidatesRequests`, `SessionScoped` | | `MagicStarterFeedbackController` | none | `ValidatesRequests`, `SessionScoped` | Each has a static `instance` accessor like the one above. `MagicStarterBillingController` is the exception: it takes required collaborators (the usage copy and number formatter), so there is no zero-argument constructor for `findOrPut` to call, and the host registers it with `Magic.put(...)`; see [Teams](https://anilcancakir.com/magic/docs/starter/basics/teams.md). > [!NOTE] > `Magic.findOrPut` is distinct from `Magic.singleton`. `singleton` registers a factory under a string key so the container can resolve it by name. `findOrPut` uses the concrete type as the implicit key and creates the instance on first access, with no upfront registration. ## MagicController and MagicStateMixin Every starter controller extends `MagicController`, which extends `ChangeNotifier`, so each one is a `Listenable`. Most add `MagicStateMixin`, a typed state machine on top of it: | Member | Description | |:-------|:------------| | `setLoading()` | Moves to the loading state and notifies listeners | | `setSuccess(T value)` | Moves to success with a typed payload | | `setError(String message)` | Moves to error with a message | | `setEmpty()` | Resets to the empty (idle) state | | `isLoading`, `isSuccess`, `isError`, `isEmpty` | The current state | | `renderState(onSuccess, {onLoading, onError, onEmpty})` | A widget factory that dispatches on the current state | `T` is the success payload type. `MagicStateMixin` is the common choice because most controllers only signal success or failure. `clearErrors()` and `hasErrors` come from the `ValidatesRequests` mixin and concern the field validation errors a backend 422 sets, not the state machine. A standard async action: ```dart Future doLogin({ required String password, String? email, }) async { setLoading(); clearErrors(); try { final response = await Http.post('/auth/login', data: { 'email': email, 'password': password, }); if (!response.successful) { handleApiError(response, fallback: trans('auth.login_failed')); return; } // ... complete the sign-in } catch (e, stackTrace) { Log.error('[doLogin] $e\n$stackTrace'); setError(trans('errors.unexpected')); } } ``` A throw before the response (a timeout, a dropped connection) would leave the controller in the loading state, so the action catches it, logs it and sets an error state. `MagicStarterAuthController.doLogin` also maps a timeout and a socket failure to their own messages. > [!TIP] > Call `setLoading()` and `clearErrors()` at the top of an async action, before the first `await`. The view gets immediate feedback and stale errors from the previous run are gone. ## Controller Lifecycle Because `findOrPut` stores the instance in the container, a controller outlives any view. Navigate away from the login screen and back and `MagicStarterAuthController.instance` is the same object. - The controller's own `onInit()` runs once per instance lifetime, the first time it backs a view, not on every mount. - The view state's `onInit()` runs on every mount. When a view mounts, magic clears the controller's validation errors and turns an error status back to empty without notifying, so a failed attempt does not greet the next visit. A controller still holds its other state (a success value, `ValueNotifier` contents) between visits: reset what you need in the view's `onInit()`. - A controller that caches data of one signed-in user or team implements magic's `SessionScoped`, so a sign-out or a team switch resets it. The team, support, feedback, handoff and billing controllers do; see [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md). - `ValueNotifier` fields are disposed with the controller. In tests call `controller.dispose()` in `tearDown`. - `Magic.flush()` or `MagicApp.reset()` replaces the container; the next `findOrPut` builds a fresh instance. That is the test isolation mechanism. ## View Binding Every page-level view extends `MagicStatefulView`. The state class resolves the controller with `Magic.find()`, so the controller has to be registered first: the starter's routes do it by calling `instance` (or `Magic.findOrPut`) in the route builder, before the view mounts. The controller is then available through the `controller` getter. ```dart class MagicStarterLoginView extends MagicStatefulView { const MagicStarterLoginView({super.key}); @override State createState() => _MagicStarterLoginViewState(); } class _MagicStarterLoginViewState extends MagicStatefulViewState< MagicStarterAuthController, MagicStarterLoginView> { late final form = MagicFormData( {'email': '', 'phone': '', 'password': '', 'remember_me': false}, controller: controller, ); @override void onInit() { controller.clearErrors(); controller.setEmpty(); } @override void onClose() => form.dispose(); @override Widget build(BuildContext context) { return controller.renderState( (_) => _buildForm(), onEmpty: _buildForm(), onLoading: _buildForm(), onError: (message) => _buildForm(errorMessage: message), ); } } ``` | Hook | Called when | Typical use | |:-----|:------------|:------------| | `onInit()` | After `initState()`, on every mount | Reset controller state, start the first load | | `onClose()` | In `dispose()` | Dispose a `MagicFormData`, cancel subscriptions | The view subscribes to the controller through `ChangeNotifier` and calls `setState` on every `notifyListeners`, so `renderState` always shows the latest state without manual subscription code. The login form renders itself in the loading state too (`onLoading`), because the form group must outlive the request. ## Fine-Grained Reactivity `MagicStateMixin` notifies on every transition, which rebuilds the whole view listening to the controller. For a view with several independently loading sections that can flicker. The cure is one `ValueNotifier` per section. The team controller keeps its member and invitation lists that way: ```dart final ValueNotifier>> members = ValueNotifier([]); final ValueNotifier>> invitations = ValueNotifier([]); ``` and the team settings view wraps only the section that depends on one: ```dart ValueListenableBuilder>>( valueListenable: controller.members, builder: (context, members, _) => _buildMembers(members), ) ``` The builder rebuilds only its own subtree when `members.value` changes. `MagicStarterProfileController` adds `withoutNotifying()`, which suppresses full-page notifications while a section-level action drives its own loading indicator through `MagicFormData.process`: ```dart await form.process(() => controller.withoutNotifying( () => controller.doUpdateProfile(name: 'Alice', email: 'a@example.com'), )); ``` The suppression is a depth counter, so two overlapping actions do not un-suppress each other. ## Consumer Apps An app building its own features on top of the starter follows the same conventions: a lazy `instance` accessor, `MagicStateMixin`, a view on `MagicStatefulView`. The registration options (lazy, eager in `boot()`, per-view `ChangeNotifier`), the view patterns and the test setup are in [State Management](https://anilcancakir.com/magic/docs/starter/guides/state-management.md). ## Related Documentation - [State Management](https://anilcancakir.com/magic/docs/starter/guides/state-management.md): writing your own controller on the same pattern. - [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md): the bootstrap, IoC bindings and Gate abilities. - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): the singleton holding every customisation registration. - [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md): resetting session-scoped controllers. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): the `MagicStatefulView` lifecycle and rendering conventions. - [Magic controllers](https://anilcancakir.com/magic/docs/basics/controllers): `MagicController` and `MagicStateMixin` in core. --- # View Registry `MagicStarterViewRegistry` is the string-keyed factory that every starter route resolves its screens, layouts and modals through, so a host app can swap any of them without touching routes or controllers. - [Introduction](#introduction) - [MagicStarterViewRegistry Class](#magicstarterviewregistry-class) - [Registering Views](#registering-views) - [Registering Layouts](#registering-layouts) - [Registering Modals](#registering-modals) - [Checking Existence](#checking-existence) - [Building Widgets](#building-widgets) - [Clearing the Registry](#clearing-the-registry) - [Default View Keys](#default-view-keys) - [Default Layout Keys](#default-layout-keys) - [Default Modal Keys](#default-modal-keys) - [Overriding Views](#overriding-views) - [Composing a Settings Page](#composing-a-settings-page) - [Overriding Layouts](#overriding-layouts) - [Overriding Modals](#overriding-modals) - [Builder Slots](#builder-slots) - [Route Integration](#route-integration) - [Testing](#testing) - [Related Documentation](#related-documentation) ## Introduction Routes and controllers never construct a screen: they ask the registry for a key such as `auth.login` and the registry calls the builder registered under it. The package registers its own builders, a host replaces the ones it wants, and everything else keeps the default. The registry lives at `lib/src/ui/magic_starter_view_registry.dart` and is held by `MagicStarterManager`, reachable as `MagicStarter.view`. ## MagicStarterViewRegistry Class The registry keeps four internal maps: view builders, layout builders, modal builders and slot builders. The builder typedefs: ```dart typedef MagicStarterViewBuilder = Widget Function(); typedef MagicStarterLayoutBuilder = Widget Function(Widget child); typedef MagicStarterModalBuilder = Widget Function(); typedef MagicStarterSlotBuilder = Widget Function(BuildContext context); ``` ### Registering Views ```dart void register(String key, MagicStarterViewBuilder builder) ``` Stores a view builder under the key. A key that already exists is replaced. ### Registering Layouts ```dart void registerLayout(String key, MagicStarterLayoutBuilder builder) ``` Stores a layout builder. A layout builder receives the page as `child` and wraps it in a shell (sidebar, header, footer). ### Registering Modals ```dart void registerModal(String key, MagicStarterModalBuilder builder) ``` Stores a modal builder under the key. A key that already exists is replaced. ### Checking Existence ```dart bool has(String key) // true when a view builder exists for key bool hasLayout(String key) // true when a layout builder exists for key bool hasModal(String key) // true when a modal builder exists for key ``` `registerDefaultViews()` uses them to register a default only when the key is absent. ### Building Widgets ```dart Widget make(String key) Widget makeLayout(String key, {required Widget child}) Widget makeModal(String key) ``` All three throw a `StateError` when the key is not registered: ```dart throw StateError('No view builder registered for key "$key".'); ``` > [!NOTE] > A `StateError` from `make()` usually means a feature flag is off. Feature-gated views are only registered when the matching `MagicStarterConfig.has*Features()` returns `true` at the moment the manager is built. ### Clearing the Registry ```dart void clear() ``` Removes every view, layout, modal and slot builder. `MagicStarterManager.reset()` calls it and then registers the defaults again. ## Default View Keys `MagicStarterManager.registerDefaultViews()` registers the default views when the manager is built. Each key, its view class and the feature that registers it are listed in [Default Views](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#default-views). The notification screens (`notifications.list`, `notifications.preferences`) are not on this registry. Both belong to `magic_notifications` and live on its own `Notify.view`, which has the same shape (`register`, `has`, `make`, `slot`, `buildSlot`, `clear`). `registerMagicStarterNotificationRoutes()` re-registers them there wrapped in this package's page geometry unless the host already overrode the key; see [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md). ## Default Layout Keys | Key | Layout | Purpose | |:----|:-------|:--------| | `layout.app` | `MagicStarterAppLayout` | Authenticated pages: sidebar, header, bottom navigation | | `layout.guest` | `MagicStarterGuestLayout` | Auth pages: centred card, minimal chrome | ## Default Modal Keys | Key | Modal | Purpose | |:----|:------|:--------| | `modal.confirm` | `MagicStarterConfirmDialog` | Generic confirmation with a `ConfirmDialogVariant` (primary, danger, warning) | | `modal.password_confirm` | `MagicStarterPasswordConfirmDialog` | Password prompt with inline error handling | | `modal.two_factor` | `MagicStarterTwoFactorModal` | The two-factor setup wizard (QR code, code confirm, recovery codes) | ## Overriding Views Register your builder through `MagicStarter.view`: ```dart // In AppServiceProvider.boot() MagicStarter.view.register( 'auth.login', () => const MyCustomLoginView(), ); ``` `register()` replaces whatever is there, and `registerDefaultViews()` never overwrites an existing key, so an override wins whether it lands before or after the defaults. Register overrides in your `AppServiceProvider.boot()`: the facade resolves the manager bound by `MagicStarterServiceProvider`, and calling it earlier would use a throwaway fallback manager instead. Override only the views you want to change. The rest keep the package defaults. ### Composing a Settings Page The settings hub (`settings.hub`, routed at `/settings`) is three sections: Account, Security and Preferences. Each is a public widget that carries its own header, rows and gating, so a host that wants one settings page with sections of its own registers its view under `settings.hub` and places the starter's groups beside its sections, without copying a feature or ability check: ```dart class AppSettingsView extends StatelessWidget { const AppSettingsView({super.key}); @override Widget build(BuildContext context) { return MSPageScaffold( title: trans('magic_starter.nav.settings'), children: [ MSSettingsSection( header: 'Playback', children: [ MSSettingsNavRow(title: 'Player', to: '/settings/player'), ], ), MagicStarterSettingsAccountGroup(), if (MagicStarterSettingsSecurityGroup.hasRows) MagicStarterSettingsSecurityGroup(), MagicStarterSettingsPreferencesGroup(), if (MagicStarterConfig.hasReleasesFeatures()) const MagicStarterAppVersion(), ], ); } } // In AppServiceProvider.boot() MagicStarter.view.register('settings.hub', () => const AppSettingsView()); ``` | Widget | Rows and their gates | |:-------|:---------------------| | `MagicStarterSettingsAccountGroup` | Profile (always); for a guest (denied `starter.delete-account`) also the upgrade and sign-in rows | | `MagicStarterSettingsSecurityGroup` | Two-factor (`two_factor` and `starter.manage-two-factor`), Password (`starter.update-password`), Browser sessions (`sessions`), Connected accounts (`social_login` and a `MagicStarter.useSocialAuth` bridge) | | `MagicStarterSettingsPreferencesGroup` | Appearance (always), Notifications (`notifications`), Language (`extended_profile`), Timezone (`timezones`), Newsletter (`newsletter` and `starter.manage-newsletter`), What's new (`releases`) | - The Security group renders a zero-size box when none of its rows is reachable. `MSPageScaffold` still puts a gap around a zero-size child, so guard the group with `hasRows`; the other two always have a row. - The groups read the user, the abilities and the flags when they build and listen to none of them. Leave them non-const when the page is rebuilt on an auth change, or the Profile subtitle and the two-factor value keep what they read first. - The version caption is not part of a group: place `MagicStarterAppVersion` yourself, as above, to close the page the way the hub does. ## Overriding Layouts Replace the layout wrapper for guest or authenticated pages: ```dart MagicStarter.view.registerLayout( 'layout.guest', (child) => MyGuestLayout(child: child), ); MagicStarter.view.registerLayout( 'layout.app', (child) => MyAppLayout(child: child), ); ``` The layout builder receives the page as `child` and must render it somewhere in the layout tree. > [!NOTE] > When you override `layout.app`, your layout is responsible for navigation, header and responsive behaviour. The controllers still work; only the shell changes. Keep your authenticated route groups on the `MagicStarterLayoutIds.app` layout id so they share one shell with the starter's pages. ### The child arrives route-keyed `makeLayout` wraps `child` in a `KeyedSubtree` keyed on the current route path before the builder sees it, so your layout renders it wherever you like and keeps the per-route remount the default layouts carry. You do not add the key yourself and should not strip it. It matters because a layout is persistent: one element holds one child slot that every route in the group takes turns in. Without the key that slot is reused across routes, and swapping one scrollable view for another tears down render objects in a confused order under accumulated navigation. The wrap goes around the child rather than around your layout's result, so your navigation chrome is not torn down on a route change. ## Overriding Modals Replace the modal registered under a key: ```dart MagicStarter.view.registerModal( 'modal.confirm', () => const MyCustomConfirmDialog(), ); ``` > [!TIP] > Override a modal when you need a completely different dialog. For style-only changes (colours, fonts, borders, presentation as a sheet), use `MagicStarter.useModalTheme()`; it needs no override. See [Modal Theme](https://anilcancakir.com/magic/docs/starter/architecture/manager.md#modal-theme). ## Builder Slots A slot injects a widget into a named insertion point of a starter view without overriding the whole view. A slot builder is a `Widget Function(BuildContext)`. ```dart MagicStarter.view.slot('auth.login', 'header', (context) { return WText('Welcome back!', className: 'text-2xl font-bold text-center'); }); MagicStarter.view.slot('settings.hub', 'footer', (context) { return MyHelpSection(); }); ``` `slot()` takes the view key, the slot name and the builder. Slots are stored under the compound key `'.'`, for example `'auth.login.header'`. A view asks for its slots while it builds: ```dart // Inside a view's build method final headerSlot = MagicStarter.view.buildSlot('auth.login', 'header', context); ``` `buildSlot()` returns `null` when no slot is registered, and `hasSlot(viewKey, slot)` answers whether one is. Register slots before the view is built, in `AppServiceProvider.boot()`. `clear()` removes slots too, and registering a view again does not bring them back. | View key | Slots | |:---------|:------| | `auth.login`, `auth.register` | `header`, `formFooter`, `footer` | | `auth.forgot_password`, `auth.reset_password`, `auth.two_factor_challenge`, `auth.otp_verify` | `header`, `footer` | | `settings.hub`, `profile.profile`, `teams.create`, `teams.invitation_accept` | `header`, `footer` | | `teams.settings` | `header`, `footer`, `afterSection:members` | | `teams.billing` | `plan_card_highlight`, a builder that renders inside one plan card | > [!TIP] > Use slots for small, targeted additions (a banner, a section, extra fields). For a structural change, override the whole view with `MagicStarter.view.register()`. ## Route Integration Starter routes resolve views and layouts through the registry. The auth routes go through the controller, whose page methods call `MagicStarter.view.make`: ```dart // MagicStarterAuthController Widget login() => MagicStarter.view.make('auth.login'); ``` and every route group wraps its pages in a registry layout: ```dart MagicRoute.group( middleware: ['auth'], layoutId: MagicStarterLayoutIds.app, layout: (child) => MagicStarter.view.makeLayout('layout.app', child: child), routes: () { MagicRoute.page( MagicStarterConfig.profileRoute(), () { Magic.findOrPut(MagicStarterProfileController.new); return MagicStarter.view.make('profile.profile'); }, ); }, ); ``` A view that extends `MagicStatefulView` resolves its controller with `Magic.find`, so the route registers the controller first, as the starter's own profile routes do. Skip that line in your own route and the default view fails to resolve it. Route files import controllers and string keys, never view classes, so the registry resolves the plugin default or the host's override at runtime. Your own authenticated routes use the same `layout` and `layoutId` to land inside the starter's shell. ## Testing `MagicStarterManager.reset()` clears the registry and registers the defaults again. Bind a fresh manager in `setUp()` to isolate tests: ```dart setUp(() { MagicApp.reset(); Magic.flush(); setUpMagicStarterForTests(); // binds a default MagicStarterManager() }); ``` To test with a custom view: ```dart test('uses the custom login view when overridden', () { MagicStarter.view.register( 'auth.login', () => const Text('Custom Login'), ); final widget = MagicStarter.view.make('auth.login'); expect(widget, isA()); }); ``` To verify that a missing key throws: ```dart test('throws StateError for an unregistered key', () { MagicStarter.view.clear(); expect( () => MagicStarter.view.make('auth.login'), throwsStateError, ); }); ``` ## Related Documentation - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): the singleton that holds the registry and registers the default views. - [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md): the bootstrap that builds the manager. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): how the starter's own views are built. - [Notifications](https://anilcancakir.com/magic/docs/starter/basics/notifications.md): the two screens that live on `Notify.view`. - [Magic service container](https://anilcancakir.com/magic/docs/architecture/service-container): singleton bindings. --- # State Management How to write a controller in your own app on the same pattern the starter's controllers use: `MagicController`, `MagicStateMixin`, a lazy `instance` accessor and a `MagicStatefulView`. - [Introduction](#introduction) - [Creating a State Class](#creating-a-state-class) - [Extend MagicController](#extend-magiccontroller) - [Add the Singleton Accessor](#add-the-singleton-accessor) - [Implement Async Methods](#implement-async-methods) - [Registration Decision Tree](#registration-decision-tree) - [Connecting State to Views](#connecting-state-to-views) - [Pattern A: MagicStatefulView](#pattern-a-magicstatefulview) - [Pattern B: StatefulWidget + Manual Access](#pattern-b-statefulwidget--manual-access) - [Testing](#testing) - [Complete Example](#complete-example) - [Related Documentation](#related-documentation) ## Introduction The model has three parts, all from the Magic framework: 1. **`MagicController`**: the base class. It extends `ChangeNotifier` and carries the `onInit()` and `onClose()` lifecycle. 2. **`MagicStateMixin`**: a four-state machine (loading, success, error, empty) driven by `setLoading()`, `setSuccess()`, `setError()` and `setEmpty()`, rendered with `renderState()`. 3. **The container**: `Magic.findOrPut()` returns the existing instance of a controller type or creates and registers one. `dart run magic:dowel make:controller Project` generates a controller of this shape; see the [Magic CLI](https://anilcancakir.com/magic/docs/packages/magic-cli). Views bind to the controller's `instance` accessor and call `renderState()` to choose what to draw. How the starter applies the pattern is in [Controllers](https://anilcancakir.com/magic/docs/starter/architecture/controllers.md). ## Creating a State Class ### Extend MagicController ```dart import 'package:magic/magic.dart'; class ProjectController extends MagicController with MagicStateMixin>> { // ... } ``` The type parameter of `MagicStateMixin` is the value passed to `setSuccess(value)`: a list for collections, `bool` for form submissions, a model class for a single resource. ### Add the Singleton Accessor ```dart class ProjectController extends MagicController with MagicStateMixin>> { static ProjectController get instance => Magic.findOrPut(ProjectController.new); } ``` `Magic.findOrPut(ProjectController.new)` returns the registered `ProjectController` if there is one; otherwise it calls the constructor tear-off, registers the result and returns it. Every view that calls `ProjectController.instance` gets the same object. > [!NOTE] > Never call `ProjectController()` in a view: the `instance` accessor is what shares one state across views. Tests are the exception, see [Testing](#testing). ### Implement Async Methods Each async action follows one lifecycle: 1. Guard against re-entrant calls with a flag. 2. Call `setLoading()`. 3. Make the HTTP call with `Http.get()`, `Http.post()` and the like. 4. Call `setSuccess(value)` (or `setEmpty()` for an empty result) on the happy path, `setError(message)` on failure. 5. Reset the guard in `finally`. ```dart class ProjectController extends MagicController with MagicStateMixin>> { static ProjectController get instance => Magic.findOrPut(ProjectController.new); bool _isLoading = false; /// Fetches all projects and exposes them through the state machine. Future loadProjects() async { if (_isLoading) return; _isLoading = true; setLoading(); try { final response = await Http.get('/api/projects'); if (!response.successful) { setError('Failed to load projects.'); return; } final data = response.data['data']; final projects = data is List ? data.cast>() : >[]; if (projects.isEmpty) { setEmpty(); return; } setSuccess(projects); } catch (e, stackTrace) { Log.error('[ProjectController.loadProjects] $e\n$stackTrace'); setError('An unexpected error occurred.'); } finally { _isLoading = false; } } } ``` | Method | Resulting state | Read with | |:-------|:----------------|:----------| | `setLoading()` | loading | `isLoading` | | `setSuccess(value)` | success, `value` available | `isSuccess`, `rxState` | | `setError(message)` | error, message stored | `isError` | | `setEmpty()` | empty | `isEmpty` | `clearErrors()` and `hasErrors` belong to the separate `ValidatesRequests` mixin, which a controller adds when it submits forms the backend validates. A controller that caches the rows of one signed-in user or team also implements magic's `SessionScoped`, so a sign-out or a team switch cannot leave the previous session's rows on screen; see [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md). ## Registration Decision Tree ``` Does the controller need to be ready before any view renders? │ ├─ YES → Register eagerly in AppServiceProvider.boot() │ Magic.findOrPut(ProjectController.new); │ Views resolve the same singleton │ └─ NO → Use lazy findOrPut() (default pattern) static ProjectController get instance => Magic.findOrPut(ProjectController.new); The first access registers it Is the controller shared across multiple views? │ ├─ YES → findOrPut(): the same singleton everywhere │ └─ NO → Consider a plain StatefulWidget with a local ChangeNotifier (no container involvement for purely local state) ``` | Scenario | Registration | Example | |:---------|:-------------|:--------| | Data needed right after sign-in (a badge count in the navigation) | Eager, `AppServiceProvider.boot()` | A controller that polls from boot | | Feature data (a project list, a report) | Lazy, `findOrPut()` | `ProjectController`, loaded when its screen mounts | | Single-view transient state (a modal open or closed) | Local `ChangeNotifier` | No container | > [!TIP] > Prefer the lazy pattern for feature controllers. Eager registration is for data that has to exist before any view asks for it. ## Connecting State to Views ### Pattern A: MagicStatefulView Use `MagicStatefulView` for full-page views. Its state class gets `controller` from `Magic.find()`, which throws when the controller was never registered, and it listens to the controller for you. So register the controller before the view mounts: call `instance` in the route builder. ```dart MagicRoute.page('/projects', () { ProjectController.instance; // registers the controller before the view mounts return const ProjectListView(); }); ``` ```dart import 'package:material_ui/material_ui.dart'; import 'package:magic/magic.dart'; import 'package:magic_starter/magic_starter.dart'; class ProjectListView extends MagicStatefulView { const ProjectListView({super.key}); @override State createState() => _ProjectListViewState(); } class _ProjectListViewState extends MagicStatefulViewState { @override void onInit() { controller.loadProjects(); } @override Widget build(BuildContext context) { return controller.renderState( (projects) => _buildList(projects), onEmpty: _buildEmpty(), onError: (message) => _buildError(message), ); } Widget _buildList(List> projects) { return WDiv( className: 'flex flex-col', children: [ MSPageHeader( title: 'Projects', subtitle: 'Manage your projects', actions: [ WButton( onTap: controller.isLoading ? null : controller.loadProjects, className: 'py-2 px-4 rounded-lg bg-primary text-white text-sm', child: WText('Refresh'), ), ], ), WDiv( className: 'flex flex-col gap-2 p-6', children: [ for (final project in projects) MSCard( child: WText( project['name'] as String, className: 'text-gray-900 dark:text-white text-sm', ), ), ], ), ], ); } Widget _buildEmpty() { return WDiv( className: 'flex flex-col items-center justify-center p-12', children: [ WText( 'No projects yet.', className: 'text-gray-500 dark:text-gray-400 text-sm', ), ], ); } Widget _buildError(String message) { return WDiv( className: 'flex flex-col items-center justify-center p-12', children: [ WText(message, className: 'text-sm text-red-500'), ], ); } } ``` `renderState()` picks the builder from the current state: | Argument | Rendered when | |:---------|:--------------| | First positional `(T value) => Widget` | The controller called `setSuccess(value)` | | `onEmpty:` | The controller called `setEmpty()`, or the state is the initial one | | `onError: (String message) => Widget` | The controller called `setError(message)` | | `onLoading:` | The controller called `setLoading()`; without it `renderState()` draws a built-in loading indicator | ### Pattern B: StatefulWidget + Manual Access Use a plain `StatefulWidget` and the `instance` accessor for a non-page widget (a dropdown, a card action, a sub-widget of an existing view): ```dart import 'package:material_ui/material_ui.dart'; import 'package:magic/magic.dart'; import 'package:magic_starter/magic_starter.dart'; class ProjectCountBadge extends StatefulWidget { const ProjectCountBadge({super.key}); @override State createState() => _ProjectCountBadgeState(); } class _ProjectCountBadgeState extends State { late final ProjectController _controller; @override void initState() { super.initState(); _controller = ProjectController.instance; _controller.addListener(_onStateChanged); } @override void dispose() { _controller.removeListener(_onStateChanged); super.dispose(); } void _onStateChanged() => setState(() {}); @override Widget build(BuildContext context) { final count = _controller.rxState?.length ?? 0; return WDiv( className: 'flex items-center gap-1', children: [ WIcon(Icons.folder_outlined, className: 'text-gray-500 text-base'), WText( '$count Projects', className: 'text-sm text-gray-700 dark:text-gray-300', ), ], ); } } ``` > [!NOTE] > `ProjectController.instance` registers the controller on demand through `findOrPut()`. Prefer it to a raw `Magic.find()`, which throws when the controller has not been registered yet. ## Testing Magic's test helpers reset the container between tests and fake the network, so a controller test needs no hand-written driver. `MagicTest.init()` registers the `setUp` and `tearDown` hooks; `Http.fake()` stubs responses by URL pattern (a leading `/` is ignored) and records requests for assertions: ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:magic/magic.dart'; import 'package:magic/testing.dart'; void main() { MagicTest.init(); group('ProjectController', () { late ProjectController controller; setUp(() { controller = ProjectController(); }); tearDown(() { controller.dispose(); }); test('loadProjects success moves to the success state', () async { final fake = Http.fake({ 'api/projects': Http.response({ 'data': [ {'id': 1, 'name': 'Apollo'}, {'id': 2, 'name': 'Borealis'}, ], }), }); await controller.loadProjects(); expect(controller.isSuccess, isTrue); fake.assertSent( (request) => request.method == 'GET' && request.url == '/api/projects', ); }); test('loadProjects 500 moves to the error state', () async { Http.fake({ 'api/projects': Http.response({}, 500), }); await controller.loadProjects(); expect(controller.isError, isTrue); }); test('loadProjects is not re-entrant', () async { final fake = Http.fake({ 'api/projects': Http.response({'data': []}), }); await Future.wait([controller.loadProjects(), controller.loadProjects()]); fake.assertSentCount(1); }); }); } ``` In a test, construct the controller directly (`ProjectController()`) rather than through `instance`: it keeps the test independent of what the container cached. A test that depends on a starter feature flag sets it with `Config.set('magic_starter.features.teams', true)` in `setUp`. The faking API, stub patterns and assertions are in the [Magic testing guide](https://anilcancakir.com/magic/docs/testing/getting-started). ## Complete Example An end-to-end `ProjectList` feature is three files and one route: | File | Holds | |:-----|:------| | `lib/app/controllers/project_controller.dart` | The `ProjectController` from [Implement Async Methods](#implement-async-methods) | | `lib/resources/views/projects/project_list_view.dart` | The `ProjectListView` from [Pattern A](#pattern-a-magicstatefulview) | | `test/app/controllers/project_controller_test.dart` | The test from [Testing](#testing) | The route goes inside the starter's authenticated group, so the page renders in the app shell and shares its layout: ```dart MagicRoute.group( layout: (child) => MagicStarter.view.makeLayout('layout.app', child: child), middleware: ['auth'], layoutId: MagicStarterLayoutIds.app, routes: () { MagicRoute.page('/projects', () { ProjectController.instance; return const ProjectListView(); }); }, ); ``` ## Related Documentation - [Controllers](https://anilcancakir.com/magic/docs/starter/architecture/controllers.md): how the starter's own controllers apply the pattern. - [Service Provider](https://anilcancakir.com/magic/docs/starter/architecture/service-provider.md): the boot sequence, where eager registration belongs. - [Session Scope](https://anilcancakir.com/magic/docs/starter/basics/session-scope.md): resetting a controller when the session changes. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): `MagicStatefulView` and `renderState()` in the starter's views. - [Magic IoC container](https://anilcancakir.com/magic/docs/architecture/service-container): `findOrPut` and the other bindings. --- # wind_kit Theme Adoption `MagicStarter.useWindTheme(WindThemeData)` aligns every built-in starter surface to a `wind_kit` semantic palette in a single call. - [The one-call adoption path](#the-one-call-adoption-path) - [How derivation works](#how-derivation-works) - [The semantic roles](#the-semantic-roles) - [Alias-to-property mapping](#alias-to-property-mapping) - [Navigation](#navigation) - [Modal](#modal) - [Form](#form) - [Card](#card) - [Page header](#page-header) - [Layout](#layout) - [Dropdown](#dropdown) - [Button](#button) - [Field](#field) - [Auth](#auth) - [Install the same WindThemeData as the ambient theme](#install-the-same-windthemedata-as-the-ambient-theme) - [Related Documentation](#related-documentation) Instead of constructing the sub-theme structs by hand, you pass the same `WindThemeData` your app already installs at its root and the starter derives the colour-bearing sub-themes (navigation, modal, form, card, page header, layout, auth, dropdown) from its semantic alias roles. The button theme and the field theme are shape and size only and are set by hand; see [Button](#button) and [Field](#field). ## The one-call adoption path ```dart import 'package:magic_starter/magic_starter.dart'; // In your service provider boot(), before any UI is painted: MagicStarter.useWindTheme( WindThemeData( colors: {'primary': myBrandColor}, aliases: MagicStarterTokens.defaultAliases, // or a design:sync-generated map ), ); ``` `useWindTheme` builds a `MagicStarterTheme` via `MagicStarterTheme.fromWind(...)` and applies it to every field you have not set yourself. A setter called before it is kept field by field; a setter called after it assigns its whole struct, so build that struct from the active theme with `copyWith`, or every field it omits, the derived colours included, goes back to its stock default: - A field counts as yours when its current value differs both from its sub-theme's default constructor value and from what the previous `useWindTheme` call derived for it. Yours are kept; every other field takes the derived value, so a second call with another palette re-skins what the first derived. - A field set to exactly its stock default, or to exactly what the previous `useWindTheme()` derived for it, reads as unset, and the next `useWindTheme()` replaces it; to keep such a value, set a different one, or set it again after `useWindTheme()` with `copyWith`. - Every individual `use*Theme()` setter (`useCardTheme`, `useFormTheme`, ...) still assigns its whole struct, so fine-tune one field of the derived theme with `copyWith`: `MagicStarter.useLayoutTheme(MagicStarter.layoutTheme.copyWith(navigationBreakpoint: 'sm'))`. - `MagicStarter.useTheme(MagicStarterTheme)` still replaces every sub-theme whole. ## How derivation works Every colour-bearing className fragment in the sub-theme defaults is rebuilt from the semantic roles. Because each alias carries its own `dark:` counterpart (for example `bg-surface` expands to `bg-white dark:bg-gray-950`), a single semantic token replaces every hand-written `bg-white dark:bg-gray-800` pair. No manual `dark:` palette utility is emitted. A role is emitted as a semantic token only when the passed `WindThemeData` defines it, either as a key in its `aliases` map or as the backing colour key in its `colors` map (`bg-primary` is backed by the `primary` colour). When the theme does not define a role, the property keeps the shipped default palette pair for that role, so a partially-configured theme never produces a silent no-op (invisible) surface. Pair `useWindTheme` with a full alias map to re-skin every surface. ## The semantic roles The role tokens match the `MagicStarterTokens.defaultAliases` contract. Generate a full alias map from a `DESIGN.md` with `dart run magic:dowel design:sync`, documented in the [Magic CLI](https://anilcancakir.com/magic/docs/packages/magic-cli). | Role token | Purpose | |:-----------|:--------| | `bg-surface` | Page and base backgrounds | | `bg-surface-container` | Cards, panels, dialog containers | | `bg-surface-container-high` | Input backgrounds, nested panels, hover fills | | `text-fg` | Primary text | | `text-fg-muted` | Secondary and muted text | | `text-fg-disabled` | Placeholder and disabled text | | `bg-primary` / `text-primary` | Brand action background and brand text | | `text-on-primary` | Text and icons on the primary surface | | `border-color-border` | Dividers and card borders | | `border-color-border-subtle` | Hairline borders (brand bar) | | `bg-destructive` / `text-on-destructive` | Danger action surface and its text | | `bg-destructive-container` | Tinted danger surface (error banners) | | `text-destructive` | Inline error text (falls back to red when undefined) | | `bg-warning` | Warning action surface | | `text-on-success` / `text-on-warning` | Text and icons on `bg-success` / `bg-warning` (when undefined, `MSToast` picks white or near-black by measured contrast against the fill) | A host that defines `text-destructive` (as an alias, or through a `destructive` colour) re-skins the outlined danger buttons, the destructive `MSSettingsRow` title and the inline error text; without it they fall back to the red pair. `MagicStarterTokens.role(theme, token)` is the lookup they share. `MSToast` is the one place that reads `text-on-success` and `text-on-warning`: its success and warning variants paint the message, the action label and the focus ring in them (the error variant reads `text-on-destructive`). The alias contract ships the fills and not these two roles, so a host that defines its own `bg-success` and `bg-warning` defines them beside the fills, and a host whose dark fills are light (a pale green on a dark surface) writes dark text for the dark half. A role the host does not define is not assumed to suit the stock fills: the toast resolves the fill it paints in the current mode and takes the better of white and near-black by WCAG contrast, so the stock green and amber get near-black and a mid-dark green gets white. A role the host defines is used as written, poor contrast included. ## Alias-to-property mapping Each sub-theme property below is rebuilt from the listed semantic roles. Layout, spacing, radius, and dimension tokens are preserved as-is. ### Navigation | Property | Roles used | |:---------|:-----------| | `activeItemClassName` | `text-primary` (+ `bg-primary/10`) | | `hoverItemClassName` | `bg-surface-container-high` | | `brandClassName` | `text-primary` | | `bottomNavActiveClassName` | `text-primary` | | `avatarTextClassName` | `text-primary` | ### Modal | Property | Roles used | |:---------|:----------| | `containerClassName` | `bg-surface-container` | | `titleClassName` | `text-fg` | | `descriptionClassName` | `text-fg-muted` | | `footerClassName` | `bg-surface-container-high` | | `primaryButtonClassName` | `bg-primary`, `text-on-primary` | | `secondaryButtonClassName` | `bg-surface-container`, `border-color-border`, `bg-surface-container-high`, `text-fg` | | `dangerButtonClassName` | `bg-destructive`, `text-on-destructive` | | `warningButtonClassName` | `bg-warning` | | `errorClassName` | `text-destructive` | | `inputClassName` | `bg-surface-container-high`, `border-color-border`, `text-fg` | ### Form | Property | Roles used | |:---------|:----------| | `inputClassName` | `bg-surface-container-high`, `border-color-border`, `text-fg` | | `labelClassName` | `text-fg` | | `errorClassName` | `text-destructive` | | `placeholderClassName` | `text-fg-disabled` | | `primaryButtonClassName` | `bg-primary`, `text-on-primary` | | `secondaryButtonClassName` | `text-fg-muted`, `bg-surface-container` (hover); the border is the button theme's | | `linkClassName` | `text-primary` | | `checkboxLabelClassName` | `text-fg-muted`, `text-fg` | ### Card | Property | Roles used | |:---------|:----------| | `surfaceClassName` | `bg-surface`, `border-color-border` | | `insetClassName` | `bg-surface-container`, `border-color-border` | | `elevatedClassName` | `bg-surface` (+ `shadow-md`) | | `titleClassName` | `text-fg` | ### Page header | Property | Roles used | |:---------|:----------| | `containerClassName` / `containerInlineClassName` | `border-color-border` | | `titleClassName` | `text-fg` | | `subtitleClassName` | `text-fg-muted` | | `backControlClassName` | `text-fg-muted`, `text-fg` | ### Layout | Property | Roles used | |:---------|:----------| | `sidebarClassName` | `bg-surface`, `border-color-border` | | `headerClassName` | `bg-surface`, `border-color-border` | | `brandBarClassName` | `border-color-border-subtle` | | `contentBackground*` and `drawerBackground*` | `bg-surface` | The content and drawer backgrounds are `wColor()` colour keys rather than classNames, so each half of the `bg-surface` role is read down to a colour name (or a `#hex`) and a shade: `bg-ink-50 dark:bg-[#0E0F11]` gives a light `ink`/`50` and a dark `#0E0F11`. Where the role names two backgrounds for one brightness, the last one is read, as Wind paints it. A role with no `dark:` utility uses its light one in both modes. A host that sets a colour or its shade keeps both halves of that pair. A half that does not resolve (an opacity step, a colour the theme does not carry), or a theme that does not define `bg-surface`, keeps the stock key. Numeric dimensions (`sidebarWidth`, `headerHeight`) keep their defaults. ### Dropdown The panels of `MSTeamSelector` and `MSUserProfileDropdown`. This is its own sub-theme, not more fields on `navigation`, because a host that sets a new `MagicStarterNavigationTheme` after `useWindTheme()` replaces the navigation theme whole and would hand any field it omitted back to the stock grey (`MagicStarter.navigationTheme.copyWith(...)` avoids that). | Property | Roles used | |:---------|:----------| | `panelClassName` | `bg-surface-container`, `border-color-border` | | `dividerClassName` | `border-color-border` | | `itemClassName` | `bg-surface-container-high` (hover) | | `tileClassName` | `bg-surface` | | `textClassName` | `text-fg` | | `mutedTextClassName` | `text-fg-muted` | | `dangerTextClassName` | `text-destructive` (danger state) | | `dangerTileClassName` | `bg-destructive-container` (danger state) | The tile takes `bg-surface` rather than `bg-surface-container-high` because the hovered row is already `bg-surface-container-high`; a tile with that fill would disappear into it. Geometry, including the `overflow-hidden` that keeps a hovered row inside the panel's rounded corners, stays in the widgets. Keep a border in `panelClassName`, even an invisible one (`border border-transparent`), for the panel's shadow to survive: Wind clips a bordered box inside the border, while a borderless one gets a `ClipRRect` around the decorated container, which cuts the box shadow off. ### Button Nothing is derived. `MSButton`'s recipe already writes the semantic aliases (`bg-primary`, `text-on-primary`, `border-color-border`, ...) itself, so an alias map re-skins every button, and `MagicStarterButtonTheme` carries only what an alias cannot: the corner radius, the padding, minimum height and label type of each size, and the secondary border. `useWindTheme()` keeps a button theme you set on either side of it; `useTheme()` resets it to its defaults, so set it after that. | Property | Default | |:---------|:--------| | `shapeClassName` | `rounded-lg` | | `smClassName` | `px-3 py-1.5 text-sm` | | `mdClassName` | `px-4 py-2 text-sm` | | `lgClassName` | `px-5 py-3 text-base` | | `secondaryBorderClassName` | `border border-color-border` | One 44 px capsule for every intent and size: ```dart const standard = 'px-5 py-[11px] text-[17px] leading-[22px] font-semibold'; MagicStarter.useButtonTheme( MagicStarterButtonTheme( shapeClassName: 'rounded-full', smClassName: standard, mdClassName: standard, lgClassName: standard, secondaryBorderClassName: '', ), ); ``` Three things to know: - **Use vertical padding around a fixed line height, not `min-h-11`.** A Wind button gives its box the minimum height and no alignment (`items-center` is ignored for a single child, and `justify-center` would stretch the button to fill its parent), so the label sits at the top of a `min-h-11` box. `py-[11px]` around `leading-[22px]` is 44 px with the label centred, and still grows with the platform text size. - **Drop the secondary border in a fixed-height design.** A border adds its width to the box, so a secondary that keeps it is 2 px taller than the rest. `''` removes it; `border-0` would leave a hairline. `buttonDangerOutlineClassName` only recolours that border. - **A `className` on a button wins, so two things never follow the theme.** The `className` is appended after it. The auth screens pass the form theme's `primaryButtonClassName` to an `lg` button, and the social and step-up buttons its `secondaryButtonClassName` and the guest button the auth theme's `guestButtonClassName` to a `secondary` `md` one. Those strings, stock and as `useWindTheme()` derives them, carry no `rounded-*`, `py-*`, `text-` or border token, only the full width, the colours, the label weight of the primary and the hover opacity of the secondary ones, so the auth screens follow the button theme. The first exception is a host's OWN strings: a `useFormTheme()` or `useAuthTheme()` call whose button strings name a shape, a padding or a label size keeps it, because the string wins. Leave those out, and change one string through `copyWith` rather than a new `MagicStarterFormTheme`, which would hand every other field back to its default: `MagicStarter.useFormTheme(MagicStarter.formTheme.copyWith(primaryButtonClassName: ...))`. The second is the dialogs, and the invite button of the team settings page: they draw raw `WButton`s on the strings of `MagicStarterModalTheme` and do not read the button theme at all. Below `lg` every `MSButton` sits in a 44 x 44 hit area. A size the theme makes 44 px tall or more is not widened by it, so there is no extra layout and no extra reach. ### Field Nothing is derived either. The recipes of `MSInput`, `MSSelect`, `MSCombobox` and `MSSegmentedControl` write their colours, borders and radius as semantic aliases, and `MagicStarterFieldTheme` carries only the height and the type: one string per control, each the run of padding, minimum height and text size the recipe used to spell out. `useWindTheme()` keeps a field theme you set on either side of it; `useTheme()` resets it to its defaults, so set it after that. | Property | Control | Default | |:---------|:--------|:--------| | `inputSizeClassName` | `MSInput`: text, placeholder and typed value | `py-3 lg:py-2.5 text-sm leading-5` (44 px, 40 px from `lg`) | | `selectSizeClassName` | trigger of `MSSelect`, `MSCombobox` and the timezone select | `py-[9px] min-h-11 lg:min-h-0` (44 px, 40 px from `lg`) | | `segmentedSmClassName` | `MSSegmentedControl` `sm` pill | `px-2 py-1 text-sm` (28 px) | | `segmentedMdClassName` | `MSSegmentedControl` `md` pill | `px-3 py-1.5 text-sm` | | `segmentedPaddingClassName` | `MSSegmentedControl` root | `p-1` | One 44 px standard with 17 on 22 type for every control: ```dart MagicStarter.useFieldTheme( MagicStarterFieldTheme( inputSizeClassName: 'py-[11px] text-[17px] leading-[22px]', selectSizeClassName: 'py-2.5 text-[17px] leading-[22px]', segmentedSmClassName: 'py-[7px] text-[17px] leading-[22px]', segmentedMdClassName: 'py-[7px] text-[17px] leading-[22px]', segmentedPaddingClassName: 'px-1 py-0 lg:py-1', ), ); ``` Four things to know: - **The string replaces the run, so state all of it.** The default input string is `py-3 lg:py-2.5 text-sm leading-5`; a host string that names `py-[11px]` only would leave `text-sm` and `leading-5` out of the box, not inherit them. The side padding (`px-3`), the colours and the border stay in the recipe. - **Each control needs its own padding for 44 px.** A text input paints its border inside its padding, so it adds no height: `py-[11px]` around `leading-[22px]` is 44, and `py-2.5` is 42. A select or combobox trigger is a Wind box whose border adds to its size, so `py-2.5` around the same line plus the two border pixels is 44. Reach both with vertical padding around a fixed `leading-*`, which also centres the text, rather than with `min-h-11` alone. - **The placeholder follows the input.** It inherits the field's text size and line height, so `inputSizeClassName` sets the placeholder and the typed value together and there is no placeholder field. - **The segmented root needs `segmentedPaddingClassName` for 44 px at every width.** Below `lg` each segment sits in a 44 px hit cell, so a control with the default `p-1` root is 52 px tall on a phone whatever the pill size. A 36 px pill (`py-[7px]` around the line) in a root of `px-1 py-0 lg:py-1` is 44 px everywhere: the hit cell supplies the 4 px above and below the pill on a phone, and the root does from `lg` up. A `className` (or the `classNames` of a slot) handed to a control is appended after the theme and wins on any family it names. `MSTextarea` and the option rows of the select and combobox menus are outside the field theme. The auth, profile and settings forms are outside it too. They draw `WFormInput`s on `MagicStarterFormTheme.inputClassName`, whose default carries `py-3`, and the starter's own `WFormSelect`s read the same string for their trigger: the role select of the team settings page (`magic_starter_team_settings_view.dart`), the language select of the profile settings view (`magic_starter_profile_settings_view.dart`) and the language preference view (`magic_starter_language_view.dart`). A host sets that one string with `MagicStarter.useFormTheme(MagicStarter.formTheme.copyWith(inputClassName: ...))`, and one string has to serve an input and a select, which reach 44 px differently: an input paints its border inside its padding and a select trigger adds it. With 17 on 22 type: | `inputClassName` size run | `WFormInput` | `WFormSelect` | |:--------------------------|:-------------|:--------------| | `py-[11px] text-[17px] leading-[22px]` | 44 | 46 | | `py-2.5 text-[17px] leading-[22px]` | 42 | 44 | | `py-[10px] min-h-11 text-[17px] leading-[22px]` | 44 | 44 | The third is the one string that gives both 44 px: the select is 10 + 22 + 10 + 2 and the minimum height lifts the input from 42 to 44, where it centres its single line (the line box measures dead centre in the test font; a real font's glyphs can sit a pixel off the middle of a taller box). The heights are line boxes measured in a widget test (`test/configuration/magic_starter_form_theme_input_test.dart`), which pins all three rows of the table, and the 22 px line centred in the 44 px box at 390 and 1440 in light and dark. A bare `min-h-11` does pin the label of a `WButton` to the top of its box, which is why buttons reach 44 px with padding around a fixed line height; a `WInput` and a `WFormSelect` trigger centre their one line, so for them the minimum height is safe. The two agree at the default text size only: once a larger text setting lifts the line past the minimum height, the select trigger is 2 px taller than the input, because its border adds to the padding where the input's sits inside it. ### Auth | Property | Roles used | |:---------|:----------| | `cardClassName` | `bg-surface-container`, `border-color-border` | | `titleClassName` | `text-fg` | | `subtitleClassName` | `text-fg-muted` | | `errorBannerClassName` | `bg-destructive-container`, `text-destructive` | | `themeToggleClassName` | `bg-surface-container-high` (hover) | | `themeToggleIconClassName` | `text-fg-muted` | | `socialDividerTextClassName` | `text-fg-muted` | | `guestButtonClassName` | `text-fg-muted`, `bg-surface-container` (hover); the border is the button theme's | | `registrationLinkClassName` | `text-fg-muted` | | `registrationLinkTextClassName` | `text-primary` | ## Install the same WindThemeData as the ambient theme `useWindTheme` derives className strings that reference semantic alias tokens (`bg-surface`, `text-fg`, `bg-primary`, ...). Those tokens only resolve to your palette when the SAME `WindThemeData` is installed as the ambient `WindTheme` that renders the app. `useWindTheme` maps the roles onto the component properties; the ambient `WindTheme` is what expands the tokens at paint time. For any role the passed theme does not define, the derivation falls back to the shipped default palette pair (so an omitted role never produces an invisible surface), but a defined role that is missing from the ambient `WindTheme` will render its bare token unresolved. ## Related Documentation - [Manager](https://anilcancakir.com/magic/docs/starter/architecture/manager.md): `useTheme()`, the sub-theme setters and their defaults. - [Components](https://anilcancakir.com/magic/docs/starter/basics/components.md): the semantic token layer the `MS` components write. - [Views and Layouts](https://anilcancakir.com/magic/docs/starter/basics/views-and-layouts.md): Wind UI conventions in the starter's views. - [Magic CLI](https://anilcancakir.com/magic/docs/packages/magic-cli): `design:sync`, which generates an alias map.