# Brand and dark mode

> A recipe — one screen answering one question.

One seed generates the whole palette, for both themes. Nothing below names a colour, which is why the switch needs no rebuild.

- Framework: CrossFly (Java; one source for Android, iOS, desktop (Windows, macOS and Linux) and the web — Chrome, Firefox, Safari and other browsers)
- Entry point: `dev.cf.recipe.R29Brand`
- Topics: theming
- Run it locally: `gradlew lwjgl3:run --args="classname dev.cf.recipe.R29Brand"`
- Run it in a browser: https://crossfly.dev/playground/index.html?ex=brand
- Page: https://crossfly.dev/examples/brand

## What this shows

Declaring a brand: one seed, and everything else follows.

You do not pick colours in a CrossFly app. You declare one seed, and the framework derives the
rest — primary and what reads on it, surfaces, containers, outlines, the tonal fill behind an
active tab, both themes. Tap the swatches below: nothing on this screen is rebuilt, and every
colour moves at once, because none of them was ever written down.

**Skip this and your app is not "unstyled", it is grey** — the skin's neutral palette is
what you get when nobody declared anything, and it reads as a rendering bug rather than as a
default. That is the first thing to check when a screen looks broken and nothing is broken.

Two calls, and the difference between them matters exactly once. `setBrand` restyles
every open window; `setBrandSilent` does not, and exists for code running before there is
anything to restyle — class initialisation, the line before the first window is shown.

## Framework types it uses

`Button`, `Card`, `ColorScheme`, `Component`, `Gap`, `HorizontalLayout`, `Styles`, `Switch`, `TextField`, `Widgets`

## Source

### dev/cf/recipe/R29Brand.java

```java
package dev.cf.recipe;

import dev.crossfly.ui.*;
import dev.crossfly.ui.color.ColorScheme;
import dev.crossfly.ui.graphics.*;
import dev.crossfly.ui.layout.*;
import dev.crossfly.ui.style.*;

import static dev.crossfly.ui.Widgets.*;

/**
 * Declaring a brand: one seed, and everything else follows.
 *
 * <p>You do not pick colours in a CrossFly app. You declare one seed, and the framework derives the
 * rest — primary and what reads on it, surfaces, containers, outlines, the tonal fill behind an
 * active tab, both themes. Tap the swatches below: nothing on this screen is rebuilt, and every
 * colour moves at once, because none of them was ever written down.</p>
 *
 * <p><b>Skip this and your app is not "unstyled", it is grey</b> — the skin's neutral palette is
 * what you get when nobody declared anything, and it reads as a rendering bug rather than as a
 * default. That is the first thing to check when a screen looks broken and nothing is broken.</p>
 *
 * <p>Two calls, and the difference between them matters exactly once. {@code setBrand} restyles
 * every open window; {@code setBrandSilent} does not, and exists for code running before there is
 * anything to restyle — class initialisation, the line before the first window is shown.</p>
 */
public class R29Brand extends Recipe
{
   /** A few seeds. Any ARGB works: the palette is generated, not looked up. */
   private static final int[] SEED = { 0xFF1565C0, 0xFFE2622C, 0xFF2E7D32, 0xFF6A1B9A,
      0xFFB71C1C };
   private static final String[] SEED_NAME = { "Blue", "Orange", "Green", "Purple", "Red" };

   /** What was in force when this recipe opened, so it can be handed back. */
   private Integer previousBrand;
   private ColorScheme previousScheme;

   public String title()
   {
      return "Brand and dark mode";
   }

   public String note()
   {
      return "One seed generates the whole palette, for both themes. Nothing below names a colour,"
         + " which is why the switch needs no rebuild.";
   }

   public void build(Component body) throws Exception
   {
      remember();

      body.add(LAY_AUTO, outgap(label("THE SEED", 1f, true, Styles.captionColor, Position.START), 0,
         0, 0, .5f));

      Component swatches = new Component();
      swatches.setLayout(new HorizontalLayout(Position.START, Position.CENTER));
      for (int i = 0; i < SEED.length; i++)
      {
         final int seed = SEED[i];
         Button b = new Button(SEED_NAME[i]);
         b.getStyle()
            .backColor(seed)
            .textColor(0xFFFFFFFF)
            .outgap(Gap.ofFont(0, 0, .4f, 0));
         b.onAction(c -> Styles.setBrand(seed));
         swatches.add(LAY_AUTO, b);
      }
      body.add(LAY_AUTO, outgap(swatches, 0, 0, 0, 1f));

      Switch dark = new Switch("Dark mode");
      dark.checked(Styles.isDarkMode());
      // One call. Every PalColor token re-resolves in place and every window is restyled — no
      // screen tracks a flag of its own, and none rebuilds.
      dark.onAction(c -> Styles.setDarkMode(dark.isChecked()));
      body.add(LAY_AUTO, outgap(dark, 0, 0, 0, 1.2f));

      body.add(LAY_AUTO, outgap(label("WHAT FOLLOWS, WITHOUT BEING TOLD", 1f, true,
         Styles.captionColor, Position.START), 0, 0, 0, .5f));

      Card c = new Card();
      c.add(LAY_AUTO, label("A card on a surface", 1.2f, true, Styles.textColor, Position.START));
      c.add(LAY_AUTO, outgap(label("Caption text, the tone below the title.", 1f, false,
         Styles.captionColor, Position.START), 0, .2f, 0, .5f));
      c.add(LAY_AUTO, outgap(new TextField().caption("A field"), 0, 0, 0, .5f));
      c.add(LAY_AUTO, outgap(new Button("A button"), 0, 0, 0, .5f));
      Component chips = new Component();
      chips.setLayout(new HorizontalLayout(Position.START, Position.CENTER));
      chips.add(LAY_AUTO, outgap(toneBadge(Styles.primaryColor, "primary"), 0, 0, .4f, 0));
      chips.add(LAY_AUTO, outgap(toneBadge(secondary(), "secondary"), 0, 0, .4f, 0));
      chips.add(LAY_AUTO, toneBadge(tertiary(), "tertiary"));
      c.add(LAY_AUTO, chips);
      body.add(LAY_AUTO, c);
   }

   /**
    * Snapshots the palette, so leaving this recipe does not repaint the app it was opened from.
    *
    * <p>A <b>copy</b>, never the reference: {@link Styles} keeps one {@link ColorScheme} instance
    * for the life of the app and mutates its roles in place on every seed change — deliberately, so
    * that a {@code PalColor} captured into a style at build time keeps resolving. Save the
    * reference and you have saved the object that is about to be overwritten.</p>
    */
   private void remember()
   {
      previousBrand = Styles.hasBrand() ? Integer.valueOf(Styles.brand()) : null;
      ColorScheme live = Styles.colorScheme();
      if (live != null)
      {
         previousScheme = ColorScheme.fromSeed(SEED[0], live.isDark);
         previousScheme.copyFrom(live);
      }
   }

   @Override
   public void onRemove()
   {
      super.onRemove();
      if (previousBrand != null)
         Styles.setBrand(previousBrand.intValue());
      else
      {
         Styles.clearBrand();
         if (previousScheme != null)
            Styles.setColorScheme(previousScheme);
      }
   }
}
```

