repository

BlowfishCMS

A small content management system for OpenBSD

version 0.45.6 · ISC · 2026-12-03 · releases

623 lines · 46.5 KB · download this file

package BlowfishCMS;
# Themes: theme rows, generated stylesheet and the themes admin.
# Every BlowfishCMS/*.pm file adds subs to the one BlowfishCMS package; request state
# is shared through the package variables below and reset by BlowfishCMS::handle_request.
use v5.36;
use utf8;
use JSON::PP qw(encode_json decode_json);
use Digest::SHA qw(hmac_sha256_hex sha256_hex);
use Encode qw(decode encode FB_CROAK);
use Fcntl qw(:flock :DEFAULT);
use Unicode::Normalize qw(NFKC);
use POSIX qw(strftime);
use File::Basename qw(basename);
our ($base,$data,$store,$cdata,$root,$db,$q,$route,$admin,$contact,$comments_route,$method,$cookie_header,$csrf);


# ---- Themes ---------------------------------------------------------------
# Each variant is a row: its colour and font variables, drawn with its theme
# folder's CSS. The public stylesheet /themes.css is generated from these rows;
# every rule is scoped to :root[data-theme="slug"] so variants never leak into
# each other.
# The values each variant sets, as CSS variables (--bg, --accent, ...): name,
# label in the editor, and kind (colour, font list or page width).
sub theme_var_fields {
    return (
        ['desktop','Desktop background','color'],['bg','Page background','color'],
        ['window','Window','color'],['window-2','Window (secondary)','color'],
        ['ink','Text','color'],['muted','Muted text','color'],['line','Lines & borders','color'],
        ['accent','Accent','color'],['accent-2','Accent (strong)','color'],['shadow','Shadow','color'],
        ['font-display','Heading font','font'],['font-ui','Interface font','font'],['font-body','Body font','font'],
        ['maxw','Maximum page width','width'],
    );
}
# ---- Theme folders ----------------------------------------------------------
# A theme is a folder: theme.json (its name, version and variants, each with
# default colours and fonts), theme.css (its rules, where :root means the page
# while one of its variants is active) and optional assets/, served at
# /themes/NAME/. Modern ships in the release's themes/; others are installed
# from the themes list (uploaded archives, blowfishctl theme add) into
# /opt/blowfishcms-themes.
# Each row of the themes table is a variant: its own name, colours and fonts,
# drawn with the files of its folder (themes.package). Duplicates share them.
my $theme_packages_cache;
my $themes_extra=$ENV{BLOWFISH_THEMES_PATH} // '/opt/blowfishcms-themes';
# Where theme folders are found: the release's own themes/, then the
# installed ones (/opt/blowfishcms-themes; BLOWFISH_THEMES_PATH in tests).
sub theme_paths { return (source_file('themes'),grep {length} $themes_extra) }
# A theme folder's name: 2-32 lowercase letters, digits and dashes.
sub theme_name_ok ($n) { return ($n//'') =~ /\A[a-z][a-z0-9-]{1,31}\z/ ? 1 : 0 }
# Checks a theme folder's theme.json (and theme.css): '' when it can be used,
# otherwise what's wrong, in words for the Themes screen. Its name must match
# its folder, it needs a label and a version, it must work with this
# BlowfishCMS, it has 1-8 variants each with every value valid, and its CSS
# must be under 200 KB, UTF-8, and pass the same checks as when it's used.
sub theme_manifest_problem ($m,$dir) {
    return 'theme.json must be a JSON object' unless ref $m eq 'HASH';
    my $name=$m->{name}//'';
    return 'name must be 2–32 lowercase letters, digits and hyphens, starting with a letter' unless theme_name_ok($name);
    return "the folder must be named $name" unless $dir =~ m{/\Q$name\E\z};
    return 'label is required' unless length($m->{label}//'');
    return 'version must look like 1.2.3' unless ($m->{version}//'') =~ /\A\d+\.\d+\.\d+\z/;
    my $needs=$m->{blowfishcms}//'';
    return 'blowfishcms must give the oldest BlowfishCMS version it works with, such as 1.0.0' unless $needs =~ /\A\d+\.\d+\.\d+\z/;
    return "needs BlowfishCMS $needs or newer (this is $BlowfishCMS::VERSION)" if version_cmp($BlowfishCMS::VERSION,$needs)<0;
    my $variants=$m->{variants};
    return 'variants must list 1 to 8 variants' unless ref $variants eq 'ARRAY' && @$variants>=1 && @$variants<=8;
    for my $v (@$variants) {
        return 'each variant needs a slug (2–24 lowercase letters, digits and hyphens), a name, and a scheme of light or dark'
            unless ref $v eq 'HASH' && ($v->{slug}//'') =~ /\A[a-z][a-z0-9-]{1,23}\z/ && length($v->{name}//'') && ($v->{scheme}//'') =~ /\A(?:light|dark)\z/;
        for my $f (theme_var_fields()) {return "variant $v->{slug}: $f->[0] is missing or not valid" unless ref $v->{vars} eq 'HASH' && theme_value_ok($f->[2],$v->{vars}{$f->[0]})}
    }
    if (-e "$dir/theme.css") {
        return 'theme.css is larger than 200 KB' if -s "$dir/theme.css" > 200*1024;
        my $css=theme_file_text("$dir/theme.css");
        return 'theme.css must be UTF-8 text' unless defined $css;
        my $ok=attempt {theme_scope_css($css,':root[data-theme="check"]');1};
        return 'theme.css: '.("$@" =~ s/\s+\z//r) unless $ok;
    }
    return '';
}
# A file as UTF-8 text with Windows line endings made plain; undef if it
# isn't valid UTF-8.
sub theme_file_text ($file) {
    open my $fh,'<:raw',$file or return undef;local $/;my $raw=<$fh>;close $fh;
    my $text=attempt {decode('UTF-8',$raw//'',FB_CROAK)};return defined $text ? $text =~ s/\r\n?/\n/gr : undef;
}
# Every theme folder found: name => manifest (with dir, core, css, and problem
# when it can't be used). The release's own come first and can't be replaced.
# Kept between requests while no theme folder changes (checked by the
# folders' and files' modification times, which an install or update changes).
my ($packages_kept,$packages_stamp)=(undef,'');
sub theme_folder_stamp ($path) { return folder_stamp($path,qw(theme.json theme.css)) }
# Every theme folder found, by name. Kept between requests while nothing in
# the folders changes (folder_stamp compares modification times). A folder
# that's also in the release (core) can't be replaced by an installed one.
sub theme_packages {
    return $theme_packages_cache if $theme_packages_cache;
    my $stamp=join '|',map {theme_folder_stamp($_)} theme_paths();
    return $theme_packages_cache=$packages_kept if $packages_kept && $stamp eq $packages_stamp;
    my %all;my $core=1;
    for my $path (theme_paths()) {
        if (opendir(my $dh,$path)) {
            for my $entry (sort readdir $dh) {
                next if $entry =~ /\A\./ || exists $all{$entry};
                my $dir="$path/$entry";next unless -f "$dir/theme.json";
                my $m=attempt {open my $fh,'<:raw',"$dir/theme.json" or die;local $/;JSON::PP->new->utf8->decode(<$fh>)};
                $m={name=>$entry} unless ref $m eq 'HASH';
                $m->{dir}=$dir;$m->{core}=$core;$m->{problem}=theme_manifest_problem($m,$dir);
                $m->{name}=$entry if $m->{problem};
                $m->{css}=$m->{problem} ? '' : (-e "$dir/theme.css" ? theme_file_text("$dir/theme.css")//'' : '');
                $all{$entry}=$m;
            }
            closedir $dh;
        }
        $core=0;
    }
    ($packages_kept,$packages_stamp)=(\%all,$stamp);
    return $theme_packages_cache=\%all;
}
# One theme folder by name, if it can be used.
sub theme_package ($name) { my $m=theme_packages()->{$name//''};return $m && !$m->{problem} ? $m : undef }
# The themes a new site starts with: the release's own variants.
# The release's own variants, as rows (used when the catalogue can't be read).
sub theme_seed {
    my @themes;
    for my $m (grep {$_->{core}} map {theme_package($_)} sort keys %{theme_packages()}) {
        push @themes,map {+{slug=>$_->{slug},name=>$_->{name},scheme=>$_->{scheme},surfaces=>($_->{page_palettes}?0:1),vars=>$_->{vars},package=>$m->{name},css=>''}} @{$m->{variants}};
    }
    return {default=>'modern',themes=>\@themes};
}
# Creates the themes table (one row per variant) and adds any variant of an
# installed theme that this site hasn't had yet: on a new site the release's
# own variants are shown, others start hidden. themes_offered remembers every
# variant ever added, so one the owner deletes doesn't come back.
sub ensure_theme_tables {
    $db->do("CREATE TABLE IF NOT EXISTS themes (slug TEXT PRIMARY KEY, name TEXT NOT NULL, scheme TEXT NOT NULL, surfaces INTEGER NOT NULL DEFAULT 1, vars TEXT NOT NULL, css TEXT NOT NULL DEFAULT '', enabled INTEGER NOT NULL DEFAULT 1, sort_order INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL, package TEXT NOT NULL DEFAULT '')");
    $db->do('CREATE TABLE IF NOT EXISTS site_settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)');
    my $fresh=!$db->selectrow_array('SELECT count(*) FROM themes');
    my $offered=$db->selectrow_array("SELECT value FROM site_settings WHERE key='themes_offered'");
    my %seen=$offered ? map {$_=>1} @{(attempt {decode_json($offered)}) // []} : map {$_=>1} @{$db->selectcol_arrayref('SELECT slug FROM themes')};
    # A variant of an installed theme that this site hasn't had yet is added
    # (the release's own switched on for a new site, others hidden until shown).
    # themes_offered remembers every variant the site has had, so one you
    # delete never comes back.
    my $changed=!$offered;
    for my $m (sort {$b->{core} <=> $a->{core} || $a->{name} cmp $b->{name}} grep {!$_->{problem}} values %{theme_packages()}) {
        for my $v (@{$m->{variants}}) {
            next if $seen{$v->{slug}};
            my $order=($db->selectrow_array('SELECT max(sort_order) FROM themes')//-1)+1;
            $db->do('INSERT OR IGNORE INTO themes (slug,name,scheme,surfaces,vars,css,enabled,sort_order,updated_at,package) VALUES (?,?,?,?,?,?,?,?,?,?)',undef,
                $v->{slug},$v->{name},$v->{scheme},($v->{page_palettes}?0:1),JSON::PP->new->canonical->encode($v->{vars}),'',($fresh && $m->{core} ? 1 : 0),$order,now(),$m->{name});
            $seen{$v->{slug}}=1;$changed=1;
        }
    }
    $db->do("INSERT OR IGNORE INTO site_settings(key,value) VALUES ('default_theme','modern')") if $fresh;
    $db->do("INSERT INTO site_settings(key,value) VALUES ('themes_offered',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",undef,encode_json([sort keys %seen])) if $changed;
    reset_theme_cache();
}
my ($theme_cache,$theme_css_cache);  # cleared at the start of every request
# Forgets the variants and stylesheets worked out during this request.
sub reset_theme_cache { undef $theme_cache; $theme_css_cache={}; undef $theme_packages_cache }
# Every variant, in the owner's order, with its values decoded.
sub all_themes {
    return $theme_cache if $theme_cache;
    # Where the catalogue couldn't be opened (the contact and mail code go on
    # without it), the release's own themes.
    my $rows=attempt {$db->selectall_arrayref('SELECT * FROM themes ORDER BY sort_order, name',{Slice=>{}})};
    if ($rows && @$rows) {$_->{vars}=json_cached($_->{vars}) // {} for @$rows}
    else {my $i=0;$rows=[map {+{%$_,enabled=>1,sort_order=>$i++}} @{theme_seed()->{themes}}]}
    return $theme_cache=$rows;
}
# One variant by its slug, or undef.
sub theme_by_slug ($slug) { return undef unless defined $slug; my ($t)=grep {$_->{slug} eq $slug} @{all_themes()}; return $t }
# "Name · light" for menus.
sub theme_label ($t) { return $t->{name}.' · '.$t->{scheme} }
# The variant new visitors get: the default_theme setting if that variant is
# shown, else the first shown one.
sub default_theme {
    my $slug=(attempt {$db->selectrow_array("SELECT value FROM site_settings WHERE key='default_theme'")}) // theme_seed()->{default};
    my @enabled=grep {$_->{enabled}} @{all_themes()};
    return $slug if grep {$_->{slug} eq $slug} @enabled;
    return @enabled ? $enabled[0]{slug} : all_themes()->[0]{slug};
}
# Whether a value may go into the stylesheet: a colour (#hex, a name, rgb()
# or hsl()), a font list, or a width of 600-2400px. Characters that could end
# a CSS declaration or rule (; { } < > \) are refused, so a value can't add
# rules of its own.
sub theme_value_ok ($type, $v) {
    return 0 if !defined $v || !length($v) || length($v)>200 || $v =~ /[;{}<>\\]/;
    return $v =~ /\A(?:#[0-9a-fA-F]{3,8}|[a-zA-Z]+|(?:rgb|rgba|hsl|hsla)\([0-9.,%\s\/-]+\))\z/ ? 1 : 0 if $type eq 'color';
    return $v =~ /\A[\pL\pN ,"'\-]+\z/ ? 1 : 0 if $type eq 'font';
    return $v =~ /\A([0-9]{3,4})px\z/ && $1>=600 && $1<=2400 ? 1 : 0 if $type eq 'width';
    return 0;
}
# Split CSS into top-level [prelude, block] pairs, honouring comments and strings.
# Splits a stylesheet into its top-level rules, as [selector, contents],
# stepping over comments, strings and escapes so a brace inside them doesn't
# count. Anything that isn't a complete rule is an error.
sub css_blocks ($css) {
    my @items;my ($i,$n,$start,$depth,$open)=(0,length $css,0,0,0);
    while ($i<$n) {
        my $c=substr($css,$i,1);
        if ($c eq '\\') {$i+=2;next}
        if ($c eq '/' && substr($css,$i+1,1) eq '*') {my $e=index($css,'*/',$i+2);die "Custom CSS has an unclosed comment.\n" if $e<0;$i=$e+2;next}
        if ($c eq '"' || $c eq "'") {my $j=$i+1;while ($j<$n && substr($css,$j,1) ne $c) {$j++ if substr($css,$j,1) eq '\\';$j++}die "Custom CSS has an unclosed string.\n" if $j>=$n;$i=$j+1;next}
        if ($c eq '{') {$open=$i if $depth==0;$depth++}
        elsif ($c eq '}') {
            $depth--;die "Custom CSS has an extra }.\n" if $depth<0;
            if ($depth==0) {push @items,[substr($css,$start,$open-$start),substr($css,$open+1,$i-$open-1)];$start=$i+1}
        }
        elsif ($c eq ';' && $depth==0) {die "Custom CSS should only contain rules such as .window { … } (found a stray ';').\n"}
        $i++;
    }
    die "Custom CSS is missing a closing }.\n" if $depth;
    my $rest=substr($css,$start);$rest =~ s{/\*.*?\*/}{}gs;
    die "Custom CSS ends with an incomplete rule.\n" if $rest =~ /\S/;
    return @items;
}
# Split a selector list on top-level commas (not inside (), [] or quotes).
# Splits "a, b:not(c, d)" on the commas that separate selectors, not those
# inside brackets or quotes.
sub split_selectors ($list) {
    my @out;my ($depth,$quote,$current)=(0,'','');
    for my $c (split //, $list) {
        if ($quote) {$quote='' if $c eq $quote}
        elsif ($c eq '"' || $c eq "'") {$quote=$c}
        elsif ($c eq '(' || $c eq '[') {$depth++}
        elsif ($c eq ')' || $c eq ']') {$depth-- if $depth}
        elsif ($c eq ',' && !$depth) {push @out,$current;$current='';next}
        $current.=$c;
    }
    push @out,$current;
    return @out;
}
# Rewrites a theme's CSS so it only applies while one of its variants is
# active: each selector gets :root[data-theme="slug"] in front (":root" and
# "html" themselves become that). Rules inside @media, @supports and the like
# are rewritten too; @keyframes and @font-face are kept as they are; any
# other @-rule (such as @import, which could load outside files) is refused.
sub theme_scope_css ($css, $scope) {
    my $out='';
    for my $item (css_blocks($css)) {
        my ($prelude,$body)=@$item;$prelude =~ s{/\*.*?\*/}{}gs;$prelude =~ s/\A\s+|\s+\z//g;
        die "Custom CSS has a block without a selector.\n" unless length $prelude;
        if ($prelude =~ /\A\@(?:media|supports|container|layer)\b/i) {$out.=$prelude.'{'.theme_scope_css($body,$scope)."}\n";next}
        if ($prelude =~ /\A\@(?:-webkit-)?(?:keyframes|font-face|property|counter-style)\b/i) {$out.=$prelude.'{'.$body."}\n";next}
        die "Theme CSS can't use $prelude (imports and other at-rules aren't allowed).\n" if $prelude =~ /\A\@/;
        my @selectors=map {s/\A\s+|\s+\z//gr} split_selectors($prelude);
        die "Custom CSS has an empty selector.\n" if grep {!length} @selectors;
        $out.=join(',',map {/\A(?::root|html)(?![\w-])(.*)\z/s ? $scope.$1 : "$scope $_"} @selectors).'{'.$body."}\n";
    }
    return $out;
}
# The variants visitors can have: the default, and the ones they may choose
# (none when the theme menu is off), plus one being previewed (?theme=, which
# may be hidden). Hidden variants aren't sent to everyone.
# The variant being previewed with ?theme=SLUG, if it exists.
sub theme_preview { my $p=param('theme',30)//'';return ($p =~ /\A[a-z][a-z0-9-]{1,23}\z/ && grep {$_->{slug} eq $p} @{all_themes()}) ? $p : '' }
# /themes.css: the variables and scoped CSS of the variants visitors can
# have: the default, the shown ones while visitors may choose, and one being
# previewed. Hidden variants are left out. Kept for the rest of the request.
sub theme_stylesheet ($with='') {
    $theme_css_cache//={};
    return $theme_css_cache->{$with} if defined $theme_css_cache->{$with};
    my $default=default_theme();my $picker=setting('theme_picker') ne '0';
    my $css="/* Generated by the BlowfishCMS theme editor. */\n";
    $css.=theme_css($_) for grep {$_->{slug} =~ /\A[a-z][a-z0-9-]{1,23}\z/ && ($_->{slug} eq $default || ($picker && $_->{enabled}) || $_->{slug} eq $with)} @{all_themes()};
    return $theme_css_cache->{$with}=$css;
}
# A theme's rules limited to one variant, kept between requests (the files
# rarely change and the scoping is the costly part).
# theme_scope_css, remembered between requests by a hash of its input (up
# to 200 results), because the rewriting is the slow part.
sub theme_scoped ($css,$scope) {
    state %done;%done=() if keys %done > 200;
    my $key=sha256_hex(encode('UTF-8',"$scope\0$css"));
    return $done{$key} if exists $done{$key};
    return $done{$key}=attempt {theme_scope_css($css,$scope)};
}
# One variant's rules: its colours and fonts, then its theme's CSS limited to it.
# One variant's part of the stylesheet: color-scheme and its variables, then
# its theme's CSS scoped to it. With "original surfaces" off ($t->{surfaces}
# false) the variables use :where(), which has no specificity, so a page's
# own later colours win.
sub theme_css ($t) {
    my $scope=':root[data-theme="'.$t->{slug}.'"]';
    my @decl=('color-scheme:'.($t->{scheme} eq 'dark' ? 'dark' : 'light'));
    for my $f (theme_var_fields()) {my $v=$t->{vars}{$f->[0]};push @decl,"--$f->[0]:$v" if theme_value_ok($f->[2],$v)}
    # Page-palette themes (like Plan9) use the same specificity as each page's own
    # :root colours, which load later and therefore win; other themes override them.
    my $css=($t->{surfaces} ? $scope : ':root:where([data-theme="'.$t->{slug}.'"])').'{'.join(';',@decl)."}\n";
    my $p=theme_package($t->{package});
    my $rules=theme_scoped($p ? $p->{css} : '',$scope);
    return $css.(defined $rules ? $rules : "/* the CSS for $t->{slug} was skipped: it could not be read */\n");
}

# ---- Live preview in the theme editor -------------------------------------------------
# The unsaved theme's stylesheet is kept for an hour in a small file, because the
# preview frame may only load stylesheets from this site (no inline styles).
# The theme editor's preview stylesheet. Inline styles aren't allowed (the
# content security policy), so the unsaved theme is written to a small file
# the preview loads, kept for an hour.
sub theme_preview_file ($id) { "$data/admin/tmp/theme-preview-$id.css" }
# Serves a preview stylesheet (?preview_css=ID).
sub theme_preview_css {
    my $id=param('preview_css',40);my $fh;
    unless ($id =~ /\A[a-f0-9]{32}\z/ && open $fh,'<:raw',theme_preview_file($id)) {header(404,'text/css; charset=UTF-8');print "/* This preview has expired. */\n";return}
    local $/;my $css=decode('UTF-8',<$fh>);close $fh;
    header(200,'text/css; charset=UTF-8');print $css;
}
# A public page drawn with the submitted (unsaved) theme as the only theme.
# A public page drawn with the unsaved variant as the only theme: its
# stylesheet saved to a preview file, then the page's theme information,
# stylesheet link and data-theme swapped for the preview's.
sub theme_preview_html ($v,$slug) {
    my $t={%$v,slug=>$slug,package=>param('package',32)};
    for my $file (glob("$data/admin/tmp/theme-preview-*.css")) {unlink $file if -M $file > 1/24}
    my $id=random_id();
    open my $fh,'>:encoding(UTF-8)',theme_preview_file($id) or die "The preview could not be prepared.\n";
    print {$fh} theme_css($t);close $fh;
    my ($page)=grep {$_->{slug} eq (param('preview_page',40)||'home')} @{all_pages()};
    $page //= page_by_slug('home');
    my $html=public_preview(sub {render_page($page)});
    my $info=JSON::PP->new->canonical->encode({default=>$slug,themes=>{$slug=>{scheme=>$t->{scheme},surfaces=>($t->{surfaces}?JSON::PP::true:JSON::PP::false),enabled=>JSON::PP::true}}});
    $html =~ s{<meta name="site-themes" content="[^"]*">}{'<meta name="site-themes" content="'.h($info).'">'}e;
    $html =~ s{<link rel="stylesheet" href="/themes\.css\?v=[^"]*">}{<link rel="stylesheet" href="/admin/?kind=themes&amp;preview_css=$id">};
    $html =~ s{data-theme="[^"]*"}{data-theme="$slug"};
    return $html;
}
# A short hash of the stylesheet, used as its ?v= so browsers can keep it
# for a year and fetch it again as soon as it changes.
sub theme_version ($with='') { return substr(sha256_hex(encode('UTF-8',theme_stylesheet($with))),0,12) }
# The <link> to /themes.css for every page.
sub theme_link { my $with=theme_preview();return '<link rel="stylesheet" href="/themes.css?v='.theme_version($with).(length $with ? '&amp;with='.$with : '').'">' }
# A <meta> tag with the variants' light/dark schemes and which ones visitors
# may pick, for theme.js (which applies a visitor's choice before the page
# is drawn, so it doesn't flash).
# Each shown variant's "pair" is its theme's shown variant of the other
# scheme (theme_groups), for the light/dark switch beside the theme menu.
sub theme_head {
    my %pair;for my $g (@{theme_groups()}) {next unless $g->{light} && $g->{dark};$pair{$g->{light}}=$g->{dark};$pair{$g->{dark}}=$g->{light}}
    my %info=(default=>default_theme(),picker=>(setting('theme_picker') eq '0' ? JSON::PP::false : JSON::PP::true),themes=>{map {($_->{slug}=>{scheme=>$_->{scheme},surfaces=>($_->{surfaces}?JSON::PP::true:JSON::PP::false),enabled=>($_->{enabled}?JSON::PP::true:JSON::PP::false),($pair{$_->{slug}} ? (pair=>$pair{$_->{slug}}) : ())})} @{all_themes()}});
    return '<meta name="site-themes" content="'.h(JSON::PP->new->canonical->encode(\%info)).'">';
}
# The shown variants as visitors choose them: one entry per theme and name
# (Modern's light and dark variants, both "Modern", are one), in the
# variants' order, each with its light and dark variant (the default
# variant first for its scheme, else the first shown) and every slug in it.
sub theme_groups {
    my $default=default_theme();my (@groups,%at);
    for my $t (grep {$_->{enabled}} @{all_themes()}) {
        my $g=$at{($t->{package}//'')."\0".$t->{name}} //= do {push @groups,{name=>$t->{name},slugs=>[]};$groups[-1]};
        push @{$g->{slugs}},$t->{slug};
        my $s=$t->{scheme} eq 'dark' ? 'dark' : 'light';
        $g->{$s}=$t->{slug} if !defined $g->{$s} || $t->{slug} eq $default;
    }
    return \@groups;
}
# The theme menu's options for visitors: one per theme (theme_groups), named
# without light or dark (the switch beside it chooses that). Its value is
# the variant it starts with: the default when it's in the group, else the
# light one; data-variants lists the group's slugs, for theme.js.
sub theme_options {
    my $default=default_theme();
    return join '',map {my $g=$_;my $value=(grep {$_ eq $default} @{$g->{slugs}}) ? $default : ($g->{light}//$g->{dark});
        '<option value="'.h($value).'" data-variants="'.h(join ' ',@{$g->{slugs}}).'"'.($value eq $default?' selected':'').'>'.h($g->{name}).'</option>'} @{theme_groups()};
}
# Deletes a theme's variants before its folder goes (refused while one of them
# is the default), and forgets that the site had them, so installing the
# theme again brings them back.
sub theme_forget ($name) {
    my @mine=grep {($_->{package}//'') eq $name} @{all_themes()};
    die "One of its variants is the default theme. Make another theme the default first.\n" if grep {$_->{slug} eq default_theme()} @mine;
    my $offered=(attempt {decode_json($db->selectrow_array("SELECT value FROM site_settings WHERE key='themes_offered'")//'[]')}) // [];my %gone=map {$_->{slug}=>1} @mine,grep {ref eq 'HASH'} @{(theme_packages()->{$name}//{})->{variants}//[]};
    $db->begin_work;
    $db->do('DELETE FROM themes WHERE slug=?',undef,$_->{slug}) for @mine;
    $db->do("UPDATE site_settings SET value=? WHERE key='themes_offered'",undef,encode_json([grep {!$gone{$_}} @$offered]));
    $db->commit;reset_theme_cache();
    return scalar @mine;
}
# The list of themes that can be installed, as the request runner last wrote it.
# The themes that can be installed, from the list the runner last wrote.
sub themes_catalog { my $c=read_json_file(system_dir().'/results/themes.json');return ref $c eq 'HASH' && ref $c->{themes} eq 'ARRAY' ? [grep {ref $_ eq 'HASH' && theme_name_ok($_->{name})} @{$c->{themes}}] : [] }
# The most recent theme request, for the "last request failed" note.
sub themes_last_request { my ($r)=grep {($_->{action}//'') =~ /\Athemes?_(?:refresh|add|install|update|remove)\z/} @{system_results()};return $r }
# What a variant's theme gives it, from the theme's theme.json: its name,
# light or dark, original surfaces, colours, fonts and width. A site keeps
# its own values when a theme is updated, so this is what the editor's "use
# the theme's colours" puts back. Undef for a copy made with "duplicate"
# (its theme has no variant by that id) or when its theme isn't installed.
sub theme_defaults ($t) {
    my $p=theme_package($t->{package}) or return undef;
    my ($v)=grep {ref $_ eq 'HASH' && ($_->{slug}//'') eq $t->{slug}} @{$p->{variants}//[]};
    return undef unless $v && ref $v->{vars} eq 'HASH';
    return {name=>$v->{name},scheme=>$v->{scheme},surfaces=>($v->{page_palettes} ? 0 : 1),vars=>{map {($_->[0]=>$v->{vars}{$_->[0]})} theme_var_fields()}};
}
# True when a variant's values aren't its theme's.
sub theme_differs ($t,$d) {
    return 1 if $t->{name} ne $d->{name} || $t->{scheme} ne $d->{scheme} || ($t->{surfaces} ? 1 : 0)!=$d->{surfaces};
    return (grep {($t->{vars}{$_->[0]}//'') ne ($d->{vars}{$_->[0]}//'')} theme_var_fields()) ? 1 : 0;
}
# The theme editor's submitted values.
sub theme_form_values {
    my %v=(name=>param('name',60),scheme=>param('scheme',5),surfaces=>(param('page_palettes',1) eq '1'?0:1),vars=>{});
    $v{vars}{$_->[0]}=param('var_'.$_->[0],200) for theme_var_fields();
    return \%v;
}
# Checks them, with a message naming the first bad one.
sub theme_validate ($v) {
    die "Give the theme a name.\n" unless length $v->{name};
    die "Choose light or dark.\n" unless $v->{scheme} =~ /\A(?:light|dark)\z/;
    for my $f (theme_var_fields()) {
        next if theme_value_ok($f->[2],$v->{vars}{$f->[0]});
        die "$f->[1]: ".($f->[2] eq 'color' ? 'enter a colour such as #1a2b3c, rgba(0,0,0,.4) or a colour name' : $f->[2] eq 'font' ? 'enter a font list using letters, numbers, spaces, commas and quotes' : 'enter a width between 600px and 2400px').".\n";
    }
    return 1;
}

# The Themes tab (owners). Actions:
#   theme_site_options   the visitors' theme menu and window title bars
#   themes_update_all / themes_upload / themes_refresh   via the runner
#   theme_install / theme_update / theme_remove          via the runner
#   theme_preview        the editor's live preview (JSON)
#   theme_save           a variant's name, scheme and values
#   theme_enable / theme_disable / theme_default
#   order / move         the variants' order (list_order)
#   theme_duplicate      a hidden copy of a variant, to make your own
#   theme_reset          a variant's values back to its theme's (theme_defaults)
#   theme_delete         a variant (not the default)
# Then the screen: the variants, the installed theme folders (update,
# remove), the themes that can be installed, and the site-wide options.
sub themes_admin {
    return theme_preview_css() if $method eq 'GET' && defined param('preview_css',40) && length param('preview_css',40);
    my $message=param('notice',2000);my $edit=param('theme',24)||param('slug',24);my $submitted;
    if ($method eq 'POST') {
        attempt {
            my $action=param('action',30);my $slug=param('slug',24);my $t=theme_by_slug($slug);
            my $default=default_theme();
            list_order(ids=>[map {$_->{slug}} @{all_themes()}],back=>'/admin/?kind=themes',
                save=>sub (@ids) {sort_order_save($db,'themes','slug',@ids);reset_theme_cache()});
            if ($action eq 'theme_site_options') {
                setting_save(theme_picker=>(param('theme_picker',1) eq '1' ? '1' : '0'),window_bars=>(param('window_bars',1) eq '1' ? '1' : '0'));
                redirect('/admin/?kind=themes&notice='.CGI::escape('Saved.').'#on-the-site');
            }
            if ($action eq 'themes_update_all') {redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8',updates_all_request('theme'))))}
            if ($action eq 'themes_upload') {my $id=system_upload('archive','themes (a .tar.gz)','Theme archives',32);system_request('themes_add','',$id);redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8','Uploaded. The server adds what’s in it to the list within a minute.')).'#more-themes')}
            if ($action eq 'themes_refresh') {system_request('themes_refresh');redirect('/admin/?kind=themes&notice='.CGI::escape('Checking for themes. The list updates within a minute or two.').'#more-themes')}
            if ($action =~ /\Atheme_(install|update|remove)\z/) {
                my $do=$1;my $name=param('name',32);die "Choose a theme.\n" unless theme_name_ok($name);
                my %offered=map {($_->{name}=>$_)} @{themes_catalog()};my $have=theme_packages()->{$name};
                die "Themes can only be installed by the server on this site; run: doas blowfishctl theme $do $name\n" unless system_ready() && !system_state()->{off};
                die "The server is busy with another request. Try again in a minute.\n" if system_pending();
                if ($do eq 'install') {
                    my $o=$offered{$name} or die "There’s no theme called that in the list. Upload it below.\n";
                    die "$o->{label} is already installed.\n" if $have;
                    die "$o->{label} needs BlowfishCMS $o->{blowfishcms} or newer. Update BlowfishCMS first.\n" if version_cmp($BlowfishCMS::VERSION,$o->{blowfishcms}//'0')<0;
                    system_request('theme_install',$name);
                    redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8',"Installing $o->{label}. Its variants appear above, hidden until you show them, within a minute or two.")));
                }
                die "That theme isn’t installed.\n" unless $have;
                die "$have->{label} comes with BlowfishCMS and stays.\n" if $have->{core};
                if ($do eq 'update') {
                    my $o=$offered{$name};
                    die "There’s no newer version of $have->{label}.\n" unless $o && version_cmp($o->{version}//'0',$have->{version}//'0')>0;
                    die "$have->{label} $o->{version} needs BlowfishCMS $o->{blowfishcms} or newer. Update BlowfishCMS first.\n" if version_cmp($BlowfishCMS::VERSION,$o->{blowfishcms}//'0')<0;
                    system_request('theme_update',$name);
                    redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8',"Updating $have->{label} to $o->{version}. Your variants keep their colours and fonts; each one’s editor can give it the new version’s.")));
                }
                theme_forget($name);
                system_request('theme_remove',$name);
                redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8',"Removing $have->{label} and its variants.")));
            }
            if ($action eq 'theme_preview') {
                my $v=theme_form_values();theme_validate($v);
                json_response({ok=>JSON::PP::true,html=>theme_preview_html($v,$t ? $t->{slug} : 'x-preview')});
            }
            if ($action eq 'theme_save') {
                $submitted=theme_form_values();theme_validate($submitted);
                my $vars=JSON::PP->new->canonical->encode($submitted->{vars});
                if ($t) {
                    $db->do('UPDATE themes SET name=?,scheme=?,surfaces=?,vars=?,updated_at=? WHERE slug=?',undef,@$submitted{qw(name scheme surfaces)},$vars,now(),$slug);
                    json_response({ok=>JSON::PP::true,message=>'Saved.'}) if fetch_request();
                    redirect('/admin/?kind=themes&theme='.$slug.'&notice='.CGI::escape(encode('UTF-8','Saved “'.$submitted->{name}.'”.')));
                }
                die "That theme no longer exists.\n";
            }
            die "That theme no longer exists.\n" unless $t;
            if ($action eq 'theme_enable' || $action eq 'theme_disable') {
                my $on=$action eq 'theme_enable'?1:0;
                die "The default theme can't be disabled. Make another theme the default first.\n" if !$on && $slug eq $default;
                $db->do('UPDATE themes SET enabled=? WHERE slug=?',undef,$on,$slug);
                redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8',($on?'Enabled':'Disabled').' “'.$t->{name}.'”.')));
            }
            if ($action eq 'theme_default') {
                die "Enable the theme before making it the default.\n" unless $t->{enabled};
                $db->do("INSERT INTO site_settings(key,value) VALUES ('default_theme',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",undef,$slug);
                redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8','“'.$t->{name}.'” is now the default theme for new visitors.')));
            }
            if ($action eq 'theme_duplicate') {
                my $base=substr($slug,0,18);my $copy="$base-copy";my $n=2;
                while (theme_by_slug($copy)) {$copy="$base-copy$n";$n++}
                my $order=($db->selectrow_array('SELECT max(sort_order) FROM themes')//0)+1;
                $db->do('INSERT INTO themes (slug,name,scheme,surfaces,vars,css,enabled,sort_order,updated_at,package) VALUES (?,?,?,?,?,?,0,?,?,?)',undef,$copy,substr('Copy of '.$t->{name},0,60),$t->{scheme},$t->{surfaces},JSON::PP->new->canonical->encode($t->{vars}),'',$order,now(),$t->{package}//'');
                redirect('/admin/?kind=themes&theme='.$copy.'&notice='.CGI::escape(encode('UTF-8','Duplicated “'.$t->{name}.'”. The copy is hidden until you enable it.')));
            }
            if ($action eq 'theme_reset') {
                my $d=theme_defaults($t) or die "“$t->{name}” has no values of its theme’s to go back to: it’s a copy, or its theme isn’t installed.\n";
                $db->do('UPDATE themes SET name=?,scheme=?,surfaces=?,vars=?,updated_at=? WHERE slug=?',undef,@$d{qw(name scheme surfaces)},JSON::PP->new->canonical->encode($d->{vars}),now(),$slug);
                redirect('/admin/?kind=themes&theme='.$slug.'&notice='.CGI::escape(encode('UTF-8','“'.$d->{name}.'” has its theme’s colours, fonts and width again.')));
            }
            if ($action eq 'theme_delete') {
                die "The default theme can't be deleted. Make another theme the default first.\n" if $slug eq $default;
                $db->do('DELETE FROM themes WHERE slug=?',undef,$slug);
                redirect('/admin/?kind=themes&notice='.CGI::escape(encode('UTF-8','Deleted “'.$t->{name}.'”.')));
            }
            die "Choose an action.\n";
        } or do {$message=failed_action($@);json_response({ok=>JSON::PP::false,message=>$message},400) if fetch_request()};
        reset_theme_cache();
    }
    my $default=default_theme();
    # A variant's editor (?theme=SLUG). New variants are made with "duplicate":
    # the old "new theme" address (?new=1) goes to the list.
    redirect('/admin/?kind=themes') if param('new',1) eq '1';
    my $t=theme_by_slug($edit);
    return theme_editor($t,$submitted,$message) if $t;
    my $ready=system_ready() && !system_state()->{off};my $pending=$ready && system_pending();
    admin_page('Themes',section=>'themes',notice=>$message,intro=>'How the site looks. Each theme comes with one or more variants; a variant has its own colours, fonts and width, and you can duplicate one to make your own. Visitors pick from the variants that are shown; new visitors get the default.');
    print '<div data-refresh="'.($pending ? 10 : 0).'"></div>';
    my $progress=updates_all_status_html(qr/\A(?:themes_update_all|updates_all)\z/);
    print '<p class="panel-note">Working on it… this page refreshes by itself.</p>' if $pending && $progress !~ /Updating/;
    print $progress,request_failed_notice(themes_last_request());
    print update_all_button_html('theme','themes');
    my @list=@{all_themes()};my $packages=theme_packages();
    my @rows;my $index=0;
    # Variants that share a name (Modern's light and dark) are told apart by their scheme.
    my %named;$named{$_->{name}}++ for @list;
    for my $t (@list) {
        $index++;my $slug=h($t->{slug});my $p=$packages->{$t->{package}//''};
        my $from=$p && !$p->{problem} ? h($p->{label}) : length($t->{package}//'') ? '<span class="admin-notice--error">'.h($t->{package}).' isn’t installed</span>' : 'no theme files';
        my $name=$named{$t->{name}}>1 ? "$t->{name} ($t->{scheme})" : $t->{name};
        # In view: shown to visitors (a switch), edit, preview and make default; the rarer actions in "…".
        push @rows,admin_row(title=>$name,order=>$t->{slug},off=>!$t->{enabled},badges=>[$t->{slug} eq $default ? 'Default' : ()],
            lead=>'<span class="theme-swatches" data-swatches="'.h(join ' ',map {$t->{vars}{$_}//''} qw(bg window accent ink)).'"></span>',
            meta=>[$slug,h($t->{scheme}),$from,$t->{enabled} ? 'shown' : 'hidden'],
            actions=>switch_button('themes',$t->{enabled}?'theme_disable':'theme_enable','',$t->{enabled},'shown',what=>'Shown to visitors',name=>$name,post=>{slug=>$t->{slug}},disabled=>$t->{slug} eq $default ? 'The default theme is always shown' : '')
                .'<a class="buttonlike" href="/admin/?kind=themes&amp;theme='.$slug.'">edit</a><a class="buttonlike" href="/?theme='.$slug.'" target="_blank" rel="noopener">preview ↗</a>'
                .'<form method="post" action="/admin/">'.fields('theme_default','themes').hidden(slug=>$t->{slug}).'<button class="buttonlike"'.($t->{slug} eq $default || !$t->{enabled}?' disabled':'').'>make default</button></form>',
            menu=>move_buttons('themes',$t->{slug},$index,scalar @list,label=>$name)
                .'<form method="post" action="/admin/">'.fields('theme_duplicate','themes').hidden(slug=>$t->{slug}).'<button class="text-button">duplicate</button></form>'
                .'<form method="post" action="/admin/" class="delete-form" data-confirm="'.h("Delete the variant $name? Its theme stays installed.").'">'.fields('theme_delete','themes').hidden(slug=>$t->{slug}).'<button class="text-button danger"'.($t->{slug} eq $default?' disabled':'').'>delete</button></form>');
    }
    window('variants',admin_list(\@rows,order=>'themes'));
    # The theme folders on this server, then the list's.
    my %offered=map {($_->{name}=>$_)} @{themes_catalog()};my $catalog=read_json_file(system_dir().'/results/themes.json');
    my $command=sub ($cmd) { return '<code class="addon-command">doas blowfishctl theme '.h($cmd).'</code>' };
    my $button=sub ($action,$name,$label,$class='',$confirm='') {
        return $ready ? '<form method="post" action="/admin/"'.(length $confirm ? ' class="delete-form" data-confirm="'.h($confirm).'"' : '').'>'.fields($action,'themes').hidden(name=>$name)
            .'<button class="'.($class eq 'danger' ? 'text-button danger' : 'buttonlike'.($class ? " $class" : '')).'" type="submit"'.($pending?' disabled':'').'>'.h($label).'</button></form>' : $command->(($action =~ s/\Atheme_//r)." $name");
    };
    my @inst;
    for my $name (sort {($packages->{$b}{core}//0) <=> ($packages->{$a}{core}//0) || $a cmp $b} keys %$packages) {
        my $m=$packages->{$name};my $o=$offered{$name};
        my $uses=grep {($_->{package}//'') eq $name} @list;
        my $update=$o && !$m->{core} && version_cmp($o->{version}//'0',$m->{version}//'0')>0
            ? (version_cmp($BlowfishCMS::VERSION,$o->{blowfishcms}//'0')<0 ? '<span class="media-label">'.h($o->{version}).' needs BlowfishCMS '.h($o->{blowfishcms}).'</span>' : $button->('theme_update',$name,'update to '.$o->{version},'is-primary')) : '';
        push @inst,admin_row(title_html=>h($m->{label}//$name).($m->{version}?' <span class="media-label">'.h($m->{version}).'</span>':''),menu_for=>$m->{label}//$name,
            text=>$m->{problem} ? '<span class="admin-notice--error">Can’t be used: '.h($m->{problem}).'</span>' : h($m->{description}//''),
            meta=>[$m->{core}?'comes with BlowfishCMS':'installed',"$uses variant".($uses==1?'':'s'),($m->{author}?'by '.h($m->{author}):())],
            actions=>$update,menu=>$m->{core} ? '' : $button->('theme_remove',$name,'remove','danger',"Remove $m->{label}? Its variants, and the colours and fonts you gave them, go with it."));
    }
    window('installed themes',admin_list(\@inst));
    my @more=grep {!$packages->{$_->{name}}} sort {($a->{label}//$a->{name}) cmp ($b->{label}//$b->{name})} values %offered;
    my $more=join '',map {my $o=$_;admin_row(title_html=>h($o->{label}//$o->{name}).' <span class="media-label">'.h($o->{version}//'').'</span>',text=>h($o->{description}//''),
        meta=>[(ref $o->{variants} eq 'ARRAY' ? scalar(@{$o->{variants}}) : 0).' variant'.(ref $o->{variants} eq 'ARRAY' && @{$o->{variants}}==1?'':'s'),($o->{author}?'by '.h($o->{author}):())],
        actions=>version_cmp($BlowfishCMS::VERSION,$o->{blowfishcms}//'0')<0 ? '<span class="media-label">needs BlowfishCMS '.h($o->{blowfishcms}).'</span>' : $button->('theme_install',$o->{name},'install','is-primary'))} @more;
    window('more themes','<div id="more-themes">'.catalog_box('themes',$catalog,$more,scalar @more,$ready,$pending).'</div>');
    window('on the site','<form method="post" action="/admin/" class="admin-form" id="on-the-site">'.fields('theme_site_options','themes')
        .switch_field('theme_picker','Let visitors choose a theme',setting('theme_picker') ne '0',hint=>'A “theme” menu in the navigation bar, listing the themes that are shown. Without it, everyone sees the default theme.')
        .switch_field('window_bars','Window title bars',setting('window_bars') ne '0',hint=>'The small title bar on each section of a page. Turn it off for a plainer look.')
        .'<button class="buttonlike" type="submit">save</button></form>');
    end_page();
}
# One variant's editor: name, light or dark, colours (each with a colour
# picker), fonts and width on the left, and on the right a live preview of
# a page drawn with the unsaved values.
sub theme_editor ($t,$submitted,$message) {
    my $v=$submitted // {name=>$t->{name},scheme=>$t->{scheme},surfaces=>$t->{surfaces},vars=>{%{$t->{vars}}}};
    my $form='<form method="post" action="/admin/" class="admin-form theme-editor" id="theme-editor">'.fields('theme_save','themes').hidden(slug=>$t->{slug},package=>$t->{package}//'');
    $form.='<div class="theme-editor__grid"><label>Name<input name="name" maxlength="60" required value="'.h($v->{name}).'"></label>';
    $form.='<label>ID<input value="'.h($t->{slug}).'" disabled></label>';
    $form.='<label>Light or dark<select name="scheme">'.join('',map {'<option value="'.$_.'"'.($v->{scheme} eq $_?' selected':'').'>'.$_.'</option>'} qw(light dark)).'</select></label>';
    $form.=switch_field('page_palettes','Original surfaces',!$v->{surfaces},hint=>'Keep cards and form fields light even in a dark variant (the original Plan9 look).').'</div>';
    $form.='<fieldset><legend>Colours</legend><div class="theme-editor__grid">';
    for my $f (grep {$_->[2] eq 'color'} theme_var_fields()) {
        $form.='<label>'.h($f->[1]).'<span class="color-field"><input type="color" data-color-for="var_'.$f->[0].'" aria-label="Pick '.h(lc $f->[1]).'"><input name="var_'.$f->[0].'" maxlength="200" required value="'.h($v->{vars}{$f->[0]}).'"></span></label>';
    }
    $form.='</div></fieldset><fieldset><legend>Fonts &amp; layout</legend><div class="theme-editor__grid">';
    for my $f (grep {$_->[2] ne 'color'} theme_var_fields()) {
        $form.='<label>'.h($f->[1]).'<input name="var_'.$f->[0].'" maxlength="200" required value="'.h($v->{vars}{$f->[0]}).'"'.($f->[2] eq 'font'?' list="font-stacks"':'').'></label>';
    }
    $form.='</div><datalist id="font-stacks">'.join('',map {'<option value="'.h($_).'">'} ('"Times New Roman","Iowan Old Style",serif','Georgia,"Times New Roman",serif','"Verdana","Geneva",system-ui,sans-serif','Tahoma,Verdana,sans-serif','"Trebuchet MS",Verdana,sans-serif','Arial,Helvetica,sans-serif','system-ui,sans-serif','"Courier New","Liberation Mono",monospace','"DejaVu Sans Mono","Courier New",monospace','ui-monospace,monospace')).'</datalist></fieldset>';
    my $p=theme_package($t->{package});
    $form.='<p class="media-label theme-editor__files">'.($p ? 'Everything beyond these colours, fonts and width comes from the files of <strong>'.h($p->{label}).'</strong> '.h($p->{version}).', which every variant of it shares.' : 'This variant’s theme isn’t installed, so only these colours, fonts and width apply. Install its theme on this tab to get the rest of its look back.').'</p>';
    $form.='<div class="editor-actions no-js-only"><button class="buttonlike" type="submit">save</button></div></form>';
    # When the variant's values aren't its theme's (changed here, or kept
    # through an update that brought new ones), a way back to the theme's.
    my $d=theme_defaults($t);
    $form.='<form method="post" action="/admin/" class="delete-form theme-editor__reset" data-confirm="'.h("Give “$t->{name}” the colours, fonts and width that $p->{label} $p->{version} gives it? The ones it has now are replaced.").'">'.fields('theme_reset','themes').hidden(slug=>$t->{slug})
        .'<p class="media-label">This variant’s name, colours, fonts or width aren’t the ones <strong>'.h($p->{label}).'</strong> '.h($p->{version}).' gives it (you changed them, or they were kept when the theme was updated).</p>'
        .'<button class="buttonlike" type="submit">use the theme’s colours</button></form>' if $p && $d && !$submitted && theme_differs($t,$d);
    my $actions='<span class="admin-top__status" id="theme-status" role="status">All changes saved</span>'
        .'<a class="buttonlike" href="/?theme='.h($t->{slug}).'" target="_blank" rel="noopener">view saved ↗</a>'
        .'<button class="buttonlike is-primary" type="submit" form="theme-editor">save</button>';
    admin_page($t->{name},section=>'themes',crumbs=>[['Themes','/admin/?kind=themes']],notice=>$message,actions=>$actions,
        intro=>'Changes show in the preview as you make them; visitors see them once you save.');
    my $pages=join '',map {'<option value="'.h($_->{slug}).'">'.h(ucfirst $_->{nav_label}).'</option>'} @{all_pages()};
    print '<div class="theme-workspace"><div class="theme-workspace__form">';
    window('edit theme', $form);
    print '</div><div class="theme-workspace__preview" hidden><label class="theme-workspace__page">Preview page <select id="theme-preview-page">'.$pages.'</select></label><div class="preview-frame" data-preview></div></div></div>';
    end_page();
}

1;