# Themes

A theme holds the colors, fonts and sizes of your app and the settings of the catalog components. Components read the theme when Ludic renders their styles, so a change in the theme restyles every component that uses it, without any CSS.

Ludic has two themes in `ludic.styles.themes`: `LightTheme`, the default, and `DarkTheme`.

## Create a Theme

Subclass `LightTheme` or `DarkTheme` as a dataclass, give it a new name and override the fields you want to change. A field that holds another dataclass, such as `colors`, needs a `default_factory`:

```python
from dataclasses import dataclass, field

from ludic.styles import themes
from ludic.styles.types import ColorRange


@dataclass
class BrandTheme(themes.LightTheme):
    name: str = "brand"

    colors: themes.Colors = field(
        default_factory=lambda: themes.Colors(
            primary=ColorRange(["#1e3a8a", "#1d4ed8", "#dbeafe"]),
        )
    )
    fonts: themes.Fonts = field(
        default_factory=lambda: themes.Fonts(
            primary="Inter, sans-serif",
            secondary="Inter, sans-serif",
        )
    )
```

For a small change, create a theme with keyword arguments:

```python
from ludic.styles import themes
from ludic.styles.types import Color

theme = themes.LightTheme(
    name="brand",
    buttons=themes.Buttons(
        color=Color("#1d4ed8"), background_color=Color("#dbeafe")
    ),
)
```

> **Give every theme its own name**
>
> Ludic caches the rendered styles by the name of the theme, so two themes with the same name would share their styles.

## Apply a Theme

Make your theme the default when the app starts, with `set_default_theme`. All components then use it:

```python
from ludic.styles.themes import set_default_theme
from ludic.web import LudicApp

from my_app.themes import BrandTheme

set_default_theme(BrandTheme())

app = LudicApp()
```

Set the default theme even when you also pass the theme to `Head(theme=...)`. `Head` renders the collected styles with it, but the styles that components compute while they render come from the default theme. For example, `CodeBlock` picks the colors of highlighted code and of line numbers this way.

### Dark Mode

Pass a second theme to `Head` as `dark_theme`. Its styles apply when the visitor's system is in dark mode, and `ColorSchemeToggle` lets the visitor switch by hand. The browser remembers the choice.

```python
from ludic.catalog.pages import Body, ColorSchemeToggle, Head, HtmlPage
from ludic.catalog.typography import Paragraph
from ludic.styles.themes import DarkTheme, LightTheme, set_default_theme

light = LightTheme()
dark = DarkTheme()
set_default_theme(light)

page = HtmlPage(
    Head(title="My App", theme=light, dark_theme=dark),
    Body(ColorSchemeToggle(), Paragraph("Hello!")),
)
```

The styles that components compute while they render come from the default theme in both schemes. Keep the settings they read the same in both themes, e.g. give both themes the same `code` settings with a dark background.

### A Part of a Page

`theme.use(element)` sets the theme that `self.theme` returns in the element and its children. It does not change the collected styles, which the page renders once with its own theme.

## Settings

