Official

themes

The stock themes: presets of every colour, type size, corner, density token and background, chosen per light and dark mode and edited in Settings, beside the themes other plugins ship.

The app opens the listing; nothing installs until an agent in your Plugins workspace has read the files and you enable the plugin. In a terminal: dvg install divergence/themes@0.3.4

Permissions in 0.3.4

  • Change app settings settings.writeHighChanges the app settings.Apply the chosen theme to the window
  • Read files fs.readMediumReads files in the listed places.Find the pictures you chose for backgrounds in this plugin's data folder, to remove the ones no preset usesPlaces: its own data folder
  • Write files fs.writeMediumCreates, changes and deletes files in the listed places.Keep a copy of each picture you choose for a background in this plugin's data folder, so it stays when the original movesPlaces: its own data folder

Files

settings.tsx16.1 KB
// The Themes section in Settings (`contributes.settings.view`): the preset of
// each mode, the presets, and the editor of the one picked. A name or a
// choice writes the plugin's settings at once; a typed value waits for
// Enter or Save. `main.ts` applies what is written.
// HTM whitespace is significant; keep these templates out of Prettier's HTML formatter.
import type { Api, Color, Element, HexColor, ThemeBackdrop, ThemeTokens, ViewContext } from "divergence";
import { KINDS, PICTURE_VEIL, PLACES, kindOf, pickPicture, picturesIn, prune, startOf, withBackdrop, withGlass } from "./backdrops.ts";
import type { Kind, Place } from "./backdrops.ts";
import { DEFAULT_SIZES } from "./presets.ts";
import { allPresets, chosen, duplicate, readSettings } from "./settings-model.ts";
import type { Preset, ThemeSettings } from "./settings-model.ts";
import { onRefresh, shipped } from "./shipped.ts";

const column = { display: "flex", flexDirection: "column" } as const;

// The preset open in the editor, kept while the section is shown.
let editing: string | null = null;
// What is typed in the editor's fields, by field id, until Enter or Save
// applies it, so typing 14 never applies 1 on the way.
const drafts = new Map<string, string>();
// Another preset opened in the editor starts without the last one's typing.
const open = (id: string | null) => {
  editing = id;
  drafts.clear();
};

const HEX = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
const isHex = (text: string): text is HexColor => HEX.test(text);

type Group = "type" | "shape" | "density";
const GROUPS: readonly { readonly key: Group; readonly title: string }[] = [
  { key: "type", title: "Type" },
  { key: "shape", title: "Shape" },
  { key: "density", title: "Density" },
];

// "fieldHeight" → "Field height".
const words = (key: string) => key.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());

// The view drawn last, which a new list of the plugins' themes draws again.
let drawn: ViewContext<object> | null = null;
onRefresh(() => drawn?.update());

