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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions .storybook/foundations/Components.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import React from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import Button from '@atoms/Button';
import Card from '@atoms/Card';
import TechBadge from '@atoms/TechBadge';
import DateChip from '@atoms/DateChip';
import SecurityBadge from '@atoms/SecurityBadge';
import SecurityClassification from '@atoms/SecurityClassification';
import SkillChip from '@molecules/SkillChip';
import SocialLinks from '@molecules/SocialLinks';
import { Group, Page, foundationParameters } from './kit';

const meta: Meta = {
title: 'Foundations/Components at a glance',
parameters: foundationParameters,
};
export default meta;

const rowStyle: React.CSSProperties = { display: 'flex', flexWrap: 'wrap', gap: 'var(--spacing-3)', alignItems: 'center' };

export const ComponentsAtAGlance: StoryObj = {
name: 'Components at a glance',
render: () => (
<Page
title="Components at a glance"
lead="The controls, containers and chips that everything else is built from, side by side. They share one radius per role, one set of surfaces, JetBrains Mono for labels and one focus ring."
>
<Group title="Buttons" note="Primary is solid cyan, secondary is outlined, ghost is low emphasis. Two heights: 2.5rem and 2rem. Press Tab to see the focus ring.">
<div style={{ display: 'grid', gap: 'var(--spacing-4)' }}>
<div style={rowStyle}>
<Button variant="primary" icon="mdi:download" iconPosition="right">Download resume</Button>
<Button variant="secondary" icon="mdi:github">Code</Button>
<Button variant="ghost">Cancel</Button>
<Button variant="primary" disabled>Disabled</Button>
<SocialLinks links={{ github: 'https://github.com/DapperDivers', linkedin: 'https://www.linkedin.com/in/dmackley/' }} animated={false} />
</div>
<div style={rowStyle}>
<Button size="sm" variant="primary">Small primary</Button>
<Button size="sm" variant="secondary">Small secondary</Button>
<Button size="sm" variant="ghost">Small ghost</Button>
</div>
</div>
</Group>

<Group title="Card" note="--surface-card fill, 1px --surface-border, --radius-card, --shadow-card. Hoverable cards lift.">
<div style={{ maxWidth: 420 }}>
<Card
title="Cluster status"
subtitle="ChelonianLabs homelab"
hoverable
animated={false}
footer={
<div style={rowStyle}>
<Button size="sm" variant="primary">Open</Button>
<Button size="sm" variant="ghost">Dismiss</Button>
</div>
}
>
<p>Three control-plane nodes and four workers, reconciled from Git by Flux.</p>
<div style={rowStyle}>
<TechBadge label="Talos Linux" size="sm" animate={false} />
<TechBadge label="Flux CD" size="sm" animate={false} />
</div>
</Card>
</div>
</Group>

<Group title="Chips" note="TechBadge, SecurityBadge, DateChip, SkillChip and SecurityClassification: --radius-chip, --surface-inset, mono xs text. Colour is only a tone; red is for alarming levels.">
<div style={{ display: 'grid', gap: 'var(--spacing-4)' }}>
<div style={rowStyle}>
<TechBadge label="Kubernetes" animate={false} />
<TechBadge label="OIDC" variant="security" animate={false} />
<TechBadge label="Exposed admin port" variant="security" level="critical" animate={false} />
<SecurityBadge text="Security Engineer" animate={false} />
<DateChip date="2020 - Present" animated={false} />
<DateChip date="Incident 2024" variant="breach" animated={false} />
</div>
<div style={rowStyle}>
<SkillChip name="Kubernetes" iconName="logos:kubernetes" animated={false} />
<SkillChip name="Threat Modeling" selected animated={false} />
</div>
<div style={{ maxWidth: 480, padding: '0 2rem' }}>
<SecurityClassification label="DECLASSIFIED" expanded animated={false} />
</div>
</div>
</Group>
</Page>
),
};
70 changes: 62 additions & 8 deletions .storybook/foundations/Layout.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ const SEMANTIC_SPACING = ['--card-padding', '--button-padding-y', '--button-padd
const RADII = ['--border-radius-sm', '--border-radius', '--border-radius-md', '--border-radius-lg', '--border-radius-xl', '--border-radius-pill', '--border-radius-circle'];
const BORDERS = ['--border-width-thin', '--border-width-medium', '--border-width-thick'];
const SHADOWS = ['--box-shadow-sm', '--shadow-md', '--box-shadow', '--box-shadow-lg'];
const SURFACE_PANELS = ['--surface-card', '--surface-card-raised', '--surface-inset'];
const SURFACE_LINES = ['--surface-border', '--surface-border-strong', '--surface-divider'];
const SURFACE_SHAPES = ['--radius-card', '--radius-control', '--radius-chip'];
const SURFACE_ELEVATION = ['--shadow-card', '--shadow-card-hover', '--ring-focus'];
const SURFACE_CONTROLS = ['--control-height-sm', '--control-height', '--control-padding-x'];
const BREAKPOINTS = ['--breakpoint-sm', '--breakpoint-md', '--breakpoint-lg', '--breakpoint-xl', '--breakpoint-xxl'];
const LAYERS = ['--z-index-dropdown', '--z-index-sticky', '--z-index-fixed', '--z-index-modal-backdrop', '--z-index-modal', '--z-index-popover', '--z-index-toast'];

Expand Down Expand Up @@ -44,7 +49,7 @@ export const SpacingAndShape: StoryObj = {
</Grid>
</Group>

<Group title="Radius" note="Pill is for badges, chips and the primary call to action. Panels and cards use lg.">
<Group title="Radius" note="Chips and pills use the pill radius. Cards and panels use lg, buttons and inputs use md.">
<Grid min={130}>
{RADII.map((name) => (
<div key={name}>
Expand All @@ -66,15 +71,64 @@ export const SpacingAndShape: StoryObj = {
</Group>

<Group title="Elevation" note="Shadows are subtle on a dark page; raised surfaces also step up in lightness.">
<div style={{ padding: 'var(--spacing-6)', borderRadius: 'var(--border-radius-lg)', background: 'var(--color-gray-200)' }}>
<Grid min={180}>
{SHADOWS.map((name) => (
<div key={name} style={{ padding: 'var(--spacing-4)', borderRadius: 'var(--border-radius-lg)', background: 'var(--color-white)', boxShadow: `var(${name})` }}>
<code style={{ padding: 0, background: 'none', fontFamily: 'var(--font-family-jetbrains)', fontSize: 'var(--font-size-xs)', color: 'var(--color-gray-900)' }}>{name}</code>
<Grid min={180}>
{SHADOWS.map((name) => (
<div key={name} style={{ padding: 'var(--spacing-4)', borderRadius: 'var(--border-radius-lg)', background: 'var(--surface-card-raised)', boxShadow: `var(${name})` }}>
<code style={{ padding: 0, background: 'none', fontFamily: 'var(--font-family-jetbrains)', fontSize: 'var(--font-size-xs)', color: 'var(--color-text)' }}>{name}</code>
</div>
))}
</Grid>
</Group>

<Group
title="Surfaces"
note="The panel tokens every card, terminal window, chip and control draws from. Card is the default fill; raised is opaque, for things over the map or a modal; inset is the faint fill for a block inside a card."
>
<Grid min={200}>
{SURFACE_PANELS.map((name) => (
<div key={name}>
<div style={{ height: 72, borderRadius: 'var(--radius-card)', background: `var(${name})`, border: '1px solid var(--surface-border)', boxShadow: 'var(--shadow-card)' }} />
<div style={{ marginTop: 'var(--spacing-2)' }}>
<TokenLabel name={name} />
</div>
))}
</Grid>
</div>
))}
</Grid>
<div style={{ marginTop: 'var(--spacing-5)' }}>
{SURFACE_LINES.map((name) => (
<Row key={name} name={name}>
<div style={{ borderTop: `2px solid var(${name})` }} />
</Row>
))}
</div>
<h3 style={{ margin: 'var(--spacing-5) 0 var(--spacing-3)', fontSize: 'var(--font-size-base)', fontWeight: 600 }}>Shape</h3>
<Grid min={150}>
{SURFACE_SHAPES.map((name) => (
<div key={name}>
<div style={{ ...tile, width: name === '--radius-chip' ? 120 : 72, height: name === '--radius-chip' ? 28 : 72, borderRadius: `var(${name})` }} />
<div style={{ marginTop: 'var(--spacing-2)' }}>
<TokenLabel name={name} />
</div>
</div>
))}
</Grid>
<h3 style={{ margin: 'var(--spacing-5) 0 var(--spacing-3)', fontSize: 'var(--font-size-base)', fontWeight: 600 }}>Elevation and focus</h3>
<Grid min={200}>
{SURFACE_ELEVATION.map((name) => (
<div key={name}>
<div style={{ height: 56, borderRadius: 'var(--radius-card)', background: 'var(--surface-card)', border: '1px solid var(--surface-border)', boxShadow: `var(${name})` }} />
<div style={{ marginTop: 'var(--spacing-2)' }}>
<TokenLabel name={name} />
</div>
</div>
))}
</Grid>
<h3 style={{ margin: 'var(--spacing-5) 0 var(--spacing-3)', fontSize: 'var(--font-size-base)', fontWeight: 600 }}>Controls</h3>
<Grid min={200}>
{SURFACE_CONTROLS.map((name) => (
<TokenLabel key={name} name={name} />
))}
</Grid>
</Group>

<Group title="Breakpoints">
Expand Down
2 changes: 1 addition & 1 deletion .storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const preview: Preview = {
layout: 'centered',
options: {
storySort: {
order: ['Introduction', 'Foundations', ['Colors', 'Typography', 'Spacing and shape', 'Motion'], 'Atoms', 'Molecules', 'Organisms', 'Layout', 'Templates'],
order: ['Introduction', 'Foundations', ['Components at a glance', 'Colors', 'Typography', 'Spacing and shape', 'Motion'], 'Atoms', 'Molecules', 'Organisms', 'Layout', 'Templates'],
},
},
},
Expand Down
38 changes: 38 additions & 0 deletions config/vite/dev/clusterStatus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import type { Plugin } from 'vite';
// @ts-expect-error plain JS module shared with the production server
import { createClusterStatusHandler } from '../prod/clusterStatus.js';

/**
* Serves GET /api/cluster-status from the Vite dev server with the same
* handler the production Express server uses.
*/
export default function clusterStatusDevPlugin(): Plugin {
const handler = createClusterStatusHandler();
return {
name: 'cluster-status-dev',
apply: 'serve',
configureServer(server) {
server.middlewares.use('/api/cluster-status', (req, res) => {
const adapter = {
status(code: number) {
res.statusCode = code;
return adapter;
},
set(name: string, value: string) {
res.setHeader(name, value);
return adapter;
},
json(body: unknown) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(body));
return adapter;
},
};
handler(req, adapter).catch(() => {
res.statusCode = 503;
res.end('{"error":"Cluster status unavailable"}');
});
});
},
};
}
8 changes: 7 additions & 1 deletion config/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import getCorePlugins from './plugins/core';
import getPwaPlugins from './plugins/pwa';
import getCodeSplittingConfig from './optimization/splitting';
import getViteDevConfig from './dev/vite';
import clusterStatusDevPlugin from './dev/clusterStatus';

// Initialize environment variables
const { initEnv, getClientEnv, isProd, isDev, getNodeEnv } = envConfig;
Expand All @@ -39,6 +40,9 @@ export default defineConfig(({ command, mode }) => {

// Progressive Web App features and analysis tools
...getPwaPlugins({ isProd: isProd(), analyze: isAnalyze }),

// Dev-only /api/cluster-status (the production Express server has its own)
clusterStatusDevPlugin(),
].filter(Boolean); // Remove any false/undefined entries

// Vite development server configuration
Expand Down Expand Up @@ -104,7 +108,9 @@ export default defineConfig(({ command, mode }) => {
terserOptions: isProd() ? {
compress: {
passes: 2,
drop_console: true,
// Strip debug logging; warnings, errors and console.info (the devtools
// greeting in src/index.tsx) stay
pure_funcs: ['console.log', 'console.debug'],
drop_debugger: true
},
format: {
Expand Down
99 changes: 99 additions & 0 deletions config/vite/prod/clusterStatus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Live cluster numbers for the site, read from Kromgo badges.
// Kromgo sends no CORS headers, so the server fetches the badges and the
// browser only ever talks to /api/cluster-status.

/* global AbortSignal */

export const CLUSTER_BADGE_IDS = [
'cluster_status',
'cluster_node_count',
'cluster_pod_count',
'services_up',
'cluster_uptime_days',
'cluster_age_days',
'cluster_cpu_usage',
'cluster_memory_usage',
'cluster_power_usage',
'cluster_alert_count',
'talos_version',
'kubernetes_version',
'flux_version',
];

const DEFAULT_KROMGO_URL = 'https://kromgo.chelonianlabs.com';
const CACHE_TTL_MS = 60_000;
const TIMEOUT_MS = 3_000;
const MAX_FIELD_LENGTH = 64;

// Keep only short non-empty strings; anything else is dropped.
const cleanString = (value) =>
typeof value === 'string' && value.length > 0 ? value.slice(0, MAX_FIELD_LENGTH) : null;

// Shape one badge down to the three public fields, or null if unusable.
export function shapeBadge(raw) {
if (!raw || typeof raw !== 'object') return null;
const value = cleanString(raw.value);
if (value === null) return null;
return {
title: cleanString(raw.title) ?? '',
value,
color: cleanString(raw.color) ?? '',
};
}

async function fetchBadge(fetchImpl, baseUrl, id, timeoutMs) {
try {
const response = await fetchImpl(`${baseUrl}/badges/${id}?format=json`, {
signal: AbortSignal.timeout(timeoutMs),
headers: { Accept: 'application/json' },
});
if (!response.ok) return null;
return shapeBadge(await response.json());
} catch {
return null;
}
}

/**
* Creates the GET /api/cluster-status handler.
* Options are injectable for tests.
*/
export function createClusterStatusHandler({
fetchImpl = (...args) => fetch(...args),
baseUrl = process.env.KROMGO_URL || DEFAULT_KROMGO_URL,
ttlMs = CACHE_TTL_MS,
timeoutMs = TIMEOUT_MS,
now = Date.now,
} = {}) {
const base = baseUrl.replace(/\/+$/, '');
let cache = null; // { at, body }
let inflight = null;

async function load() {
const results = await Promise.all(
CLUSTER_BADGE_IDS.map(async (id) => [id, await fetchBadge(fetchImpl, base, id, timeoutMs)])
);
const badges = {};
for (const [id, badge] of results) {
if (badge) badges[id] = badge;
}
if (Object.keys(badges).length === 0) return null;
return { updatedAt: new Date(now()).toISOString(), badges };
}

return async function clusterStatusHandler(req, res) {
let body = cache && now() - cache.at < ttlMs ? cache.body : null;
if (!body) {
inflight ??= load().finally(() => {
inflight = null;
});
body = await inflight;
if (body) cache = { at: now(), body };
}
if (!body) {
res.status(503).set('Cache-Control', 'no-store').json({ error: 'Cluster status unavailable' });
return;
}
res.set('Cache-Control', 'public, max-age=60').json(body);
};
}
4 changes: 4 additions & 0 deletions config/vite/prod/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import { existsSync } from 'fs';
import { createClusterStatusHandler } from './clusterStatus.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Expand Down Expand Up @@ -35,6 +36,9 @@ const prodConfig = {
const app = createBaseServer({ ...prodConfig, registerRoutes: registerHealthRoutes });

function registerHealthRoutes(app) {
// Live cluster numbers from Kromgo (cached 60 s)
app.get('/api/cluster-status', createClusterStatusHandler());

// Production-specific comprehensive health check
app.get('/health/comprehensive', async (req, res) => {
const healthReport = {
Expand Down
10 changes: 10 additions & 0 deletions config/vite/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@ export function createBaseServer(config = {}) {
}
}));

// RFC 8615 well-known files (security.txt). express.static skips dot-folders,
// so mount this one explicitly; nothing else starting with a dot is served.
app.use('/.well-known', express.static(path.join(buildPath, '.well-known'), {
setHeaders: (res) => {
res.set('X-Content-Type-Options', 'nosniff');
res.set('Cache-Control', 'public, max-age=86400');
}
}));
app.use('/.well-known', (req, res) => res.status(404).type('text/plain').send('Not found'));

// Serve main static files AFTER specific routes to avoid conflicts
app.use(express.static(buildPath, {
...getStaticHeaders(),
Expand Down
Loading
Loading