diff --git a/.gitignore b/.gitignore index b3846c8..095d774 100644 --- a/.gitignore +++ b/.gitignore @@ -5,5 +5,6 @@ .DS_Store /.phpstan.cache/ tests/Fixtures/modules/*/resources/js/ +/node_modules/ /resources/js/node_modules/ /stubs/stack/*/config/node_modules/ diff --git a/resources/boost/skills/saucebase-module-development/SKILL.md b/resources/boost/skills/saucebase-module-development/SKILL.md index 8e3ebe0..b04d435 100644 --- a/resources/boost/skills/saucebase-module-development/SKILL.md +++ b/resources/boost/skills/saucebase-module-development/SKILL.md @@ -14,10 +14,10 @@ Ask one question at a time, and skip frontend questions for admin-only modules: 1. Does it have Inertia pages, or is it admin-only (Filament)? 2. Does it need models and migrations? 3. Does it need Filament resources? If yes, activate `saucebase-filament-development`. -4. *(frontend)* Does it have public pages that need SSR? +4. _(frontend)_ Does it have public pages that need SSR? 5. Does it need a seeder? -6. *(frontend, logged-in area)* Does it need navigation entries and breadcrumbs? -7. *(frontend)* Should it have E2E tests? +6. _(frontend, logged-in area)_ Does it need navigation entries and breadcrumbs? +7. _(frontend)_ Should it have E2E tests? Write each behavior's failing test before its implementation. @@ -65,6 +65,22 @@ List extra providers in `protected array $providers`. `replaceConfig($path, $key config key where `mergeConfigFrom` would merge numeric arrays wrongly. Call `parent::boot()` when overriding `boot()`. +## Event Listeners + +Put listeners in `src/Listeners/` with a `handle()` method typed to the event +(`handle(PasswordReset $event)`). The module loader discovers them while event discovery is on, which is +Laravel's default (`app-modules.should_discover_events` overrides it). Never also call `Event::listen()` for +them in the provider: the listener would run twice. `php artisan event:list` shows each listener once. + +Discovery only covers dispatched events. Eloquent model events on a model the module doesn't own (the +app's `User`) are hooked in the provider's `boot()`: + +```php +$users = config('auth.providers.users.model'); + +$users::deleted(fn (Model $user) => ...); +``` + ## Navigation Core loads `routes/navigation.php` from the app and from every installed module. diff --git a/resources/js/lib/dates.test.ts b/resources/js/lib/dates.test.ts index 06460c8..a49a45c 100644 --- a/resources/js/lib/dates.test.ts +++ b/resources/js/lib/dates.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { formatDate } from './dates'; +import { formatDate, formatRelative } from './dates'; describe('formatDate', () => { it('formats in the language it is given', () => { @@ -25,3 +25,39 @@ describe('formatDate', () => { expect(formatDate('', 'en')).toBe(''); }); }); + +describe('formatRelative', () => { + const now = new Date('2026-10-28T12:00:00Z'); + const at = (seconds: number) => + new Date(now.getTime() + seconds * 1000).toISOString(); + const day = 86_400; + + it('says how long ago, or how long until, in the largest whole unit', () => { + expect(formatRelative(at(-30), 'en', now)).toBe('now'); + expect(formatRelative(at(-5 * 60), 'en', now)).toBe('5 minutes ago'); + expect(formatRelative(at(-3 * 3600), 'en', now)).toBe('3 hours ago'); + expect(formatRelative(at(-day), 'en', now)).toBe('yesterday'); + expect(formatRelative(at(3 * day), 'en', now)).toBe('in 3 days'); + expect(formatRelative(at(21 * day), 'en', now)).toBe('in 3 weeks'); + expect(formatRelative(at(-62 * day), 'en', now)).toBe('2 months ago'); + expect(formatRelative(at(400 * day), 'en', now)).toBe('next year'); + }); + + it('rounds past and future alike', () => { + expect(formatRelative(at(-90 * 60), 'en', now)).toBe('2 hours ago'); + expect(formatRelative(at(90 * 60), 'en', now)).toBe('in 2 hours'); + }); + + it('returns an empty string for a date it cannot read', () => { + expect(formatRelative('not-a-date', 'en', now)).toBe(''); + }); + + it('speaks the language it is given', () => { + expect(formatRelative(at(-day), 'pt-BR', now)).toBe('ontem'); + }); + + it('returns an empty string when there is no date', () => { + expect(formatRelative(null, 'en', now)).toBe(''); + expect(formatRelative('', 'en', now)).toBe(''); + }); +}); diff --git a/resources/js/lib/dates.ts b/resources/js/lib/dates.ts index 066711f..67e69e7 100644 --- a/resources/js/lib/dates.ts +++ b/resources/js/lib/dates.ts @@ -52,3 +52,46 @@ export function formatDateTime( minute: '2-digit', }); } + +const RELATIVE_UNITS: [Intl.RelativeTimeFormatUnit, number][] = [ + ['year', 365 * 86_400], + ['month', 30 * 86_400], + ['week', 7 * 86_400], + ['day', 86_400], + ['hour', 3_600], + ['minute', 60], +]; + +/** + * How long ago, or how long until, in the app's language: "yesterday", "in 3 weeks", + * "2 months ago". Under a minute is "now". + * + * Only for pages that never render on the server, like `formatDateTime()`: the + * server's "now" is not the reader's, so the text would change on hydration. + */ +export function formatRelative( + value: string | Date | null | undefined, + locale: string | undefined, + now: Date = new Date(), +): string { + if (!value) { + return ''; + } + + const seconds = (new Date(value).getTime() - now.getTime()) / 1000; + + if (Number.isNaN(seconds)) { + return ''; + } + const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' }); + const unit = RELATIVE_UNITS.find(([, size]) => Math.abs(seconds) >= size); + + if (!unit) { + return format.format(0, 'second'); + } + + // Rounded by size, then signed, so 90 minutes is "2 hours" either way. + const amount = Math.round(Math.abs(seconds) / unit[1]); + + return format.format(seconds < 0 ? -amount : amount, unit[0]); +} diff --git a/src/Console/Commands/InstallCommand.php b/src/Console/Commands/InstallCommand.php index 15da6f5..640f6a8 100644 --- a/src/Console/Commands/InstallCommand.php +++ b/src/Console/Commands/InstallCommand.php @@ -39,6 +39,7 @@ class InstallCommand extends Command '/test-results', '/storage/framework/playwright', // Every env file, the E2E suite's `.env.e2e` included, but the examples. + '.env', '.env.*', '!.env.*.example', '!.env.example', @@ -98,7 +99,17 @@ private function ignoreGeneratedFiles(Filesystem $files): void { $path = $this->laravel->basePath('.gitignore'); $current = $files->exists($path) ? $files->get($path) : ''; - $missing = array_diff(self::GENERATED, array_map(trim(...), explode("\n", $current))); + $present = array_map(trim(...), explode("\n", $current)); + $missing = array_diff(self::GENERATED, $present); + + // A negation only works after the pattern it undoes, so a `.env.*` appended now + // brings its exceptions along, even ones the file already has. + if (in_array('.env.*', $missing, true)) { + $missing = array_filter( + self::GENERATED, + fn (string $line) => in_array($line, $missing, true) || str_starts_with($line, '!.env'), + ); + } if ($missing !== []) { $files->put($path, ($current === '' ? '' : rtrim($current, "\n")."\n\n")."# Saucebase\n".implode("\n", $missing)."\n"); diff --git a/stubs/stack/react/js/components/DynamicDialog.tsx b/stubs/stack/react/js/components/DynamicDialog.tsx index 64ac617..c621225 100644 --- a/stubs/stack/react/js/components/DynamicDialog.tsx +++ b/stubs/stack/react/js/components/DynamicDialog.tsx @@ -7,7 +7,6 @@ import { AlertDialogHeader, AlertDialogTitle, } from '@/components/ui/alert-dialog'; -import { buttonVariants } from '@/components/ui/button'; import { cn } from '@/lib/utils'; import { useDialog } from '@saucebase/react/hooks/useDialog'; import { useT } from '@saucebase/react/i18n'; @@ -74,12 +73,10 @@ export default function DynamicDialog() { {options.cancelLabel ?? t('Cancel')} resolve(true)} > diff --git a/stubs/stack/react/js/components/ui/saucebase/CopyField.tsx b/stubs/stack/react/js/components/ui/saucebase/CopyField.tsx new file mode 100644 index 0000000..3fbf06f --- /dev/null +++ b/stubs/stack/react/js/components/ui/saucebase/CopyField.tsx @@ -0,0 +1,66 @@ +import { + InputGroup, + InputGroupAddon, + InputGroupButton, + InputGroupInput, +} from '@/components/ui/input-group'; +import { useT } from '@saucebase/react/i18n'; +import { Check, Copy } from 'lucide-react'; +import { useEffect, useRef, useState } from 'react'; +import { toast } from 'sonner'; + +interface CopyFieldProps { + value: string; + testId: string; + className?: string; +} + +export function CopyField({ value, testId, className }: CopyFieldProps) { + const t = useT(); + + // The tick is feedback the user can see without reading the toast, so it clears + // itself on a timer rather than waiting for something else to re-render. + const [copied, setCopied] = useState(false); + const copyTimerRef = useRef | null>(null); + + useEffect( + () => () => { + if (copyTimerRef.current) clearTimeout(copyTimerRef.current); + }, + [], + ); + + const copy = () => { + navigator.clipboard + .writeText(value) + .then(() => { + toast.success(t('Copied to clipboard')); + if (copyTimerRef.current) clearTimeout(copyTimerRef.current); + setCopied(true); + copyTimerRef.current = setTimeout(() => setCopied(false), 2000); + }) + .catch(() => toast.error(t('Failed to copy'))); + }; + + return ( + + e.target.select()} + /> + + + {copied ? : } + + + + ); +} diff --git a/stubs/stack/react/js/components/ui/saucebase/index.ts b/stubs/stack/react/js/components/ui/saucebase/index.ts index 2945b78..c39a6c1 100644 --- a/stubs/stack/react/js/components/ui/saucebase/index.ts +++ b/stubs/stack/react/js/components/ui/saucebase/index.ts @@ -242,3 +242,4 @@ export const modules: Module[] = [ export { ModuleCard } from './ModuleCard'; export { ModuleModal } from './ModuleModal'; export { default as PageHero } from './PageHero'; +export { CopyField } from './CopyField'; diff --git a/stubs/stack/vue/js/components/ui/saucebase/CopyField.vue b/stubs/stack/vue/js/components/ui/saucebase/CopyField.vue new file mode 100644 index 0000000..f0df7e4 --- /dev/null +++ b/stubs/stack/vue/js/components/ui/saucebase/CopyField.vue @@ -0,0 +1,65 @@ + + + diff --git a/stubs/stack/vue/js/components/ui/saucebase/index.ts b/stubs/stack/vue/js/components/ui/saucebase/index.ts index de007d9..b27fd7f 100644 --- a/stubs/stack/vue/js/components/ui/saucebase/index.ts +++ b/stubs/stack/vue/js/components/ui/saucebase/index.ts @@ -287,3 +287,4 @@ export type Module = ReturnType['value'][number]; export { default as ModuleCard } from './ModuleCard.vue'; export { default as ModuleModal } from './ModuleModal.vue'; export { default as PageHero } from './PageHero.vue'; +export { default as CopyField } from './CopyField.vue'; diff --git a/tests/Feature/InstallCommandTest.php b/tests/Feature/InstallCommandTest.php index db3740c..c403947 100644 --- a/tests/Feature/InstallCommandTest.php +++ b/tests/Feature/InstallCommandTest.php @@ -315,6 +315,30 @@ public function test_it_ignores_every_env_file_but_the_examples(): void $this->assertGreaterThan($envs, strpos($ignored, "\n!.env.example\n")); } + public function test_a_new_gitignore_ignores_the_env_file(): void + { + $this->files->delete($this->appPath.'/.gitignore'); + + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); + + $this->assertContains('.env', explode("\n", $this->read('.gitignore'))); + } + + /** Exceptions already in the file still have to follow the pattern they undo. */ + public function test_existing_env_exceptions_still_follow_the_pattern(): void + { + $this->files->put($this->appPath.'/.gitignore', "/vendor\n.env\n!.env.*.example\n!.env.example\n"); + + $this->artisan('saucebase:install', ['framework' => 'vue', '--force' => true])->assertSuccessful(); + + $ignored = $this->read('.gitignore'); + $envs = strrpos($ignored, "\n.env.*\n"); + + $this->assertNotFalse($envs); + $this->assertGreaterThan($envs, strrpos($ignored, "\n!.env.*.example\n")); + $this->assertGreaterThan($envs, strrpos($ignored, "\n!.env.example\n")); + } + public function test_it_does_not_ignore_a_path_twice(): void { $this->files->put($this->appPath.'/.gitignore', "/vendor\n/bootstrap/ssr\n");