export function render(ctx: ViewContext<object>, api: Api): Element {
  drawn = ctx;
  const values = readSettings(api.settings.get());
  const { themes, problems } = shipped();
  const presets = allPresets(values, themes);
  const shown = presets.find((preset) => preset.id === editing) ?? null;
  const save = async (next: ThemeSettings["presets"]) => {
    await api.settings.set("presets", next);
    await prune(api, picturesIn(Object.values(values.presets)), picturesIn(Object.values(next)));
  };
  const choose = (mode: "light" | "dark", id: string) => api.settings.set("active", { ...values.active, [mode]: id });

  const chooser = (mode: "light" | "dark") => (
    <setting title={mode === "light" ? "Light theme" : "Dark theme"} description={`Drawn when the appearance is ${mode === "light" ? "Light" : "Dark"} (or the system's is).`}>
      <select id={`theme-${mode}`} value={chosen(values, mode, themes).id} options={presets.filter((preset) => preset.mode === mode).map((preset) => ({ value: preset.id, label: preset.name }))} onChange={(e: { value: string }) => choose(mode, e.value)} />
    </setting>
  );

  const copyOf = (source: Preset) => {
    const copy = duplicate(source, presets);
    open(copy.id);
    void save({ ...values.presets, [copy.id]: { name: copy.name, mode: copy.mode, tokens: copy.tokens } }).then(() =>
      choose(copy.mode, copy.id),
    );
  };

  const row = (preset: Preset) => {
    const used = chosen(values, preset.mode, themes).id === preset.id;
    const mode = preset.mode === "light" ? "Light" : "Dark";
    const origin = preset.stock ? " · stock" : preset.from ? ` · from ${preset.from}` : "";
    return (
      <item key={preset.id} id={`preset-${preset.id}`} label={preset.name} borderRadius="inner" sublabel={`${mode}${origin}${used ? " · in use" : ""}`} icon={preset.mode === "light" ? "sun" : "moon"} iconTone={used ? "primary" : undefined} selected={preset.id === editing} actions={[
          ...(used ? [] : [{ icon: "check", tooltip: `Use for ${mode}`, onClick: () => choose(preset.mode, preset.id) }]),
          { icon: "copy", tooltip: "Duplicate", onClick: () => copyOf(preset) },
          ...(preset.stock || preset.from
            ? []
            : [
                {
                  icon: "trash-2",
                  tooltip: "Delete",
                  onClick: () => {
                    const { [preset.id]: _gone, ...rest } = values.presets;
                    if (editing === preset.id) open(null);
                    void save(rest);
                  },
                },
              ]),
        ]} onClick={() => {
          open(preset.id);
          ctx.update();
        }} />
    );
  };

  return (
    <div {...column} gap="large">
      <div {...column}>
          <setting heading title="In use" description="The preset drawn in each appearance; System, Light and Dark in General choose between them." />
          <card divided>{chooser("light")}{chooser("dark")}</card>
        </div>
      <div {...column}>
          <setting heading title="Presets" description="Open one to see its tokens. A stock preset is read only: duplicate it to edit a copy." />
          <card divided>{presets.map(row)}</card>
        </div>
      {problems.length ? <callout tone="warning" title="Some plugins' themes were left out" text={problems.join("\n")} /> : null}
      {shown ? editor(ctx, api, shown, values, save, copyOf) : null}
    </div>
  );
}

type Save = (next: ThemeSettings["presets"]) => Promise<void>;

// A field whose typing waits for Enter or Save; Save shows once the text
// differs and is enabled only while `apply` accepts it.
function field(ctx: ViewContext<object>, id: string, value: string, apply: (text: string) => boolean): Element {
  const text = drafts.get(id) ?? value;
  const commit = () => {
    if (apply(text.trim())) drafts.delete(id);
    ctx.update();
  };
  return (
    <div display="flex" flexDirection="row" alignItems="center" gap="small">
      <input id={id} value={text} onChange={(e: { value: string }) => {
          drafts.set(id, e.value);
          ctx.update();
        }} onSubmit={commit} />
      {text !== value ? <button id={`${id}-save`} label="Save" small variant="primary" onClick={commit} /> : null}
    </div>
  );
}

