feat: error pages, consent gate, installer license + web code-splitting — v1.6.0 (#65)

See PR #65 for full details.
This commit is contained in:
poli0981 authored and GitHub committed 2026-06-14 14:49:26 +07:00
1 parent 6197334326
commit b89d99807d
44 files changed
+1065 -83

No files matched your search

+19
View File
@@ -8,6 +8,25 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond".
## [1.6.0] — 2026-06-14
### Added
- **Custom error pages.** A reusable presentational `ErrorState` component (`src/components/common/ErrorState.tsx`) backs a 404 catch-all route (`src/pages/errors/NotFound.tsx`) and a generic `/error/:code` route (`src/pages/errors/ErrorRoute.tsx`) with dedicated copy for 403 / 404 / 419 / 500 and a fallback for anything else. JSONPrism is a static client-side SPA and never emits these from a server itself — the route exists so any code (a future backend, a Tauri IPC failure) can render a polished, consistent page. New `error_page.*` i18n group in EN + VI.
- **First-launch legal consent gate (web only).** A non-dismissible modal (`src/components/common/ConsentGate.tsx`, built on a new `src/components/ui/dialog.tsx` Radix wrapper) blocks the app on first launch / incognito until the user ticks agreement to the License, Terms (EULA), Privacy Policy, and Disclaimer (linked to GitHub). Acceptance persists to `localStorage` (`jsonprism.consent` — flag + version + timestamp) via `src/lib/consent-storage.ts` and a Zustand store (`src/stores/consentStore.ts`); bump `CONSENT_VERSION` to re-prompt when terms change. Skipped in desktop builds (gated by the installer instead) with zero runtime branching, via the build-time `__IS_TAURI_BUILD__` flag. New `consent.*` i18n group in EN + VI; `PRIVACY.md` documents the new key.
- **Windows installer license-acceptance page.** `bundle.licenseFile` in `tauri.conf.json` now points at `src-tauri/license.rtf` (a short EULA referencing Apache-2.0 + TERMS / PRIVACY / DISCLAIMER). Both the NSIS `.exe` and the WiX `.msi` show an accept-to-continue license page — RTF satisfies both, so `targets: "all"` is preserved.
- **Offline indicator.** `useOnlineStatus` hook + a non-blocking `OfflineBanner` strip between the header and content. Informational only — JSONPrism keeps working offline.
- **GitHub Pages deep-link support.** `public/404.html` (spa-github-pages redirect, `pathSegmentsToKeep = 1` for the `/jsonPrism/` base) plus a tiny decoder in `index.html` make refreshing a deep link (e.g. `/jsonPrism/about`) resolve to the right route instead of GitHub's 404. No-op under Tauri.
### Changed
- **Lazy-loading + finer code-splitting (web).** Routes (`Home`, `About`, error pages) and the CodeMirror editor are now `React.lazy` + `Suspense` (the editor degrades to a real `<textarea>` while its chunk loads, so input stays usable). A `ChunkErrorBoundary` catches a failed dynamic import (e.g. stale deploy) and offers reload without crashing the page; non-chunk errors rethrow to the existing crash `ErrorBoundary`, which now shares the `ErrorState` visual. `manualChunks` in `vite.config.ts` was refined to split `react` / `router` / `i18n` / `cm-core` / `cm-langs` / one chunk per parser / `ui` — the heavy CodeMirror core is no longer in the initial paint graph.
- **Removed a hidden `bson` leak.** `decodeBytes` / `encodeBytes` moved from `src/converters/bson.ts` to a parser-free `src/lib/bytes.ts`; `OutputPanel` and the CBOR / MessagePack converters import from there, so the `bson` library no longer enters the initial bundle graph just because the output panel renders.
### Tests
- **+16 unit tests (209 total).** New coverage for `consent-storage`, `consentStore`, `bytes` codec, `isChunkLoadError`, the `ErrorState` component, and the `useOnlineStatus` hook. Typecheck, lint, `knip`, `prettier --check`, and `npm audit` (0 vulnerabilities) all green; consent gate / 404 / `/error/:code` verified in a running dev build.
## [1.5.0] — 2026-05-21
### Added
+1
View File
@@ -31,6 +31,7 @@ These keys are written by JSONPrism:
| `jsonprism.selected_format` | The target format chip you last selected |
| `jsonprism.direction` | Conversion direction (`forward` / `reverse`) |
| `jsonprism.options.<format>` | Per-format options (e.g. CSV header on/off) |
| `jsonprism.consent` | That you accepted the License / Terms / Privacy / Disclaimer (acceptance flag + version + timestamp). Web only — the desktop app gates this in its installer. |
That is the entire on-disk footprint. Clearing your browser's site data
removes everything. Nothing leaves your device.
+1
View File
@@ -38,6 +38,7 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
## Features
- **Client-side only** — no server, no telemetry, no upload. Your JSON stays in your browser.
- **Fast first paint** — routes and the CodeMirror editor are lazy-loaded, and vendor/parser code is split into small per-feature chunks, so the browser only downloads what you actually use.
- **Batch processing** — up to 500 files at once (Phase 2).
- **Smart shape detection** — recognizes flat objects, arrays of objects, scalars; suggests the best target format.
- **Per-format options** — pretty-print, indentation, dialect (for SQL), alignment (for Markdown), and more.
+1
View File
@@ -38,6 +38,7 @@ JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu v
## Tính năng
- **Chạy hoàn toàn client-side** — không server, không telemetry, không upload. JSON của bạn ở lại trong trình duyệt.
- **Khởi động nhanh** — route và editor CodeMirror được lazy-load, mã vendor/parser tách thành nhiều chunk nhỏ theo tính năng, nên trình duyệt chỉ tải đúng phần bạn dùng.
- **Xử lý batch** — tới 500 file cùng lúc (Phase 2).
- **Phát hiện shape thông minh** — nhận diện flat object, mảng object, scalar; gợi ý format đích phù hợp.
- **Tuỳ chọn theo từng format** — pretty-print, indentation, dialect (SQL), alignment (Markdown), v.v.
+14
View File
@@ -245,6 +245,20 @@ Codebase hygiene plus a small UX addition — no converter behavior changed.
---
## Phase 6 — Legal gates, error pages & load performance ✅
**Status**: complete (shipped in v1.6.0)
Compliance + reliability + first-paint performance. No converter behavior changed.
- [x] Custom error pages: reusable `ErrorState`, 404 catch-all, generic `/error/:code` (403/419/5xx variants), offline banner, and a chunk-load error boundary folded into the existing crash boundary's look.
- [x] GitHub Pages SPA deep-link fix (`public/404.html` + `index.html` decoder for the `/jsonPrism/` base).
- [x] First-launch legal consent gate (web only) — accept License/Terms/Privacy/Disclaimer, persisted to `localStorage` with a version for re-prompting; skipped on desktop.
- [x] Windows installer license-acceptance page via Tauri `bundle.licenseFile` (`src-tauri/license.rtf`), covering both NSIS `.exe` and WiX `.msi`.
- [x] Lazy-load routes + the CodeMirror editor; refined `manualChunks` (react/router/i18n/cm-core/cm-langs/per-parser/ui); removed the `bson` initial-graph leak via `lib/bytes.ts`. +16 tests (209 total).
---
## Beyond — Ideas (no commitment)
- **JSON → Excel (.xlsx)** via SheetJS — possible if Markdown/CSV doesn't cover the use case
+21
View File
@@ -7,6 +7,27 @@
<meta name="color-scheme" content="dark light" />
<meta name="theme-color" content="#0a0b14" />
<!--
Restores a deep-link path that public/404.html encoded into the query
string on GitHub Pages (see that file). Must run before the SPA router
reads the URL. No-op everywhere else (including Tauri) since `?/` is only
ever present right after the 404 redirect.
-->
<script type="text/javascript">
(function (l) {
if (l.search[1] === '/') {
var decoded = l.search
.slice(1)
.split('&')
.map(function (s) {
return s.replace(/~and~/g, '&');
})
.join('?');
window.history.replaceState(null, null, l.pathname.slice(0, -1) + decoded + l.hash);
}
})(window.location);
</script>
<meta name="description" content="JSONPrism — disperse JSON into many formats. Convert to JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL. Fully client-side, batch up to 500 files." />
<meta name="keywords" content="JSON, converter, JSONL, YAML, CSV, XML, TOML, RESX, Markdown, SQL, batch, offline" />
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "jsonprism",
"version": "1.4.3",
"version": "1.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "jsonprism",
"version": "1.4.3",
"version": "1.6.0",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/lang-json": "^6.0.0",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "jsonprism",
"private": true,
"version": "1.5.0",
"version": "1.6.0",
"type": "module",
"description": "Disperse JSON into many formats — JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL — fully client-side.",
"author": "poli0981 <https://github.com/poli0981>",
+41
View File
@@ -0,0 +1,41 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JSONPrism</title>
<!--
GitHub Pages serves this file for any unknown path. Because JSONPrism is a
BrowserRouter SPA, a deep-link refresh (e.g. /jsonPrism/about) would 404
here. This script encodes the requested path into a query string and
redirects to the app's index, where a small decoder in index.html restores
the real route. Technique: https://github.com/rafgraph/spa-github-pages
pathSegmentsToKeep = 1 preserves the project-page base segment (/jsonPrism/).
-->
<script type="text/javascript">
var pathSegmentsToKeep = 1;
var l = window.location;
l.replace(
l.protocol +
'//' +
l.hostname +
(l.port ? ':' + l.port : '') +
l.pathname
.split('/')
.slice(0, 1 + pathSegmentsToKeep)
.join('/') +
'/?/' +
l.pathname
.slice(1)
.split('/')
.slice(pathSegmentsToKeep)
.join('/')
.replace(/&/g, '~and~') +
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
l.hash,
);
</script>
</head>
<body></body>
</html>
+19
View File
@@ -0,0 +1,19 @@
{\rtf1\ansi\ansicpg1252\deff0
{\fonttbl{\f0\fswiss Segoe UI;}}
\f0\fs20
\b JSONPrism \endash End User License Agreement\b0\par
\par
By installing and using JSONPrism, you agree to the terms below.\par
\par
JSONPrism is free, open-source software licensed under the Apache License 2.0:\par
https://github.com/poli0981/jsonPrism/blob/main/LICENSE\par
\par
Your use is also governed by the following documents:\par
\bullet\tab Terms of Use (EULA): https://github.com/poli0981/jsonPrism/blob/main/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/main/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/main/DISCLAIMER.md\par
\par
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. It runs fully on your device and sends no data to any server.\par
\par
If you do not agree to these terms, do not install or use this software.\par
}
+2 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "JSONPrism",
"version": "1.4.3",
"version": "1.6.0",
"identifier": "com.poli0981.jsonprism",
"build": {
"beforeDevCommand": "npm run dev",
@@ -32,6 +32,7 @@
"bundle": {
"active": true,
"targets": "all",
"licenseFile": "license.rtf",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
+20 -9
View File
@@ -1,22 +1,33 @@
import { lazy } from 'react';
import { Route, Routes } from 'react-router-dom';
import { ThemeProvider } from '@/lib/theme';
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
import { ConsentGate } from '@/components/common/ConsentGate';
import { Layout } from '@/components/layout/Layout';
import { Toaster } from '@/components/ui/sonner';
import { Home } from '@/pages/Home';
import { About } from '@/pages/About';
// Routes are code-split so the entry chunk stays small and the consent gate +
// app shell paint before any page's heavy graph (editor, parsers) loads.
const Home = lazy(() => import('@/pages/Home').then((m) => ({ default: m.Home })));
const About = lazy(() => import('@/pages/About').then((m) => ({ default: m.About })));
const NotFound = lazy(() => import('@/pages/errors/NotFound'));
const ErrorRoute = lazy(() => import('@/pages/errors/ErrorRoute'));
export function App() {
return (
<ThemeProvider defaultTheme="system">
<ErrorBoundary>
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
</Route>
</Routes>
<Toaster />
<ConsentGate>
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
<Route path="error/:code" element={<ErrorRoute />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
<Toaster />
</ConsentGate>
</ErrorBoundary>
</ThemeProvider>
);
@@ -0,0 +1,43 @@
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { ChunkErrorFallback } from '@/components/common/ChunkErrorFallback';
import { isChunkLoadError } from '@/lib/chunk-error';
interface Props {
children: ReactNode;
/** Rendered instead of the default panel on a chunk error (e.g. a textarea editor). */
fallback?: ReactNode;
}
interface State {
error: Error | null;
}
/**
* Catches failed lazy `import()` loads and degrades gracefully. Non-chunk errors
* are rethrown so the outer crash {@link ErrorBoundary} handles them instead.
*/
export class ChunkErrorBoundary extends Component<Props, State> {
override state: State = { error: null };
static getDerivedStateFromError(error: Error): State {
return { error };
}
override componentDidCatch(error: Error, info: ErrorInfo): void {
if (isChunkLoadError(error)) {
console.error('JSONPrism chunk-load error:', error, info);
}
}
override render(): ReactNode {
const { error } = this.state;
if (error) {
if (isChunkLoadError(error)) {
return this.props.fallback ?? <ChunkErrorFallback />;
}
// Not ours — let an outer boundary deal with it.
throw error;
}
return this.props.children;
}
}
@@ -0,0 +1,24 @@
import { useTranslation } from 'react-i18next';
import { RotateCw } from 'lucide-react';
import { ErrorState, errorActionPrimary } from '@/components/common/ErrorState';
/** Default panel shown by ChunkErrorBoundary when a lazy chunk fails to load. */
export function ChunkErrorFallback() {
const { t } = useTranslation();
return (
<ErrorState
title={t('error_page.chunk.title')}
message={t('error_page.chunk.message')}
actions={
<button
type="button"
onClick={() => window.location.reload()}
className={errorActionPrimary}
>
<RotateCw className="h-4 w-4" />
{t('error_page.actions.reload')}
</button>
}
/>
);
}
+89
View File
@@ -0,0 +1,89 @@
import { useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { ExternalLink } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { useConsentStore } from '@/stores/consentStore';
const REPO_URL = 'https://github.com/poli0981/jsonPrism';
const LEGAL_LINKS = [
{ key: 'license', href: `${REPO_URL}/blob/main/LICENSE` },
{ key: 'terms', href: `${REPO_URL}/blob/main/TERMS.md` },
{ key: 'privacy', href: `${REPO_URL}/blob/main/PRIVACY.md` },
{ key: 'disclaimer', href: `${REPO_URL}/blob/main/DISCLAIMER.md` },
] as const;
/**
* First-launch legal gate (web only). Blocks the app behind a non-dismissible
* modal until the user accepts. On desktop the store seeds `accepted = true`
* (the installer's license page already gated acceptance), so this renders its
* children straight through.
*/
export function ConsentGate({ children }: { children: ReactNode }) {
const accepted = useConsentStore((s) => s.accepted);
const accept = useConsentStore((s) => s.accept);
const { t } = useTranslation();
const [checked, setChecked] = useState(false);
if (accepted) return <>{children}</>;
return (
<div className="bg-background h-dvh w-full">
<Dialog open>
<DialogContent
showCloseButton={false}
onEscapeKeyDown={(e) => e.preventDefault()}
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
className="max-w-md"
>
<DialogHeader>
<DialogTitle>{t('consent.title')}</DialogTitle>
<DialogDescription>{t('consent.intro')}</DialogDescription>
</DialogHeader>
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
{LEGAL_LINKS.map((l) => (
<li key={l.key}>
<a
href={l.href}
target="_blank"
rel="noopener noreferrer"
className="text-primary inline-flex items-center gap-1 underline-offset-4 hover:underline"
>
{t(`consent.links.${l.key}`)}
<ExternalLink className="h-3 w-3" />
</a>
</li>
))}
</ul>
<label className="flex cursor-pointer items-start gap-2 text-sm">
<input
type="checkbox"
checked={checked}
onChange={(e) => setChecked(e.target.checked)}
className="accent-primary mt-0.5 h-4 w-4 shrink-0"
/>
<span>{t('consent.agree')}</span>
</label>
<button
type="button"
disabled={!checked}
onClick={accept}
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
>
{t('consent.continue')}
</button>
</DialogContent>
</Dialog>
</div>
);
}
+11 -9
View File
@@ -1,4 +1,5 @@
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { ErrorState, errorActionPrimary } from '@/components/common/ErrorState';
interface Props {
children: ReactNode;
@@ -24,22 +25,23 @@ export class ErrorBoundary extends Component<Props, State> {
override render(): ReactNode {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
// Last-resort crash screen. Intentionally hardcoded English (no i18n) so
// it still renders even when the crash originated inside i18n itself.
return (
<div className="bg-background text-foreground flex min-h-screen items-center justify-center p-8">
<div className="border-border bg-card max-w-md rounded-lg border p-6">
<h1 className="font-display mb-2 text-2xl">Something refracted unexpectedly.</h1>
<p className="text-muted-foreground mb-4 text-sm">
{this.state.error?.message ?? 'Unknown error.'}
</p>
<ErrorState
className="min-h-dvh"
title="Something refracted unexpectedly."
message={this.state.error?.message ?? 'Unknown error.'}
actions={
<button
type="button"
onClick={() => window.location.reload()}
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90"
className={errorActionPrimary}
>
Reload
</button>
</div>
</div>
}
/>
);
}
return this.props.children;
+45
View File
@@ -0,0 +1,45 @@
import type { ReactNode } from 'react';
import { cn } from '@/lib/utils';
interface ErrorStateProps {
/** HTTP-style code or short token (404, 403, "offline") shown large above the title. */
code?: string | number;
title: string;
message?: string;
icon?: ReactNode;
/** Buttons / links — use `errorActionPrimary` / `errorActionSecondary` for styling. */
actions?: ReactNode;
className?: string;
}
export const errorActionPrimary =
'bg-primary text-primary-foreground inline-flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90';
export const errorActionSecondary =
'border-border text-foreground hover:bg-muted inline-flex items-center gap-1.5 rounded-md border px-4 py-2 text-sm font-medium transition';
/**
* Shared presentational error panel. Stays i18n-free — callers pass already
* translated strings — so it renders even if a crash is inside i18n itself.
*/
export function ErrorState({ code, title, message, icon, actions, className }: ErrorStateProps) {
return (
<div
className={cn(
'bg-background text-foreground flex min-h-0 flex-1 items-center justify-center p-8',
className,
)}
>
<div className="border-border bg-card flex w-full max-w-md flex-col items-center gap-4 rounded-lg border p-8 text-center">
{code !== undefined && (
<span className="font-display text-spectrum text-6xl leading-none italic">{code}</span>
)}
{icon}
<h1 className="font-display text-2xl">{title}</h1>
{message && <p className="text-muted-foreground text-sm">{message}</p>}
{actions && (
<div className="mt-2 flex flex-wrap items-center justify-center gap-2">{actions}</div>
)}
</div>
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import { useTranslation } from 'react-i18next';
import { WifiOff } from 'lucide-react';
import { useOnlineStatus } from '@/hooks/useOnlineStatus';
/**
* Non-blocking strip shown when the browser goes offline. Deliberately not a
* route — going offline must never interrupt a conversion in progress.
*/
export function OfflineBanner() {
const { t } = useTranslation();
const online = useOnlineStatus();
if (online) return null;
return (
<div
role="status"
className="border-border/60 bg-card flex items-center justify-center gap-2 border-b px-4 py-1.5 text-xs"
style={{ color: 'var(--color-prism-amber)' }}
>
<WifiOff className="h-3.5 w-3.5" />
<span>{t('error_page.offline.message')}</span>
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { useTranslation } from 'react-i18next';
import { LoaderCircle } from 'lucide-react';
/** Suspense fallback shown while a lazily-loaded route chunk is fetched. */
export function RouteFallback() {
const { t } = useTranslation();
return (
<div className="text-muted-foreground flex min-h-0 flex-1 items-center justify-center gap-2 p-8">
<LoaderCircle className="h-4 w-4 animate-spin" />
<span className="text-sm">{t('common.loading')}</span>
</div>
);
}
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest';
import { render, screen } from '@testing-library/react';
import { ErrorState } from '../ErrorState';
describe('ErrorState', () => {
it('renders code, title, message and actions', () => {
render(
<ErrorState
code={404}
title="Not found"
message="That route doesn't exist."
actions={<button type="button">Home</button>}
/>,
);
expect(screen.getByText('404')).toBeInTheDocument();
expect(screen.getByRole('heading', { name: 'Not found' })).toBeInTheDocument();
expect(screen.getByText("That route doesn't exist.")).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Home' })).toBeInTheDocument();
});
it('omits the code block when no code is given', () => {
render(<ErrorState title="Generic error" />);
expect(screen.getByRole('heading', { name: 'Generic error' })).toBeInTheDocument();
expect(screen.queryByText('404')).not.toBeInTheDocument();
});
});
+1 -1
View File
@@ -14,7 +14,7 @@ import { cn } from '@/lib/utils';
export type EditorLanguage = 'json' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
interface CodeEditorProps {
export interface CodeEditorProps {
value: string;
onChange?: (v: string) => void;
readOnly?: boolean;
@@ -0,0 +1,47 @@
import { lazy, Suspense } from 'react';
import { cn } from '@/lib/utils';
import { ChunkErrorBoundary } from '@/components/common/ChunkErrorBoundary';
import type { CodeEditorProps } from './CodeEditor';
// CodeMirror + its language packs are the heaviest part of the bundle. Defer
// them so first paint never waits on the `cm-core`/`cm-langs` chunks.
const CodeEditor = lazy(() => import('./CodeEditor').then((m) => ({ default: m.CodeEditor })));
/**
* Plain-textarea stand-in shown while the editor chunk loads (and reused as the
* graceful fallback if that chunk fails to load — see ChunkErrorBoundary).
* It's a real controlled input, so typing before CodeMirror arrives is kept
* (the value lives in the Zustand store, not the editor).
*/
function EditorFallback({
value,
onChange,
placeholder,
readOnly = false,
className,
}: CodeEditorProps) {
return (
<div className={cn('h-full overflow-hidden', className)}>
<textarea
value={value}
readOnly={readOnly}
spellCheck={false}
placeholder={placeholder}
onChange={onChange ? (e) => onChange(e.target.value) : undefined}
className="text-foreground placeholder:text-muted-foreground/50 h-full w-full resize-none bg-transparent px-4 py-4 font-mono text-[13px] leading-[1.6] outline-none"
/>
</div>
);
}
export function CodeEditorLazy(props: CodeEditorProps) {
return (
// If the editor chunk fails to load, keep the input usable via the textarea
// rather than blanking the panel or crashing the app.
<ChunkErrorBoundary fallback={<EditorFallback {...props} />}>
<Suspense fallback={<EditorFallback {...props} />}>
<CodeEditor {...props} />
</Suspense>
</ChunkErrorBoundary>
);
}
+2 -2
View File
@@ -11,7 +11,7 @@ import { readFileText } from '@/lib/read-file';
import { SAMPLE_JSON } from '@/lib/sample';
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
import type { FormatId } from '@/converters/types';
import { CodeEditor } from './CodeEditor';
import { CodeEditorLazy } from './CodeEditorLazy';
import type { Direction } from './DirectionToggle';
interface InputPanelProps {
@@ -188,7 +188,7 @@ export function InputPanel({
</div>
<div className="relative min-h-0 flex-1">
<CodeEditor
<CodeEditorLazy
value={value}
onChange={onChange}
language={editorLanguage}
+1 -1
View File
@@ -5,7 +5,7 @@ import { toast } from '@/components/ui/sonner';
import { ToolbarButton } from '@/components/common/ToolbarButton';
import type { FormatId } from '@/converters/types';
import { getConverter } from '@/converters/registry';
import { decodeBytes } from '@/converters/bson';
import { decodeBytes } from '@/lib/bytes';
import type { Direction } from './DirectionToggle';
interface OutputPanelProps {
+12 -1
View File
@@ -1,4 +1,8 @@
import { Suspense } from 'react';
import { Outlet } from 'react-router-dom';
import { ChunkErrorBoundary } from '@/components/common/ChunkErrorBoundary';
import { OfflineBanner } from '@/components/common/OfflineBanner';
import { RouteFallback } from '@/components/common/RouteFallback';
import { Header } from './Header';
import { Footer } from './Footer';
@@ -6,8 +10,15 @@ export function Layout() {
return (
<div className="flex h-dvh flex-col">
<Header />
<OfflineBanner />
<main className="flex min-h-0 flex-1 flex-col">
<Outlet />
{/* Boundary catches a failed route chunk (e.g. stale deploy) and keeps
the header/footer; Suspense shows the loader while it streams in. */}
<ChunkErrorBoundary>
<Suspense fallback={<RouteFallback />}>
<Outlet />
</Suspense>
</ChunkErrorBoundary>
</main>
<Footer />
</div>
+106
View File
@@ -0,0 +1,106 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogClose = DialogPrimitive.Close;
const DialogPortal = DialogPrimitive.Portal;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50 backdrop-blur-sm',
className,
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
interface DialogContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
/** Render the top-right close (X) button. Disable for non-dismissible modals. */
showCloseButton?: boolean;
}
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
DialogContentProps
>(({ className, children, showCloseButton = true, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-1/2 left-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg border p-6 shadow-lg duration-200',
className,
)}
{...props}
>
{children}
{showCloseButton && (
<DialogClose className="ring-offset-background focus:ring-ring data-[state=open]:bg-muted absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogClose>
)}
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
);
DialogHeader.displayName = 'DialogHeader';
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
{...props}
/>
);
DialogFooter.displayName = 'DialogFooter';
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn('font-display text-xl tracking-tight', className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogTrigger,
DialogClose,
DialogPortal,
DialogOverlay,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};
+3 -33
View File
@@ -1,7 +1,9 @@
import { serialize } from 'bson';
import type { Converter } from './types';
import { encodeBytes, type Encoding } from '@/lib/bytes';
type Encoding = 'base64' | 'hex';
// Re-exported for existing test imports (`../bson`) and any legacy callers.
export { encodeBytes, decodeBytes } from '@/lib/bytes';
interface BsonOptions {
encoding: Encoding;
@@ -45,35 +47,3 @@ export const bsonConverter: Converter<BsonOptions> = {
}
},
};
export function encodeBytes(bytes: Uint8Array, encoding: Encoding): string {
if (encoding === 'hex') {
let out = '';
for (let i = 0; i < bytes.length; i++) {
out += bytes[i]!.toString(16).padStart(2, '0');
}
return out;
}
// base64 — encode 3 bytes at a time without using a giant String.fromCharCode call.
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]!);
}
return btoa(binary);
}
export function decodeBytes(encoded: string, encoding: Encoding): Uint8Array {
if (encoding === 'hex') {
const clean = encoded.replace(/\s+/g, '');
if (clean.length % 2 !== 0) throw new Error('Hex string has odd length');
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
const binary = atob(encoded);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}
+1 -3
View File
@@ -1,8 +1,6 @@
import { encode } from 'cbor-x';
import type { Converter } from './types';
import { encodeBytes } from './bson';
type Encoding = 'base64' | 'hex';
import { encodeBytes, type Encoding } from '@/lib/bytes';
interface CborOptions {
encoding: Encoding;
+1 -3
View File
@@ -1,8 +1,6 @@
import { encode } from '@msgpack/msgpack';
import type { Converter } from './types';
import { encodeBytes } from './bson';
type Encoding = 'base64' | 'hex';
import { encodeBytes, type Encoding } from '@/lib/bytes';
interface MsgpackOptions {
encoding: Encoding;
@@ -0,0 +1,35 @@
import { afterEach, describe, expect, it } from 'vitest';
import { act, renderHook } from '@testing-library/react';
import { useOnlineStatus } from '../useOnlineStatus';
function setNavigatorOnline(value: boolean) {
Object.defineProperty(navigator, 'onLine', { configurable: true, value });
}
afterEach(() => {
setNavigatorOnline(true);
});
describe('useOnlineStatus', () => {
it('reflects the initial navigator.onLine value', () => {
setNavigatorOnline(false);
const { result } = renderHook(() => useOnlineStatus());
expect(result.current).toBe(false);
});
it('updates when online / offline events fire', () => {
setNavigatorOnline(true);
const { result } = renderHook(() => useOnlineStatus());
expect(result.current).toBe(true);
act(() => {
window.dispatchEvent(new Event('offline'));
});
expect(result.current).toBe(false);
act(() => {
window.dispatchEvent(new Event('online'));
});
expect(result.current).toBe(true);
});
});
+25
View File
@@ -0,0 +1,25 @@
import { useEffect, useState } from 'react';
/**
* Tracks browser connectivity via `navigator.onLine` + the `online`/`offline`
* events. JSONPrism runs fully client-side, so this is informational only
* (the app keeps working offline — only web fonts need the network).
*/
export function useOnlineStatus(): boolean {
const [online, setOnline] = useState(() =>
typeof navigator === 'undefined' ? true : navigator.onLine,
);
useEffect(() => {
const goOnline = () => setOnline(true);
const goOffline = () => setOnline(false);
window.addEventListener('online', goOnline);
window.addEventListener('offline', goOffline);
return () => {
window.removeEventListener('online', goOnline);
window.removeEventListener('offline', goOffline);
};
}, []);
return online;
}
+47
View File
@@ -233,6 +233,41 @@
"batch_limit": "Batch limit reached ({{max}} files). Remove some files first.",
"unknown": "Something went wrong. {{message}}"
},
"error_page": {
"generic": {
"title": "Something went wrong",
"message": "An unexpected error occurred. Try reloading the page."
},
"404": {
"title": "Page not found",
"message": "The prism only refracts what's here — this route doesn't exist."
},
"403": {
"title": "Forbidden",
"message": "You don't have permission to view this."
},
"419": {
"title": "Session expired",
"message": "Your session timed out. Reload to start fresh."
},
"500": {
"title": "Server error",
"message": "Something broke on the way back. Try again in a moment."
},
"offline": {
"title": "You're offline",
"message": "You're offline — JSONPrism keeps working; only web fonts may not load."
},
"chunk": {
"title": "Couldn't load part of the app",
"message": "A resource failed to load — usually a new version was just deployed. Reload to get the latest."
},
"actions": {
"home": "Back to Convert",
"reload": "Reload",
"retry": "Retry"
}
},
"about": {
"title": "About JSONPrism",
"lead": "A refracting tool for developers.",
@@ -294,6 +329,18 @@
"retry": "Retry",
"scroll_to_top": "Back to top"
},
"consent": {
"title": "Before you start",
"intro": "JSONPrism runs entirely in your browser — your data never leaves your device. Please review and accept the terms:",
"agree": "I have read and agree to the License, Terms (EULA), Privacy Policy, and Disclaimer.",
"continue": "Continue",
"links": {
"license": "License",
"terms": "Terms (EULA)",
"privacy": "Privacy Policy",
"disclaimer": "Disclaimer"
}
},
"disclaimer": {
"translation": "Non-English translations are AI-generated. Accuracy is not guaranteed."
},
+47
View File
@@ -233,6 +233,41 @@
"batch_limit": "Đã đạt giới hạn batch ({{max}} file). Hãy bỏ bớt file.",
"unknown": "Đã có lỗi xảy ra. {{message}}"
},
"error_page": {
"generic": {
"title": "Đã có lỗi xảy ra",
"message": "Một lỗi không mong muốn đã xảy ra. Hãy thử tải lại trang."
},
"404": {
"title": "Không tìm thấy trang",
"message": "Lăng kính chỉ tán sắc những gì đang có — đường dẫn này không tồn tại."
},
"403": {
"title": "Bị cấm truy cập",
"message": "Bạn không có quyền xem nội dung này."
},
"419": {
"title": "Phiên đã hết hạn",
"message": "Phiên làm việc đã hết hạn. Hãy tải lại để bắt đầu lại."
},
"500": {
"title": "Lỗi máy chủ",
"message": "Có gì đó hỏng trên đường về. Hãy thử lại sau giây lát."
},
"offline": {
"title": "Bạn đang ngoại tuyến",
"message": "Bạn đang ngoại tuyến — JSONPrism vẫn chạy bình thường; chỉ font web có thể không tải được."
},
"chunk": {
"title": "Không tải được một phần ứng dụng",
"message": "Một tài nguyên không tải được — thường do vừa có phiên bản mới. Hãy tải lại để cập nhật."
},
"actions": {
"home": "Về trang Chuyển đổi",
"reload": "Tải lại",
"retry": "Thử lại"
}
},
"about": {
"title": "Về JSONPrism",
"lead": "Một công cụ tán sắc cho developer.",
@@ -294,6 +329,18 @@
"retry": "Thử lại",
"scroll_to_top": "Về đầu trang"
},
"consent": {
"title": "Trước khi bắt đầu",
"intro": "JSONPrism chạy hoàn toàn trong trình duyệt của bạn — dữ liệu không bao giờ rời khỏi thiết bị. Vui lòng đọc và chấp nhận các điều khoản:",
"agree": "Tôi đã đọc và đồng ý với Giấy phép, Điều khoản (EULA), Chính sách bảo mật và Tuyên bố miễn trừ trách nhiệm.",
"continue": "Tiếp tục",
"links": {
"license": "Giấy phép",
"terms": "Điều khoản (EULA)",
"privacy": "Chính sách bảo mật",
"disclaimer": "Miễn trừ trách nhiệm"
}
},
"disclaimer": {
"translation": "Các bản dịch không phải tiếng Anh do AI tạo, không đảm bảo chính xác 100%."
},
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { decodeBytes, encodeBytes } from '../bytes';
describe('bytes codec', () => {
it('round-trips base64', () => {
const src = new Uint8Array([0, 1, 2, 250, 255]);
expect(decodeBytes(encodeBytes(src, 'base64'), 'base64')).toEqual(src);
});
it('round-trips hex and pads to two chars per byte', () => {
const src = new Uint8Array([0, 15, 16, 255]);
expect(encodeBytes(src, 'hex')).toBe('000f10ff');
expect(decodeBytes('000f10ff', 'hex')).toEqual(src);
});
it('tolerates whitespace in hex input', () => {
expect(decodeBytes('00 0f 10 ff', 'hex')).toEqual(new Uint8Array([0, 15, 16, 255]));
});
it('throws on odd-length hex', () => {
expect(() => decodeBytes('abc', 'hex')).toThrow(/odd length/i);
});
});
+19
View File
@@ -0,0 +1,19 @@
import { describe, expect, it } from 'vitest';
import { isChunkLoadError } from '../chunk-error';
describe('isChunkLoadError', () => {
it('detects dynamic-import / chunk load failures', () => {
expect(
isChunkLoadError(new Error('Failed to fetch dynamically imported module: /assets/x.js')),
).toBe(true);
expect(isChunkLoadError(new Error('Loading chunk 5 failed'))).toBe(true);
expect(isChunkLoadError(new Error('error loading dynamically imported module'))).toBe(true);
expect(isChunkLoadError('importing a module script failed')).toBe(true);
});
it('ignores unrelated errors and falsy values', () => {
expect(isChunkLoadError(new Error('Cannot read properties of undefined'))).toBe(false);
expect(isChunkLoadError(null)).toBe(false);
expect(isChunkLoadError(undefined)).toBe(false);
});
});
+42
View File
@@ -0,0 +1,42 @@
import { afterEach, describe, expect, it } from 'vitest';
import {
CONSENT_VERSION,
isConsentValid,
loadConsent,
saveConsent,
type StoredConsent,
} from '../consent-storage';
const KEY = 'jsonprism.consent';
afterEach(() => {
window.localStorage.clear();
});
describe('consent-storage', () => {
it('returns null when nothing is stored', () => {
expect(loadConsent()).toBeNull();
});
it('round-trips through saveConsent / loadConsent', () => {
const consent: StoredConsent = { accepted: true, version: CONSENT_VERSION, acceptedAt: 123 };
saveConsent(consent);
expect(loadConsent()).toEqual(consent);
});
it('returns null when the stored value is malformed', () => {
window.localStorage.setItem(KEY, '{not valid json');
expect(loadConsent()).toBeNull();
});
it('isConsentValid is true only for accepted + current version', () => {
expect(isConsentValid(null)).toBe(false);
expect(isConsentValid({ accepted: false, version: CONSENT_VERSION, acceptedAt: 0 })).toBe(
false,
);
expect(isConsentValid({ accepted: true, version: CONSENT_VERSION - 1, acceptedAt: 0 })).toBe(
false,
);
expect(isConsentValid({ accepted: true, version: CONSENT_VERSION, acceptedAt: 0 })).toBe(true);
});
});
+41
View File
@@ -0,0 +1,41 @@
/**
* Pure byte ⇄ text codecs shared by the binary converters (BSON, CBOR,
* MessagePack) and the output panel's download path.
*
* Kept parser-free and outside `src/converters/` so importing it never pulls a
* heavy serialization library (e.g. `bson`) into the consumer's bundle graph.
*/
export type Encoding = 'base64' | 'hex';
export function encodeBytes(bytes: Uint8Array, encoding: Encoding): string {
if (encoding === 'hex') {
let out = '';
for (let i = 0; i < bytes.length; i++) {
out += bytes[i]!.toString(16).padStart(2, '0');
}
return out;
}
// base64 — encode byte-by-byte without a giant String.fromCharCode call.
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]!);
}
return btoa(binary);
}
export function decodeBytes(encoded: string, encoding: Encoding): Uint8Array {
if (encoding === 'hex') {
const clean = encoded.replace(/\s+/g, '');
if (clean.length % 2 !== 0) throw new Error('Hex string has odd length');
const out = new Uint8Array(clean.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
const binary = atob(encoded);
const out = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
return out;
}
+11
View File
@@ -0,0 +1,11 @@
// A dynamic import() rejects with one of these messages when its chunk can't be
// fetched — typically a stale deploy (hashed filename gone) or a dropped network
// mid-navigation.
const CHUNK_ERROR_RE =
/Loading chunk|Loading CSS chunk|dynamically imported module|Failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed/i;
export function isChunkLoadError(error: unknown): boolean {
if (!error) return false;
const msg = error instanceof Error ? error.message : String(error);
return CHUNK_ERROR_RE.test(msg);
}
+39
View File
@@ -0,0 +1,39 @@
/**
* Persists the user's acceptance of the legal terms (web only). Mirrors the
* defensive pattern in {@link file://./options-storage.ts}: SSR-safe, never
* throws (private-mode / quota errors degrade to "not accepted" → re-prompt).
*/
/** Bump when the referenced terms change to re-prompt previously-consented users. */
export const CONSENT_VERSION = 1;
const KEY = 'jsonprism.consent';
export interface StoredConsent {
accepted: boolean;
version: number;
acceptedAt: number;
}
export function loadConsent(): StoredConsent | null {
if (typeof window === 'undefined') return null;
try {
const raw = window.localStorage.getItem(KEY);
if (!raw) return null;
return JSON.parse(raw) as StoredConsent;
} catch {
return null;
}
}
export function saveConsent(consent: StoredConsent): void {
try {
window.localStorage.setItem(KEY, JSON.stringify(consent));
} catch {
/* quota / serialization / private-mode write errors are non-fatal */
}
}
export function isConsentValid(consent: StoredConsent | null): boolean {
return !!consent && consent.accepted === true && consent.version === CONSENT_VERSION;
}
+45
View File
@@ -0,0 +1,45 @@
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router-dom';
import { House, RotateCw } from 'lucide-react';
import {
ErrorState,
errorActionPrimary,
errorActionSecondary,
} from '@/components/common/ErrorState';
// Codes that get dedicated copy. JSONPrism is a static client-side SPA, so it
// never emits these from a server itself — this route exists so any code (e.g.
// surfaced from a future backend or a Tauri IPC failure) can render a polished,
// consistent page. Unknown codes fall back to generic copy but still show the
// number.
const DEDICATED = new Set(['403', '404', '419', '500']);
export default function ErrorRoute() {
const { t } = useTranslation();
const { code } = useParams<{ code: string }>();
const dedicated = code !== undefined && DEDICATED.has(code);
return (
<ErrorState
code={code ?? '?'}
title={t(dedicated ? `error_page.${code}.title` : 'error_page.generic.title')}
message={t(dedicated ? `error_page.${code}.message` : 'error_page.generic.message')}
actions={
<>
<Link to="/" className={errorActionPrimary}>
<House className="h-4 w-4" />
{t('error_page.actions.home')}
</Link>
<button
type="button"
onClick={() => window.location.reload()}
className={errorActionSecondary}
>
<RotateCw className="h-4 w-4" />
{t('error_page.actions.reload')}
</button>
</>
}
/>
);
}
+21
View File
@@ -0,0 +1,21 @@
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { House } from 'lucide-react';
import { ErrorState, errorActionPrimary } from '@/components/common/ErrorState';
export default function NotFound() {
const { t } = useTranslation();
return (
<ErrorState
code={404}
title={t('error_page.404.title')}
message={t('error_page.404.message')}
actions={
<Link to="/" className={errorActionPrimary}>
<House className="h-4 w-4" />
{t('error_page.actions.home')}
</Link>
}
/>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { useConsentStore } from '../consentStore';
import { CONSENT_VERSION } from '@/lib/consent-storage';
beforeEach(() => {
window.localStorage.clear();
useConsentStore.setState({ accepted: false });
});
describe('consentStore', () => {
it('starts not accepted on the web', () => {
expect(useConsentStore.getState().accepted).toBe(false);
});
it('accept() flips state and persists version + timestamp', () => {
useConsentStore.getState().accept();
expect(useConsentStore.getState().accepted).toBe(true);
const raw = window.localStorage.getItem('jsonprism.consent');
expect(raw).not.toBeNull();
const parsed = JSON.parse(raw as string) as {
accepted: boolean;
version: number;
acceptedAt: number;
};
expect(parsed.accepted).toBe(true);
expect(parsed.version).toBe(CONSENT_VERSION);
expect(typeof parsed.acceptedAt).toBe('number');
});
});
+22
View File
@@ -0,0 +1,22 @@
import { create } from 'zustand';
import { CONSENT_VERSION, isConsentValid, loadConsent, saveConsent } from '@/lib/consent-storage';
interface ConsentState {
accepted: boolean;
accept(): void;
}
function initialAccepted(): boolean {
// Desktop builds gate acceptance through the installer's license page, so the
// in-app web gate is a no-op there.
if (__IS_TAURI_BUILD__) return true;
return isConsentValid(loadConsent());
}
export const useConsentStore = create<ConsentState>((set) => ({
accepted: initialAccepted(),
accept: () => {
saveConsent({ accepted: true, version: CONSENT_VERSION, acceptedAt: Date.now() });
set({ accepted: true });
},
}));
+28 -17
View File
@@ -55,31 +55,42 @@ export default defineConfig(({ mode }) => ({
minify: 'oxc',
rollupOptions: {
output: {
// Vite 8 / Rolldown only accepts the function form here.
// Vite 8 / Rolldown only accepts the function form here. Split into the
// smallest sensible vendor chunks so a stale deploy only re-downloads
// the pieces that actually changed, and so heavy parsers/lang-packs are
// their own files (loaded lazily once their format/editor is needed).
// Clause order matters: react must win before react-router/react-i18next.
manualChunks(id) {
if (!id.includes('node_modules')) return undefined;
// React core (react, react-dom, scheduler) — exclude react-router /
// react-i18next / @uiw/react-codemirror which match their own clauses.
if (id.includes('/react-dom/') || /\/react\//.test(id) || id.includes('/scheduler/')) {
return 'react';
}
if (id.includes('react-router')) return 'router';
if (id.includes('i18next')) return 'i18n';
// CodeMirror: language packs split from the core editor.
if (id.includes('@codemirror/lang-') || id.includes('@codemirror/legacy-modes')) {
return 'cm-langs';
}
if (
id.includes('@codemirror/') ||
id.includes('@uiw/react-codemirror') ||
id.includes('@lezer/')
) {
return 'codemirror';
}
if (
id.includes('js-yaml') ||
id.includes('smol-toml') ||
id.includes('fast-xml-parser') ||
id.includes('papaparse')
) {
return 'parsers';
}
if (
id.includes('node_modules/bson/') ||
id.includes('node_modules/cbor-x/') ||
id.includes('node_modules/@msgpack/')
) {
return 'binary-parsers';
return 'cm-core';
}
// One chunk per parser library.
if (id.includes('js-yaml')) return 'p-yaml';
if (id.includes('papaparse')) return 'p-csv';
if (id.includes('fast-xml-parser')) return 'p-xml';
if (id.includes('smol-toml')) return 'p-toml';
if (id.includes('node_modules/bson/')) return 'p-bson';
if (id.includes('node_modules/cbor-x/')) return 'p-cbor';
if (id.includes('node_modules/@msgpack/')) return 'p-msgpack';
if (id.includes('fflate')) return 'fflate';
// Radix primitives + icon set.
if (id.includes('@radix-ui') || id.includes('lucide-react')) return 'ui';
return undefined;
},
},