diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 510d9c0..cbb0c1f 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -169,10 +169,18 @@ jobs: - uses: actions/checkout@v7 with: ref: ${{ github.head_ref }} - - name: "laravel-pint" - uses: aglipanci/laravel-pint-action@36de00d5f5a8a4e12d443e01671daa12a18f4c79 # 2.6 + - name: Setup PHP + uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 with: - configPath: './pint.json' + php-version: '8.4' + coverage: none + + - name: Install dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + + # The project's own Pint (composer.lock), so CI formats exactly as a local run does. + - name: Pint + run: vendor/bin/pint --config pint.json - name: Commit changes uses: stefanzweifel/git-auto-commit-action@d0b01107b5db882071f96de5dd4b54961ea93f4c # v7.2.1 diff --git a/composer.json b/composer.json index 6f305b7..7b5beca 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,7 @@ "saucebase", "saas" ], - "version": "v3.0.0", + "version": "v3.1.0", "license": "MIT", "authors": [ { @@ -62,7 +62,7 @@ }, "extra": { "branch-alias": { - "dev-dev": "3.0.x-dev" + "dev-dev": "3.x-dev" }, "laravel": { "providers": [ diff --git a/phpstan.neon b/phpstan.neon index b586584..2b5d02f 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -24,3 +24,6 @@ parameters: # analysed. - identifier: trait.unused path: src/Filament/ModulePlugin.php + # Same for the test helper modules and templates use in their own tests. + - identifier: trait.unused + path: src/Testing/AssertsDemoAccounts.php diff --git a/resources/boost/skills/saucebase-module-development/SKILL.md b/resources/boost/skills/saucebase-module-development/SKILL.md index 1b296a5..d6e78ea 100644 --- a/resources/boost/skills/saucebase-module-development/SKILL.md +++ b/resources/boost/skills/saucebase-module-development/SKILL.md @@ -167,6 +167,12 @@ no module provides fails. In production it asks first; `--force` (also on `sauce same kind; modules that aren't installed are ignored. A module with an admin area creates its `manage {module}` permission there (see `saucebase-filament-development`); state seeders never hold anything an install needs. +A state seeder that creates accounts declares them on its class, one attribute each: +`#[DemoAccount('owner@saucebase.dev', 'owns Acme and Globex', featured: true)]` +(`Saucebase\Core\Attributes\DemoAccount`). `php artisan modules:demo-accounts --state=showcase` lists them +(`--json` for the installer); `featured` ones are named where people start, after `modules:seed --state` and in +the installer's summary. Feature only the one or two to sign in with first. They all use `DEMO_PASSWORD`. + ## Patches A module changes application files it doesn't own (the `User` model, `routes/web.php`) with diff --git a/resources/boost/skills/saucebase-template-development/SKILL.md b/resources/boost/skills/saucebase-template-development/SKILL.md index c36460e..a2ea534 100644 --- a/resources/boost/skills/saucebase-template-development/SKILL.md +++ b/resources/boost/skills/saucebase-template-development/SKILL.md @@ -26,7 +26,7 @@ The recipe writes it: `type: saucebase-template`, `require` = core and every Sau - A module added later: `saucebase:module-install `, then add it to `require` by hand. - `extra.saucebase.configure` (optional): module settings for the install, e.g. `{"auth": {"registration_enabled": true}}`. -- `extra.saucebase.demo_account` (optional): the email the demo signs in with; the installer prints it after `--demo`. +- The demo's account goes on `Default{Template}DatabaseSeeder`, not here: `#[DemoAccount('notes@saucebase.dev', 'your notes and lists', featured: true)]`. The installer names it after `--demo` (see `saucebase-module-development`, Seeders). - Keep the template's frontend in `resources/js/{stack}/`. The installer flattens it into apps of that stack and refuses a module without the folder. ## Stubs: replacing app files diff --git a/resources/js/lib/modal.test.ts b/resources/js/lib/modal.test.ts index 0414ca4..e7c5165 100644 --- a/resources/js/lib/modal.test.ts +++ b/resources/js/lib/modal.test.ts @@ -14,11 +14,16 @@ class FakeKeyboardEvent extends Event { const layerAbove = { closest: () => null }; +/** reka marks its layers; Radix (React) doesn't, so its open layers are found by shadcn's slot. */ +let layerSelector = '[data-dismissable-layer]'; + beforeEach(() => { const document = Object.assign(new EventTarget(), { + documentElement: new EventTarget(), querySelector: (selector: string) => selector === '.im-modal-wrapper' ? {} : null, - querySelectorAll: () => [layerAbove], + querySelectorAll: (selector: string) => + selector.includes(layerSelector) ? [layerAbove] : [], }); Object.assign(globalThis, { @@ -30,11 +35,125 @@ beforeEach(() => { }); afterEach(() => { - for (const key of ['document', 'window', 'KeyboardEvent']) { + for (const key of ['document', 'window', 'KeyboardEvent', 'Element']) { Reflect.deleteProperty(globalThis, key); } }); +/** Just enough of CSS attribute selectors: `[a]`, `[a="v"]`, `[a$="v"]` and `:not(...)` of those. */ +function matches(element: Record, selector: string): boolean { + const test = ( + attribute: string, + operator?: string, + value?: string, + ): boolean => { + const actual = element[attribute]; + if (operator === undefined) return actual !== undefined; + if (actual === undefined) return false; + + return operator === '$=' ? actual.endsWith(value!) : actual === value; + }; + + const parts = [ + ...selector.matchAll(/(:not\()?\[([\w-]+)(?:(\$?=)"([^"]*)")?\]\)?/g), + ]; + + return ( + parts.length > 0 && + parts.every( + ([, not, attribute, operator, value]) => + Boolean(not) !== test(attribute, operator, value), + ) + ); +} + +/** A node in a tiny page: listeners by phase, and an event's way down and back up. */ +class FakeNode { + listeners: { listener: (event: object) => void; capture: boolean }[] = []; + + constructor( + public parent: FakeNode | null = null, + public attributes: Record = {}, + ) {} + + addEventListener( + _type: string, + listener: (event: object) => void, + capture = false, + ): void { + this.listeners.push({ listener, capture }); + } + + contains(other: FakeNode | null): boolean { + for (let node = other; node; node = node.parent) { + if (node === this) return true; + } + + return false; + } + + closest(selector: string): FakeNode | null { + for (let node: FakeNode | null = this; node; node = node.parent) { + const attributes = node.attributes; + if ( + selector + .split(',') + .some((part) => matches(attributes, part.trim())) + ) { + return node; + } + } + + return null; + } +} + +/** document > html > body > the modal; React listens on body, the portals' container. */ +function page(): { document: FakeNode; body: FakeNode } { + const document = new FakeNode(); + const html = new FakeNode(document); + const body = new FakeNode(html); + const modal = new FakeNode(body, { class: 'im-modal-wrapper' }); + + Object.assign(document, { + documentElement: html, + querySelector: (selector: string) => + selector === '.im-modal-wrapper' ? modal : null, + querySelectorAll: () => [], + }); + Object.assign(globalThis, { document, Element: FakeNode }); + initializeModals(() => {}); + + return { document, body }; +} + +/** focusin down from the document (capture), then back up (bubble), until stopped. */ +function focus(target: FakeNode): void { + const path: FakeNode[] = []; + for (let node: FakeNode | null = target; node; node = node.parent) { + path.push(node); + } + + let stopped = false; + const event = { + type: 'focusin', + target, + stopPropagation: () => (stopped = true), + }; + + for (const [nodes, capture] of [ + [[...path].reverse(), true], + [path, false], + ] as const) { + for (const node of nodes) { + if (stopped) return; + node.listeners + .filter((entry) => entry.capture === capture) + .forEach((entry) => entry.listener(event)); + } + } +} + function pressEscape(): Event { const event = new FakeKeyboardEvent('keydown', { key: 'Escape', @@ -56,6 +175,41 @@ describe('Escape over a modal', () => { expect(layerHeardIt).toBe(true); }); + /** + * React's menus and selects (Radix) carry no layer mark, only shadcn's open content slot. + * An open collapsible (the sidebar's nav groups) carries one too, but is no layer: Escape + * must still reach the modal. + */ + it('goes to a Radix overlay above, not to any open content slot', () => { + const heard = (slot: string, state = 'open'): boolean => { + const element = { 'data-slot': slot, 'data-state': state }; + Object.assign(document, { + querySelectorAll: (selector: string) => + selector + .split(',') + .some((part) => matches(element, part.trim())) + ? [layerAbove] + : [], + }); + let layerHeardIt = false; + const listener = () => (layerHeardIt = true); + window.addEventListener('keydown', listener); + pressEscape(); + window.removeEventListener('keydown', listener); + + return layerHeardIt; + }; + + expect(heard('collapsible-content')).toBe(false); + expect(heard('sidebar-group-content')).toBe(false); + expect(heard('dropdown-menu-content')).toBe(true); + expect(heard('select-content')).toBe(true); + expect(heard('dialog-content')).toBe(true); + // Radix's tooltip is never "open", only delayed or instant. + expect(heard('tooltip-content', 'delayed-open')).toBe(true); + expect(heard('dialog-content', 'closed')).toBe(false); + }); + /** A layer may refuse Escape (mid-submit, say); the refusal must hold. */ it('keeps a refusal from the layer above', () => { window.addEventListener('keydown', (event) => event.preventDefault()); @@ -63,3 +217,35 @@ describe('Escape over a modal', () => { expect(pressEscape().defaultPrevented).toBe(true); }); }); + +describe('Focus while a modal is open', () => { + /** React reads onFocus from focusin on its containers; the traps listen on document. */ + it('reaches an overlay above, but not the modal trap', () => { + const { document, body } = page(); + const input = new FakeNode( + new FakeNode(body, { 'data-slot': 'popover-content' }), + ); + const heard: string[] = []; + body.addEventListener('focusin', () => heard.push('react')); + document.addEventListener('focusin', () => heard.push('trap')); + + focus(input); + + expect(heard).toEqual(['react']); + }); + + /** Page content behind the modal is no overlay: the trap pulls focus back from it. */ + it('is left to the trap in page content behind the modal', () => { + const { document, body } = page(); + const link = new FakeNode( + new FakeNode(body, { 'data-slot': 'card-content' }), + ); + const heard: string[] = []; + body.addEventListener('focusin', () => heard.push('react')); + document.addEventListener('focusin', () => heard.push('trap')); + + focus(link); + + expect(heard).toEqual(['react', 'trap']); + }); +}); diff --git a/resources/js/lib/modal.ts b/resources/js/lib/modal.ts index f15889a..dcee0d9 100644 --- a/resources/js/lib/modal.ts +++ b/resources/js/lib/modal.ts @@ -26,6 +26,30 @@ export function initializeModals(putConfig: PutConfig): void { escapeClosesTheTopLayerFirst(); } +/** + * Overlays in core's shadcn UI, by content slot. Not every `-content` slot: a card, a + * field or an open collapsible (the sidebar's nav groups) has one too, and is no layer. + */ +const OVERLAY_CONTENT = [ + 'dialog', + 'alert-dialog', + 'sheet', + 'popover', + 'dropdown-menu', + 'dropdown-menu-sub', + 'select', + 'tooltip', +].map((slot) => `[data-slot="${slot}-content"]`); + +/** + * Open layers (menus, selects, popovers, dialogs) in either stack: reka-ui (Vue) marks + * its own; Radix (React) marks none, so its are found by shadcn's content slot. Not + * closed, rather than open: a Radix tooltip is `delayed-open` or `instant-open`. + */ +const OPEN_LAYERS = ['[data-dismissable-layer]', ...OVERLAY_CONTENT] + .map((layer) => `${layer}:not([data-state="closed"])`) + .join(', '); + /** * Escape closes what is on top: a menu, select or dialog opened over a modal, not the * modal under it. @@ -49,11 +73,9 @@ function escapeClosesTheTopLayerFirst(): void { } // A closing layer stays in the page until its exit animation ends. - const layerAbove = [ - ...document.querySelectorAll( - '[data-dismissable-layer]:not([data-state="closed"])', - ), - ].some((layer) => !layer.closest('.im-modal-wrapper')); + const layerAbove = [...document.querySelectorAll(OPEN_LAYERS)].some( + (layer) => !layer.closest('.im-modal-wrapper'), + ); if (layerAbove) { event.stopPropagation(); @@ -86,40 +108,38 @@ function escapeClosesTheTopLayerFirst(): void { * An overlay marks everything it covered with `data-aria-hidden` when it opens, * so a covered modal has an overlay above it and no business holding focus. A * non-modal layer (popover, combobox) marks nothing, so focus landing inside one - * counts too. Swallowing the event in the capture phase keeps it from reaching - * either trap. + * counts too. Every trap (the modal's, reka-ui's, Radix's) listens on `document`, so + * stopping the event on `` on its way up keeps it from all of them, after + * React has read its `onFocus` from it on its own containers below. */ function releaseCoveredModalFocus(): void { // The server renders the same app but has no document to listen on. if (typeof document === 'undefined') return; - document.addEventListener( - 'focusin', - (event) => { - const modal = document.querySelector('.im-modal-wrapper'); - const target = event.target; + document.documentElement.addEventListener('focusin', (event) => { + const modal = document.querySelector('.im-modal-wrapper'); + const target = event.target; - if ( - !modal || - !(target instanceof Element) || - modal.contains(target) - ) { - return; - } + if (!modal || !(target instanceof Element) || modal.contains(target)) { + return; + } - // Covered by a modal layer, or focus moving into a non-modal one (a popover - // or combobox opened from the modal): either way the trap must let go, or - // it pulls focus back and the layer closes as soon as it opens. - const covered = modal.closest('[data-aria-hidden]') !== null; - const intoLayer = - target.closest( - '[data-reka-popper-content-wrapper], [data-dismissable-layer]', - ) !== null; + // Covered by a modal layer, or focus moving into a non-modal one (a popover + // or combobox opened from the modal): either way the trap must let go, or + // it pulls focus back and the layer closes as soon as it opens. + const covered = modal.closest('[data-aria-hidden]') !== null; + const intoLayer = + target.closest( + [ + '[data-reka-popper-content-wrapper]', + '[data-dismissable-layer]', + '[data-radix-popper-content-wrapper]', + ...OVERLAY_CONTENT, + ].join(', '), + ) !== null; - if (covered || intoLayer) { - event.stopPropagation(); - } - }, - true, - ); + if (covered || intoLayer) { + event.stopPropagation(); + } + }); } diff --git a/src/Attributes/DemoAccount.php b/src/Attributes/DemoAccount.php new file mode 100644 index 0000000..c247f51 --- /dev/null +++ b/src/Attributes/DemoAccount.php @@ -0,0 +1,20 @@ +option('state')); + $accounts = $this->demoAccounts($this->seeders($registry->modules(), fn (string $studly) => "{$state}{$studly}DatabaseSeeder")); + + if ($this->option('json')) { + $this->line((string) json_encode($accounts)); + + return self::SUCCESS; + } + + if ($accounts === []) { + $this->components->info("No module declares demo accounts for the \"{$this->option('state')}\" state."); + + return self::SUCCESS; + } + + $this->table(['Module', 'Account', 'What it sees', 'Start here'], array_map( + fn (array $account): array => [$account['module'], $account['email'], $account['description'], $account['featured'] ? 'yes' : ''], + $accounts, + )); + $this->line(' They sign in with DEMO_PASSWORD from .env.'); + + return self::SUCCESS; + } +} diff --git a/src/Console/Commands/ModuleInstallCommand.php b/src/Console/Commands/ModuleInstallCommand.php index 80b2b9a..9449ec3 100644 --- a/src/Console/Commands/ModuleInstallCommand.php +++ b/src/Console/Commands/ModuleInstallCommand.php @@ -46,8 +46,8 @@ public function handle(): int $locked = $this->lockedModules(); - if (! $this->requirePackages($packages)) { - $this->components->error('Composer could not install the modules. composer.json and composer.lock are back as they were; run composer install to remove anything Composer left in vendor/ or modules/.'); + if (($failed = $this->requirePackages($packages)) !== null) { + $this->components->error("Composer could not install the modules. {$failed}"); return self::FAILURE; } @@ -60,7 +60,17 @@ public function handle(): int ...$modules, ], $after); - return $this->runSetup($modules, $this->option('state'), (bool) $this->option('force')) ? self::SUCCESS : self::FAILURE; + $force = (bool) $this->option('force'); + + if (! $this->runSetup($modules, null, $force)) { + return self::FAILURE; + } + + // Last, in a process of its own, as template-install does: setup patches models + // (api-tokens adds HasApiTokens to User) in a process that already loaded them. + $state = $this->option('state'); + + return $state === null || $this->seedState($modules, $state, $force) ? self::SUCCESS : self::FAILURE; } /** @return string[]|null Module names on Packagist the app doesn't require yet; null when it has them all. */ diff --git a/src/Console/Commands/SeedModulesCommand.php b/src/Console/Commands/SeedModulesCommand.php index 82c1637..a957ae9 100644 --- a/src/Console/Commands/SeedModulesCommand.php +++ b/src/Console/Commands/SeedModulesCommand.php @@ -11,11 +11,13 @@ use ReflectionAttribute; use ReflectionClass; use Saucebase\Core\Attributes\SeedAfter; +use Saucebase\Core\Console\Traits\FindsModuleSeeders; use Saucebase\Core\Support\DependencyOrder; class SeedModulesCommand extends Command { use ConfirmableTrait; + use FindsModuleSeeders; protected $signature = 'modules:seed {--module=* : Seed specific modules (case-insensitive), together. Omit to seed all.} @@ -72,7 +74,18 @@ public function handle(ModuleRegistry $registry): int } // Every module's required data exists before any state refers to it. - return $this->seed($required) && $this->seed($stated) ? self::SUCCESS : self::FAILURE; + if (! $this->seed($required) || ! $this->seed($stated)) { + return self::FAILURE; + } + + $featured = collect($this->demoAccounts($stated))->where('featured', true) + ->map(fn (array $account): string => "{$account['email']} ({$account['description']})"); + + if ($featured->isNotEmpty()) { + $this->components->info('Sign in as '.$featured->implode(' or ').' with DEMO_PASSWORD. All of them: php artisan modules:demo-accounts --state='.$this->option('state')); + } + + return self::SUCCESS; } /** @@ -114,22 +127,6 @@ private function makeDemoPassword(): void $this->components->warn("DEMO_PASSWORD was not set. The demo accounts use {$password}, now saved in .env."); } - /** - * @param Collection $modules - * @param callable(string): string $seederName - * @return Collection Module name => seeder class, for those that have one. - */ - private function seeders(Collection $modules, callable $seederName): Collection - { - return $modules - ->mapWithKeys(function ($module) use ($seederName): array { - $studly = Str::studly($module->name); - - return [$module->name => "Modules\\{$studly}\\Database\\Seeders\\".$seederName($studly)]; - }) - ->filter(fn (string $seeder): bool => class_exists($seeder)); - } - /** @param Collection $seeders */ private function seed(Collection $seeders): bool { diff --git a/src/Console/Commands/TemplateCaptureCommand.php b/src/Console/Commands/TemplateCaptureCommand.php index 53103f6..69b06f9 100644 --- a/src/Console/Commands/TemplateCaptureCommand.php +++ b/src/Console/Commands/TemplateCaptureCommand.php @@ -13,12 +13,16 @@ * stubs/, which saucebase:template-install later copies into customers' apps. * stubs/ is the list: only its files are refreshed, so module patches and other * app changes stay out. A file joins the list when named. + * + * --restore runs it backwards, for a workspace that has just switched stacks: the stubs for + * the stack now in use go back into the app, over what the switch put there. */ class TemplateCaptureCommand extends Command { protected $signature = 'saucebase:template-capture {files?* : App files to add to the stubs (routes/web.php)} - {--check : Fail if stubs/ is out of date, without writing}'; + {--check : Fail if stubs/ is out of date, without writing} + {--restore : The other way: copy the stubs for the stack in use into the app (after switching stacks)}'; protected $description = 'Copy the app files a template overrides into its stubs'; @@ -33,8 +37,13 @@ public function handle(Filesystem $files, ProjectConfig $config): int return $this->refuse('Run this in an app that builds a template: "template" in saucebase.json.'); } + if ($this->option('check') && $this->option('restore')) { + return $this->refuse('--check never writes, so it cannot run with --restore. Run one of them.'); + } + // An installed app's frontend is flat; the stubs keep the stack folder install drops. - $stack = $config->isContributor() ? null : $config->getFramework(); + // A workspace keeps resources/js/ as the stubs do, but its view is flat too. + $stack = ['js' => $config->isContributor() ? null : $config->getFramework(), 'views' => $config->getFramework()]; $stubs = base_path("modules/{$template}/stubs"); $paths = $files->isDirectory($stubs) @@ -57,6 +66,10 @@ public function handle(Filesystem $files, ProjectConfig $config): int ->mapWithKeys(fn (string $path) => [$path => $this->appPath($path, $stack)]) ->filter(); + if ($this->option('restore')) { + return $this->restore($files, $stubs, $sources->all(), $config); + } + $missing = $sources->reject(fn (string $app) => $files->isFile(base_path($app))); if ($missing->isNotEmpty()) { @@ -83,24 +96,82 @@ public function handle(Filesystem $files, ProjectConfig $config): int return self::SUCCESS; } - /** resources/js/pages/Index.vue → resources/js/vue/pages/Index.vue, in an installed app. */ - private function stubPath(?string $path, ?string $stack): ?string + /** + * Each stub over its app file, overwritten: it is what the template ships. In a workspace, + * type-checking is then pointed at resources/js/ before core's, as Vite already is. + * + * @param array $sources Stub => app file. + */ + private function restore(Filesystem $files, string $stubs, array $sources, ProjectConfig $config): int + { + // A workspace keeps both stacks' frontends; only the one in use is restored. + $sources = array_filter($sources, fn (string $stub) => ! preg_match('#^resources/js/(vue|react)/#', $stub, $match) + || $match[1] === $config->getFramework(), ARRAY_FILTER_USE_KEY); + + $missing = array_filter(array_keys($sources), fn (string $stub) => ! $files->isFile("{$stubs}/{$stub}")); + + if ($missing !== []) { + return $this->refuse('These files have no stub to restore: '.implode(', ', $missing).'. Nothing was restored.'); + } + + foreach ($sources as $stub => $app) { + $files->ensureDirectoryExists(dirname(base_path($app))); + $files->copy("{$stubs}/{$stub}", base_path($app)); + } + + if ($config->isContributor()) { + $this->typeCheckOwnFilesFirst($files, (string) $config->getFramework()); + } + + $this->components->info('Restored '.count($sources).' files from the stubs.'); + $this->components->bulletList(array_values($sources)); + + return self::SUCCESS; + } + + private function typeCheckOwnFilesFirst(Filesystem $files, string $framework): void + { + $path = base_path('tsconfig.json'); + $tsconfig = $files->exists($path) ? json_decode($files->get($path), true) : null; + + if (! is_array($tsconfig)) { + return; + } + + $own = "./resources/js/{$framework}/*"; + $paths = $tsconfig['compilerOptions']['paths']['@/*'] ?? []; + $tsconfig['compilerOptions']['paths']['@/*'] = [$own, ...array_values(array_diff($paths, [$own]))]; + $tsconfig['include'] = array_values(array_unique([...($tsconfig['include'] ?? []), "resources/js/{$framework}/**/*"])); + + $files->put($path, json_encode($tsconfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL); + } + + /** + * resources/js/pages/Index.vue → resources/js/vue/pages/Index.vue, where that folder is flat. + * + * @param array{js: ?string, views: ?string} $stack The stack each folder is flat for; null: kept as is. + */ + private function stubPath(?string $path, array $stack): ?string { - if ($path === null || $stack === null || ! preg_match('#^resources/(js|views)/(?!vue/|react/)(.+)$#', $path, $match)) { + if ($path === null || ! preg_match('#^resources/(js|views)/(?!vue/|react/)(.+)$#', $path, $match) || $stack[$match[1]] === null) { return $path; } - return "resources/{$match[1]}/{$stack}/{$match[2]}"; + return "resources/{$match[1]}/{$stack[$match[1]]}/{$match[2]}"; } - /** The app file a stub comes from; null for another stack's stub in an installed app. */ - private function appPath(string $stub, ?string $stack): ?string + /** + * The app file a stub comes from; null for another stack's stub where the folder is flat. + * + * @param array{js: ?string, views: ?string} $stack + */ + private function appPath(string $stub, array $stack): ?string { - if ($stack === null || ! preg_match('#^resources/(js|views)/(vue|react)/(.+)$#', $stub, $match)) { + if (! preg_match('#^resources/(js|views)/(vue|react)/(.+)$#', $stub, $match) || $stack[$match[1]] === null) { return $stub; } - return $match[2] === $stack ? "resources/{$match[1]}/{$match[3]}" : null; + return $match[2] === $stack[$match[1]] ? "resources/{$match[1]}/{$match[3]}" : null; } /** `./.env` and `routes/../.env` are `.env`: dot segments resolved, so no spelling slips past OWN. Null: outside the app. */ diff --git a/src/Console/Commands/TemplateInstallCommand.php b/src/Console/Commands/TemplateInstallCommand.php index f6349f0..e2348df 100644 --- a/src/Console/Commands/TemplateInstallCommand.php +++ b/src/Console/Commands/TemplateInstallCommand.php @@ -53,8 +53,8 @@ public function handle(Filesystem $files, ProjectConfig $config): int return $this->refuse("This app already has the {$other} template. An app takes one template, installed fresh."); } - if (! $this->requirePackages([$package])) { - return $this->refuse('Composer could not install the template. composer.json and composer.lock are back as they were; run composer install to remove anything Composer left in vendor/ or modules/.'); + if (($failed = $this->requirePackages([$package])) !== null) { + return $this->refuse("Composer could not install the template. {$failed}"); } if (($this->lockedPackages()[$template]['type'] ?? null) !== 'saucebase-template') { diff --git a/src/Console/Traits/FindsModuleSeeders.php b/src/Console/Traits/FindsModuleSeeders.php new file mode 100644 index 0000000..f61e021 --- /dev/null +++ b/src/Console/Traits/FindsModuleSeeders.php @@ -0,0 +1,48 @@ + $modules + * @param callable(string): string $seederName + * @return Collection Module name => seeder class, for those that have one. + */ + protected function seeders(Collection $modules, callable $seederName): Collection + { + return $modules + ->mapWithKeys(function ($module) use ($seederName): array { + $studly = Str::studly($module->name); + + return [$module->name => "Modules\\{$studly}\\Database\\Seeders\\".$seederName($studly)]; + }) + ->filter(fn (string $seeder): bool => class_exists($seeder)); + } + + /** + * @param Collection $seeders Module name => seeder class. + * @return list + */ + protected function demoAccounts(Collection $seeders): array + { + return $seeders + ->flatMap(fn (string $seeder, string $module): array => array_map( + function (ReflectionAttribute $attribute) use ($module): array { + $account = $attribute->newInstance(); + + return ['module' => $module, 'email' => $account->email, 'description' => $account->description, 'featured' => $account->featured]; + }, + (new ReflectionClass($seeder))->getAttributes(DemoAccount::class), + )) + ->values() + ->all(); + } +} diff --git a/src/Console/Traits/InstallsSaucebasePackages.php b/src/Console/Traits/InstallsSaucebasePackages.php index db65ad4..f7a123c 100644 --- a/src/Console/Traits/InstallsSaucebasePackages.php +++ b/src/Console/Traits/InstallsSaucebasePackages.php @@ -2,6 +2,7 @@ namespace Saucebase\Core\Console\Traits; +use Illuminate\Filesystem\Filesystem; use Illuminate\Support\Facades\Process; use Illuminate\Support\Str; use Symfony\Component\Process\Process as SymfonyProcess; @@ -14,25 +15,45 @@ trait InstallsSaucebasePackages { /** * Composer reverts its own failures, but not one in a plugin or script after it wrote - * the lock: composer.json and composer.lock are put back here either way. + * the lock: composer.json, composer.lock and modules/ are put back here either way. * * @param string[] $packages vendor/name + * @return string|null Null once installed; otherwise what the failure left, for the error. */ - protected function requirePackages(array $packages): bool + protected function requirePackages(array $packages): ?string { $saved = collect(['composer.json', 'composer.lock']) ->mapWithKeys(fn (string $file) => [base_path($file) => @file_get_contents(base_path($file))]); + $modules = $this->moduleFolders(); if (Process::path(base_path())->forever() ->run(['composer', 'require', ...$packages, '--no-interaction'], $this->writeOutput(...)) ->successful()) { - return true; + return null; } $saved->filter(fn ($contents) => $contents !== false) ->each(fn (string $contents, string $path) => file_put_contents($path, $contents)); - return false; + // vendor/, a module Composer upgraded, and the generated autoloader still follow the + // new lock: installing from the restored one puts them back with it. + $reinstalled = $saved[base_path('composer.lock')] === false + || Process::path(base_path())->forever()->run(['composer', 'install', '--no-interaction'], $this->writeOutput(...))->successful(); + + // Folders this run unpacked: left behind, core refuses to boot (UnloadableModules). + foreach (array_diff($this->moduleFolders(), $modules) as $folder) { + (new Filesystem)->deleteDirectory(base_path("modules/{$folder}")); + } + + return $reinstalled + ? 'Nothing was changed: composer.json, composer.lock and modules/ are back as they were.' + : 'composer.json, composer.lock and modules/ are back as they were, but Composer could not reinstall vendor/ from them. Run: composer install'; + } + + /** @return string[] */ + private function moduleFolders(): array + { + return array_map('basename', glob(base_path('modules/*'), GLOB_ONLYDIR) ?: []); } /** diff --git a/src/CoreServiceProvider.php b/src/CoreServiceProvider.php index 917b347..efadbcd 100644 --- a/src/CoreServiceProvider.php +++ b/src/CoreServiceProvider.php @@ -14,6 +14,7 @@ use InterNACHI\Modular\Support\ModularizedCommandsServiceProvider; use InterNACHI\Modular\Support\ModularServiceProvider; use InterNACHI\Modular\Support\ModuleRegistry; +use Saucebase\Core\Console\Commands\DemoAccountsCommand; use Saucebase\Core\Console\Commands\GenerateModuleTypesCommand; use Saucebase\Core\Console\Commands\InstallCommand; use Saucebase\Core\Console\Commands\ModuleInstallCommand; @@ -110,6 +111,7 @@ public function boot(): void ModuleSetupCommand::class, RecipeToModuleCommand::class, SeedModulesCommand::class, + DemoAccountsCommand::class, SyncModuleTaskfileCommand::class, SyncModuleBoostCommand::class, ]); diff --git a/src/Navigation/Navigation.php b/src/Navigation/Navigation.php index 4f19210..ab5d455 100644 --- a/src/Navigation/Navigation.php +++ b/src/Navigation/Navigation.php @@ -4,6 +4,7 @@ use Illuminate\Support\Str; use InterNACHI\Modular\Support\ModuleRegistry; +use Spatie\Navigation\Helpers\ActiveUrlChecker; use Spatie\Navigation\Navigation as SpatieNavigation; /** @@ -16,12 +17,22 @@ class Navigation extends SpatieNavigation { protected bool $loaded = false; + /** + * Built while the app boots, with routes not cached: internachi/modular runs every module's + * routes/*.php then, navigation.php included, so the module items are already here. + */ + protected bool $modulesRanAtBoot; + + public function __construct(ActiveUrlChecker $activeUrlChecker) + { + parent::__construct($activeUrlChecker); + + $this->modulesRanAtBoot = ! app()->isBooted() && ! app()->routesAreCached(); + } + protected function ensureLoaded(): void { - if (! $this->loaded) { - $this->loaded = true; - $this->load(); - } + $this->load(); } /** @@ -263,8 +274,9 @@ private function isItemActiveForUrl(?string $itemUrl): bool $currentUrl = request()->url(); - $itemPath = rtrim(parse_url($itemUrl, PHP_URL_PATH), '/'); - $currentPath = rtrim(parse_url($currentUrl, PHP_URL_PATH), '/'); + // The site root has no path: parse_url() gives null. + $itemPath = rtrim((string) parse_url($itemUrl, PHP_URL_PATH), '/'); + $currentPath = rtrim((string) parse_url($currentUrl, PHP_URL_PATH), '/'); return $currentPath === $itemPath; } @@ -309,21 +321,35 @@ protected function sortByOrder(array $items): array * * Only loads module navigation if the module is enabled. * + * Once per instance, with `require`: the instance is scoped, so an Octane worker or a + * queue gets a fresh one per request or job, and `require_once` would leave every one + * after the first empty. Module files modular already ran into this instance at boot are + * not run again, or every item would be listed twice. + * * @return $this */ public function load(): self { - // Load core navigation + if ($this->loaded) { + return $this; + } + + $this->loaded = true; + $coreNavigationPath = base_path('routes/navigation.php'); if (file_exists($coreNavigationPath)) { - require_once $coreNavigationPath; + require $coreNavigationPath; + } + + if ($this->modulesRanAtBoot) { + return $this; } // Load navigation from all modules discovered by InterNACHI app(ModuleRegistry::class)->modules()->each(function ($module): void { $path = $module->path('routes/navigation.php'); if (file_exists($path)) { - require_once $path; + require $path; } }); diff --git a/src/RegistrationInvite.php b/src/RegistrationInvite.php new file mode 100644 index 0000000..e88a4d7 --- /dev/null +++ b/src/RegistrationInvite.php @@ -0,0 +1,37 @@ +put(self::KEY, Str::lower($email)); + } + + public static function email(): ?string + { + return session(self::KEY); + } + + public static function allows(string $email): bool + { + return self::email() !== null && hash_equals(self::email(), Str::lower($email)); + } + + public static function forget(): void + { + session()->forget(self::KEY); + } +} diff --git a/src/Testing/AssertsDemoAccounts.php b/src/Testing/AssertsDemoAccounts.php new file mode 100644 index 0000000..340dd26 --- /dev/null +++ b/src/Testing/AssertsDemoAccounts.php @@ -0,0 +1,41 @@ +seed(array_values(array_filter([class_exists($required) ? $required : null, $seeder]))); + } + + $accounts = array_map( + fn (ReflectionAttribute $attribute): DemoAccount => $attribute->newInstance(), + (new ReflectionClass($seeder))->getAttributes(DemoAccount::class), + ); + + $this->assertNotEmpty($accounts, class_basename($seeder).' declares no #[DemoAccount].'); + + foreach ($accounts as $account) { + $this->assertDatabaseHas('users', ['email' => $account->email]); + } + } +} diff --git a/stubs/stack/react/config/tsconfig.json b/stubs/stack/react/config/tsconfig.json index 93a2b72..50f66d2 100644 --- a/stubs/stack/react/config/tsconfig.json +++ b/stubs/stack/react/config/tsconfig.json @@ -27,6 +27,7 @@ "exclude": [ "stubs", "modules/**/vendor", + "modules/*/stubs", "modules/*/resources/js/vue", "node_modules" ], diff --git a/stubs/stack/react/js/components/ui/empty.tsx b/stubs/stack/react/js/components/ui/empty.tsx new file mode 100644 index 0000000..46e0f92 --- /dev/null +++ b/stubs/stack/react/js/components/ui/empty.tsx @@ -0,0 +1,103 @@ +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '@/lib/utils'; + +function Empty({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function EmptyHeader({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +const emptyMediaVariants = cva( + 'mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0', + { + variants: { + variant: { + default: 'bg-transparent', + icon: "flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-foreground [&_svg:not([class*='size-'])]:size-6", + }, + }, + defaultVariants: { + variant: 'default', + }, + }, +); + +function EmptyMedia({ + className, + variant = 'default', + ...props +}: React.ComponentProps<'div'> & VariantProps) { + return ( +
+ ); +} + +function EmptyTitle({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +function EmptyDescription({ className, ...props }: React.ComponentProps<'p'>) { + return ( +
a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary', + className, + )} + {...props} + /> + ); +} + +function EmptyContent({ className, ...props }: React.ComponentProps<'div'>) { + return ( +
+ ); +} + +export { + Empty, + EmptyHeader, + EmptyTitle, + EmptyDescription, + EmptyContent, + EmptyMedia, +}; diff --git a/stubs/stack/react/js/components/ui/saucebase/EmptyState.tsx b/stubs/stack/react/js/components/ui/saucebase/EmptyState.tsx index 8e1a048..684f9a6 100644 --- a/stubs/stack/react/js/components/ui/saucebase/EmptyState.tsx +++ b/stubs/stack/react/js/components/ui/saucebase/EmptyState.tsx @@ -1,3 +1,11 @@ +import { + Empty, + EmptyContent, + EmptyDescription, + EmptyHeader, + EmptyMedia, + EmptyTitle, +} from '@/components/ui/empty'; import { cn } from '@/lib/utils'; import type { ComponentProps, ReactNode } from 'react'; @@ -7,6 +15,10 @@ type EmptyStateProps = ComponentProps<'div'> & { icon?: ReactNode; }; +/** + * The common empty state: an icon, a title, a line and an action. `className` lands on the + * container. Other sizes or an illustration: compose `@/components/ui/empty` instead. + */ export default function EmptyState({ title, description, @@ -16,23 +28,32 @@ export default function EmptyState({ ...props }: EmptyStateProps) { return ( -
- {icon && ( -
- {icon} -
+ + {icon && ( + + {icon} + + )} + + {title} + + {description && ( + {description} + )} + + {children && ( + {children} )} -

{title}

- {description && ( -

{description}

- )} - {children &&
{children}
} -
+ ); } diff --git a/stubs/stack/react/js/components/ui/saucebase/navigation/NavItem.tsx b/stubs/stack/react/js/components/ui/saucebase/navigation/NavItem.tsx index 80dea09..7005858 100644 --- a/stubs/stack/react/js/components/ui/saucebase/navigation/NavItem.tsx +++ b/stubs/stack/react/js/components/ui/saucebase/navigation/NavItem.tsx @@ -15,7 +15,7 @@ import { useT } from '@saucebase/react/i18n'; import { handleAction } from '@saucebase/react/lib/navigation'; import type { MenuBadge, MenuItem } from '@saucebase/core/types'; import { Link } from '@inertiajs/react'; -import { ChevronRight } from 'lucide-react'; +import { ArrowUpRight, ChevronRight } from 'lucide-react'; import { Badge } from '@/components/ui/badge'; import { Separator } from '@/components/ui/separator'; import NavIcon from './NavIcon'; @@ -41,12 +41,18 @@ function isItemActive(item: MenuItem): boolean { } } -function NavBadge({ badge }: { badge: MenuBadge | null }) { +function NavBadge({ + badge, + beforeIcon = false, +}: { + badge: MenuBadge | null; + beforeIcon?: boolean; +}) { if (!badge) return null; return ( {badge.content ?? ( @@ -55,13 +61,18 @@ function NavBadge({ badge }: { badge: MenuBadge | null }) { ); } +/** Icon, title and badge; an item opening in a new tab ends on an arrow, pushed right like the badge. */ function NavLinkContent({ item }: { item: MenuItem }) { const badge = getBadgeConfig(item); + const newTab = item.newPage === true; + return ( <> {useT()(item.title)} - + + {newTab && !badge && } + {newTab && } ); } diff --git a/stubs/stack/react/js/components/ui/select.tsx b/stubs/stack/react/js/components/ui/select.tsx new file mode 100644 index 0000000..9e6d515 --- /dev/null +++ b/stubs/stack/react/js/components/ui/select.tsx @@ -0,0 +1,193 @@ +import * as React from 'react'; +import { cn } from '@/lib/utils'; +import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react'; +import { Select as SelectPrimitive } from 'radix-ui'; + +function Select({ + ...props +}: React.ComponentProps) { + return ; +} + +function SelectGroup({ + ...props +}: React.ComponentProps) { + return ; +} + +function SelectValue({ + ...props +}: React.ComponentProps) { + return ; +} + +function SelectTrigger({ + className, + size = 'default', + children, + ...props +}: React.ComponentProps & { + size?: 'sm' | 'default'; +}) { + return ( + + {children} + + + + + ); +} + +function SelectContent({ + className, + children, + position = 'item-aligned', + align = 'center', + ...props +}: React.ComponentProps) { + return ( + + + + + {children} + + + + + ); +} + +function SelectLabel({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function SelectItem({ + className, + children, + ...props +}: React.ComponentProps) { + return ( + + + + + + + {children} + + ); +} + +function SelectSeparator({ + className, + ...props +}: React.ComponentProps) { + return ( + + ); +} + +function SelectScrollUpButton({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ); +} + +function SelectScrollDownButton({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + ); +} + +export { + Select, + SelectContent, + SelectGroup, + SelectItem, + SelectLabel, + SelectScrollDownButton, + SelectScrollUpButton, + SelectSeparator, + SelectTrigger, + SelectValue, +}; diff --git a/stubs/stack/react/js/components/ui/table.tsx b/stubs/stack/react/js/components/ui/table.tsx new file mode 100644 index 0000000..411e4a0 --- /dev/null +++ b/stubs/stack/react/js/components/ui/table.tsx @@ -0,0 +1,113 @@ +import * as React from 'react'; +import { cn } from '@/lib/utils'; + +function Table({ className, ...props }: React.ComponentProps<'table'>) { + return ( +
+ + + ); +} + +function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) { + return ( + + ); +} + +function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) { + return ( + + ); +} + +function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) { + return ( + tr]:last:border-b-0', + className, + )} + {...props} + /> + ); +} + +function TableRow({ className, ...props }: React.ComponentProps<'tr'>) { + return ( + + ); +} + +function TableHead({ className, ...props }: React.ComponentProps<'th'>) { + return ( +
[role=checkbox]]:translate-y-[2px]', + className, + )} + {...props} + /> + ); +} + +function TableCell({ className, ...props }: React.ComponentProps<'td'>) { + return ( + [role=checkbox]]:translate-y-[2px]', + className, + )} + {...props} + /> + ); +} + +function TableCaption({ + className, + ...props +}: React.ComponentProps<'caption'>) { + return ( +
+ ); +} + +export { + Table, + TableHeader, + TableBody, + TableFooter, + TableHead, + TableRow, + TableCell, + TableCaption, +}; diff --git a/stubs/stack/vue/config/tsconfig.json b/stubs/stack/vue/config/tsconfig.json index 85dac63..4bcb9dd 100644 --- a/stubs/stack/vue/config/tsconfig.json +++ b/stubs/stack/vue/config/tsconfig.json @@ -27,6 +27,7 @@ "exclude": [ "stubs", "modules/**/vendor", + "modules/*/stubs", "modules/*/resources/js/react", "node_modules" ], diff --git a/stubs/stack/vue/js/components/ui/empty/Empty.vue b/stubs/stack/vue/js/components/ui/empty/Empty.vue new file mode 100644 index 0000000..d186340 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/Empty.vue @@ -0,0 +1,22 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/empty/EmptyContent.vue b/stubs/stack/vue/js/components/ui/empty/EmptyContent.vue new file mode 100644 index 0000000..ca96162 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/EmptyContent.vue @@ -0,0 +1,22 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/empty/EmptyDescription.vue b/stubs/stack/vue/js/components/ui/empty/EmptyDescription.vue new file mode 100644 index 0000000..72ba6b3 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/EmptyDescription.vue @@ -0,0 +1,22 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/empty/EmptyHeader.vue b/stubs/stack/vue/js/components/ui/empty/EmptyHeader.vue new file mode 100644 index 0000000..b71e289 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/EmptyHeader.vue @@ -0,0 +1,22 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/empty/EmptyMedia.vue b/stubs/stack/vue/js/components/ui/empty/EmptyMedia.vue new file mode 100644 index 0000000..84b2598 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/EmptyMedia.vue @@ -0,0 +1,21 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/empty/EmptyTitle.vue b/stubs/stack/vue/js/components/ui/empty/EmptyTitle.vue new file mode 100644 index 0000000..eb2fa14 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/EmptyTitle.vue @@ -0,0 +1,17 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/empty/index.ts b/stubs/stack/vue/js/components/ui/empty/index.ts new file mode 100644 index 0000000..4da8966 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/empty/index.ts @@ -0,0 +1,26 @@ +import type { VariantProps } from 'class-variance-authority'; +import { cva } from 'class-variance-authority'; + +export { default as Empty } from './Empty.vue'; +export { default as EmptyContent } from './EmptyContent.vue'; +export { default as EmptyDescription } from './EmptyDescription.vue'; +export { default as EmptyHeader } from './EmptyHeader.vue'; +export { default as EmptyMedia } from './EmptyMedia.vue'; +export { default as EmptyTitle } from './EmptyTitle.vue'; + +export const emptyMediaVariants = cva( + 'mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0', + { + variants: { + variant: { + default: 'bg-transparent', + icon: "bg-muted text-foreground flex size-10 shrink-0 items-center justify-center rounded-lg [&_svg:not([class*='size-'])]:size-6", + }, + }, + defaultVariants: { + variant: 'default', + }, + }, +); + +export type EmptyMediaVariants = VariantProps; diff --git a/stubs/stack/vue/js/components/ui/saucebase/EmptyState.vue b/stubs/stack/vue/js/components/ui/saucebase/EmptyState.vue index e394774..c79c1d1 100644 --- a/stubs/stack/vue/js/components/ui/saucebase/EmptyState.vue +++ b/stubs/stack/vue/js/components/ui/saucebase/EmptyState.vue @@ -1,4 +1,17 @@ diff --git a/tests/Feature/DemoAccountsCommandTest.php b/tests/Feature/DemoAccountsCommandTest.php new file mode 100644 index 0000000..01f3c0d --- /dev/null +++ b/tests/Feature/DemoAccountsCommandTest.php @@ -0,0 +1,52 @@ +artisan('modules:demo-accounts', ['--state' => 'showcase']) + ->expectsOutputToContain('fixture-admin@example.com') + ->expectsOutputToContain('fixture-staff@example.com') + ->assertSuccessful(); + + $this->assertSame([], DatabaseSeeder::$ran); + } + + public function test_json_gives_each_account_with_its_module_and_whether_it_is_featured(): void + { + Artisan::call('modules:demo-accounts', ['--state' => 'showcase', '--json' => true]); + + $this->assertSame([ + ['module' => 'module-test-fixture', 'email' => 'fixture-admin@example.com', 'description' => 'sees everything', 'featured' => true], + ['module' => 'module-test-fixture', 'email' => 'fixture-staff@example.com', 'description' => 'staff', 'featured' => false], + ], json_decode(Artisan::output(), true)); + } + + /** The installer asks after any demo; a state nobody declares accounts for is no error. */ + public function test_a_state_without_accounts_gives_an_empty_list(): void + { + Artisan::call('modules:demo-accounts', ['--state' => 'nothing-here', '--json' => true]); + + $this->assertSame([], json_decode(Artisan::output(), true)); + } +} diff --git a/tests/Feature/ModuleInstallCommandTest.php b/tests/Feature/ModuleInstallCommandTest.php index a268d17..a51c9d5 100644 --- a/tests/Feature/ModuleInstallCommandTest.php +++ b/tests/Feature/ModuleInstallCommandTest.php @@ -90,7 +90,8 @@ public function test_a_template_is_set_up_with_and_after_the_modules_it_requires $this->artisan('saucebase:module-install', ['modules' => ['uptime'], '--state' => 'uptime'])->assertSuccessful(); - Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'auth', 'billing', 'uptime', '--state=uptime', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'auth', 'billing', 'uptime', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'modules:seed', '--module=auth', '--module=billing', '--module=uptime', '--state=uptime']); } public function test_modules_are_set_up_after_the_modules_they_require(): void @@ -129,13 +130,25 @@ private function lock(array $modules, array $templates = []): string return (string) json_encode(['packages' => [['name' => 'laravel/sanctum', 'type' => 'library'], ...$packages]]); } - public function test_a_state_is_passed_on_to_the_setup(): void + /** + * Seeded in a process of its own, after setup: setup patches models (api-tokens adds + * HasApiTokens to User) in a process that already loaded them, so a seeder there + * would call the unpatched class. + */ + public function test_a_state_is_seeded_after_the_setup_in_a_new_process(): void { - Process::fake(); + $order = []; + Process::fake(function (PendingProcess $p) use (&$order) { + $order[] = $p->command[0] === 'composer' ? 'composer' : $p->command[2]; + + return Process::result(); + }); config(['saucebase.demo_password' => 'secret']); $this->artisan('saucebase:module-install', ['modules' => ['blog'], '--state' => 'showcase'])->assertSuccessful(); - Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'blog', '--state=showcase', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'blog', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'modules:seed', '--module=blog', '--state=showcase']); + $this->assertSame(['composer', 'saucebase:module-setup', 'modules:seed'], $order); } /** The seeding makes a missing DEMO_PASSWORD (modules:seed), so the install doesn't stop for it. */ @@ -145,7 +158,7 @@ public function test_a_blank_demo_password_does_not_stop_a_state(): void config(['saucebase.demo_password' => null]); $this->artisan('saucebase:module-install', ['modules' => ['blog'], '--state' => 'showcase'])->assertSuccessful(); - Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'blog', '--state=showcase', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'modules:seed', '--module=blog', '--state=showcase']); } public function test_force_is_passed_on_to_the_setup(): void @@ -154,7 +167,8 @@ public function test_force_is_passed_on_to_the_setup(): void config(['saucebase.demo_password' => 'secret']); $this->artisan('saucebase:module-install', ['modules' => ['blog'], '--state' => 'showcase', '--force' => true])->assertSuccessful(); - Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'blog', '--state=showcase', '--force', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'saucebase:module-setup', 'blog', '--force', '--configure']); + Process::assertRan(fn (PendingProcess $p) => $p->command === [PHP_BINARY, 'artisan', 'modules:seed', '--module=blog', '--state=showcase', '--force']); } public function test_install_settings_are_passed_on_to_the_setup(): void diff --git a/tests/Feature/ModuleIntegrationTest.php b/tests/Feature/ModuleIntegrationTest.php index c5b5157..2d0f772 100644 --- a/tests/Feature/ModuleIntegrationTest.php +++ b/tests/Feature/ModuleIntegrationTest.php @@ -92,6 +92,15 @@ public function test_module_breadcrumbs_are_registered(): void $this->assertTrue(Breadcrumbs::exists('module-test-fixture.index')); } + /** A second application in the same process (Octane workers, a test suite) registers them too. */ + public function test_every_application_registers_module_breadcrumbs(): void + { + $this->refreshApplication(); + Breadcrumbs::clearResolvedInstances(); + + $this->assertTrue(Breadcrumbs::exists('module-test-fixture.index')); + } + /** * The command resolves paths through module_path(), so it follows the configured * modules directory rather than assuming `modules/` under the base path. diff --git a/tests/Feature/NavigationLoadingTest.php b/tests/Feature/NavigationLoadingTest.php new file mode 100644 index 0000000..639fabb --- /dev/null +++ b/tests/Feature/NavigationLoadingTest.php @@ -0,0 +1,85 @@ +assertSame('Module Test Fixture', $this->freshNavigation()->treeGrouped()['main'][0]['title']); + } + + public function test_every_fresh_instance_loads_module_navigation(): void + { + $this->freshNavigation()->treeGrouped(); + + $this->assertSame('Module Test Fixture', $this->freshNavigation()->treeGrouped()['main'][0]['title']); + } + + public function test_an_explicit_load_is_not_repeated_on_first_use(): void + { + $navigation = $this->freshNavigation(); + + $this->assertCount(1, $navigation->load()->tree()); + } + + public function test_navigation_files_load_once_per_instance(): void + { + $navigation = $this->freshNavigation(); + $navigation->tree(); + + $this->assertCount(1, $navigation->tree()); + } + + /** As with `require_once` before: a second explicit load is a no-op. */ + public function test_loading_twice_lists_each_item_once(): void + { + $this->assertCount(1, $this->freshNavigation()->load()->load()->tree()); + } + + /** Without cached routes, modular already ran the module's file into this instance at boot. */ + public function test_the_instance_filled_at_boot_lists_each_item_once(): void + { + $this->assertCount(1, app(Navigation::class)->tree()); + } + + public function test_breadcrumbs_load_navigation_on_first_use(): void + { + $path = base_path('routes/navigation.php'); + @mkdir(dirname($path), 0777, true); + file_put_contents($path, <<<'PHP' + instance('request', Request::create('http://localhost/reports')); + + $this->assertSame('Reports', $this->freshNavigation()->breadcrumbs()[0]['title']); + } finally { + unlink($path); + } + } + + /** Simulates a new request: the scoped instance is rebuilt. */ + private function freshNavigation(): Navigation + { + $this->app->forgetScopedInstances(); + NavigationFacade::clearResolvedInstances(); + + return app(Navigation::class); + } +} diff --git a/tests/Feature/RegistrationInviteTest.php b/tests/Feature/RegistrationInviteTest.php new file mode 100644 index 0000000..78a3201 --- /dev/null +++ b/tests/Feature/RegistrationInviteTest.php @@ -0,0 +1,34 @@ +assertNull(RegistrationInvite::email()); + $this->assertFalse(RegistrationInvite::allows('ana@example.com')); + } + + /** Only the invited address, whatever its case; nothing else. */ + public function test_an_invite_allows_its_own_address_only(): void + { + RegistrationInvite::allow('Ana@Example.com'); + + $this->assertSame('ana@example.com', RegistrationInvite::email()); + $this->assertTrue(RegistrationInvite::allows('ANA@example.com')); + $this->assertFalse(RegistrationInvite::allows('bob@example.com')); + } + + public function test_a_used_invite_is_forgotten(): void + { + RegistrationInvite::allow('ana@example.com'); + + RegistrationInvite::forget(); + + $this->assertNull(RegistrationInvite::email()); + } +} diff --git a/tests/Feature/SeedModulesCommandTest.php b/tests/Feature/SeedModulesCommandTest.php index 9327be7..c862610 100644 --- a/tests/Feature/SeedModulesCommandTest.php +++ b/tests/Feature/SeedModulesCommandTest.php @@ -48,6 +48,15 @@ public function test_a_state_runs_its_seeders_after_the_required_ones(): void } /** No DEMO_PASSWORD: one is made, saved in .env, and shown, so the demo accounts can be used. */ + /** Seeding by hand ends the way the installer does: with the account to sign in with. */ + public function test_a_state_names_its_featured_accounts_to_sign_in_with(): void + { + $this->artisan('modules:seed', ['--state' => 'showcase']) + ->expectsOutputToContain('fixture-admin@example.com') + ->doesntExpectOutputToContain('fixture-staff@example.com') + ->assertSuccessful(); + } + public function test_a_state_without_a_demo_password_makes_one_and_saves_it(): void { config(['saucebase.demo_password' => null]); diff --git a/tests/Feature/TemplateCaptureCommandTest.php b/tests/Feature/TemplateCaptureCommandTest.php index 23eefc3..95ac0b4 100644 --- a/tests/Feature/TemplateCaptureCommandTest.php +++ b/tests/Feature/TemplateCaptureCommandTest.php @@ -162,6 +162,112 @@ public function test_an_app_leaves_another_stacks_stubs_alone(): void $this->assertSame('react', $this->stub('resources/js/react/pages/Index.tsx')); } + /** + * A workspace keeps its stack's frontend under resources/js/, as the stubs do, but + * Laravel loads its one view from resources/views: the view stubs keep the stack folder. + */ + public function test_a_workspace_files_its_view_under_its_stack_and_leaves_the_other(): void + { + $this->write('resources/views/app.blade.php', 'vue view'); + $this->write('modules/uptime/stubs/resources/views/react/app.blade.php', 'react view'); + + $this->artisan('saucebase:template-capture', ['files' => ['resources/views/app.blade.php']])->assertSuccessful(); + + $this->assertSame('vue view', $this->stub('resources/views/vue/app.blade.php')); + $this->assertSame('react view', $this->stub('resources/views/react/app.blade.php')); + $this->assertFileDoesNotExist($this->appPath.'/modules/uptime/stubs/resources/views/app.blade.php'); + $this->artisan('saucebase:template-capture', ['--check' => true])->assertSuccessful(); + } + + /** --restore runs capture backwards: after a stack switch, this stack's stubs go back into the app. */ + public function test_restore_puts_this_stacks_stubs_back_into_the_workspace(): void + { + $this->write('modules/uptime/stubs/routes/web.php', 'routes'); + $this->write('modules/uptime/stubs/resources/css/theme.css', 'template css'); + $this->write('modules/uptime/stubs/resources/js/vue/pages/Index.vue', 'vue home'); + $this->write('modules/uptime/stubs/resources/views/vue/app.blade.php', 'vue view'); + $this->write('modules/uptime/stubs/resources/views/react/app.blade.php', 'react view'); + // What switching to Vue left: core's CSS and view. + $this->write('resources/css/theme.css', 'core css'); + $this->write('resources/views/app.blade.php', 'core view'); + + $this->artisan('saucebase:template-capture', ['--restore' => true])->assertSuccessful(); + + $this->assertSame('routes', $this->app('routes/web.php')); + $this->assertSame('template css', $this->app('resources/css/theme.css')); + $this->assertSame('vue home', $this->app('resources/js/vue/pages/Index.vue')); + $this->assertSame('vue view', $this->app('resources/views/app.blade.php')); + $this->artisan('saucebase:template-capture', ['--check' => true])->assertSuccessful(); + } + + /** "The stack in use": the other stack's frontend in a workspace is not this restore's to overwrite. */ + public function test_restore_in_a_workspace_leaves_the_other_stacks_frontend_alone(): void + { + $this->write('modules/uptime/stubs/resources/js/vue/pages/Index.vue', 'vue home'); + $this->write('modules/uptime/stubs/resources/js/react/pages/Index.tsx', 'react home'); + $this->write('resources/js/react/pages/Index.tsx', 'react work in progress'); + + $this->artisan('saucebase:template-capture', ['--restore' => true])->assertSuccessful(); + + $this->assertSame('vue home', $this->app('resources/js/vue/pages/Index.vue')); + $this->assertSame('react work in progress', $this->app('resources/js/react/pages/Index.tsx')); + } + + /** --check never writes, so it can't ride along with --restore. */ + public function test_check_and_restore_together_are_refused_before_writing(): void + { + $this->write('modules/uptime/stubs/routes/web.php', 'template'); + $this->write('routes/web.php', 'mine'); + + $this->artisan('saucebase:template-capture', ['--check' => true, '--restore' => true])->assertFailed(); + + $this->assertSame('mine', $this->app('routes/web.php')); + } + + /** A named file with no stub fails the restore before any file is overwritten. */ + public function test_restore_without_a_stub_writes_nothing(): void + { + $this->write('modules/uptime/stubs/resources/css/theme.css', 'template css'); + $this->write('resources/css/theme.css', 'mine'); + + $this->artisan('saucebase:template-capture', ['--restore' => true, 'files' => ['routes/new.php']])->assertFailed(); + + $this->assertSame('mine', $this->app('resources/css/theme.css')); + } + + /** Vite reads a workspace's resources/js/ before core's; type-checking is pointed the same way. */ + public function test_restore_points_a_workspaces_type_checking_at_its_own_files_first(): void + { + $this->write('tsconfig.json', json_encode([ + 'compilerOptions' => ['paths' => ['@/*' => ['./vendor/saucebase/core/stubs/stack/vue/js/*']]], + 'include' => ['resources/js/*.ts'], + ])); + + $this->artisan('saucebase:template-capture', ['--restore' => true])->assertSuccessful(); + + $tsconfig = json_decode($this->app('tsconfig.json'), true); + $this->assertSame(['./resources/js/vue/*', './vendor/saucebase/core/stubs/stack/vue/js/*'], $tsconfig['compilerOptions']['paths']['@/*']); + $this->assertContains('resources/js/vue/**/*', $tsconfig['include']); + } + + /** An installed app is flat: its stubs land where install put them, and its tsconfig is its own. */ + public function test_restore_in_an_installed_app_is_flat(): void + { + $this->write('saucebase.json', '{"framework": "vue", "template": "uptime"}'); + $this->write('modules/uptime/stubs/resources/js/vue/pages/Index.vue', 'vue home'); + $this->write('tsconfig.json', '{"include": []}'); + + $this->artisan('saucebase:template-capture', ['--restore' => true])->assertSuccessful(); + + $this->assertSame('vue home', $this->app('resources/js/pages/Index.vue')); + $this->assertSame('{"include": []}', $this->app('tsconfig.json')); + } + + private function app(string $path): string + { + return $this->files->get($this->appPath.'/'.$path); + } + private function write(string $path, string $contents): void { $this->files->ensureDirectoryExists(dirname($this->appPath.'/'.$path)); diff --git a/tests/Feature/TemplateInstallCommandTest.php b/tests/Feature/TemplateInstallCommandTest.php index 405f632..f001fef 100644 --- a/tests/Feature/TemplateInstallCommandTest.php +++ b/tests/Feature/TemplateInstallCommandTest.php @@ -199,7 +199,15 @@ public function test_the_same_template_can_be_installed_again(): void /** Composer can fail after writing them (a plugin, a script): the app gets its files back. */ public function test_a_failed_composer_require_puts_composer_files_back(): void { + $this->files->ensureDirectoryExists($this->appPath.'/modules/blog'); Process::fake(function (PendingProcess $process) { + if ($process->command[1] !== 'require') { + return Process::result(); + } + + // A plugin fails after Composer unpacked packages into modules/. + $this->files->ensureDirectoryExists($this->appPath.'/modules/uptime/src'); + $this->files->ensureDirectoryExists($this->appPath.'/modules/auth'); $this->files->put($this->appPath.'/composer.json', '{"require": {"saucebase/uptime": "*"}}'); $this->files->put($this->appPath.'/composer.lock', $this->lock(['saucebase/uptime' => []], templates: ['saucebase/uptime'])); @@ -207,11 +215,51 @@ public function test_a_failed_composer_require_puts_composer_files_back(): void }); $this->artisan('saucebase:template-install', ['template' => 'uptime']) - ->expectsOutputToContain('composer install') + ->expectsOutputToContain('Nothing was changed') ->assertFailed(); $this->assertSame('{}', $this->files->get($this->appPath.'/composer.json')); $this->assertSame($this->lock([]), $this->files->get($this->appPath.'/composer.lock')); + // Left behind, they stop the app booting (Composer does not autoload them). + $this->assertDirectoryDoesNotExist($this->appPath.'/modules/uptime'); + $this->assertDirectoryDoesNotExist($this->appPath.'/modules/auth'); + $this->assertDirectoryExists($this->appPath.'/modules/blog'); + } + + /** + * A failed require can leave vendor/, a module Composer upgraded, and the generated + * autoloader on the new lock. Installing from the restored lock puts them back with it. + */ + public function test_a_failed_composer_require_reinstalls_from_the_restored_lock(): void + { + $restored = null; + Process::fake(function (PendingProcess $process) use (&$restored) { + if ($process->command[1] === 'install') { + $restored = $this->files->get($this->appPath.'/composer.lock'); + + return Process::result(); + } + + $this->files->put($this->appPath.'/composer.lock', $this->lock(['saucebase/uptime' => []], templates: ['saucebase/uptime'])); + + return Process::result(exitCode: 1); + }); + + $this->artisan('saucebase:template-install', ['template' => 'uptime'])->assertFailed(); + + Process::assertRan(fn (PendingProcess $p) => $p->command === ['composer', 'install', '--no-interaction']); + $this->assertSame($this->lock([]), $restored); + } + + /** The reinstall can fail too (a pre-install script): then vendor/ is not back, and the error says how to fix it. */ + public function test_a_failed_reinstall_says_vendor_is_not_back(): void + { + Process::fake(fn () => Process::result(exitCode: 1)); + + $this->artisan('saucebase:template-install', ['template' => 'uptime']) + ->doesntExpectOutputToContain('Nothing was changed') + ->expectsOutputToContain('Run: composer install') + ->assertFailed(); } public function test_a_package_that_is_not_a_template_is_refused(): void diff --git a/tests/Fixtures/modules/module-test-fixture/database/seeders/ShowcaseModuleTestFixtureDatabaseSeeder.php b/tests/Fixtures/modules/module-test-fixture/database/seeders/ShowcaseModuleTestFixtureDatabaseSeeder.php index f26b3ee..11b025c 100644 --- a/tests/Fixtures/modules/module-test-fixture/database/seeders/ShowcaseModuleTestFixtureDatabaseSeeder.php +++ b/tests/Fixtures/modules/module-test-fixture/database/seeders/ShowcaseModuleTestFixtureDatabaseSeeder.php @@ -3,7 +3,10 @@ namespace Modules\ModuleTestFixture\Database\Seeders; use Illuminate\Database\Seeder; +use Saucebase\Core\Attributes\DemoAccount; +#[DemoAccount('fixture-admin@example.com', 'sees everything', featured: true)] +#[DemoAccount('fixture-staff@example.com', 'staff')] class ShowcaseModuleTestFixtureDatabaseSeeder extends Seeder { public function run(): void diff --git a/tests/Unit/BranchAliasTest.php b/tests/Unit/BranchAliasTest.php index f59a935..afd4e82 100644 --- a/tests/Unit/BranchAliasTest.php +++ b/tests/Unit/BranchAliasTest.php @@ -2,24 +2,24 @@ namespace Saucebase\Core\Tests\Unit; -use Composer\Semver\Comparator; use PHPUnit\Framework\TestCase; use Symfony\Component\Process\Process; /** - * The `dev` branch installs as `dev-dev`, which no `^2.x` constraint accepts on its - * own. Its branch alias names the next minor, so apps can test it against modules - * that require a release. After a release, the alias moves to the minor after it. + * The `dev` branch installs as `dev-dev`, which no `^3.x` constraint accepts on its + * own. Its branch alias names the major (`3.x-dev`, as Laravel does), which sorts above + * every 3.x release, so apps can test it against modules that require a release and it + * never falls behind a minor release. Only a new major moves it. */ class BranchAliasTest extends TestCase { - public function test_the_dev_branch_is_aliased_ahead_of_the_newest_release(): void + public function test_the_dev_branch_is_aliased_to_the_newest_releases_major(): void { $composer = json_decode((string) file_get_contents(__DIR__.'/../../composer.json'), true); $alias = $composer['extra']['branch-alias']['dev-dev'] ?? null; $this->assertIsString($alias, 'composer.json needs extra.branch-alias.dev-dev'); - $this->assertMatchesRegularExpression('/^\d+\.\d+\.x-dev$/', $alias); + $this->assertMatchesRegularExpression('/^\d+\.x-dev$/', $alias, 'Alias the major only, like 3.x-dev.'); $tags = new Process(['git', 'tag', '--list', 'v*', '--sort=-v:refname'], dirname(__DIR__, 2)); $newest = strtok((string) $tags->mustRun()->getOutput(), "\n"); @@ -28,10 +28,10 @@ public function test_the_dev_branch_is_aliased_ahead_of_the_newest_release(): vo $this->markTestSkipped('No release tags in this checkout.'); } - // 2.13.x-dev against v2.12.0: compare the alias's minor as 2.13.0. - $this->assertTrue( - Comparator::greaterThan(str_replace('.x-dev', '.0', $alias), ltrim($newest, 'v')), - "dev-dev is aliased {$alias}, but {$newest} is already released: move the alias past it.", + $this->assertGreaterThanOrEqual( + (int) ltrim($newest, 'v'), + (int) $alias, + "dev-dev is aliased {$alias}, behind {$newest}: alias the new major.", ); } } diff --git a/tests/Unit/Services/NavigationTest.php b/tests/Unit/Services/NavigationTest.php index 32e83c7..b0898c6 100644 --- a/tests/Unit/Services/NavigationTest.php +++ b/tests/Unit/Services/NavigationTest.php @@ -300,6 +300,26 @@ public function test_is_item_active_returns_false_for_different_url(): void $this->assertFalse($grouped['main'][0]['active']); } + /** The site root has no path at all (`parse_url` gives null), on either side. */ + public function test_a_home_item_is_active_at_the_site_root(): void + { + app()->instance('request', Request::create('http://localhost')); + + $this->navigation->add('Home', 'http://localhost', function (Section $section) { + $section->attributes(['group' => 'main']); + }); + + set_error_handler(fn (int $level, string $message) => throw new \ErrorException($message, 0, $level), E_DEPRECATED); + + try { + $grouped = $this->navigation->treeGrouped(); + } finally { + restore_error_handler(); + } + + $this->assertTrue($grouped['main'][0]['active']); + } + public function test_is_item_active_normalizes_trailing_slashes(): void { app()->instance('request', Request::create('http://localhost/dashboard/'));