Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 9 additions & 10 deletions resources/boost/skills/saucebase-themes-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ A developer-facing visual theming system for Saucebase. Lets the SaaS owner desi
- Google Fonts loaded on demand
- Theme picker with circle-reveal transition (`@saucebase/core/lib/themeReveal`)
- Preview persists in `localStorage` key `sb-theme-theme` (this browser only)
- Footer: Delete (saved presets) · Reset · **Set as default** (local only) · Save menu (Save / Save as)
- Footer: Delete (saved presets) · Reset · **Set as default** (`writable`) · Save menu (Save / Save as)
- Filament admin theme: a separate settings page (`AdminThemeSettings`), colours/font/radius for the admin panel via `ThemesPlugin`

---
Expand All @@ -50,19 +50,19 @@ Theme selection is **global** (one theme for all users). Per-user or per-tenant

### Admin Permission

`manage themes` covers the `AdminThemeSettings` page (`canAccess()`). `access admin panel` alone only opens the panel. `Database\Seeders\DatabaseSeeder` creates it, granted to nobody; the app's roles seeder decides who gets it, and `admin` passes every check. The frontend theme routes are gated by `themes.writable` and the local environment, not by this permission.
`manage themes` covers the `AdminThemeSettings` page (`canAccess()`). `access admin panel` alone only opens the panel. `Database\Seeders\DatabaseSeeder` creates it, granted to nobody; the app's roles seeder decides who gets it, and `admin` passes every check. The frontend theme write routes, Set as default included, are gated by `themes.writable`, not by this permission.

### Data flow

```
ThemePanel "Set as default" (POST /themes/apply, local only)
ThemePanel "Set as default" (POST /themes/apply, `themes.writable`)
↓ ThemeService::applyToCss() + replaceDefault() (merges into default.json, so vars the editor doesn't manage stay)
resources/css/theme.css ← baked CSS vars (:root / .dark), what everyone sees
resources/themes/default.json ← the picker's "Default" entry, kept equal to theme.css
storage/app/themes/default.json.backup ← previous default; not listed; copy back to restore

ThemesServiceProvider ← discovers bundled + storage/app/themes/*.json, shares `themes` prop
↓ (items, fonts, canSave, canApply)
↓ (items, fonts, canSave)
ThemePanel ← previews via inline CSS var overrides (applyThemeVars)
```