## Shared scaffolding

Not part of this recipe, but read by it: the base class every recipe inherits its top bar and scrolling body from.

### dev/cf/recipe/Recipe.java

```java
package dev.cf.recipe;

import dev.cf.*;
import dev.crossfly.ui.*;
import dev.crossfly.ui.graphics.*;
import dev.crossfly.ui.layout.*;
import dev.crossfly.ui.skin.*;
import dev.crossfly.ui.style.*;

import static dev.crossfly.ui.Widgets.*;

/**
 * Base of a <b>recipe</b>: one screen that shows one thing, and nothing else.
 *
 * <p>A recipe is not a sample. A sample shows a component with all its knobs; a recipe answers a
 * question somebody actually has — "how do I put a filter sheet over a list?", "how do I make this
 * follow the theme?" — in as few lines as it takes, so the answer can be read in one screen and
 * copied without editing.</p>
 *
 * <p>That is the whole design constraint: <b>the boilerplate lives here, the substance lives in the
 * subclass.</b> A recipe that spends twenty lines building a title bar teaches the title bar.</p>
 *
 * <p>Write one as:</p>
 *
 * <pre>
 * public class MyRecipe extends Recipe
 * {
 *    public String title() { return "What this shows"; }
 *    public String note()  { return "The one sentence worth knowing."; }
 *
 *    public void build(Component body) throws Exception
 *    {
 *       body.add(LAY_AUTO, new Button("Tap"));
 *    }
 * }
 * </pre>
 */
public abstract class Recipe extends SampleWindow implements Described
{
   @Override
   public abstract String title();

   /**
    * The one thing a reader should take away — printed above the recipe, in caption tone.
    *
    * @return the note, or null for none
    */
   @Override
   public String note()
   {
      return null;
   }

   /**
    * Builds the recipe.
    *
    * @param body a vertical, scrollable container with sensible padding — add to it and stop
    * @throws Exception when building fails
    */
   public abstract void build(Component body) throws Exception;

   @Override
   public void onAdd(boolean firstTime) throws Exception
   {
      addTopBar(title());

      // The page, not the surface. addTopBar just set fullscreenColor to the surface,
      // and on a white page a white card has no edges — see Tones.page(). Re-derived on restyle so
      // a dark-mode flip does not leave the light page behind.
      fullscreenColor = Tones.page();
      onRestyle(() -> fullscreenColor = Tones.page());

      contents.setLayout(new VerticalLayout(Position.START, Position.START));
      contents.getStyle()
         .ingap(Gap.ofFont(1f, 1f, 1f, 1f));

      String n = note();
      if (n != null)
         contents.add(LAY_AUTO, outgap(nota(n), 0, 0, 0, 1f));

      Component body = new Component();
      body.setLayout(new VerticalLayout(Position.START, Position.START));
      body.setScrollable(ScrollDirection.VERTICAL);
      body.testTag("recipe.body");
      contents.add(LAY_FILL, body);
      build(body);
      if (pinned != null)
      {
         // Measured again once its labels have sizes: the band's AUTO height is taken in the first
         // layout, before them, and on the iPhone it showed only its first line - the odometer's
         // "No text recognizer on this device." was set and never seen (17/10/2026).
         final Component band = pinned;
         onUI(band::invalidateMeasure);
      }
      if (pinned != null)
         body.add(LAY_AUTO, new Component()
         {
            @Override
            public int getAutoHeight()
            {
               // Room for the last row to scroll clear of the floating band.
               return pinned.getAutoHeight();
            }
         });
   }

   /**
    * The note, as a tinted band rather than three lines of grey.
    *
    * <p>It is the one sentence the reader is meant to leave with, and it used to be the least
    * legible thing on the screen: caption-coloured, caption-sized, indistinguishable from the
    * captions further down that are only labels. A tone and a glyph cost nothing here — nobody has
    * to read the band to know what it is.</p>
    *
    * @param n the note text
    * @return the band
    * @throws Exception when building fails
    */
   /**
    * Pins {@code c} to the bottom of the screen, in a band that FLOATS over the scrolling body: it
    * stays on screen however far the body is scrolled, and the body scrolls underneath it. That is the
    * place a recipe says what just happened. An answer at the top of the body went out of view as soon
    * as the person scrolled down to the button that produced it (14/10/2026).
    * <p>
    * The band is 80% OPAQUE (the surface at alpha 0xCC), as the user asked; it floats rather than
    * sitting below the body because a transparency with nothing behind it cannot be seen -- the first
    * version had the band under the body, and the person saw a plain bar. The body gets a spacer as
    * tall as the band at its end, so its last row can still scroll clear of it.
    *
    * @param c the component to pin, usually the answer label
    * @return {@code c}, to chain
    * @throws Exception if the layout refuses
    */
   protected <T extends Component> T pin(T c) throws Exception
   {
      Component band = new Component();
      band.setLayout(new VerticalLayout(Position.START, Position.START));
      band.style(Skin.get()
         .card()
         .backColor(Styles.backColor.withAlpha(0xCC))
         .borderColor(Styles.borderColor.withAlpha(0x33))
         .borderRadius(0)
         .shadow(0, 0, 0, 0)
         .ingap(Gap.ofFont(1f, 1f, 1f, 1.2f))
         .outgap(Gap.ofFont(0)));
      band.add(LAY_AUTO, c);
      // Floated: positioned at the bottom, full width, over whatever the body has there.
      band.setRelativeBounds(Relative.START, Relative.END, Relative.FULL, Relative.AUTO);
      contents.add(LAY_AUTO, band);
      pinned = band;
      return c;
   }

   /** The floating band {@link #pin} made, or null; the body ends in a spacer as tall as it. */
   private Component pinned;

   private Component nota(String n) throws Exception
   {
      Component band = new Component();
      band.setLayout(new GridLayout(Position.START, Position.START));
      band.style(Skin.get()
         .card()
         .backColor(Tones.accent().withAlpha(0x16))
         .borderColor(Tones.accent().withAlpha(0x4A))
         .shadow(0, 0, 0, 0)
         .outgap(Gap.ofFont(0)));
      // 0xE88E is the outlined "info". The glyph column hugs; the text takes the rest and wraps.
      // The weights are GridLayout's own — 0f hugs, 1f takes what is left. LAY_FILL belongs to the
      // vertical and horizontal layouts and means nothing here: it collapsed the text to nothing.
      band.add(LAY_AUTO, 1f, matglyph(0xE88E, Tones.accent(), 1.05f),
         outgap(label(n, 1f, false, secondary(), Position.START), .5f, 0, 0, 0));
      return band;
   }
}
```

