create-tigra 4.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +17 -2
  3. package/bin/create-tigra.js +72 -1
  4. package/lib/patchers/diagnostics.patcher.js +149 -0
  5. package/lib/patchers/metrics.patcher.js +145 -0
  6. package/modules/diagnostics/diagnostics.md +65 -0
  7. package/modules/diagnostics/prisma/diagnostic-bucket.prisma +22 -0
  8. package/modules/diagnostics/prisma/migration.sql +43 -0
  9. package/modules/diagnostics/server/__tests__/diagnostics.collector.test.ts +72 -0
  10. package/modules/diagnostics/server/__tests__/diagnostics.context.test.ts +51 -0
  11. package/modules/diagnostics/server/__tests__/diagnostics.integration.test.ts +107 -0
  12. package/modules/diagnostics/server/__tests__/diagnostics.service.test.ts +31 -0
  13. package/modules/diagnostics/server/diagnostics.collector.ts +95 -0
  14. package/modules/diagnostics/server/diagnostics.context.ts +73 -0
  15. package/modules/diagnostics/server/diagnostics.repo.ts +69 -0
  16. package/modules/diagnostics/server/diagnostics.routes.ts +17 -0
  17. package/modules/diagnostics/server/diagnostics.sample.ts +92 -0
  18. package/modules/diagnostics/server/diagnostics.schemas.ts +33 -0
  19. package/modules/diagnostics/server/diagnostics.service.ts +44 -0
  20. package/modules/metrics/client/WebVitalsReporter.tsx +35 -0
  21. package/modules/metrics/client/__tests__/WebVitalsReporter.test.ts +65 -0
  22. package/modules/metrics/client/metrics.pages.ts +5 -0
  23. package/modules/metrics/performance.md +56 -0
  24. package/modules/metrics/prisma/metric-bucket.prisma +18 -0
  25. package/modules/metrics/prisma/migration.sql +17 -0
  26. package/modules/metrics/server/__tests__/metrics.collector.test.ts +75 -0
  27. package/modules/metrics/server/__tests__/metrics.integration.test.ts +88 -0
  28. package/modules/metrics/server/__tests__/metrics.schemas.test.ts +36 -0
  29. package/modules/metrics/server/__tests__/metrics.service.test.ts +84 -0
  30. package/modules/metrics/server/metrics.collector.ts +130 -0
  31. package/modules/metrics/server/metrics.pages.ts +3 -0
  32. package/modules/metrics/server/metrics.repo.ts +45 -0
  33. package/modules/metrics/server/metrics.routes.ts +46 -0
  34. package/modules/metrics/server/metrics.schemas.ts +57 -0
  35. package/modules/metrics/server/metrics.service.ts +100 -0
  36. package/package.json +1 -1
  37. package/template/AGENTS.md +17 -10
  38. package/template/client/src/app/focus-rings.policy.test.ts +88 -0
  39. package/template/client/src/app/globals.css +46 -0
  40. package/template/client/src/app/layout.tsx +5 -0
  41. package/template/client/src/app/page.tsx +2 -2
  42. package/template/client/src/components/common/InputModalityTracker.tsx +12 -0
  43. package/template/client/src/components/ui/input.tsx +3 -2
  44. package/template/client/src/lib/input-modality.test.ts +79 -0
  45. package/template/client/src/lib/input-modality.ts +52 -0