Expand Down Expand Up @@ -139,8 +139,7 @@ documentElement inline styles ← set by applyThemeVars() when a theme is activ
| `src/Console/Commands/ApplyThemeCommand.php` | CLI wrapper around `applyToCss()` |
| `src/Http/Controllers/ThemesController.php` | store / update / destroy presets, apply |
| `src/Http/Requests/ApplyThemeRequest.php` | `cssVars` rules: size caps, keys `[a-z0-9-]`, values without `;{}\`, `/*` `*/`, `url(`, `image-set(` (they end up in theme.css); `SaveThemeRequest` extends it |
| `src/Http/Middleware/EnsureThemesWritable.php` | 404 on preset writes unless `themes.writable` |
| `src/Http/Middleware/EnsureLocalEnvironment.php` | 404 on apply outside `local` |
| `src/Http/Middleware/EnsureThemesWritable.php` | 404 on every write (presets and Set as default) unless `themes.writable` |
| `src/Providers/ThemesServiceProvider.php` | Shares the `themes` Inertia prop |
| `src/Filament/…`, `src/Admin/AdminTheme.php`, `src/Settings/AdminThemeSettings.php` | Filament admin theme |
| `resources/js/lib/fields.ts` | `themeFields()`: every editable field with type, vars, constraints |
Expand Down Expand Up @@ -242,10 +241,10 @@ When a synced field is edited in one mode, the value is mirrored to `modeSyncCac

```env
THEMES_ENABLED= # show the ThemePanel — default: on in local only
THEMES_WRITABLE= # allow save/update/delete of presets — default: on in local only
THEMES_WRITABLE= # allow save/update/delete of presets and Set as default — default: on in local only
```

Owners may opt in outside local (e.g. a demo shows the panel with writes off). With `writable` off the write routes return 404 and the panel hides Save (`themes.canSave`). The write routes are `themes.store`, `themes.update` and `themes.destroy`; `themes.apply` (Set as default) only answers in the local environment. All are throttled (30/min) and `cssVars` is capped (100 keys per section, 255 chars per value).
Owners may opt in outside local (e.g. a demo shows the panel with writes off). With `writable` off the write routes return 404 and the panel hides Save and Set as default (`themes.canSave`). The write routes are `themes.store`, `themes.update`, `themes.destroy` and `themes.apply` (Set as default, which rewrites `theme.css`, a source file: keep `writable` off in production). The E2E suite turns `enabled` and `writable` on per test with `laravel.config()`. All are throttled (30/min) and `cssVars` is capped (100 keys per section, 255 chars per value).

---

Expand All @@ -267,11 +266,11 @@ npm run test:unit # lib/
npx playwright test --project="@themes*" # E2E
```

- `tests/Feature/ThemesApplyTest.php`: Set as default (local only, theme.css + default.json + backup)
- `tests/Feature/ThemesApplyTest.php`: Set as default (`themes.writable`, theme.css + default.json + backup)
- `tests/Feature/ThemesAccessTest.php`: `enabled`/`writable` flags, throttling, payload caps
- `tests/Feature/ThemesControllerTest.php`, `ThemesConfigTest.php`: preset CRUD, shared props
- `tests/Feature/ApplyThemeCommandTest.php`: CSS patching via the command
- `tests/Feature/AdminTheme*Test.php`: Filament admin theme
- `resources/js/lib/*.test.ts`: colour maths, fields, theme vars, panel payload, Tailwind palette

Tests that simulate `local` must disable `PreventRequestForgery`: Laravel only skips CSRF in `testing`.
Tests that post to the write routes disable `PreventRequestForgery` (`allowWrites()` in `ThemesApplyTest`), so the CSRF check stays out of what they test.
5 changes: 2 additions & 3 deletions resources/js/react/components/ThemePanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,6 @@ export default function ThemePanel() {
const themesProp = page.props?.themes;
const themes: Theme[] = themesProp?.items ?? [];
const canSave = themesProp?.canSave === true;
const canApply = themesProp?.canApply === true;
const fontOptions: Record<string, Font[]> = {
'font-sans': themesProp?.fonts?.sans ?? [],
'font-serif': themesProp?.fonts?.serif ?? [],
Expand Down Expand Up @@ -808,7 +807,7 @@ export default function ThemePanel() {
<IconRotateCcw className="size-4" />
{t('Reset')}
</button>
{canApply && (
{canSave && (
<button
data-testid="theme-panel-apply"
disabled={!canReset}
Expand Down Expand Up @@ -862,7 +861,7 @@ export default function ThemePanel() {
</button>
</IconTooltip>
))}
{!canApply && (
{!canSave && (
<IconTooltip
label={t('How to use this theme')}
>
Expand Down
1 change: 0 additions & 1 deletion resources/js/types/page-props.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ declare module '@inertiajs/core' {
themes?: {
items: Theme[];
canSave: boolean;
canApply: boolean;
fonts: {
sans: Font[];
serif: Font[];
Expand Down
5 changes: 2 additions & 3 deletions resources/js/vue/components/ThemePanel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ const themesEnabled = computed(() => page.props?.themes != null);
// The panel lives in <body>, which the server can't render into: mount it first.
const mounted = useMounted();
const canSave = computed(() => page.props?.themes?.canSave === true);
const canApply = computed(() => page.props?.themes?.canApply === true);

const themes = computed<Theme[]>(() => page.props?.themes?.items ?? []);
const fontOptions = computed<Record<string, Font[]>>(() => ({
Expand Down Expand Up @@ -964,7 +963,7 @@ const dialogCommandOpen = ref(false);
{{ $t('Reset') }}
</button>
<button
v-if="canApply"
v-if="canSave"
data-testid="theme-panel-apply"
:disabled="!canReset"
class="border-border hover:bg-accent hover:text-accent-foreground focus-visible:ring-ring flex flex-1 cursor-pointer items-center justify-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors focus-visible:ring-2 focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50"
Expand Down Expand Up @@ -1018,7 +1017,7 @@ const dialogCommandOpen = ref(false);
</TooltipContent>
</Tooltip>
</template>
<Tooltip v-if="!canApply">
<Tooltip v-if="!canSave">
<TooltipTrigger as-child>
<button
data-testid="theme-panel-command"
Expand Down
3 changes: 0 additions & 3 deletions routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

use Illuminate\Support\Facades\Route;
use Modules\Themes\Http\Controllers\ThemesController;
use Modules\Themes\Http\Middleware\EnsureLocalEnvironment;
use Modules\Themes\Http\Middleware\EnsureThemesWritable;

Route::middleware(['web', EnsureThemesWritable::class, 'throttle:30,1'])->group(function (): void {
Expand All @@ -16,9 +15,7 @@
Route::delete('/themes/{name}', [ThemesController::class, 'destroy'])
->name('themes.destroy')
->where('name', '[a-z0-9-]+');
});

Route::middleware(['web', EnsureLocalEnvironment::class, 'throttle:30,1'])->group(function (): void {
Route::post('/themes/apply', [ThemesController::class, 'apply'])
->name('themes.apply');
});
20 changes: 0 additions & 20 deletions src/Http/Middleware/EnsureLocalEnvironment.php

This file was deleted.

1 change: 0 additions & 1 deletion src/Providers/ThemesServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ protected function shareInertiaData(): void
Inertia::share('themes', fn () => config('themes.enabled') ? [
'items' => ThemeService::discoverThemes(),
'canSave' => (bool) config('themes.writable'),
'canApply' => app()->isLocal(),
'fonts' => [
'sans' => ThemeService::loadFonts('sans'),
'serif' => ThemeService::loadFonts('serif'),
Expand Down
42 changes: 23 additions & 19 deletions tests/Feature/ThemesApplyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ protected function tearDown(): void
}

/** Laravel only skips the CSRF check in the `testing` environment, so it's off here explicitly. */
private function actLocally(): void
private function allowWrites(): void
{
$this->app['env'] = 'local';
config(['themes.writable' => true]);
$this->withoutMiddleware(PreventRequestForgery::class);
}

Expand All @@ -76,7 +76,7 @@ private function payload(): array

public function test_applying_the_default_theme_to_itself_is_refused_and_changes_nothing(): void
{
$this->actLocally();
$this->allowWrites();
@unlink($this->backupJsonPath);

$stored = json_decode($this->originalDefaultJson, true)['cssVars'];
Expand All @@ -90,16 +90,16 @@ public function test_applying_the_default_theme_to_itself_is_refused_and_changes
$this->assertFileDoesNotExist($this->backupJsonPath);
}

public function test_apply_does_not_exist_outside_local(): void
public function test_apply_does_not_exist_while_not_writable(): void
{
$this->postJson(route('themes.apply'), $this->payload())->assertNotFound();

$this->assertSame($this->originalCss, file_get_contents($this->themeCssPath));
}

public function test_apply_writes_the_theme_into_theme_css_locally(): void
public function test_apply_writes_the_theme_into_theme_css(): void
{
$this->actLocally();
$this->allowWrites();

$this->postJson(route('themes.apply'), $this->payload())->assertOk();

Expand All @@ -112,7 +112,7 @@ public function test_apply_writes_the_theme_into_theme_css_locally(): void

public function test_values_that_would_break_the_css_are_rejected(): void
{
$this->actLocally();
$this->allowWrites();
$payload = $this->payload();
$payload['cssVars']['light']['primary'] = 'red; } body { display: none';

Expand All @@ -122,18 +122,22 @@ public function test_values_that_would_break_the_css_are_rejected(): void
$this->assertSame($this->originalCss, file_get_contents($this->themeCssPath));
}

public function test_can_apply_is_shared_only_locally(): void
/** Set as default is a write like any other: `themes.writable` decides, in any environment. */
public function test_apply_follows_the_writable_setting(): void
{
config(['themes.enabled' => true]);
$this->get('/')->assertInertia(fn ($page) => $page->where('themes.canApply', false));
$this->withoutMiddleware(PreventRequestForgery::class);

config(['themes.writable' => false]);
$this->postJson(route('themes.apply'), $this->payload())->assertNotFound();
$this->assertSame($this->originalCss, file_get_contents($this->themeCssPath));

$this->actLocally();
$this->get('/')->assertInertia(fn ($page) => $page->where('themes.canApply', true));
config(['themes.writable' => true]);
$this->postJson(route('themes.apply'), $this->payload())->assertOk();
}

public function test_setting_a_default_updates_default_json_and_backs_up_the_previous_one(): void
{
$this->actLocally();
$this->allowWrites();
$original = json_decode($this->originalDefaultJson, true);

$this->postJson(route('themes.apply'), $this->payload())->assertOk();
Expand All @@ -151,7 +155,7 @@ public function test_setting_a_default_updates_default_json_and_backs_up_the_pre

public function test_setting_a_default_keeps_vars_the_editor_does_not_manage(): void
{
$this->actLocally();
$this->allowWrites();
$default = json_decode($this->originalDefaultJson, true);
$default['cssVars']['light']['destructive-foreground'] = 'oklch(1 0 0)';
file_put_contents($this->defaultJsonPath, json_encode($default));
Expand All @@ -165,7 +169,7 @@ public function test_setting_a_default_keeps_vars_the_editor_does_not_manage():

public function test_the_default_entry_shows_the_new_default_and_the_backup_stays_out_of_the_picker(): void
{
$this->actLocally();
$this->allowWrites();
config(['themes.enabled' => true]);

$themeCount = count(ThemeService::discoverThemes());
Expand All @@ -181,7 +185,7 @@ public function test_the_default_entry_shows_the_new_default_and_the_backup_stay

public function test_keys_that_would_break_the_css_are_rejected(): void
{
$this->actLocally();
$this->allowWrites();
$payload = $this->payload();
$payload['cssVars']['light']['x: red; } body { display: none } :root { --y'] = 'red';

Expand All @@ -193,7 +197,7 @@ public function test_keys_that_would_break_the_css_are_rejected(): void

public function test_values_that_open_a_css_comment_are_rejected(): void
{
$this->actLocally();
$this->allowWrites();
$payload = $this->payload();
$payload['cssVars']['light']['primary'] = 'red /* the rest of theme.css';

Expand All @@ -205,7 +209,7 @@ public function test_values_that_open_a_css_comment_are_rejected(): void

public function test_values_that_load_external_resources_are_rejected(): void
{
$this->actLocally();
$this->allowWrites();
$payload = $this->payload();
$payload['cssVars']['light']['primary'] = 'url(https://evil.test/track.png)';

Expand All @@ -216,7 +220,7 @@ public function test_values_that_load_external_resources_are_rejected(): void

public function test_values_are_written_literally(): void
{
$this->actLocally();
$this->allowWrites();
$payload = $this->payload();
$payload['cssVars']['light']['font-sans'] = '"$0 Sans", sans-serif';

Expand Down
8 changes: 8 additions & 0 deletions tests/e2e/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ const THEME_STORAGE_KEY = 'sb-theme-theme';
// "Set as default" rewrites. One worker runs them in order so they can't collide.
test.describe.configure({ mode: 'serial' });

// The suite runs in its own `e2e` environment, where the panel and its writes are
// off by default, as anywhere but local. Each test turns them on for itself; a
// describe that tests them off overrides this after it.
test.beforeEach(async ({ laravel }) => {
await laravel.config('themes.enabled', true);
await laravel.config('themes.writable', true);
});

async function getCssVar(page: Page, varName: string): Promise<string> {
return page.evaluate(
(v) =>
Expand Down
Loading