### dev/cf/SampleWindow.java

```java
package dev.cf;

import dev.crossfly.ui.*;
import dev.crossfly.ui.graphics.*;
import dev.crossfly.ui.layout.*;
import dev.crossfly.ui.style.*;

import static dev.cf.sample.CrossFlySamplesColors.*;

/**
 * Base class for all CrossFly sample windows.
 * <p>
 * Provides common infrastructure:
 * <ul>
 *   <li>Shared color palette and styles from {@link dev.cf.sample.CrossFlySamplesColors}</li>
 *   <li>{@link #addTopBar(String, Button...)} — standard deep-indigo top bar with back button</li>
 *   <li>{@link #barButton(String, Runnable)} — helper to create icon buttons for the bar</li>
 * </ul>
 *
 * <h3>Usage</h3>
 * <pre>
 * public class MySample extends SampleWindow {
 *     public void onAdd(boolean firstTime) throws Exception {
 *         if (!firstTime) return;
 *         initWindow();
 *         addTopBar("My Sample");
 *         // ... add content
 *     }
 * }
 * </pre>
 */
public abstract class SampleWindow extends Window
{
   /** The main content area of the window, added by {@link #addTopBar(String, Button...)}, for subclasses to add their content into. */
   protected Component contents;

   // ─── Top bar ─────────────────────────────────────────────────────────────

   /**
    * Builds and adds a standard top bar with a back (←) button on the left,
    * a centered title, and any optional extra buttons on the right.
    *
    * @param title        the text shown in the bar
    * @param rightButtons zero or more icon buttons placed aligned to the right
    * @throws Exception if component construction fails
    */
   protected void addTopBar(String title, Button... rightButtons) throws Exception
   {
      fullscreenColor = Styles.backColor.color();
      setLayout(new VerticalLayout());
      add(0f, buildTopBar(title, rightButtons));
      add(LAY_FILL, contents = new Component());
      contents.getStyle()
         .ingap(Gap.ofFont(0, .5f, 0, .5f));
   }

   /**
    * Same as {@link #addTopBar(String, Button...)}, but returns the bar component
    * instead of adding it, for callers that need to position it manually.
    *
    * @param title        the bar title
    * @param rightButtons optional right-side icon buttons
    * @return the assembled top-bar {@link Component}
    * @throws Exception if component construction fails
    */
   protected Component buildTopBar(String title, Button... rightButtons) throws Exception
   {
      Button btBack = barButton("\ue5c4", this::hide);   // arrow_back
      btBack.testTag("sample.back");
      // Padded on every side, like the bar's right buttons: with none above and below, the target
      // was the arrow itself, too small to hit on a small phone (iPhone 5s, 17/10/2026).
      btBack.getStyle()
         .ingap(Gap.ofFont(.75f))
         .outgap(Gap.ofFont(0, 0, .25f, 0));

      Component bar = new Component().style(barStyle);
      bar.setLayout(new GridLayout(Position.START, Position.CENTER));

      int n = 2 + rightButtons.length;
      Object[] params = new Object[n * 2];
      params[0] = 0f;
      params[1] = 1f;
      for (int i = 0; i < rightButtons.length; i++)
         params[2 + i] = 0f;
      params[n] = btBack;
      params[n + 1] = new Label(title).style(barTitleStyle);
      for (int i = 0; i < rightButtons.length; i++)
      {
         params[n + 2 + i] = rightButtons[i];
         rightButtons[i].getStyle()
            .ingap(Gap.ofFont(.75f));
      }

      bar.add(params);
      return bar;
   }

   /**
    * Creates a standard bar icon button (transparent, white icon, pressed feedback).
    *
    * @param materialIcon the Material Icon unicode codepoint string
    * @param action       the action to run when the button is tapped
    * @return the configured {@link Button}
    */
   protected Button barButton(String materialIcon, Runnable action)
   {
      return new Button(new MaterialIcon(materialIcon)).style(barButtonNormal)
         .pressedStyle(barButtonPressed)
         .onAction(e -> action.run());
   }
}
```