// The open preset: a stock one, or one another plugin ships, offers a copy;
// one of the user's edits its tokens.
function editor(ctx: ViewContext<object>, api: Api, preset: Preset, values: ThemeSettings, save: Save, copyOf: (source: Preset) => void): Element {
  if (preset.stock || preset.from) {
    const text = preset.from
      ? `The ${preset.from} plugin ships this preset, and it does not change here. Duplicate it to make one of your own to edit.`
      : "A stock preset does not change. Duplicate it to make one of your own to edit.";
    return <callout title={preset.name} text={text}><button id="duplicate-open" label="Duplicate" onClick={() => copyOf(preset)} /></callout>;
  }
  const own = values.presets[preset.id]!;
  const write = (tokens: ThemeTokens) =>
    void save({ ...values.presets, [preset.id]: { ...own, tokens } }).catch((error: Error) => api.notify(`The preset was not saved: ${error.message}`, "error"));
  const colors = preset.tokens.colors ?? {};
  const sizes = (group: Group): Readonly<Record<string, number>> => ({
    ...DEFAULT_SIZES[group],
    ...((preset.tokens[group] ?? {}) as Readonly<Record<string, number>>),
  });
  return (
    <div {...column} gap="large">
      <div {...column}>
            <setting heading title={preset.name} description="A typed value applies on Enter or Save." />
            <card divided>
                  <setting title="Name">
                        <input id="preset-name" value={preset.name} onChange={(e: { value: string }) => e.value.trim() && void save({ ...values.presets, [preset.id]: { ...own, name: e.value.trim(), tokens: { ...own.tokens, name: e.value.trim() } } })} />
                      </setting>
                  <setting title="Ground opacity" description="How much of the ground colour lies over the blurred desktop, 0 to 1 (macOS).">
                        {field(ctx, "preset-ground", String(preset.tokens.groundAlpha ?? 0.95), (text) => {
                                        const n = Number(text);
                                        if (!text || !(n >= 0 && n <= 1)) return false;
                                        write({ ...own.tokens, groundAlpha: n });
                                        return true;
                                      })}
                      </setting>
                </card>
          </div>
      <div {...column}>
            <setting heading title="Backgrounds" description="What the preset draws behind the new chat page and behind chats. App default keeps the choice in Settings > Chat." />
            {PLACES.map(({ key, title }) => backdropCard(ctx, api, key, title, preset.tokens, write))}
          </div>
      {GROUPS.map(
                ({ key, title }) => (
                  <div {...column}>
                    <setting heading title={title} />
                    <card divided>
                                {Object.entries(sizes(key)).map(
                                              ([name, value]) => (
                                                <setting key={name} title={words(name)}>
                                                  {field(ctx, `preset-${key}-${name}`, String(value), (text) => {
                                                                      const n = Number(text);
                                                                      if (!text || !Number.isFinite(n) || n < 0) return false;
                                                                      write({ ...own.tokens, [key]: { ...sizes(key), [name]: n } });
                                                                      return true;
                                                                    })}
                                                </setting>
                                              ),
                                            )}
                              </card>
                  </div>
                ),
              )}
      <div {...column}>
            <setting heading title="Colors" description="Hex values, #rrggbb or #rrggbbaa." />
            <card divided>
                  {Object.entries(colors)
                              .filter(([, value]) => value.startsWith("#"))
                              .map(
                                ([name, value]) => (
                                  <setting key={name} title={name}>
                                    <div display="flex" flexDirection="row" alignItems="center" gap="small">
                                                    <div width={16} height={16} borderRadius="sm" background={value} />
                                                    {field(ctx, `preset-color-${name}`, value, (text) => {
                                                                        if (!HEX.test(text)) return false;
                                                                        write({ ...own.tokens, colors: { ...colors, [name]: text.toLowerCase() } });
                                                                        return true;
                                                                      })}
                                                  </div>
                                  </setting>
                                ),
                              )}
                </card>
          </div>
    </div>
  );
}

const number = (text: string, min: number, max: number): number | null => {
  const n = Number(text);
  return text && Number.isFinite(n) && n >= min && n <= max ? n : null;
};

