Package Tansy UI as @openkhalix/tansy-ui in a monorepo (v0.4.0)
Restructure the repo into npm workspaces so the component kit publishes as its own package, like MUI and shadcn/ui: - packages/ui: @openkhalix/tansy-ui (published), with components, stories, tests, tokens and the library build - packages/brand: private logo and catalogue data shared by both apps - apps/site: the landing page - apps/docs: Storybook The package: - MIT licence (copyright OpenKhalix) - per-component ES modules and type declarations - "use client" on component modules so they import into Next.js Server Components; helpers stay server-safe - tokens.css for Tailwind v4 apps, and a prebuilt styles.css for apps without Tailwind - lucide-react 1.x, whose types compile against current React 19 types The apps resolve the package through a "source" export condition, so they hot-reload component edits, while outside users get dist/. scripts/test-package.mjs packs the package and installs the tarball into Vite + Tailwind (strict types), plain React and Next.js apps; each must build and render correctly. Gitea workflows run CI on push and publish to npm when a vX.Y.Z tag matching the package version is pushed.
This commit is contained in:
1 parent
23e67006d3
commit
9255b255a6
214 files changed
+1521
-389
No files matched your search
+4
-2
@@ -30,8 +30,10 @@ environment instead, which is what CI should do.
|
||||
|
||||
## How it works
|
||||
|
||||
1. `npm ci`, `npm run lint`, `npm run build`, `npm run build-storybook`
|
||||
2. Stage `dist/` at the root and `storybook-static/` under `docs/`, zip with
|
||||
1. `npm ci`, `npm run lint`, `npm test`, `npm run build` (package, landing
|
||||
page, Storybook)
|
||||
2. Stage `apps/site/dist/` at the root and `apps/docs/storybook-static/` under
|
||||
`docs/`, zip with
|
||||
Python's `zipfile` (there is no `zip` binary on the build host), base64 it
|
||||
3. Upload `scripts/cpanel-deploy.php` to the docroot over the cPanel UAPI
|
||||
4. POST the base64 payload to it with a `Host` header for the subdomain,
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
/**
|
||||
* Render every story in a real browser and report what's broken.
|
||||
*
|
||||
* For each story in storybook-static/index.json it:
|
||||
* For each story in apps/docs/storybook-static/index.json it:
|
||||
* - loads the story in Chrome (light or dark mode),
|
||||
* - records page errors and console errors,
|
||||
* - runs axe, including colour contrast (jsdom tests can't check that),
|
||||
* - saves a screenshot.
|
||||
*
|
||||
* npm run build-storybook
|
||||
* npm run build:docs
|
||||
* node scripts/check-stories.mjs [--filter forms-] [--mode dark] [--palette emerald] [--width 375] [--out dir] [--no-shots]
|
||||
*
|
||||
* Exits non-zero when any story has an error or an axe violation.
|
||||
@@ -25,7 +25,7 @@ const opt = (name, fallback) => {
|
||||
const i = args.indexOf(`--${name}`)
|
||||
return i === -1 ? fallback : args[i + 1]
|
||||
}
|
||||
const DIR = resolve(opt('dir', 'storybook-static'))
|
||||
const DIR = resolve(opt('dir', 'apps/docs/storybook-static'))
|
||||
const FILTER = opt('filter', '')
|
||||
const MODE = opt('mode', 'light')
|
||||
const PALETTE = opt('palette', '')
|
||||
|
||||
+12
-9
@@ -37,6 +37,8 @@ REPO = Path(__file__).resolve().parent.parent
|
||||
STAGE = Path("/tmp/tansy-stage")
|
||||
ZIP = Path("/tmp/tansy-deploy.zip")
|
||||
ENV_FILE = REPO / "scripts" / "deploy.env"
|
||||
SITE_DIST = REPO / "apps" / "site" / "dist"
|
||||
STORYBOOK = REPO / "apps" / "docs" / "storybook-static"
|
||||
|
||||
# The docroot must keep these regardless of what a build contains: cPanel
|
||||
# writes them, and removing .htaccess would take the site offline.
|
||||
@@ -157,10 +159,11 @@ def run(cmd: list[str], cwd: Path = REPO, timeout: int = 900) -> None:
|
||||
def build() -> None:
|
||||
run(["npm", "ci"])
|
||||
run(["npm", "run", "lint"])
|
||||
run(["npm", "test"])
|
||||
# Builds the package, then the landing page and Storybook.
|
||||
run(["npm", "run", "build"])
|
||||
run(["npm", "run", "build-storybook"])
|
||||
if not (REPO / "storybook-static" / "index.json").exists():
|
||||
die("storybook-static/index.json missing after build-storybook")
|
||||
if not (STORYBOOK / "index.json").exists():
|
||||
die(f"{STORYBOOK}/index.json missing after the Storybook build")
|
||||
|
||||
|
||||
def git(*args: str) -> str:
|
||||
@@ -177,7 +180,7 @@ def require_clean_tree() -> None:
|
||||
|
||||
|
||||
def build_stamp() -> dict:
|
||||
version = json.loads((REPO / "package.json").read_text())["version"]
|
||||
version = json.loads((REPO / "packages" / "ui" / "package.json").read_text())["version"]
|
||||
return {
|
||||
"version": version,
|
||||
"commit": git("rev-parse", "--short", "HEAD"),
|
||||
@@ -187,11 +190,11 @@ def build_stamp() -> dict:
|
||||
|
||||
|
||||
def package() -> dict:
|
||||
dist = REPO / "dist"
|
||||
sb = REPO / "storybook-static"
|
||||
dist = SITE_DIST
|
||||
sb = STORYBOOK
|
||||
for d in (dist, sb):
|
||||
if not d.is_dir():
|
||||
die(f"{d} does not exist - run: npm run build && npm run build-storybook")
|
||||
die(f"{d} does not exist - run: npm run build")
|
||||
|
||||
if STAGE.exists():
|
||||
shutil.rmtree(STAGE)
|
||||
@@ -366,14 +369,14 @@ def verify(panel: Panel) -> None:
|
||||
|
||||
idx = panel.get_from_origin("/index.html")
|
||||
live_sha = _h.sha256(idx.encode()).hexdigest()
|
||||
local_sha = _h.sha256((REPO / "dist" / "index.html").read_bytes()).hexdigest()
|
||||
local_sha = _h.sha256((SITE_DIST / "index.html").read_bytes()).hexdigest()
|
||||
if live_sha != local_sha:
|
||||
die(f"index.html mismatch\n live {live_sha[:32]}\n local {local_sha[:32]}")
|
||||
log("index.html matches the local build")
|
||||
|
||||
sb = panel.get_from_origin("/docs/index.json")
|
||||
sb_sha = _h.sha256(sb.encode()).hexdigest()
|
||||
sb_local = _h.sha256((REPO / "storybook-static" / "index.json").read_bytes()).hexdigest()
|
||||
sb_local = _h.sha256((STORYBOOK / "index.json").read_bytes()).hexdigest()
|
||||
if sb_sha != sb_local:
|
||||
die("docs/index.json mismatch")
|
||||
log("docs/index.json matches")
|
||||
|
||||
@@ -3,12 +3,12 @@
|
||||
Generate the landing page's component catalogue from the built Storybook
|
||||
index, so it cannot drift from the stories again.
|
||||
|
||||
Run it after `npm run build-storybook` and before `npm run build` when you
|
||||
Run it after `npm run build:docs` and before `npm run build:site` when you
|
||||
add or remove a component. It prints the entries to paste into
|
||||
src/data/catalogue.ts and writes /tmp/component_catalogue.json.
|
||||
packages/brand/src/catalogue.ts and writes /tmp/component_catalogue.json.
|
||||
|
||||
python3 scripts/gen_catalogue.py # print entries
|
||||
python3 scripts/gen_catalogue.py --patch # also rewrite src/data/catalogue.ts
|
||||
python3 scripts/gen_catalogue.py --patch # also rewrite packages/brand/src/catalogue.ts
|
||||
|
||||
Components are read from story titles (`Group/Name`), so a new component
|
||||
appears here without editing this script; only DETAIL is hand-written.
|
||||
@@ -22,8 +22,8 @@ import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parent.parent
|
||||
IDX = REPO / "storybook-static" / "index.json"
|
||||
CATALOGUE = REPO / "src" / "data" / "catalogue.ts"
|
||||
IDX = REPO / "apps" / "docs" / "storybook-static" / "index.json"
|
||||
CATALOGUE = REPO / "packages" / "brand" / "src" / "catalogue.ts"
|
||||
OUT = Path("/tmp/component_catalogue.json")
|
||||
|
||||
# Group order on the landing page; matches the Storybook sidebar.
|
||||
@@ -75,7 +75,7 @@ DETAIL = {
|
||||
|
||||
def collect():
|
||||
if not IDX.is_file():
|
||||
sys.exit(f"{IDX} not found - run: npm run build-storybook")
|
||||
sys.exit(f"{IDX} not found - run: npm run build:docs")
|
||||
|
||||
entries = json.loads(IDX.read_text())["entries"].values()
|
||||
comps: dict[str, dict] = {}
|
||||
@@ -150,7 +150,7 @@ def patch_catalogue(entries) -> None:
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--patch", action="store_true",
|
||||
help="rewrite the catalogue and story counts in src/data/catalogue.ts")
|
||||
help="rewrite the catalogue and story counts in packages/brand/src/catalogue.ts")
|
||||
args = ap.parse_args()
|
||||
|
||||
entries = collect()
|
||||
@@ -167,7 +167,7 @@ def main() -> None:
|
||||
|
||||
if args.patch:
|
||||
patch_catalogue(entries)
|
||||
print("now run: npm run build")
|
||||
print("now run: npm run build:site")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Install the packed package into fresh apps, the way a user would, and prove
|
||||
* it works. Run before publishing:
|
||||
*
|
||||
* npm run test:package # all scenarios
|
||||
* npm run test:package -- vite # one scenario: vite | plain | next
|
||||
*
|
||||
* 1. vite Vite + Tailwind v4 + strict TypeScript (library types checked too).
|
||||
* Must type-check, build and render without errors.
|
||||
* 2. plain React without Tailwind, using only the prebuilt styles.css. The
|
||||
* primary button must get its brand colour.
|
||||
* 3. next Next.js App Router. A Server Component imports the components;
|
||||
* `next build` must prerender it, which fails unless the component
|
||||
* modules are marked "use client".
|
||||
*
|
||||
* Apps are created under $TMPDIR/tansy-package-test and installed from npm.
|
||||
*/
|
||||
import { execSync } from 'node:child_process'
|
||||
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { createServer } from 'node:http'
|
||||
import { createRequire } from 'node:module'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, extname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const PKG_DIR = join(ROOT, 'packages/ui')
|
||||
const WORK = join(tmpdir(), 'tansy-package-test')
|
||||
const only = process.argv[2]
|
||||
const require = createRequire(import.meta.url)
|
||||
|
||||
const sh = (cmd, cwd) => execSync(cmd, { cwd, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' })
|
||||
const write = (dir, files) => {
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
mkdirSync(dirname(join(dir, path)), { recursive: true })
|
||||
writeFileSync(join(dir, path), content.trimStart())
|
||||
}
|
||||
}
|
||||
const log = (msg) => console.log(`[test:package] ${msg}`)
|
||||
|
||||
// --- pack ---------------------------------------------------------------------
|
||||
rmSync(WORK, { recursive: true, force: true })
|
||||
mkdirSync(WORK, { recursive: true })
|
||||
log('building and packing @openkhalix/tansy-ui')
|
||||
sh('npm run build', PKG_DIR)
|
||||
const tarball = join(WORK, sh(`npm pack --pack-destination ${WORK}`, PKG_DIR).trim().split('\n').pop())
|
||||
const { version } = JSON.parse(readFileSync(join(PKG_DIR, 'package.json'), 'utf8'))
|
||||
log(`packed ${tarball}`)
|
||||
|
||||
const APP = `
|
||||
import { Mail } from 'lucide-react'
|
||||
import { Badge, Button, Dialog, FeaturedInput, Select, Tabs, VERSION } from '@openkhalix/tansy-ui'
|
||||
|
||||
export function Demo() {
|
||||
return (
|
||||
<div style={{ display: 'grid', gap: 16, maxWidth: 420, padding: 24 }}>
|
||||
<Badge color="success">tansy {VERSION}</Badge>
|
||||
<FeaturedInput label="Work email" startIcon={<Mail />} />
|
||||
<Select label="Team" defaultValue="design" options={[{ value: 'design', label: 'Design' }, { value: 'eng', label: 'Engineering' }]} />
|
||||
<Tabs label="Sections" items={[{ value: 'a', label: 'Overview', content: 'Overview panel' }, { value: 'b', label: 'Activity', content: 'Activity panel' }]} />
|
||||
<Button id="primary-button">Save</Button>
|
||||
<Dialog defaultOpen title="Installed from npm" footer={<Button>OK</Button>}>It works.</Dialog>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
`
|
||||
|
||||
const VITE_BASE = {
|
||||
'index.html': `<!doctype html><html><head><meta charset="UTF-8"/><title>t</title></head><body><div id="root"></div><script type="module" src="/src/main.tsx"></script></body></html>`,
|
||||
'src/Demo.tsx': APP,
|
||||
'tsconfig.json': JSON.stringify({
|
||||
compilerOptions: {
|
||||
target: 'es2022', module: 'esnext', moduleResolution: 'bundler', jsx: 'react-jsx',
|
||||
strict: true, skipLibCheck: false, noEmit: true, types: ['vite/client'],
|
||||
},
|
||||
include: ['src'],
|
||||
}),
|
||||
}
|
||||
|
||||
const scenarios = {
|
||||
vite: {
|
||||
files: {
|
||||
...VITE_BASE,
|
||||
'package.json': JSON.stringify({ name: 'vite-tailwind', private: true, type: 'module', scripts: { build: 'tsc && vite build' } }),
|
||||
'vite.config.ts': `import react from '@vitejs/plugin-react'\nimport tailwindcss from '@tailwindcss/vite'\nimport { defineConfig } from 'vite'\nexport default defineConfig({ plugins: [react(), tailwindcss()] })\n`,
|
||||
'src/app.css': `@import "tailwindcss";\n@import "@openkhalix/tansy-ui/tokens.css";\n@source "../node_modules/@openkhalix/tansy-ui/dist";\n`,
|
||||
'src/main.tsx': `import { createRoot } from 'react-dom/client'\nimport { Demo } from './Demo'\nimport './app.css'\ncreateRoot(document.getElementById('root')!).render(<Demo />)\n`,
|
||||
},
|
||||
deps: 'react@19 react-dom@19 lucide-react vite@8 @vitejs/plugin-react tailwindcss@4 @tailwindcss/vite@4 typescript @types/react @types/react-dom',
|
||||
build: 'npm run build',
|
||||
serve: 'dist',
|
||||
},
|
||||
plain: {
|
||||
files: {
|
||||
...VITE_BASE,
|
||||
'package.json': JSON.stringify({ name: 'plain-react', private: true, type: 'module', scripts: { build: 'tsc && vite build' } }),
|
||||
'vite.config.ts': `import react from '@vitejs/plugin-react'\nimport { defineConfig } from 'vite'\nexport default defineConfig({ plugins: [react()] })\n`,
|
||||
'src/main.tsx': `import { createRoot } from 'react-dom/client'\nimport '@openkhalix/tansy-ui/styles.css'\nimport { Demo } from './Demo'\ncreateRoot(document.getElementById('root')!).render(<Demo />)\n`,
|
||||
},
|
||||
deps: 'react@19 react-dom@19 lucide-react vite@8 @vitejs/plugin-react typescript @types/react @types/react-dom',
|
||||
build: 'npm run build',
|
||||
serve: 'dist',
|
||||
},
|
||||
next: {
|
||||
files: {
|
||||
'package.json': JSON.stringify({ name: 'next-app', private: true, scripts: { build: 'next build' } }),
|
||||
'next.config.mjs': 'export default {}\n',
|
||||
'tsconfig.json': JSON.stringify({
|
||||
compilerOptions: {
|
||||
target: 'es2022', lib: ['dom', 'dom.iterable', 'esnext'], strict: true, noEmit: true, module: 'esnext',
|
||||
moduleResolution: 'bundler', jsx: 'react-jsx', skipLibCheck: true, isolatedModules: true, incremental: true,
|
||||
plugins: [{ name: 'next' }],
|
||||
},
|
||||
include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],
|
||||
}),
|
||||
'app/layout.tsx': `import '@openkhalix/tansy-ui/styles.css'\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return <html lang="en"><body>{children}</body></html>\n}\n`,
|
||||
// A Server Component: no "use client" here.
|
||||
'app/page.tsx': `import { Badge, Button, cn } from '@openkhalix/tansy-ui'\nexport default function Page() {\n return <main className={cn('p-6')}><Badge color="success">server rendered</Badge><Button id="primary-button">Save</Button></main>\n}\n`,
|
||||
},
|
||||
deps: 'next@16 react@19 react-dom@19 lucide-react typescript @types/react @types/react-dom @types/node',
|
||||
build: 'npm run build',
|
||||
},
|
||||
}
|
||||
|
||||
// --- run ------------------------------------------------------------------------
|
||||
const results = []
|
||||
for (const [name, s] of Object.entries(scenarios)) {
|
||||
if (only && only !== name) continue
|
||||
const dir = join(WORK, name)
|
||||
write(dir, s.files)
|
||||
try {
|
||||
log(`${name}: installing`)
|
||||
sh(`npm install --no-audit --no-fund ${s.deps} ${tarball}`, dir)
|
||||
log(`${name}: building`)
|
||||
const out = sh(s.build, dir)
|
||||
if (name === 'next' && !/[○●ƒ]\s+\//.test(out)) throw new Error('next build did not report the / route')
|
||||
if (s.serve) await renderCheck(name, join(dir, s.serve))
|
||||
results.push([name, 'pass'])
|
||||
} catch (e) {
|
||||
const detail = String(e.stdout || '') + String(e.stderr || '') || e.message
|
||||
results.push([name, 'FAIL', detail.split('\n').filter(Boolean).slice(-15).join('\n')])
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n@openkhalix/tansy-ui@${version} install tests`)
|
||||
for (const [name, status, detail] of results) {
|
||||
console.log(` ${status === 'pass' ? '✓' : '✗'} ${name}`)
|
||||
if (detail) console.log(detail.replace(/^/gm, ' '))
|
||||
}
|
||||
process.exit(results.some((r) => r[1] !== 'pass') ? 1 : 0)
|
||||
|
||||
/** Serve a built app, open it in Chrome, and check it rendered and is styled. */
|
||||
async function renderCheck(name, dir) {
|
||||
const types = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml' }
|
||||
const server = createServer((req, res) => {
|
||||
const path = new URL(req.url, 'http://x').pathname
|
||||
try {
|
||||
const body = readFileSync(join(dir, path === '/' ? 'index.html' : path))
|
||||
res.writeHead(200, { 'content-type': types[extname(path)] ?? 'text/html' })
|
||||
res.end(body)
|
||||
} catch {
|
||||
res.writeHead(404)
|
||||
res.end()
|
||||
}
|
||||
})
|
||||
await new Promise((ok) => server.listen(0, '127.0.0.1', ok))
|
||||
const { chromium } = require('playwright')
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROME_PATH ?? '/usr/bin/google-chrome' })
|
||||
try {
|
||||
const page = await browser.newPage()
|
||||
const errors = []
|
||||
page.on('pageerror', (e) => errors.push(e.message))
|
||||
await page.goto(`http://127.0.0.1:${server.address().port}/`, { waitUntil: 'networkidle' })
|
||||
await page.getByRole('dialog', { name: 'Installed from npm' }).waitFor({ timeout: 10000 })
|
||||
const look = await page.evaluate(() => {
|
||||
const button = getComputedStyle(document.getElementById('primary-button'))
|
||||
const tab = getComputedStyle(document.querySelector('[role="tab"]'))
|
||||
return { bg: button.backgroundColor, text: button.color, tabBorder: tab.borderTopWidth, tabBg: tab.backgroundColor }
|
||||
})
|
||||
await page.screenshot({ path: join(WORK, `${name}.png`) })
|
||||
if (errors.length) throw new Error(`page errors: ${errors.join('; ')}`)
|
||||
// Classic Blue primary-500 (#305ddd) with white text, and tabs without the
|
||||
// browser's default button chrome: proves utilities and reset both applied.
|
||||
const problems = []
|
||||
if (look.bg !== 'rgb(48, 93, 221)') problems.push(`button background ${look.bg}`)
|
||||
if (look.text !== 'rgb(255, 255, 255)') problems.push(`button text ${look.text}`)
|
||||
if (look.tabBorder !== '0px') problems.push(`tab border ${look.tabBorder}`)
|
||||
if (!/rgba\(0, 0, 0, 0\)|transparent/.test(look.tabBg)) problems.push(`tab background ${look.tabBg}`)
|
||||
if (problems.length) throw new Error(`components look wrong: ${problems.join(', ')}`)
|
||||
} finally {
|
||||
await browser.close()
|
||||
server.close()
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user