These are the fields of a theme. Their default values are in [ludic/styles/themes.py](https://github.com/getludic/ludic/blob/main/ludic/styles/themes.py).

| Field | What it changes |
|---|---|
| `measure` | The maximum width of text, `70ch` by default. |
| `line_height` | The line height of the page, `1.5`. Headings use 90 % of it. |
| `color_scheme` | `light` or `dark`: the CSS `color-scheme` of the page and the icon of `ColorSchemeToggle`. |
| `colors` | Colors |
| `fonts` | Fonts |
| `sizes` | The spacing scale from `xxxxs` to `xxxxl`. The catalog uses it for padding, gaps and margins. |
| `borders` | Border widths: `thin`, `normal` and `thick`. |
| `rounding` | Border radius: `less`, `normal` and `more`. |
| `headers` | Headers |
| `layouts` | Layouts |
| `code` | Code blocks |
| `buttons` | Buttons |

### Colors

The `Colors` dataclass:

| Field | What it changes |
|---|---|
| `primary` | Links, `ButtonPrimary`, the active tab and navigation item, and inline code. |
| `secondary`, `success`, `info`, `warning`, `danger` | The variants of buttons and messages, e.g. `ButtonDanger` or `MessageSuccess`. |
| `white` | The background of the page, cards, messages and form fields. |
| `dark` | The color of text. |
| `light` | The background of default buttons, inline code and navigation items, and in darker shades the borders. |
| `black` | The text of default buttons. |

In a dark theme, `white` is the dark background and `dark` the light text. The names describe the role of the color in the light theme.

### Fonts

| Field | What it changes |
|---|---|
| `primary` | The font of text. |
| `secondary` | The font of headings. |
| `monospace` | The font of code. |
| `size` | The base font size, `1em`. Other font sizes are relative to it. |

### Headers

`headers.h1` to `headers.h6` are a `Header` with the font `size` and `anchor`. With `anchor=True`, the catalog headers `H1` to `H4` get an id and a link to themselves:

```python
from ludic.styles import themes
from ludic.styles.types import SizeClamp

theme = themes.LightTheme(
    name="anchors",
    headers=themes.Headers(
        h2=themes.Header(size=SizeClamp(1.5, 1.3, 2.8), anchor=True),
    ),
)
```

### Layouts

`layouts` configures the [layouts](https://getludic.dev/catalog/layouts) of the catalog:

| Field | What it changes |
|---|---|
| `sidebar.side_width` | The width of the sidebar in `WithSidebar`. With `None`, the default, the sidebar is as wide as its content. |
| `sidebar.content_min_width` | The narrowest the content can be before the sidebar wraps above it, `60%`. |
| `switcher.threshold` | The width of the container at which `Switcher` switches between a row and a column, `40rem`. |
| `switcher.limit` | The most elements `Switcher` shows in a row, `4`. |
| `cover.min_height` | The minimum height of `Cover`, `100vh`. |
| `cover.element` | The selector of the child that `Cover` centers vertically, `h1`. |
| `grid.cell_size` | The minimum width of a `Grid` cell, `250px`. |
| `frame.numerator`, `frame.denominator` | The aspect ratio of `Frame`, `16:9`. |

```python
from ludic.styles import themes
from ludic.styles.types import Size

theme = themes.LightTheme(
    name="wide-sidebar",
    layouts=themes.Layouts(
        sidebar=themes.Sidebar(side_width="20rem"),
        grid=themes.Grid(cell_size=Size(18, "rem")),
    ),
)
```

### Code Blocks

`code` configures `CodeBlock`:

| Field | What it changes |
|---|---|
| `color`, `background_color` | The colors. |
| `line_number_color` | The color of line numbers. |
| `line_numbers` | Whether code blocks have line numbers, `True`. A code block can override it with `line_numbers=False`. |
| `font_size` | The font size, `0.9rem`. |
| `style` | The [Pygments style](https://pygments.org/styles/) that highlights the code: a name, e.g. `github-dark`, or a style class. |

```python
from ludic.styles import themes
from ludic.styles.types import Color

theme = themes.LightTheme(
    name="dark-code",
    code=themes.CodeBlock(
        color=Color("#e2e8f0"),
        background_color=Color("#0f172a"),
        line_number_color=Color("#64748b"),
        style="github-dark",
    ),
)
```

The catalog component `CodeBlock` and the theme's `CodeBlock` share the name. Import the theme's one through the module, as `themes.CodeBlock`.

### Buttons

`buttons` sets the `color` and `background_color` of the default `Button` and of `ButtonLink`. Without them, the default button has the background of `colors.light` and the text of `colors.black`. The other buttons, such as `ButtonPrimary`, take their colors from `colors`.

## Colors and Sizes

The values in a theme are strings, so you can use them anywhere CSS expects a color or a size. The classes in `ludic.styles.types` add a few helpers.

### Color and ColorRange

- `Color("#0f766e")` is a color. `darken(n)` and `lighten(n)` return a darker or lighter shade, and `readable()` returns black or white, whichever is readable on the color.
- `ColorRange([...])` is a list of variants of one color, from the darkest to the lightest. It is the middle variant, and `darken(n)` and `lighten(n)` move `n` steps along the list. The colors of the built-in themes are ranges.

```python
from ludic.styles.types import Color, ColorRange

primary = ColorRange(["#0b5f59", "#0f766e", "#ccfbf1"])
primary             # "#0f766e"
primary.darken()    # "#0b5f59"
primary.lighten()   # "#ccfbf1"
primary.readable()  # "#fff"

Color("#0f766e").darken()  # "#0e7068"
```

### Size and SizeClamp

- `Size(1.5)` is a size in `rem`, or in the unit you pass. Multiplying, adding and subtracting a number keeps the unit.
- `SizeClamp(minimum, value, maximum)` is a size that grows with the width of the window: from `minimum` rem, by `value` vw, up to `maximum` rem. It renders as the CSS `clamp()`, and arithmetic changes all three numbers.

```python
from ludic.styles.types import Size, SizeClamp

Size(1.5)       # "1.5rem"
Size(1.5) * 2   # "3rem"
Size(70, "ch")  # "70ch"

SizeClamp(1, 0.3, 1.16)      # "clamp(1rem, 1rem + 0.3vw, 1.16rem)"
SizeClamp(1, 0.3, 1.16) * 2  # "clamp(2rem, 2rem + 0.6vw, 2.32rem)"
```

## Use the Theme in Your Components

Read the theme in the `styles` of a component with `style.use`. Ludic renders these styles with the theme of the page, so they also switch with the dark theme:

```python
from typing import override

from ludic.attrs import GlobalAttrs
from ludic.components import Component
from ludic.html import div, style
from ludic.types import AnyChildren


class Callout(Component[AnyChildren, GlobalAttrs]):
    classes = ["callout"]
    styles = style.use(
        lambda theme: {
            ".callout": {
                "background-color": theme.colors.primary.lighten(),
                "color": theme.colors.primary.darken(),
                "padding": theme.sizes.m,
                "border-radius": theme.rounding.normal,
            }
        }
    )

    @override
    def render(self) -> div:
        return div(*self.children, **self.attrs)
```

In `render()`, the theme is `self.theme`. Inline styles computed from it do not switch with the dark theme, so prefer `styles` for colors. The [Styles](https://getludic.dev/docs/styles) page describes how the styles of components are collected.

Source: https://getludic.dev/docs/themes