@@ -0,0 +1,3 @@
1
+ // Add stable public page groups here and in the browser page matcher. This
2
+ // allowlist keeps submitted paths and visitor identifiers out of storage.
3
+ export const METRICS_PAGE_GROUPS = ['home', 'other'] as const;
@@ -0,0 +1,45 @@
1
+ import { prisma } from '@libs/prisma.js';
2
+ import type { MetricBucket as StoredBucket } from '@prisma/client';
3
+ import type { MetricBucket } from './metrics.collector.js';
4
+ import type { MetricsQuery } from './metrics.schemas.js';
5
+
6
+ export async function persistMetricBuckets(rows: MetricBucket[]): Promise<void> {
7
+ // One bounded transaction per sealed window. A retry with the same row IDs
8
+ // is a no-op for rows that committed before a lost acknowledgement.
9
+ await prisma.$transaction(async (tx) => {
10
+ await tx.metricBucket.createMany({ data: rows, skipDuplicates: true });
11
+ }, { maxWait: 500, timeout: 1_500 });
12
+ }
13
+
14
+ export async function readMetricBuckets(query: MetricsQuery): Promise<{
15
+ buckets: Omit<StoredBucket, 'id'>[];
16
+ nextCursor: string | null;
17
+ }> {
18
+ const { from, to, kind, limit, cursor } = query;
19
+ const rows = await prisma.metricBucket.findMany({
20
+ where: {
21
+ bucketStart: { gte: from, lt: to },
22
+ ...(kind ? { kind } : {}),
23
+ ...(cursor ? {
24
+ OR: [
25
+ { bucketStart: { gt: cursor[0] } },
26
+ { bucketStart: cursor[0], id: { gt: cursor[1] } },
27
+ ],
28
+ } : {}),
29
+ },
30
+ orderBy: [{ bucketStart: 'asc' }, { id: 'asc' }],
31
+ take: limit + 1,
32
+ select: {
33
+ id: true, bucketStart: true, kind: true, label: true, method: true,
34
+ unit: true, count: true, sum: true, bounds: true, histogram: true, release: true,
35
+ },
36
+ });
37
+ const page = rows.slice(0, limit);
38
+ const last = page.at(-1);
39
+ return {
40
+ buckets: page.map(({ id: _id, ...row }) => row),
41
+ nextCursor: last && rows.length > limit
42
+ ? Buffer.from(JSON.stringify([last.bucketStart.toISOString(), last.id])).toString('base64url')
43
+ : null,
44
+ };
45
+ }
@@ -0,0 +1,46 @@
1
+ import type { FastifyInstance } from 'fastify';
2
+ import { env } from '@config/env.js';
3
+ import { RATE_LIMITS } from '@config/rate-limit.config.js';
4
+ import { isOriginAllowed } from '@libs/origin-check.js';
5
+ import { ForbiddenError } from '@shared/errors/errors.js';
6
+ import { successResponse } from '@shared/responses/successResponse.js';
7
+ import type { MetricCollector } from './metrics.collector.js';
8
+ import { readMetricBuckets } from './metrics.repo.js';
9
+ import { metricsQuerySchema, webVitalsSchema, type MetricsQuery, type WebVitalsInput } from './metrics.schemas.js';
10
+
11
+ const origins = new Set(env.CORS_ORIGINS);
12
+
13
+ export async function webVitalsRoutes(app: FastifyInstance, options: { collector?: MetricCollector }): Promise<void> {
14
+ app.post<{ Body: WebVitalsInput }>('/metrics/web-vitals', {
15
+ schema: { body: webVitalsSchema },
16
+ bodyLimit: 2048,
17
+ config: {
18
+ // A busy shared IP may hit this endpoint's limit. It must not earn
19
+ // IP-wide auto-block strikes from best-effort telemetry.
20
+ rateLimit: { ...RATE_LIMITS.METRICS_INGESTION, onExceeded: () => {} },
21
+ },
22
+ onRequest: async (request) => {
23
+ const origin = request.headers.origin;
24
+ if (!origin || origin === 'null' || !isOriginAllowed(origin, request.headers.host, origins, env.NODE_ENV === 'development')) {
25
+ throw new ForbiddenError('Origin not allowed', 'ORIGIN_NOT_ALLOWED');
26
+ }
27
+ },
28
+ }, async (request, reply) => {
29
+ for (const { kind, value } of request.body.samples) {
30
+ options.collector?.record(kind, request.body.page, value);
31
+ }
32
+ return reply.code(204).send();
33
+ });
34
+ }
35
+
36
+ /** Mount inside adminRoutes, whose authentication and role hooks guard this
37
+ * read even when the collector is disabled. */
38
+ export function registerAdminMetricsRoute(app: FastifyInstance): void {
39
+ app.get<{ Querystring: MetricsQuery }>('/admin/metrics', {
40
+ schema: { querystring: metricsQuerySchema },
41
+ config: { rateLimit: RATE_LIMITS.ADMIN_DEFAULT },
42
+ }, async (request, reply) => {
43
+ reply.header('Cache-Control', 'no-store');
44
+ return successResponse('Metric buckets', await readMetricBuckets(request.query));
45
+ });
46
+ }
@@ -0,0 +1,57 @@
1
+ import { z } from 'zod';
2
+ import { METRICS, type MetricKind } from './metrics.collector.js';
3
+ import { METRICS_PAGE_GROUPS } from './metrics.pages.js';
4
+
5
+ const sevenDays = 7 * 24 * 60 * 60_000;
6
+ const dateTime = z.iso.datetime({ offset: true }).transform((value) => new Date(value))
7
+ .pipe(z.date().min(new Date('1000-01-01T00:00:00Z')).max(new Date('9999-12-31T23:59:59.999Z')));
8
+ const metricKind = z.custom<MetricKind>(
9
+ (value) => typeof value === 'string' && Object.hasOwn(METRICS, value),
10
+ 'Unknown metric kind',
11
+ );
12
+
13
+ // The cursor identifies a position, not a capability or a database query.
14
+ const cursorSchema = z.tuple([dateTime, z.string().regex(/^[a-f0-9]{64}$/)]);
15
+ const cursor = z.string().max(192).regex(/^[A-Za-z0-9_-]+$/).transform((value, ctx) => {
16
+ let decoded: unknown;
17
+ try { decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')); } catch { /* invalid cursor */ }
18
+ const result = cursorSchema.safeParse(decoded);
19
+ if (result.success) return result.data;
20
+ ctx.addIssue({ code: 'custom', message: 'Invalid metrics cursor' });
21
+ return z.NEVER;
22
+ });
23
+
24
+ export const metricsQuerySchema = z.strictObject({
25
+ from: dateTime,
26
+ to: dateTime,
27
+ kind: metricKind.optional(),
28
+ limit: z.string().regex(/^\d{1,3}$/).transform(Number).pipe(z.number().int().min(1).max(100)).default(50),
29
+ cursor: cursor.optional(),
30
+ }).superRefine(({ from, to, cursor }, ctx) => {
31
+ // Zod can run refinements after a field check fails, with its original input.
32
+ if (!(from instanceof Date) || !(to instanceof Date)) return;
33
+ const range = to.getTime() - from.getTime();
34
+ if (range <= 0 || range > sevenDays) {
35
+ ctx.addIssue({ code: 'custom', path: ['to'], message: 'The interval must be positive and at most seven days' });
36
+ }
37
+ if (Array.isArray(cursor) && (cursor[0] < from || cursor[0] >= to)) {
38
+ ctx.addIssue({ code: 'custom', path: ['cursor'], message: 'The cursor must be inside the requested interval' });
39
+ }
40
+ });
41
+ export type MetricsQuery = z.output<typeof metricsQuerySchema>;
42
+
43
+ export const webVitalsSchema = z.strictObject({
44
+ page: z.enum(METRICS_PAGE_GROUPS),
45
+ samples: z.array(z.strictObject({
46
+ kind: z.enum(['lcp', 'inp', 'cls']),
47
+ value: z.number().finite().min(0).max(86_400_000),
48
+ })).min(1).max(3),
49
+ }).superRefine(({ samples }, ctx) => {
50
+ if (new Set(samples.map((sample) => sample.kind)).size !== samples.length) {
51
+ ctx.addIssue({ code: 'custom', path: ['samples'], message: 'Send each vital at most once per batch' });
52
+ }
53
+ if (samples.some(({ kind, value }) => kind === 'cls' && value > 100)) {
54
+ ctx.addIssue({ code: 'custom', path: ['samples'], message: 'CLS must not exceed 100' });
55
+ }
56
+ });
57
+ export type WebVitalsInput = z.output<typeof webVitalsSchema>;
@@ -0,0 +1,100 @@
1
+ import { monitorEventLoopDelay, performance } from 'node:perf_hooks';
2
+ import type { FastifyInstance, FastifyRequest } from 'fastify';
3
+ import { env } from '@config/env.js';
4
+ import { startRecurringJob } from '@/jobs/schedule.js';
5
+ import { logger } from '@libs/logger.js';
6
+ import { MONITORING_PATHS } from '@libs/rate-limiting.js';
7
+ import { MetricCollector } from './metrics.collector.js';
8
+ import { persistMetricBuckets } from './metrics.repo.js';
9
+
10
+ const EXCLUDED = new Set([...MONITORING_PATHS, '/api/v1/metrics/web-vitals', '/api/v1/admin/metrics']);
11
+ let activeCollector: MetricCollector | undefined;
12
+
13
+ /** Time an explicitly named operation without changing its return or error
14
+ * behavior. Names must describe code paths, never individual resources. */
15
+ export async function measureOperation<T>(name: string, run: () => T | Promise<T>): Promise<T> {
16
+ const collector = activeCollector;
17
+ if (!collector || !/^[a-z][a-z0-9._-]{0,79}$/.test(name)) return run();
18
+ const start = performance.now();
19
+ try {
20
+ return await run();
21
+ } finally {
22
+ collector.record('operation', name, performance.now() - start);
23
+ }
24
+ }
25
+
26
+ export function registerMetrics(app: FastifyInstance): MetricCollector | undefined {
27
+ if (!env.METRICS_ENABLED) return undefined;
28
+ const release = env.SOURCE_COMMIT?.trim();
29
+ const collector = new MetricCollector(persistMetricBuckets, {
30
+ release: release && /^[a-f0-9]{7,64}$/i.test(release) ? release.toLowerCase() : null,
31
+ });
32
+ activeCollector = collector;
33
+ const starts = new WeakMap<FastifyRequest, number>();
34
+
35
+ // Register at the root before route plugins so auth, validation and future
36
+ // routes are covered. A socket abort/timeout without a reply is excluded.
37
+ app.addHook('onRequest', async (request) => {
38
+ if (request.method === 'OPTIONS' || EXCLUDED.has(request.routeOptions.url ?? '')) return;
39
+ starts.set(request, performance.now());
40
+ });
41
+ app.addHook('onRequestAbort', async (request) => { starts.delete(request); });
42
+ app.addHook('onTimeout', async (request) => { starts.delete(request); });
43
+ app.addHook('onResponse', async (request) => {
44
+ const start = starts.get(request);
45
+ if (start === undefined) return;
46
+ starts.delete(request);
47
+ const route = request.is404 ? undefined : request.routeOptions.url;
48
+ const label = route && route.length <= 191 ? route : '(unmatched)';
49
+ collector.record('request', label, performance.now() - start, request.method);
50
+ });
51
+
52
+ const eventLoop = monitorEventLoopDelay({ resolution: 20 });
53
+ eventLoop.enable();
54
+ let cpu = process.cpuUsage();
55
+ let sampledAt = performance.now();
56
+ startRecurringJob(app, {
57
+ name: 'metrics-flush',
58
+ firstRunDelayMs: 5_000,
59
+ intervalMs: 15_000,
60
+ run: async () => {
61
+ const now = performance.now();
62
+ const spent = process.cpuUsage(cpu);
63
+ cpu = process.cpuUsage();
64
+ const memory = process.memoryUsage();
65
+ collector.record('rss', 'process', memory.rss);
66
+ collector.record('heap', 'process', memory.heapUsed);
67
+ collector.record('cpu', 'process', (spent.user + spent.system) / (10 * (now - sampledAt)));
68
+ // One mean-delay observation per sample period. This is not a histogram
69
+ // of individual event-loop ticks, and the units here are milliseconds.
70
+ collector.record('event-loop-delay', 'process', eventLoop.mean / 1_000_000);
71
+ eventLoop.reset();
72
+ sampledAt = now;
73
+ await collector.flush();
74
+ },
75
+ });
76
+
77
+ app.addHook('onClose', async () => {
78
+ eventLoop.disable();
79
+ if (activeCollector === collector) activeCollector = undefined;
80
+ // The collector shares the app's shutdown budget with Redis and Prisma.
81
+ // A stalled store must never keep the Fastify close hook waiting forever.
82
+ let deadline: ReturnType<typeof setTimeout> | undefined;
83
+ try {
84
+ await Promise.race([
85
+ collector.close(),
86
+ new Promise<never>((_resolve, reject) => {
87
+ deadline = setTimeout(() => reject(new Error('Metrics flush deadline')), 2_500);
88
+ }),
89
+ ]);
90
+ } catch {
91
+ logger.warn('[METRICS] Final batch could not be persisted before shutdown');
92
+ } finally {
93
+ clearTimeout(deadline);
94
+ if (collector.droppedSamples) {
95
+ logger.warn({ droppedSamples: collector.droppedSamples }, '[METRICS] Samples dropped at buffer limit');
96
+ }
97
+ }
98
+ });
99
+ return collector;
100
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-tigra",
3
- "version": "4.0.1",
3
+ "version": "4.1.0",
4
4
  "type": "module",
5
5
  "description": "Create a production-ready full-stack app with Next.js 16 + Fastify 5 + Prisma + Redis",
6
6
  "bin": {
@@ -1,6 +1,22 @@
1
1
  # Agent instructions
2
2
 
3
- **Read the scoped file first.** Before changing anything in `server/`, read `server/AGENTS.md`; before changing anything in `client/`, read `client/AGENTS.md`. Claude Code loads them by itself when it opens files there. Codex does not: it loads only the AGENTS.md files from the project root down to the folder it was started in, so started here it never sees them.
3
+ **Read the scoped rules before editing.** For `server/` work, read [server/AGENTS.md](server/AGENTS.md). For `client/` work, read [client/AGENTS.md](client/AGENTS.md). Read both for a change that crosses the API boundary.
4
+
5
+ ## Architecture rules
6
+
7
+ - Keep the Next.js App Router client and Fastify API independently deployable. The server uses Prisma, MySQL, and Redis and owns authorization, business rules, and authoritative validation. The client owns presentation, interaction, and validation feedback.
8
+ - Extend the domain that already owns the behavior. Use the existing route, controller, service, and repository boundaries on the server. Keep client feature behavior in its domain and reuse shared components and theme tokens for UI.
9
+ - Use the existing shared contracts for API paths, responses, authentication, and security. Extend the owning code when behavior changes so all callers use the same policy.
10
+ - Use `server/prisma/schema.prisma` and Prisma migrations for database changes. Define environment variables in `server/src/config/env.ts` or `client/src/lib/env.ts` and update the corresponding examples without credentials.
11
+ - Treat changes to these boundaries as explicit project decisions. Record agreed exceptions and their reasons in **Project facts → Special rules** so later agents can follow them.
12
+
13
+ ### Check for reuse before implementing
14
+
15
+ Before writing code, search across each side you touch (`client/` or `server/`) for the closest behavior, including features outside the directory you are editing. Follow imports and callers to find where that behavior is implemented and how it is used. Reuse or extend the component, hook, service, or helper that already owns the behavior when it fits. If nothing fits, follow the established pattern for the most similar behavior.
16
+
17
+ Shared behavior should have one owner so a change can be made once and reach every caller. This keeps the application consistent and maintainable as it grows.
18
+
19
+ Extract shared code when it has real callers that should change together. Keep code separate when the similarity is superficial, the callers need to evolve independently, or sharing would make them harder to understand. In your handoff, briefly name what you reused or explain why new code was needed.
4
20
 
5
21
  ## MUST FOLLOW — comment important code
6
22
 
@@ -22,15 +38,6 @@ Every implementation change MUST include a human-readability pass. Add or update
22
38
  - **Special rules:** none
23
39
  <!-- project-facts:end -->
24
40
 
25
- ## Architecture and sources of truth
26
-
27
- - `client/` is a Next.js App Router application; `server/` is a Fastify API backed by Prisma/MySQL and Redis. They deploy independently.
28
- - The server owns authorization, business rules, and security validation. Client validation exists for UX and is never a trust boundary.
29
- - `server/prisma/schema.prisma` is the database-schema source of truth. Use Prisma migrations for schema changes.
30
- - `server/src/config/env.ts` and `client/src/lib/env.ts` define valid environment variables. Keep the corresponding `.env.example` files synchronized without real credentials.
31
- - Shared route/API constants, response helpers, and security middleware are canonical; extend them instead of creating competing shapes or duplicate policy.
32
- - Client font preset tokens are declared on `:root`. Apply every referenced `next/font` variable class to `<html>`, never only to `<body>`, so the root-scoped Tailwind tokens can resolve it.
33
-
34
41
  ## Naming
35
42
 
36
43
  - Use functional kebab-case for project names and anything surfaced in CLIs, logs, queues, jobs, or worker/process names.
@@ -0,0 +1,88 @@
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { describe, expect, it } from 'vitest';
4
+
5
+ /**
6
+ * Guard: focus rings show only for keyboard users. jsdom cannot evaluate `:focus-visible` or cascade layers, so this
7
+ * pins the wiring and the CSS (proven in a real browser on iAI, 2026-10-25); lib/input-modality.test.ts covers the
8
+ * mode switching itself.
9
+ */
10
+ const src = join(__dirname, '..');
11
+ const read = (path: string): string => readFileSync(join(src, path), 'utf8').replace(/\r\n/g, '\n');
12
+ const globals = read('app/globals.css');
13
+
14
+ describe('focus rings are keyboard-only', () => {
15
+ it('the root layout starts in pointer mode and mounts the tracker', () => {
16
+ const layout = read('app/layout.tsx');
17
+ expect(layout).toMatch(/<html[^>]*data-input="pointer"/u);
18
+ expect(layout).toMatch(/<InputModalityTracker\s*\/>/u);
19
+ });
20
+
21
+ it('Tailwind focus-visible utilities never fire in pointer mode, except on text fields', () => {
22
+ const variant = globals.match(/@custom-variant focus-visible \(([^\n]+)\);/u)?.[1] ?? '';
23
+ expect(variant).toContain('&:focus-visible');
24
+ expect(variant).toContain(":not([data-input='pointer'] *)");
25
+ for (const field of ['textarea', 'select', "[contenteditable]:not([contenteditable='false'])", 'input:not(']) {
26
+ expect(variant).toContain(field);
27
+ }
28
+ });
29
+
30
+ it('a global rule outside every cascade layer drops plain-CSS focus outlines in pointer mode', () => {
31
+ const rule = globals.match(/\nhtml\[data-input='pointer'\] :focus:not\([^{]+\{\s*outline: none !important;\s*\}/u);
32
+ expect(rule).not.toBeNull();
33
+ const before = globals.slice(0, rule!.index);
34
+ expect((before.match(/\{/gu) ?? []).length).toBe((before.match(/\}/gu) ?? []).length);
35
+ });
36
+
37
+ it('keyboard focus is one style everywhere: a 1px accent edge on the element and a faint tint, never outside it', () => {
38
+ const rule = globals.match(/\nhtml\[data-input='keyboard'\] :focus-visible:not\(([^{]+)\) \{([^}]+)\}/u);
39
+ expect(rule).not.toBeNull();
40
+ const [, excluded, body] = rule!;
41
+ expect(body).toContain('outline: 1px solid var(--ring) !important;');
42
+ expect(body).toContain('outline-offset: -1px !important;');
43
+ // `transparent` first: Tailwind's build copies the FIRST colour of a color-mix() into a fallback for browsers
44
+ // without it; `var(--ring)` first would fill the whole control with the accent there.
45
+ expect(body).toMatch(/box-shadow: inset 0 0 0 100vmax color-mix\(in srgb, transparent \d+%, var\(--ring\)\) !important;/u);
46
+ // Menus and select options keep their highlight only; programmatic focus targets are not tab stops.
47
+ for (const part of ["[role='menuitem']", "[role='option']", "[tabindex='-1']", 'textarea']) expect(excluded).toContain(part);
48
+ const before = globals.slice(0, rule!.index);
49
+ expect((before.match(/\{/gu) ?? []).length).toBe((before.match(/\}/gu) ?? []).length);
50
+ });
51
+
52
+ it('filled controls add a page-coloured line inside the edge instead of the tint', () => {
53
+ // The primary fill equals --ring here, so the accent edge alone would vanish on a primary button.
54
+ const filled = globals.match(/\nhtml\[data-input='keyboard'\] :is\(([^{]+)\):focus-visible \{([^}]+)\}/u);
55
+ expect(filled).not.toBeNull();
56
+ // Hand-styled fills count too (the welcome page's links are `bg-primary` anchors, not the UI kit's Button).
57
+ for (const part of ["[data-slot='button'][data-variant='default']", "[data-slot='button'][data-variant='destructive']",
58
+ '.bg-primary', '.bg-destructive']) {
59
+ expect(filled![1]).toContain(part);
60
+ }
61
+ expect(filled![2].trim()).toBe('box-shadow: inset 0 0 0 2px var(--background) !important;');
62
+ // Same specificity as the general rule, so it must come after it to win.
63
+ expect(filled!.index).toBeGreaterThan(globals.indexOf("\nhtml[data-input='keyboard'] :focus-visible:not("));
64
+ });
65
+
66
+ it('text fields show focus by their border turning accent, never a glow outside the field', () => {
67
+ // Text fields keep a focus look for mouse users too (you need to see where you type), so it follows the same
68
+ // "nothing outside the element" rule: accent border on focus, red border when invalid, no ring.
69
+ const input = read('components/ui/input.tsx');
70
+ expect(input).toContain('focus-visible:border-ring');
71
+ expect(input).toContain('aria-invalid:border-destructive');
72
+ expect(input).not.toMatch(/focus-visible:ring|aria-invalid:ring/u);
73
+ });
74
+
75
+ it('a focused invalid field keeps its red border and gets a faint red tint, so focus stays visible', () => {
76
+ // The red border is the same with or without focus; without the old red glow, the tint is what marks focus.
77
+ const rule = globals.match(/\n:is\(([^{]+)\)\[aria-invalid='true'\]:focus-visible \{([^}]+)\}/u);
78
+ expect(rule).not.toBeNull();
79
+ for (const field of ['textarea', 'select', 'input:not(']) expect(rule![1]).toContain(field);
80
+ expect(rule![2]).toMatch(/box-shadow: inset 0 0 0 100vmax color-mix\(in srgb, transparent \d+%, var\(--destructive\)\) !important;/u);
81
+ });
82
+
83
+ it('no UI kit component draws a ring on plain :focus (it would show on every mouse click)', () => {
84
+ const offenders = readdirSync(join(src, 'components/ui')).filter((file) => file.endsWith('.tsx'))
85
+ .filter((file) => /(^|[\s"'`])focus:(ring|outline-(?!hidden|none))/u.test(read(`components/ui/${file}`)));
86
+ expect(offenders).toEqual([]);
87
+ });
88
+ });
@@ -29,6 +29,13 @@
29
29
 
30
30
  @custom-variant dark (&:is(.dark *));
31
31
 
32
+ /* Focus rings are for keyboard users. Tailwind's own focus-visible variant is replaced so that every `focus-visible:`
33
+ * utility (rings, borders) stays off while the page is in pointer mode (`<html data-input>`, set by
34
+ * lib/input-modality.ts). Text fields keep their focus look in every mode: it shows where the visitor is typing.
35
+ * Static selection rings (a plain `ring-2`) are untouched; see "Focus rings" at the end of this file for plain-CSS
36
+ * outlines. */
37
+ @custom-variant focus-visible (&:focus-visible:where(:not([data-input='pointer'] *), textarea, select, [contenteditable]:not([contenteditable='false']), input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image'])));
38
+
32
39
  @theme inline {
33
40
  --color-background: var(--background);
34
41
  --color-foreground: var(--foreground);
@@ -105,3 +112,42 @@
105
112
  min-height: var(--smooth-navigation-min-height);
106
113
  }
107
114
  }
115
+
116
+ /* Focus rings. Radix menus and selects move focus by script after a mouse click, and Chrome then reports
117
+ * `:focus-visible`, so keyboard-only rings appeared for mouse users. In pointer mode (lib/input-modality.ts) no focused
118
+ * element draws an outline, except text fields. Unlayered and !important on purpose: it must beat Tailwind's layered
119
+ * utilities and any CSS module's `:focus-visible { outline }`. Keyboard mode always shows focus (WCAG 2.4.7), in the
120
+ * one style defined below. */
121
+ html[data-input='pointer'] :focus:not(textarea, select, [contenteditable]:not([contenteditable='false']), input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image'])) {
122
+ outline: none !important;
123
+ }
124
+
125
+ /* Keyboard focus: one style everywhere. A 1px accent line drawn exactly on the element's edge (it covers a 1px border,
126
+ * or hugs a borderless edge) and a faint accent tint painted under the content (an inset shadow, so backgrounds and
127
+ * images stay). Nothing grows outside the element. Replaces the browser's default ring and the UI kit's
128
+ * `focus-visible:ring-*` rings while the keyboard is in use.
129
+ * Not here: text fields (their border turns accent, components/ui/input.tsx), menu items and select options (their highlight is the focus), and
130
+ * focus targets that are not tab stops (tabindex -1: a main region after a skip link, menus, dialogs).
131
+ * `transparent` comes first in the color-mix() on purpose: Tailwind's build copies the first colour into a fallback for
132
+ * browsers without color-mix(), so those get no tint (just the edge) instead of a control filled with the accent. */
133
+ html[data-input='keyboard'] :focus-visible:not(textarea, select, [contenteditable]:not([contenteditable='false']), input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image']), [role='menuitem'], [role='menuitemcheckbox'], [role='menuitemradio'], [role='option'], [tabindex='-1']) {
134
+ outline: 1px solid var(--ring) !important;
135
+ outline-offset: -1px !important;
136
+ box-shadow: inset 0 0 0 100vmax color-mix(in srgb, transparent 92%, var(--ring)) !important;
137
+ }
138
+
139
+ /* Filled controls (primary and destructive buttons, hand-styled `bg-primary` / `bg-destructive` links and buttons;
140
+ * shadcn checkboxes and switches once added): the primary fill is the ring colour, so the edge alone would vanish, and
141
+ * a tint does not show on a strong fill. They keep the edge above and get a 1px page-coloured line just inside it,
142
+ * which reads on any fill. Same specificity as the rule above, so it must stay after it. */
143
+ html[data-input='keyboard'] :is([data-slot='button'][data-variant='default'], [data-slot='button'][data-variant='destructive'], .bg-primary, .bg-destructive, [data-slot='checkbox'][data-state='checked'], [data-slot='switch'][data-state='checked']):focus-visible {
144
+ box-shadow: inset 0 0 0 2px var(--background) !important;
145
+ }
146
+
147
+ /* Text fields show focus on their own border (accent, components/ui/input.tsx), for mouse and keyboard alike. An
148
+ * invalid field's border stays red with or without focus, so a focused one also gets a faint red tint inside;
149
+ * otherwise a keyboard user could not see which field with an error they are in. `transparent` first for the same
150
+ * fallback reason as above. */
151
+ :is(textarea, select, input:not([type='button'], [type='submit'], [type='reset'], [type='checkbox'], [type='radio'], [type='range'], [type='file'], [type='color'], [type='image']))[aria-invalid='true']:focus-visible {
152
+ box-shadow: inset 0 0 0 100vmax color-mix(in srgb, transparent 92%, var(--destructive)) !important;
153
+ }
@@ -4,6 +4,7 @@ import type React from 'react';
4
4
  import { Inter, JetBrains_Mono } from 'next/font/google';
5
5
 
6
6
  import { Providers } from './providers';
7
+ import { InputModalityTracker } from '@/components/common/InputModalityTracker';
7
8
  import { APP_NAME } from '@/lib/constants/app.constants';
8
9
  import { SESSION_MARKER_COOKIE } from '@/lib/utils/session-marker';
9
10
  import './globals.css';
@@ -49,13 +50,17 @@ export default async function RootLayout({
49
50
  // The font preset consumes these next/font variables from :root. Keep the
50
51
  // generated classes on <html>; variables introduced only on <body> cannot
51
52
  // resolve the root-scoped Tailwind font tokens.
53
+ // data-input: focus rings are keyboard-only. The page starts in pointer mode, so nothing shows a ring before the
54
+ // first key press; InputModalityTracker switches it (lib/input-modality.ts, globals.css "Focus rings").
52
55
  <html
53
56
  lang="en"
54
57
  className={`${inter.variable} ${jetbrainsMono.variable}`}
58
+ data-input="pointer"
55
59
  suppressHydrationWarning
56
60
  >
57
61
  <body className="font-sans antialiased">
58
62
  <Providers nonce={nonce} hasSession={hasSession}>{children}</Providers>
63
+ <InputModalityTracker />
59
64
  </body>
60
65
  </html>
61
66
  );
@@ -56,7 +56,7 @@ export default function WelcomePage(): React.ReactElement {
56
56
  href="https://github.com/blessandsoul/create-tigra"
57
57
  target="_blank"
58
58
  rel="noopener noreferrer"
59
- className="inline-flex min-h-11 items-center justify-center rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 md:hover:brightness-110"
59
+ className="inline-flex min-h-11 items-center justify-center rounded-lg bg-primary px-5 py-2.5 text-sm font-medium text-primary-foreground shadow-sm transition-all duration-200 active:scale-[0.97] md:hover:brightness-110"
60
60
  >
61
61
  Documentation
62
62
  </a>
@@ -64,7 +64,7 @@ export default function WelcomePage(): React.ReactElement {
64
64
  href="https://github.com/blessandsoul/create-tigra/issues"
65
65
  target="_blank"
66
66
  rel="noopener noreferrer"
67
- className="inline-flex min-h-11 items-center justify-center rounded-lg border border-border bg-secondary px-5 py-2.5 text-sm font-medium text-secondary-foreground transition-all duration-200 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 md:hover:bg-accent"
67
+ className="inline-flex min-h-11 items-center justify-center rounded-lg border border-border bg-secondary px-5 py-2.5 text-sm font-medium text-secondary-foreground transition-all duration-200 active:scale-[0.97] md:hover:bg-accent"
68
68
  >
69
69
  Report an issue
70
70
  </a>
@@ -0,0 +1,12 @@
1
+ 'use client';
2
+
3
+ import { useEffect } from 'react';
4
+
5
+ import { installInputModality } from '@/lib/input-modality';
6
+
7
+ /** Keeps `<html data-input>` current so focus rings show only for keyboard users (lib/input-modality.ts). Renders
8
+ * nothing; mounted once in the root layout, which also server-renders the starting "pointer" mode. */
9
+ export function InputModalityTracker(): null {
10
+ useEffect(() => installInputModality(document), []);
11
+ return null;
12
+ }
@@ -9,8 +9,9 @@ function Input({ className, type, ...props }: React.ComponentProps<"input">) {
9
9
  data-slot="input"
10
10
  className={cn(
11
11
  "file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
12
- "focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
13
- "aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
12
+ // Focus and errors show on the field's own border, never as a glow outside it (globals.css "Focus rings").
13
+ "focus-visible:border-ring",
14
+ "aria-invalid:border-destructive",
14
15
  className
15
16
  )}
16
17
  {...props}
@@ -0,0 +1,79 @@
1
+ // @vitest-environment jsdom
2
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
+
4
+ import { installInputModality } from './input-modality';
5
+
6
+ /**
7
+ * Focus rings are for keyboard users. Radix menus and selects move focus by script after a mouse click
8
+ * whose default they cancel, so Chrome reports `:focus-visible` and every keyboard ring showed for mouse users. The
9
+ * page records how the owner last interacted (`<html data-input>`) and the CSS hides focus rings in "pointer" mode.
10
+ */
11
+ let uninstall: () => void;
12
+ const mode = (): string | null => document.documentElement.getAttribute('data-input');
13
+ const key = (target: Element, keyName: string, init: KeyboardEventInit = {}): void => {
14
+ target.dispatchEvent(new KeyboardEvent('keydown', { key: keyName, bubbles: true, ...init }));
15
+ };
16
+
17
+ beforeEach(() => {
18
+ document.body.innerHTML = '<button id="b">B</button><textarea id="t"></textarea><input id="i" type="text">'
19
+ + '<input id="c" type="checkbox"><div id="e" contenteditable="true"></div>';
20
+ document.documentElement.removeAttribute('data-input');
21
+ uninstall = installInputModality(document);
22
+ });
23
+ afterEach(() => { uninstall(); });
24
+
25
+ describe('installInputModality', () => {
26
+ it('starts in pointer mode, so nothing shows a ring before the first key press', () => {
27
+ expect(mode()).toBe('pointer');
28
+ });
29
+
30
+ it('switches to keyboard on Tab and on navigation keys outside text fields', () => {
31
+ key(document.getElementById('b')!, 'Tab');
32
+ expect(mode()).toBe('keyboard');
33
+ document.getElementById('b')!.dispatchEvent(new Event('pointerdown', { bubbles: true }));
34
+ expect(mode()).toBe('pointer');
35
+ for (const name of ['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End', 'PageUp', 'PageDown', 'Escape']) {
36
+ document.documentElement.setAttribute('data-input', 'pointer');
37
+ key(document.getElementById('b')!, name);
38
+ expect(mode(), name).toBe('keyboard');
39
+ }
40
+ // A checkbox is not a text field: arrows there are focus navigation.
41
+ document.documentElement.setAttribute('data-input', 'pointer');
42
+ key(document.getElementById('c')!, 'ArrowDown');
43
+ expect(mode()).toBe('keyboard');
44
+ });
45
+
46
+ it('typing, arrows and Enter inside a text field never switch to keyboard', () => {
47
+ for (const id of ['t', 'i', 'e']) {
48
+ for (const name of ['a', 'Enter', ' ', 'ArrowLeft', 'ArrowDown', 'Home', 'Escape', 'Backspace']) {
49
+ key(document.getElementById(id)!, name);
50
+ expect(mode(), `${id} ${name}`).toBe('pointer');
51
+ }
52
+ }
53
+ // Tab moves focus out of the field: that is keyboard navigation.
54
+ key(document.getElementById('t')!, 'Tab');
55
+ expect(mode()).toBe('keyboard');
56
+ });
57
+
58
+ it('ignores shortcuts with Ctrl, Alt or Meta and lone modifier keys', () => {
59
+ for (const init of [{ ctrlKey: true }, { altKey: true }, { metaKey: true }]) {
60
+ key(document.getElementById('b')!, 'ArrowDown', init);
61
+ expect(mode()).toBe('pointer');
62
+ }
63
+ for (const name of ['Shift', 'Control', 'Alt', 'Meta']) key(document.getElementById('b')!, name);
64
+ expect(mode()).toBe('pointer');
65
+ });
66
+
67
+ it('a pointer press anywhere returns to pointer mode (mouse, touch or pen)', () => {
68
+ key(document.getElementById('b')!, 'Tab');
69
+ document.body.dispatchEvent(new Event('pointerdown', { bubbles: true }));
70
+ expect(mode()).toBe('pointer');
71
+ });
72
+
73
+ it('uninstall removes the listeners', () => {
74
+ uninstall();
75
+ key(document.getElementById('b')!, 'Tab');
76
+ expect(mode()).toBe('pointer');
77
+ uninstall = (): void => undefined;
78
+ });
79
+ });