// One place's background: its kind, the values of that kind, and the veil
// over it.
function backdropCard(ctx: ViewContext<object>, api: Api, place: Place, title: string, tokens: ThemeTokens, write: (tokens: ThemeTokens) => void): Element {
  const backdrop = tokens.backdrop?.[place];
  const kind = kindOf(backdrop);
  const set = (next: ThemeBackdrop | undefined) => write(withBackdrop(tokens, place, next));
  const id = `backdrop-${place}`;
  const pick = () =>
    void pickPicture(api).then(
      (image) => image && set({ image, glass: backdrop?.glass ?? PICTURE_VEIL }),
      (error: Error) => api.notify(`The picture was not kept: ${error.message}`, "error"),
    );
  const change = (next: Kind) => {
    if (next === "none") set(undefined);
    else if (next === "image") pick();
    else {
      const ground = tokens.colors?.["background"] ?? "";
      set(startOf(next, backdrop, isHex(ground) ? ground : "background"));
    }
  };
  const hex = (fieldId: string, value: string, apply: (color: HexColor) => void) =>
    field(ctx, fieldId, value, (text) => {
      const color = text.toLowerCase();
      if (!isHex(color)) return false;
      apply(color);
      return true;
    });
  const rows: Element[] = [];
  if (backdrop && "scene" in backdrop) {
    const hue: string | undefined = backdrop.color;
    rows.push(
      <setting title="Colour" description="The hue of its light; empty takes the theme's info colour.">
        {field(ctx, `${id}-color`, hue ?? "", (text) => {
          const color = text.toLowerCase();
          const { color: _old, ...rest } = backdrop;
          if (!color) set(rest);
          else if (isHex(color)) set({ ...rest, color });
          else return false;
          return true;
        })}
      </setting>,
      <setting title="Speed" description="1 is the stock speed, 0 holds it still, 4 at most.">
        {field(ctx, `${id}-speed`, String(backdrop.speed ?? 1), (text) => {
          const speed = number(text, 0, 4);
          if (speed === null) return false;
          set({ ...backdrop, speed });
          return true;
        })}
      </setting>,
    );
  } else if (backdrop && "fill" in backdrop && typeof backdrop.fill === "string") {
    rows.push(<setting title="Colour">{hex(`${id}-fill`, backdrop.fill, (fill) => set({ ...backdrop, fill }))}</setting>);
  } else if (backdrop && "fill" in backdrop && typeof backdrop.fill !== "string") {
    const gradient = backdrop.fill.linearGradient;
    const [first, last] = [gradient.stops[0]![0], gradient.stops.at(-1)![0]];
    const stops = (from: Color, to: Color) => set({ ...backdrop, fill: { linearGradient: { ...gradient, stops: [[from, 0], [to, 1]] } } });
    rows.push(
      <setting title="From">{hex(`${id}-from`, first, (color) => stops(color, last))}</setting>,
      <setting title="To">{hex(`${id}-to`, last, (color) => stops(first, color))}</setting>,
      <setting title="Angle" description="Degrees; 180 runs from the top down.">
        {field(ctx, `${id}-angle`, String(gradient.angle ?? 180), (text) => {
          const angle = number(text, -360, 360);
          if (angle === null) return false;
          set({ ...backdrop, fill: { linearGradient: { ...gradient, angle } } });
          return true;
        })}
      </setting>,
    );
  } else if (backdrop && "image" in backdrop) {
    rows.push(
      <setting title="Picture" description={backdrop.image.split("/").at(-1)}>
        <button id={`${id}-pick`} label="Choose…" small onClick={pick} />
      </setting>,
    );
  }
  if (backdrop) {
    rows.push(
      <setting title="Veil" description="How much of the theme's background lies over it, 0 to 1, so text stays readable.">
        {field(ctx, `${id}-veil`, String(backdrop.glass ? (backdrop.glass.opacity ?? 0.6) : 0), (text) => {
          const opacity = number(text, 0, 1);
          if (opacity === null) return false;
          set(withGlass(backdrop, { opacity }));
          return true;
        })}
      </setting>,
      <setting title="Blur" description="How far the veil blurs what is under it, in pixels.">
        {field(ctx, `${id}-blur`, String(backdrop.glass?.blur ?? 0), (text) => {
          const blur = number(text, 0, 64);
          if (blur === null) return false;
          set(withGlass(backdrop, { blur }));
          return true;
        })}
      </setting>,
    );
  }
  return (
    <card divided>
      <setting title={title}>
        <select id={id} value={kind} options={KINDS} onChange={(e: { value: Kind }) => change(e.value)} />
      </setting>
      {rows}
    </card>
  );
}

Versions

VersionPublishedPlugin APISizePermissionsStatus
0.3.5latestNov 21, 2026>=5 <614.2 KB3 permissionsListed
0.3.4Nov 16, 2026>=5 <613.8 KB3 permissionsListed
0.3.3Nov 11, 2026>=5 <68.9 KB1 permissionListed
0.3.2Nov 9, 2026>=5 <68.1 KB1 permissionListed
0.3.1Oct 27, 2026>=2 <48 KB1 permissionListed

Reviews and comments

0 threads · 0 reviews

No comments yet.