9 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.8 3657e21f11 chore(release): v1.6.1 — CodeMirror chunk split + web source-map removal (#76)
Patch release bundling the build-only changes since 1.6.0:
- Split the CodeMirror core chunk (cm-view + cm-core) so no chunk trips
  Vite's 500 kB warning; migrated to Rolldown advancedChunks (#74).
- Stopped shipping source maps on the public web build (#72).
- 27 grouped npm minor/patch dependency updates (#67).

Bumps package.json, package-lock.json, src-tauri/Cargo.toml,
src-tauri/Cargo.lock, src-tauri/tauri.conf.json to 1.6.1 and moves the
CHANGELOG [Unreleased] section to [1.6.1].

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 21:59:53 +07:00
poli0981andClaude Opus 4.8 3d424f7c0b perf(build): split CodeMirror core chunk to clear 500 kB warning (#74)
Migrate vite.config.ts chunking from the deprecated manualChunks
function form to advancedChunks.groups. Rolldown's optimizer silently
re-merged manualChunks sub-chunks, so a cm-core split was ignored.

Split the ~614 kB cm-core into cm-view (~245 kB, the @codemirror/view
engine) + cm-core (~362 kB, state/language/lezer/@uiw); cm-langs is
unchanged (~60 kB). No chunk now exceeds Vite's 500 kB warning limit.
Same total/gzip bytes — the editor still loads all three behind its
existing React.lazy boundary, so this is finer file granularity for
better cross-deploy caching. No converter or UI behavior changed.

Verified: clean build (no warning), 209 tests pass, production preview
renders/highlights/converts with all cm-* chunks 200 OK, no console errors.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 21:44:18 +07:00
poli0981andClaude Opus 4.8 29eace4302 fix(build): stop shipping source maps on the public web build (#72)
The web production build emitted .js.map files into dist/, and deploy.yml
uploads the whole dist/ to GitHub Pages — exposing full original source via
DevTools on the public site. Nothing consumes the maps (PRIVACY.md: no remote
error reporting), so gate them to local non-production web builds only; prod
web and Tauri now emit none.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 21:06:53 +07:00
dependabot[bot] 4c25ea1c07 build(deps): Bump the npm-minor-patch group across 1 directory with 27 updates (#67)
Bumps the npm-minor-patch group with 24 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [@codemirror/legacy-modes](https://github.com/codemirror/legacy-modes) | `6.5.2` | `6.5.3` |
| [@codemirror/lint](https://github.com/codemirror/lint) | `6.9.6` | `6.9.7` |
| [@codemirror/view](https://github.com/codemirror/view) | `6.42.1` | `6.43.1` |
| [@radix-ui/react-dialog](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/dialog) | `1.1.15` | `1.1.16` |
| [@radix-ui/react-switch](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/switch) | `1.2.6` | `1.3.0` |
| [@radix-ui/react-tabs](https://github.com/radix-ui/primitives/tree/HEAD/packages/react/tabs) | `1.1.13` | `1.1.14` |
| [@uiw/react-codemirror](https://github.com/uiwjs/react-codemirror) | `4.25.9` | `4.25.10` |
| [fflate](https://github.com/101arrowz/fflate) | `0.8.2` | `0.8.3` |
| [js-yaml](https://github.com/nodeca/js-yaml) | `4.1.1` | `4.2.0` |
| [react](https://github.com/facebook/react/tree/HEAD/packages/react) | `19.2.6` | `19.2.7` |
| [@types/react](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/HEAD/types/react) | `19.2.14` | `19.2.17` |
| [react-dom](https://github.com/facebook/react/tree/HEAD/packages/react-dom) | `19.2.6` | `19.2.7` |
| [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom) | `7.15.0` | `7.17.0` |
| [zustand](https://github.com/pmndrs/zustand) | `5.0.13` | `5.0.14` |
| [@tailwindcss/vite](https://github.com/tailwindlabs/tailwindcss/tree/HEAD/packages/@tailwindcss-vite) | `4.3.0` | `4.3.1` |
| [@tauri-apps/cli](https://github.com/tauri-apps/tauri) | `2.11.1` | `2.11.2` |
| [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/tree/HEAD/packages/plugin-react) | `6.0.1` | `6.0.2` |
| [@vitest/coverage-v8](https://github.com/vitest-dev/vitest/tree/HEAD/packages/coverage-v8) | `4.1.6` | `4.1.8` |
| [eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) | `0.4.26` | `0.5.2` |
| [knip](https://github.com/webpro-nl/knip/tree/HEAD/packages/knip) | `6.14.1` | `6.16.1` |
| [prettier](https://github.com/prettier/prettier) | `3.8.3` | `3.8.4` |
| [prettier-plugin-tailwindcss](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) | `0.6.14` | `0.8.0` |
| [typescript-eslint](https://github.com/typescript-eslint/typescript-eslint/tree/HEAD/packages/typescript-eslint) | `8.59.3` | `8.61.0` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.0.12` | `8.0.16` |



Updates `@codemirror/legacy-modes` from 6.5.2 to 6.5.3
- [Changelog](https://github.com/codemirror/legacy-modes/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/legacy-modes/commits)

Updates `@codemirror/lint` from 6.9.6 to 6.9.7
- [Changelog](https://github.com/codemirror/lint/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/lint/commits)

Updates `@codemirror/view` from 6.42.1 to 6.43.1
- [Changelog](https://github.com/codemirror/view/blob/main/CHANGELOG.md)
- [Commits](https://github.com/codemirror/view/commits)

Updates `@radix-ui/react-dialog` from 1.1.15 to 1.1.16
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/dialog/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/dialog)

Updates `@radix-ui/react-slot` from 1.2.4 to 1.2.5
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/slot/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/slot)

Updates `@radix-ui/react-switch` from 1.2.6 to 1.3.0
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/switch/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/switch)

Updates `@radix-ui/react-tabs` from 1.1.13 to 1.1.14
- [Changelog](https://github.com/radix-ui/primitives/blob/main/packages/react/tabs/CHANGELOG.md)
- [Commits](https://github.com/radix-ui/primitives/commits/HEAD/packages/react/tabs)

Updates `@uiw/react-codemirror` from 4.25.9 to 4.25.10
- [Release notes](https://github.com/uiwjs/react-codemirror/releases)
- [Commits](https://github.com/uiwjs/react-codemirror/compare/v4.25.9...v4.25.10)

Updates `fflate` from 0.8.2 to 0.8.3
- [Release notes](https://github.com/101arrowz/fflate/releases)
- [Changelog](https://github.com/101arrowz/fflate/blob/master/CHANGELOG.md)
- [Commits](https://github.com/101arrowz/fflate/compare/v0.8.2...v0.8.3)

Updates `js-yaml` from 4.1.1 to 4.2.0
- [Changelog](https://github.com/nodeca/js-yaml/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/commits)

Updates `react` from 19.2.6 to 19.2.7
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/react/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.7/packages/react)

Updates `@types/react` from 19.2.14 to 19.2.17
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `react-dom` from 19.2.6 to 19.2.7
- [Release notes](https://github.com/facebook/react/releases)
- [Changelog](https://github.com/react/react/blob/main/CHANGELOG.md)
- [Commits](https://github.com/facebook/react/commits/v19.2.7/packages/react-dom)

Updates `react-router-dom` from 7.15.0 to 7.17.0
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.17.0/packages/react-router-dom)

Updates `zustand` from 5.0.13 to 5.0.14
- [Release notes](https://github.com/pmndrs/zustand/releases)
- [Commits](https://github.com/pmndrs/zustand/compare/v5.0.13...v5.0.14)

Updates `@tailwindcss/vite` from 4.3.0 to 4.3.1
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/@tailwindcss-vite)

Updates `@tauri-apps/cli` from 2.11.1 to 2.11.2
- [Release notes](https://github.com/tauri-apps/tauri/releases)
- [Commits](https://github.com/tauri-apps/tauri/compare/@tauri-apps/cli-v2.11.1...@tauri-apps/cli-v2.11.2)

Updates `@types/react` from 19.2.14 to 19.2.17
- [Release notes](https://github.com/DefinitelyTyped/DefinitelyTyped/releases)
- [Commits](https://github.com/DefinitelyTyped/DefinitelyTyped/commits/HEAD/types/react)

Updates `@vitejs/plugin-react` from 6.0.1 to 6.0.2
- [Release notes](https://github.com/vitejs/vite-plugin-react/releases)
- [Changelog](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite-plugin-react/commits/plugin-react@6.0.2/packages/plugin-react)

Updates `@vitest/coverage-v8` from 4.1.6 to 4.1.8
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.8/packages/coverage-v8)

Updates `eslint-plugin-react-refresh` from 0.4.26 to 0.5.2
- [Release notes](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/releases)
- [Changelog](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/blob/main/CHANGELOG.md)
- [Commits](https://github.com/ArnaudBarre/eslint-plugin-react-refresh/compare/v0.4.26...v0.5.2)

Updates `knip` from 6.14.1 to 6.16.1
- [Release notes](https://github.com/webpro-nl/knip/releases)
- [Commits](https://github.com/webpro-nl/knip/commits/knip@6.16.1/packages/knip)

Updates `prettier` from 3.8.3 to 3.8.4
- [Release notes](https://github.com/prettier/prettier/releases)
- [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md)
- [Commits](https://github.com/prettier/prettier/compare/3.8.3...3.8.4)

Updates `prettier-plugin-tailwindcss` from 0.6.14 to 0.8.0
- [Release notes](https://github.com/tailwindlabs/prettier-plugin-tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/prettier-plugin-tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/prettier-plugin-tailwindcss/compare/v0.6.14...v0.8.0)

Updates `tailwindcss` from 4.3.0 to 4.3.1
- [Release notes](https://github.com/tailwindlabs/tailwindcss/releases)
- [Changelog](https://github.com/tailwindlabs/tailwindcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/tailwindlabs/tailwindcss/commits/v4.3.1/packages/tailwindcss)

Updates `typescript-eslint` from 8.59.3 to 8.61.0
- [Release notes](https://github.com/typescript-eslint/typescript-eslint/releases)
- [Changelog](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/typescript-eslint/CHANGELOG.md)
- [Commits](https://github.com/typescript-eslint/typescript-eslint/commits/v8.61.0/packages/typescript-eslint)

Updates `vite` from 8.0.12 to 8.0.16
- [Release notes](https://github.com/vitejs/vite/releases)
- [Changelog](https://github.com/vitejs/vite/blob/main/packages/vite/CHANGELOG.md)
- [Commits](https://github.com/vitejs/vite/commits/v8.0.16/packages/vite)

Updates `vitest` from 4.1.6 to 4.1.8
- [Release notes](https://github.com/vitest-dev/vitest/releases)
- [Changelog](https://github.com/vitest-dev/vitest/blob/main/docs/releases.md)
- [Commits](https://github.com/vitest-dev/vitest/commits/v4.1.8/packages/vitest)

---
updated-dependencies:
- dependency-name: "@codemirror/legacy-modes"
  dependency-version: 6.5.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@codemirror/lint"
  dependency-version: 6.9.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@codemirror/view"
  dependency-version: 6.43.1
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: "@radix-ui/react-dialog"
  dependency-version: 1.1.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@radix-ui/react-slot"
  dependency-version: 1.2.5
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@radix-ui/react-switch"
  dependency-version: 1.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: "@radix-ui/react-tabs"
  dependency-version: 1.1.14
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@uiw/react-codemirror"
  dependency-version: 4.25.10
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: fflate
  dependency-version: 0.8.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: js-yaml
  dependency-version: 4.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: react
  dependency-version: 19.2.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@types/react"
  dependency-version: 19.2.17
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: react-dom
  dependency-version: 19.2.7
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: react-router-dom
  dependency-version: 7.17.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: zustand
  dependency-version: 5.0.14
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@tailwindcss/vite"
  dependency-version: 4.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@tauri-apps/cli"
  dependency-version: 2.11.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@types/react"
  dependency-version: 19.2.17
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@vitejs/plugin-react"
  dependency-version: 6.0.2
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: "@vitest/coverage-v8"
  dependency-version: 4.1.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: eslint-plugin-react-refresh
  dependency-version: 0.5.2
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: knip
  dependency-version: 6.16.1
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: prettier
  dependency-version: 3.8.4
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: prettier-plugin-tailwindcss
  dependency-version: 0.8.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: tailwindcss
  dependency-version: 4.3.1
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: typescript-eslint
  dependency-version: 8.61.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: vite
  dependency-version: 8.0.16
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: vitest
  dependency-version: 4.1.8
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-06-14 17:53:33 +07:00
poli0981 e6ab02cdef fix(tauri): commit Cargo.lock to fix release build (#68)
See PR #68.
2026-06-14 15:17:47 +07:00
poli0981 b89d99807d feat: error pages, consent gate, installer license + web code-splitting — v1.6.0 (#65)
See PR #65 for full details.
2026-06-14 14:49:26 +07:00
poli0981andClaude Opus 4.7 6197334326 chore(release): v1.5.0 — component refactor, knip, scroll-to-top (#58)
- Refactor: decompose BatchPanel (515→289), ConverterWorkspace (314→206),
  and InputPanel (278→216) into pure utilities, leaf components, and hooks.
  Behavior-preserving; all 193 unit tests still pass.
- Tooling: integrate knip for dead-code analysis (knip.json + npm script +
  CI step). Remove orphaned useLocalStorage.ts; declare the previously
  phantom `globals` devDependency.
- Feature: scroll-to-top button on the About page (prefers-reduced-motion
  aware, i18n across all four locales).
- Docs: bump to 1.5.0; update CHANGELOG, THIRD-PARTY, ROADMAP (Phase 4 + 5),
  CONTRIBUTING.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 20:06:51 +07:00
poli0981andClaude Opus 4.7 30f10cfc36 chore(release): v1.4.3 (#54)
Patch release for the toast close-button regression (#52):
- Upgrade sonner v1.7 to v2 — close button now dismisses on click on both desktop and mobile
- Touch hit-area expansion on close button + touch-action: manipulation
- docs/tested-viewports.md documents the manual device test matrix
- README EN + VI link to the new doc

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 14:02:34 +07:00
poli0981andClaude Opus 4.7 a6caa88d9c fix(toast): close button now dismisses on click — upgrade sonner v1.7 to v2 (#52)
User report: the toast close button (×) was visible on both desktop and mobile,
but clicking/tapping it didn't dismiss the toast. Reading sonner v1.7.4's
bundled source, the toast root attaches an `onPointerDown` that calls
`r.target.setPointerCapture(r.pointerId)` unconditionally whenever the toast is
dismissible. Combined with React 19's new event delegation (root-attached
listeners instead of document-wide), this pointer capture quirk swallows the
synthetic click event on the close button — so the bundled handler that calls
`dismiss()` never runs. The bug fires on both mouse and touch because the
PointerEvent capture is API-unified.

Upgrade sonner from ^1.7.0 to ^2.0.7. Sonner v2 rewrote the pointer/swipe
handling and ships first-class React 19 support; the close-button click now
fires reliably on both desktop and mobile. The seven `toast.success/warning/
error/info` usage sites and the `<Toaster>` props (`position`, `theme`,
`richColors`, `closeButton`, `toastOptions.classNames`) are API-compatible
between v1 and v2 — typecheck and the 193 unit tests pass without changes.

Bonus: add a `::after` hit-area expansion on `[data-close-button]` (visible
size stays at sonner's 20px default; effective tap target ~36–40px) plus
`touch-action: manipulation` to eliminate the 300ms tap delay on touch
devices. Defensive — sonner v2 already fixes the underlying click issue, but
the larger hit target is a free mobile UX win.

Also adds:
- `docs/tested-viewports.md` — the manual device test matrix the maintainer
  has been verifying against (BlackBerry Z30 / Galaxy S9+ / Pixel 3/4/7 /
  iPhone SE/12/14 Pro/XR/Pro Max / iPad / BlackBerry PlayBook). Documents the
  Nokia Lumia 520 (320x533) as a known limitation below the recommended
  minimum 360x640.
- README EN + VI link to the new doc.
- THIRD-PARTY.md bumps sonner version 1.7 to 2.0.7.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 14:01:10 +07:00
74 changed files with 8865 additions and 1489 deletions

No files matched your search

+3
View File
@@ -42,6 +42,9 @@ jobs:
- name: Lint
run: npm run lint
- name: Knip
run: npm run knip
- name: Typecheck
run: npm run typecheck
-1
View File
@@ -32,7 +32,6 @@ dist-ssr
# Tauri (Phase 2C)
src-tauri/target
src-tauri/Cargo.lock
src-tauri/gen
src-tauri/icons/*.png
src-tauri/icons/*.ico
+75 -1
View File
@@ -6,7 +6,81 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
## [Unreleased]
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond Phase 3".
No unreleased changes at this time. Future work tracked in `docs/ROADMAP.md` under "Beyond".
## [1.6.1] — 2026-06-14
### Changed
- **Split the CodeMirror core chunk to clear the 500 kB build warning.** The `cm-core` chunk was ~614 kB raw (210 kB gzip) and tripped Vite's `chunkSizeWarningLimit` on every build, even though it is already lazy-loaded behind the editor. Vite 8 / Rolldown deprecates the `manualChunks` function form (its optimizer silently merged sub-chunks back together), so `vite.config.ts` now uses `advancedChunks.groups` with explicit `priority`-ordered, honored boundaries. The CodeMirror core splits into `cm-view` (~245 kB, the `@codemirror/view` DOM engine) + `cm-core` (~362 kB, state/language/lezer/`@uiw` wrapper); `cm-langs` is unchanged (~60 kB). No chunk now exceeds 500 kB. Total bytes and gzip size are unchanged — the editor still loads all three pieces together behind its existing `React.lazy` boundary, so this is purely finer file granularity (better cache reuse across deploys). No converter or UI behavior changed; verified in a production preview build (editor renders, highlights, and converts; all `cm-*` chunks 200 OK, no console errors).
### Fixed
- **Stop shipping source maps on the public web build.** `vite.config.ts` now emits source maps only for local non-production web builds (`sourcemap: !isTauriContext && mode !== 'production'`) — never for the GitHub Pages deploy or Tauri bundles. The entire `dist/` is uploaded to Pages, so earlier production builds exposed the full original source via `.map` files even though nothing consumes them (`PRIVACY.md`: no remote error reporting). Smaller deploy, no source exposure.
### Dependencies
- **27 npm minor/patch updates** (the grouped `npm-minor-patch` Dependabot bump).
## [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
- **Scroll-to-top button on the About page.** A floating up-arrow button (`src/components/common/ScrollToTop.tsx`) fades in at the bottom-right once the About page is scrolled past ~320px, and smoothly returns to the top on click. The About page hides its scrollbar (`.scrollbar-hide`), so there was previously no quick way back up. Respects `prefers-reduced-motion` (jumps instead of animating) and stays out of the keyboard tab order / accessibility tree while hidden. New i18n key `common.scroll_to_top` across all four locales (en/vi/ja/zh-CN). The button is About-only by design — the converter workspace uses a fixed `h-dvh` layout that never page-scrolls.
### Changed
- **Internal refactor — three oversized components decomposed (behavior-preserving).** `BatchPanel.tsx` (515 lines), `ConverterWorkspace.tsx` (314), and `InputPanel.tsx` (278) were split into focused, reusable units: pure utilities (`lib/format-bytes.ts`, `lib/editor-language.ts`, `lib/read-file.ts`), leaf components (`common/ToolbarButton.tsx` — de-duplicated from InputPanel + OutputPanel — plus `converter/BatchItemRow.tsx` and `converter/BatchSummaryChips.tsx`), and hooks (`useFileAccept`, `useBatchActions`, `useConversionResult`, `useOutputBadge`, `useBatchFileRouter`). No converter or UI behavior changed; all 193 unit tests still pass.
### Tooling
- **`knip` integrated for dead-code analysis.** New `knip.json` config, an `npm run knip` script, and a `Knip` step in CI (`.github/workflows/ci.yml`) — unused files and dependencies are now caught on every push. The initial sweep deleted the orphaned `src/hooks/useLocalStorage.ts` (superseded by `lib/options-storage.ts`), dropped the unused `i18n` default export and the unused `BatchPanel` prop `onAddExternalFiles`, and un-exported the internally-used `nativeReadText`. knip's export-level `types` check is disabled — the converter-contract types in `converters/types.ts` are intentional public vocabulary, not dead code.
### Fixed
- **`globals` was a phantom (undeclared) devDependency.** `eslint.config.js` imports `globals`, but it was never listed in `package.json` — linting only worked because ESLint pulls `globals` in transitively. Now declared explicitly so a stricter or deduped install can't break `npm run lint`. Surfaced by the new `knip` check.
### Dependencies
- Added `knip` `^6.14.1` (ISC, dead-code analyzer, devDep) and `globals` `^14.0.0` (MIT, explicit devDep — previously resolved transitively). `THIRD-PARTY.md` updated.
### Tests
- No new tests this round — the refactor is behavior-preserving and the scroll button is editor/CSS/i18n surface best verified manually. The **193** existing unit tests still pass; typecheck, lint, `knip`, and `prettier --check` are all green.
## [1.4.3] — 2026-05-14
### Fixed
- **Toast close button (`×`) did nothing on click/tap** on both desktop and mobile. `sonner@1.7.4`'s toast root attached `r.target.setPointerCapture(r.pointerId)` unconditionally on `pointerdown`, and combined with React 19's new container-root event delegation, the pointer-capture quirk swallowed the synthetic click event on the close button — so the bundled `dismiss()` handler never ran. The bug fired on both mouse and touch because the PointerEvent API is unified. Upgraded `sonner` `^1.7.0` → `^2.0.7`, which rewrote pointer/swipe handling and ships first-class React 19 support. `<Toaster>` props (`position`, `theme`, `richColors`, `closeButton`, `toastOptions.classNames`) and the `toast.success/warning/error/info` call sites are API-compatible — no code changes needed beyond the version bump.
### Added
- **`docs/tested-viewports.md`** — the maintainer's manual device test matrix (BlackBerry Z30 / Galaxy S9+ / Pixel 3/4/7 / iPhone SE/12/14 Pro/XR/Pro Max / iPad / BlackBerry PlayBook). Documents Nokia Lumia 520 (320×533) as a known limitation below the recommended `360×640` minimum. README EN + VI link to it.
- **Touch hit-area expansion on the toast close button.** A `::after` pseudo gives an effective ~36–40px tap target (visible size stays at sonner's 20px default), plus `touch-action: manipulation` to drop the 300ms tap delay on touch devices. Defensive — sonner v2 already fixes the underlying click — but a free mobile UX win.
### Dependencies
- Bumped `sonner` `^1.7.0` → `^2.0.7` (MIT). THIRD-PARTY.md updated.
## [1.4.2] — 2026-05-14
+2 -1
View File
@@ -20,11 +20,12 @@ Open <http://localhost:5173>.
```bash
npm run format
npm run lint
npm run knip
npm run typecheck
npm run build
```
CI runs all four. If any fails, your PR can't be merged.
CI runs all of these. If any fails, your PR can't be merged.
2. **Match the project style.** Read [`CLAUDE.md`](CLAUDE.md) for non-negotiable conventions (converter shape, error handling, i18n requirements).
+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.
+2 -1
View File
@@ -38,11 +38,12 @@ 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.
- **Dark + light themes** — Prism Spectrum palette with violet / cyan / amber / rose accents.
- **Responsive — designed for viewports ≥ 360 × 640.** Smaller screens still work but may feel cramped; on mobile, Input and Output use a Tabs UI to give each panel full height.
- **Responsive — designed for viewports ≥ 360 × 640.** Smaller screens still work but may feel cramped; on mobile, Input and Output use a Tabs UI to give each panel full height. See [`docs/tested-viewports.md`](docs/tested-viewports.md) for the full device test matrix.
- **EN + VI** — bilingual interface out of the box. More languages welcome.
- **Tauri desktop build** — drag-and-drop file workflow, offline-first (Phase 2 milestone).
+2 -1
View File
@@ -38,11 +38,12 @@ 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.
- **Theme sáng/tối** — bảng màu Prism Spectrum với violet / cyan / amber / rose.
- **Responsive — tối ưu cho viewport ≥ 360 × 640.** Màn hình nhỏ hơn vẫn dùng được nhưng có thể chật; trên mobile, Input và Output dùng Tabs UI để mỗi panel có toàn bộ chiều cao.
- **Responsive — tối ưu cho viewport ≥ 360 × 640.** Màn hình nhỏ hơn vẫn dùng được nhưng có thể chật; trên mobile, Input và Output dùng Tabs UI để mỗi panel có toàn bộ chiều cao. Xem [`docs/tested-viewports.md`](docs/tested-viewports.md) cho ma trận thiết bị đã kiểm thử.
- **Đa ngôn ngữ EN + VI** — sẵn sàng từ ngày đầu. Hoan nghênh thêm ngôn ngữ khác.
- **Bản desktop Tauri** — drag-and-drop file, hoạt động offline (mốc Phase 2).
+3 -1
View File
@@ -31,7 +31,7 @@ the relevant notices. This file is a starting point.
| `@radix-ui/react-switch` | ^1.1.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `@radix-ui/react-tabs` | ^1.1.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `lucide-react` | ^0.460.0 | ISC | [lucide.dev](https://lucide.dev/) |
| `sonner` | ^1.7.0 | MIT | [sonner.emilkowal.ski](https://sonner.emilkowal.ski/) |
| `sonner` | ^2.0.7 | MIT | [sonner.emilkowal.ski](https://sonner.emilkowal.ski/) |
| `react-dropzone` | ^14.3.0 | MIT | [react-dropzone.js.org](https://react-dropzone.js.org/) |
The component patterns under `src/components/ui/` are generated from
@@ -122,6 +122,8 @@ installed as a runtime dependency.
| `@testing-library/jest-dom` | ^6.6.0 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/user-event` | ^14.5.0 | MIT | [testing-library.com](https://testing-library.com/) |
| `jsdom` | ^29.0.0 | MIT | [github.com/jsdom/jsdom](https://github.com/jsdom/jsdom) |
| `knip` | ^6.14.1 | ISC | [knip.dev](https://knip.dev/) |
| `globals` | ^14.0.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
## Fonts
+42 -2
View File
@@ -219,7 +219,47 @@ Goal: ship the .NET RESX converter and integrate with existing AutoClickForge /
---
## Beyond Phase 3 — Ideas (no commitment)
## Phase 4 — Binary formats & reverse conversion ✅
**Status**: complete (shipped in v1.1.0)
Post-1.0 expansion: three binary target formats and bidirectional conversion.
- [x] **BSON / CBOR / MessagePack** converters — output rendered as base64 (default) or hex; downloads decode back to raw bytes. New `ConverterMeta.binary` flag.
- [x] **Reverse conversion** — optional `Converter<T>.reverse()` interface method; JSONL, CSV/TSV, YAML, TOML, RESX → JSON. New `DirectionToggle` component, direction persisted to localStorage.
- [x] Reverse batch processing — drop non-JSON files, get a `.zip` of `.json` outputs back.
**12/12 formats production-ready.**
---
## Phase 5 — Maintenance & refactor ✅
**Status**: complete (shipped in v1.5.0)
Codebase hygiene plus a small UX addition — no converter behavior changed.
- [x] Decomposed three oversized components (`BatchPanel`, `ConverterWorkspace`, `InputPanel`) into focused pure utilities, leaf components, and hooks — behavior-preserving, all 193 tests still green.
- [x] Integrated `knip` for dead-code analysis: `knip.json` config, `npm run knip` script, and a CI step. Initial sweep removed orphaned code and a phantom dependency.
- [x] Scroll-to-top button on the long, scrollbar-hidden About page (respects `prefers-reduced-motion`).
---
## 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
- **Reverse direction** (other format → JSON): different mental model; might warrant a sibling app
@@ -228,7 +268,7 @@ Goal: ship the .NET RESX converter and integrate with existing AutoClickForge /
- **VS Code extension**: surface the converters in the editor command palette
- **Sharing**: hash-based shareable URLs (`#data=...`) for sample inputs (privacy: opt-in only)
These are deliberately deferred — Phase 1–3 first.
These are deliberately deferred — Phase 1–5 first.
---
+54
View File
@@ -0,0 +1,54 @@
# Tested viewports
JSONPrism's mobile and tablet rendering is verified across the devices below.
Status legend:
- ✅ Works as expected
- ⚠️ Cramped but functional
- ❌ Known limitation (typically below recommended minimum)
Recommended minimum viewport: **360 × 640**. Phones in landscape orientation are best-effort — see [recommendation](#recommendation).
## Test results (last verified 2026-05-14)
### Phones (portrait)
| Device | Viewport | Status | Notes |
| ------------------------------------------------ | --------- | ------ | ------------------------------ |
| BlackBerry Z30 / Samsung Galaxy Note 3 / Nexus 5 | 360 × 640 | ✅ | Minimum recommended viewport |
| Samsung Galaxy S9+ | 320 × 658 | ✅ | Below recommended width, works |
| Pixel 4 | 353 × 745 | ✅ | |
| Pixel 3 | 393 × 786 | ✅ | |
| iPhone SE (2nd/3rd gen) | 375 × 667 | ✅ | |
| iPhone 12 Pro | 390 × 844 | ✅ | |
| iPhone 14 Pro | 393 × 852 | ✅ | Verified on real device |
| iPhone XR | 414 × 896 | ✅ | |
| Pixel 7 | 412 × 915 | ✅ | |
| iPhone 14 Pro Max | 420 × 932 | ✅ | |
### Tablets
| Device | Viewport | Status | Notes |
| ------------------- | ---------- | ------ | -------------------------------------------------- |
| BlackBerry PlayBook | 600 × 1024 | ✅ | |
| iPad | 768 × 1024 | ✅ | Side-by-side input/output kicks in at `md` (768px) |
### Known limitations
| Device | Viewport | Status | Notes |
| -------------- | --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| Nokia Lumia 520 | 320 × 533 | ❌ | Code editor disappears — viewport is below the recommended minimum height (640). Worth revisiting in a future round if demand surfaces. |
## Recommendation
- **Portrait orientation only on phones.** Landscape on phones (height < width) compresses each tab's content area to ~150–200px after chrome and is best-effort.
- **Below recommended minimum (360 × 640)**: layout is functional but the code editor may collapse on very short heights (< 600px).
## How to retest
1. Open Chrome DevTools → "Toggle device toolbar" (Ctrl+Shift+M).
2. Pick a device from the dropdown or set a custom viewport.
3. Verify on the Home page: Header navigation visible, Input/Output Tabs accessible, FormatPicker trigger fits, no horizontal scroll on `<body>`.
Test results contributed by the maintainer. PRs welcome to expand the matrix.
+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" />
+15
View File
@@ -0,0 +1,15 @@
{
"project": ["src/**/*.{ts,tsx}"],
"ignore": ["src/components/ui/**"],
"ignoreDependencies": [
"@radix-ui/react-slot",
"tailwindcss",
"tw-animate-css",
"@tauri-apps/plugin-os",
"@tauri-apps/plugin-shell",
"@testing-library/user-event"
],
"rules": {
"types": "off"
}
}
+1450 -683
View File
File diff suppressed because it is too large. Load diff
+28 -25
View File
@@ -1,7 +1,7 @@
{
"name": "jsonprism",
"private": true,
"version": "1.4.2",
"version": "1.6.1",
"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>",
@@ -20,6 +20,7 @@
"preview": "vite preview",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"knip": "knip",
"format": "prettier --write \"src/**/*.{ts,tsx,css,md,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,md,json}\"",
"typecheck": "tsc -b --noEmit",
@@ -39,68 +40,70 @@
"@codemirror/lang-xml": "^6.1.0",
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.10.0",
"@codemirror/legacy-modes": "^6.5.2",
"@codemirror/lint": "^6.8.0",
"@codemirror/legacy-modes": "^6.5.3",
"@codemirror/lint": "^6.9.7",
"@codemirror/state": "^6.4.0",
"@codemirror/view": "^6.34.0",
"@codemirror/view": "^6.43.1",
"@lezer/highlight": "^1.2.0",
"@msgpack/msgpack": "^3.1.3",
"@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-dialog": "^1.1.16",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-switch": "^1.3.0",
"@radix-ui/react-tabs": "^1.1.14",
"@tauri-apps/api": "^2.0.0",
"@tauri-apps/plugin-dialog": "^2.0.0",
"@tauri-apps/plugin-fs": "^2.0.0",
"@tauri-apps/plugin-os": "^2.0.0",
"@tauri-apps/plugin-shell": "^2.0.0",
"@uiw/react-codemirror": "^4.23.0",
"@uiw/react-codemirror": "^4.25.10",
"bson": "^7.2.0",
"cbor-x": "^1.6.4",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"fast-xml-parser": "^5.8.0",
"fflate": "^0.8.2",
"fflate": "^0.8.3",
"i18next": "^23.0.0",
"i18next-browser-languagedetector": "^8.0.0",
"js-yaml": "^4.1.0",
"js-yaml": "^4.2.0",
"lucide-react": "^0.460.0",
"papaparse": "^5.4.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-dropzone": "^14.3.0",
"react-i18next": "^15.0.0",
"react-router-dom": "^7.0.0",
"react-router-dom": "^7.17.0",
"smol-toml": "^1.3.0",
"sonner": "^1.7.0",
"sonner": "^2.0.7",
"tailwind-merge": "^2.5.0",
"zustand": "^5.0.0"
"zustand": "^5.0.14"
},
"devDependencies": {
"@eslint/js": "^9.15.0",
"@tailwindcss/vite": "^4.0.0",
"@tauri-apps/cli": "^2.0.0",
"@tailwindcss/vite": "^4.3.1",
"@tauri-apps/cli": "^2.11.2",
"@testing-library/jest-dom": "^6.6.0",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.0",
"@types/js-yaml": "^4.0.0",
"@types/node": "^22.0.0",
"@types/papaparse": "^5.3.0",
"@types/react": "^19.0.0",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^6.0.0",
"@vitest/coverage-v8": "^4.1.6",
"@vitejs/plugin-react": "^6.0.2",
"@vitest/coverage-v8": "^4.1.8",
"eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.0",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^14.0.0",
"jsdom": "^29.0.0",
"prettier": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"knip": "^6.16.1",
"prettier": "^3.8.4",
"prettier-plugin-tailwindcss": "^0.8.0",
"tailwindcss": "^4.0.0",
"tw-animate-css": "^1.2.0",
"typescript": "^5.7.0",
"typescript-eslint": "^8.15.0",
"vite": "^8.0.0",
"typescript-eslint": "^8.61.0",
"vite": "^8.0.16",
"vitest": "^4.1.6"
}
}
+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>
-1
View File
@@ -1,6 +1,5 @@
/target/
/gen/schemas/
Cargo.lock
# Icon binaries are generated from icon.svg via `npm run tauri:icon`.
# Comment these out and commit the binaries if your CI doesn't run the generation step.
+5360
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "jsonprism"
version = "1.4.2"
version = "1.6.1"
description = "Disperse JSON into many formats."
authors = ["poli0981 <https://github.com/poli0981>"]
license = "Apache-2.0"
+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.2",
"version": "1.6.1",
"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>
);
}
+51
View File
@@ -0,0 +1,51 @@
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ArrowUp } from 'lucide-react';
import { cn } from '@/lib/utils';
interface ScrollToTopProps {
/** The scroll container to watch and scroll back to top. */
scrollRef: React.RefObject<HTMLDivElement | null>;
/** Reveal the button once the container is scrolled past this many pixels. */
threshold?: number;
}
export function ScrollToTop({ scrollRef, threshold = 320 }: ScrollToTopProps) {
const { t } = useTranslation();
const [visible, setVisible] = useState(false);
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
const onScroll = () => setVisible(el.scrollTop > threshold);
onScroll();
el.addEventListener('scroll', onScroll, { passive: true });
return () => el.removeEventListener('scroll', onScroll);
}, [scrollRef, threshold]);
const handleClick = () => {
const el = scrollRef.current;
if (!el) return;
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
el.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
};
return (
<button
type="button"
onClick={handleClick}
aria-label={t('common.scroll_to_top')}
title={t('common.scroll_to_top')}
aria-hidden={!visible}
tabIndex={visible ? 0 : -1}
className={cn(
'absolute right-4 bottom-4 z-20 inline-flex h-10 w-10 items-center justify-center',
'border-border/60 bg-card/90 text-muted-foreground rounded-full border shadow-sm',
'hover:border-primary/40 hover:bg-card hover:text-foreground backdrop-blur-sm transition',
visible ? 'opacity-100' : 'pointer-events-none opacity-0',
)}
>
<ArrowUp className="h-4 w-4" />
</button>
);
}
+22
View File
@@ -0,0 +1,22 @@
interface ToolbarButtonProps {
onClick: () => void;
label: string;
icon: React.ReactNode;
disabled?: boolean;
}
export function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={label}
title={label}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
>
{icon}
<span className="hidden sm:inline">{label}</span>
</button>
);
}
@@ -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();
});
});
+114
View File
@@ -0,0 +1,114 @@
import { useTranslation } from 'react-i18next';
import { Loader2, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { formatBytes } from '@/lib/format-bytes';
import type { BatchItem } from '@/stores/batchStore';
interface BatchItemRowProps {
item: BatchItem;
outputExt: string;
onRemove: () => void;
disabled: boolean;
}
export function BatchItemRow({ item, outputExt, onRemove, disabled }: BatchItemRowProps) {
const { t } = useTranslation();
const Icon = statusIcon(item.status);
const tone = statusTone(item.status);
return (
<li className="flex items-start gap-2 py-2.5">
<Icon className={cn('mt-0.5 h-4 w-4 shrink-0', tone)} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-foreground truncate font-mono text-xs">{item.filename}</span>
<span className="text-muted-foreground/60 font-mono text-[10px]">→ .{outputExt}</span>
</div>
<div className="text-muted-foreground mt-0.5 flex items-center gap-2 font-mono text-[10px]">
<span>{formatBytes(item.size)}</span>
{item.outputSize !== undefined && (
<>
<span>·</span>
<span>
{t('batch.row.out')}: {formatBytes(item.outputSize)}
</span>
</>
)}
</div>
{item.error && (
<p className="text-destructive mt-1 font-mono text-[10px] break-words">{item.error}</p>
)}
</div>
<button
type="button"
onClick={onRemove}
disabled={disabled}
aria-label={t('batch.row.remove')}
className="text-muted-foreground hover:bg-muted hover:text-foreground rounded p-1 transition disabled:cursor-not-allowed disabled:opacity-40"
>
<Trash2 className="h-3 w-3" />
</button>
</li>
);
}
function statusIcon(status: BatchItem['status']) {
switch (status) {
case 'queued':
return CircleIcon;
case 'processing':
return ProcessingIcon;
case 'done':
return CheckIcon;
case 'error':
return ErrorIcon;
}
}
function statusTone(status: BatchItem['status']): string {
switch (status) {
case 'done':
return 'text-primary';
case 'error':
return 'text-destructive';
case 'processing':
return 'text-foreground';
case 'queued':
default:
return 'text-muted-foreground/60';
}
}
function CircleIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5" />
</svg>
);
}
function ProcessingIcon({ className }: { className?: string }) {
return <Loader2 className={cn(className, 'animate-spin')} />;
}
function CheckIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path
d="M3 8.5L6.5 12L13 5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
function ErrorIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
);
}
+22 -248
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useCallback, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import { Download, FileStack, FolderOpen, Loader2, Play, StopCircle, Trash2 } from 'lucide-react';
import { Download, FileStack, FolderOpen, Play, StopCircle, Trash2 } from 'lucide-react';
import {
Sheet,
SheetContent,
@@ -11,14 +11,16 @@ import {
SheetTrigger,
} from '@/components/ui/sheet';
import { toast } from '@/components/ui/sonner';
import { useBatchStore, BATCH_MAX_FILES, type BatchItem } from '@/stores/batchStore';
import { processBatch, zipOutputs, downloadBlob } from '@/lib/batch-processor';
import { filterByExtension, getAllowedExtensions } from '@/lib/file-filter';
import { isTauri, nativeOpenFiles, nativeSaveBlob, fileFromNativePath } from '@/lib/tauri';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { useBatchActions } from '@/hooks/useBatchActions';
import { useFileAccept } from '@/hooks/useFileAccept';
import { filterByExtension } from '@/lib/file-filter';
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
import { cn } from '@/lib/utils';
import { useBatchStore, BATCH_MAX_FILES } from '@/stores/batchStore';
import type { FormatId } from '@/converters/types';
import type { Direction } from './DirectionToggle';
import { BatchItemRow } from './BatchItemRow';
import { BatchSummaryChips } from './BatchSummaryChips';
interface BatchPanelProps {
format: FormatId;
@@ -26,8 +28,6 @@ interface BatchPanelProps {
options: Record<string, unknown>;
open: boolean;
onOpenChange: (open: boolean) => void;
/** Filenames added via this trigger button are also routed into the queue. */
onAddExternalFiles?: (files: File[]) => void;
}
export function BatchPanel({ format, direction, options, open, onOpenChange }: BatchPanelProps) {
@@ -38,9 +38,6 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
const addFiles = useBatchStore((s) => s.addFiles);
const removeItem = useBatchStore((s) => s.removeItem);
const clear = useBatchStore((s) => s.clear);
const setProcessing = useBatchStore((s) => s.setProcessing);
const setAbortController = useBatchStore((s) => s.setAbortController);
const updateItem = useBatchStore((s) => s.updateItem);
const resetStatuses = useBatchStore((s) => s.resetStatuses);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -50,29 +47,11 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
const errorCount = itemOrder.filter((id) => items[id]?.status === 'error').length;
const queuedCount = itemOrder.filter((id) => items[id]?.status === 'queued').length;
const isReverse = direction === 'reverse';
const converter = getConverter(format);
const accept = useMemo(() => {
if (isReverse) {
return {
[converter.meta.mimeType]: [`.${converter.meta.extension}`],
'text/plain': ['.txt'],
};
}
return { 'application/json': ['.json'], 'text/plain': ['.txt'] };
}, [isReverse, converter.meta.mimeType, converter.meta.extension]);
const fileInputAccept = isReverse
? `.${converter.meta.extension},.txt,${converter.meta.mimeType}`
: '.json,.txt,application/json';
// Whitelist of file extensions that match the current direction × format.
// The browser's native `<input accept>` is only a hint, so we re-validate
// in JS to reject files chosen via "Browse" with "All files" filter.
const allowedExtensions = useMemo(
() => getAllowedExtensions(isReverse ? 'reverse' : 'forward', converter.meta.extension),
[isReverse, converter.meta.extension],
const { converter, isReverse, accept, fileInputAccept, allowedExtensions } = useFileAccept(
format,
direction,
);
const { start, cancel, downloadZip } = useBatchActions(format, direction, options);
const handleAddFiles = useCallback(
(files: File[]) => {
@@ -124,78 +103,6 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
noKeyboard: true,
});
const handleStart = useCallback(async () => {
const queued = itemOrder
.map((id) => items[id])
.filter((it): it is BatchItem => !!it && it.status !== 'done' && it.status !== 'processing');
if (queued.length === 0) {
toast.info(t('batch.toast.nothing_to_process'));
return;
}
const controller = new AbortController();
setAbortController(controller);
setProcessing(true);
toast.success(t('batch.toast.started', { count: queued.length }));
try {
await processBatch(
queued,
format,
options,
{
onUpdate: (id, patch) => updateItem(id, patch),
},
controller.signal,
direction,
);
if (!controller.signal.aborted) {
toast.success(t('batch.toast.finished'));
}
} catch (err) {
toast.error(t('batch.toast.failed', { message: (err as Error).message }));
} finally {
setProcessing(false);
setAbortController(null);
}
}, [
direction,
format,
items,
itemOrder,
options,
setAbortController,
setProcessing,
t,
updateItem,
]);
const handleCancel = useCallback(() => {
useBatchStore.getState().abortController?.abort();
toast.info(t('batch.toast.cancelled'));
}, [t]);
const handleDownloadZip = useCallback(async () => {
const done = itemOrder.map((id) => items[id]).filter((it): it is BatchItem => !!it);
try {
const { blob, fileCount } = await zipOutputs(done, format, direction);
const ts = new Date().toISOString().slice(0, 10);
const filename = `jsonprism-batch-${ts}.zip`;
if (isTauri()) {
const saved = await nativeSaveBlob(blob, filename);
if (saved) {
toast.success(t('batch.toast.zipped', { count: fileCount }));
}
} else {
downloadBlob(blob, filename);
toast.success(t('batch.toast.zipped', { count: fileCount }));
}
} catch (err) {
toast.error(t('batch.toast.zip_failed', { message: (err as Error).message }));
}
}, [direction, format, items, itemOrder, t]);
const handleOpenFiles = async () => {
if (isTauri()) {
const paths = await nativeOpenFiles({ multiple: true });
@@ -296,13 +203,11 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
{/* Summary chips */}
{totalCount > 0 && (
<div className="text-muted-foreground flex flex-wrap items-center gap-2 px-6 pb-3 font-mono text-[11px]">
<Chip label={t('batch.stat.queued')} value={queuedCount} />
<Chip label={t('batch.stat.done')} value={doneCount} tone="ok" />
{errorCount > 0 && (
<Chip label={t('batch.stat.failed')} value={errorCount} tone="err" />
)}
</div>
<BatchSummaryChips
queuedCount={queuedCount}
doneCount={doneCount}
errorCount={errorCount}
/>
)}
{/* Queue list */}
@@ -346,7 +251,7 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
{processing ? (
<button
type="button"
onClick={handleCancel}
onClick={cancel}
className="bg-destructive/10 text-destructive hover:bg-destructive/20 inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition"
>
<StopCircle className="h-3.5 w-3.5" />
@@ -357,7 +262,7 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
type="button"
onClick={() => {
resetStatuses();
void handleStart();
void start();
}}
disabled={totalCount === 0}
className="bg-primary/15 text-primary hover:bg-primary/25 inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
@@ -369,7 +274,7 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
<button
type="button"
onClick={() => void handleDownloadZip()}
onClick={() => void downloadZip()}
disabled={doneCount === 0 || processing}
className="bg-foreground/90 text-background hover:bg-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
>
@@ -382,134 +287,3 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
</Sheet>
);
}
function Chip({ label, value, tone }: { label: string; value: number; tone?: 'ok' | 'err' }) {
return (
<span
className={cn(
'inline-flex items-center gap-1 rounded px-1.5 py-0.5',
tone === 'ok' && 'bg-primary/10 text-primary',
tone === 'err' && 'bg-destructive/10 text-destructive',
!tone && 'bg-muted/40',
)}
>
<span className="opacity-70">{label}:</span>
<span>{value}</span>
</span>
);
}
interface BatchItemRowProps {
item: BatchItem;
outputExt: string;
onRemove: () => void;
disabled: boolean;
}
function BatchItemRow({ item, outputExt, onRemove, disabled }: BatchItemRowProps) {
const { t } = useTranslation();
const Icon = statusIcon(item.status);
const tone = statusTone(item.status);
return (
<li className="flex items-start gap-2 py-2.5">
<Icon className={cn('mt-0.5 h-4 w-4 shrink-0', tone)} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-foreground truncate font-mono text-xs">{item.filename}</span>
<span className="text-muted-foreground/60 font-mono text-[10px]">→ .{outputExt}</span>
</div>
<div className="text-muted-foreground mt-0.5 flex items-center gap-2 font-mono text-[10px]">
<span>{formatBytes(item.size)}</span>
{item.outputSize !== undefined && (
<>
<span>·</span>
<span>
{t('batch.row.out')}: {formatBytes(item.outputSize)}
</span>
</>
)}
</div>
{item.error && (
<p className="text-destructive mt-1 font-mono text-[10px] break-words">{item.error}</p>
)}
</div>
<button
type="button"
onClick={onRemove}
disabled={disabled}
aria-label={t('batch.row.remove')}
className="text-muted-foreground hover:bg-muted hover:text-foreground rounded p-1 transition disabled:cursor-not-allowed disabled:opacity-40"
>
<Trash2 className="h-3 w-3" />
</button>
</li>
);
}
function statusIcon(status: BatchItem['status']) {
switch (status) {
case 'queued':
return CircleIcon;
case 'processing':
return ProcessingIcon;
case 'done':
return CheckIcon;
case 'error':
return ErrorIcon;
}
}
function statusTone(status: BatchItem['status']): string {
switch (status) {
case 'done':
return 'text-primary';
case 'error':
return 'text-destructive';
case 'processing':
return 'text-foreground';
case 'queued':
default:
return 'text-muted-foreground/60';
}
}
function CircleIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5" />
</svg>
);
}
function ProcessingIcon({ className }: { className?: string }) {
return <Loader2 className={cn(className, 'animate-spin')} />;
}
function CheckIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path
d="M3 8.5L6.5 12L13 5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
);
}
function ErrorIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
);
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
@@ -0,0 +1,35 @@
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
interface BatchSummaryChipsProps {
queuedCount: number;
doneCount: number;
errorCount: number;
}
export function BatchSummaryChips({ queuedCount, doneCount, errorCount }: BatchSummaryChipsProps) {
const { t } = useTranslation();
return (
<div className="text-muted-foreground flex flex-wrap items-center gap-2 px-6 pb-3 font-mono text-[11px]">
<Chip label={t('batch.stat.queued')} value={queuedCount} />
<Chip label={t('batch.stat.done')} value={doneCount} tone="ok" />
{errorCount > 0 && <Chip label={t('batch.stat.failed')} value={errorCount} tone="err" />}
</div>
);
}
function Chip({ label, value, tone }: { label: string; value: number; tone?: 'ok' | 'err' }) {
return (
<span
className={cn(
'inline-flex items-center gap-1 rounded px-1.5 py-0.5',
tone === 'ok' && 'bg-primary/10 text-primary',
tone === 'err' && 'bg-destructive/10 text-destructive',
!tone && 'bg-muted/40',
)}
>
<span className="opacity-70">{label}:</span>
<span>{value}</span>
</span>
);
}
+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>
);
}
+14 -122
View File
@@ -1,14 +1,13 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/components/ui/sonner';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useBatchFileRouter } from '@/hooks/useBatchFileRouter';
import { useConversionResult } from '@/hooks/useConversionResult';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useOutputBadge } from '@/hooks/useOutputBadge';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { parseJsonInput } from '@/lib/detect';
import { filterByExtension, getAllowedExtensions } from '@/lib/file-filter';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useTauriDragDrop } from '@/hooks/useTauriDragDrop';
import { useBatchStore } from '@/stores/batchStore';
import { useWorkspaceStore } from '@/stores/workspaceStore';
import { DirectionToggle, type Direction } from './DirectionToggle';
import { FormatPicker } from './FormatPicker';
@@ -39,40 +38,9 @@ export function ConverterWorkspace() {
const [settingsOpen, setSettingsOpen] = useState(false);
// Mobile tab state — desktop ignores this and renders both panels side-by-side.
const [activeTab, setActiveTab] = useState<'input' | 'output'>('input');
// Badge dot on Output tab when output changes while user is on Input tab.
const [hasUnreadOutput, setHasUnreadOutput] = useState(false);
const prevOutputRef = useRef('');
const addBatchFiles = useBatchStore((s) => s.addFiles);
const handleMultiFileDrop = useCallback(
(files: File[]) => {
const allowed = getAllowedExtensions(
direction === 'reverse' ? 'reverse' : 'forward',
getConverter(format).meta.extension,
);
const { valid, wrongFormat } = filterByExtension(files, allowed);
if (wrongFormat > 0) {
toast.warning(t('batch.toast.wrong_format', { count: wrongFormat }));
}
if (valid.length === 0) return;
const result = addBatchFiles(valid);
if (result.added > 0) {
toast.success(t('batch.toast.added', { count: result.added }));
setBatchOpen(true);
}
if (result.skipped > 0) {
if (result.reason === 'duplicate') {
toast.warning(t('batch.toast.duplicate', { count: result.skipped }));
} else {
toast.warning(t('batch.toast.skipped', { count: result.skipped, max: 500 }));
}
}
},
[addBatchFiles, direction, format, t],
);
// Native OS drag-drop bridge (no-op outside Tauri).
useTauriDragDrop(handleMultiFileDrop);
const openBatch = useCallback(() => setBatchOpen(true), []);
const handleMultiFileDrop = useBatchFileRouter(format, direction, openBatch);
const switchFormat = useCallback(
(next: FormatId) => {
@@ -109,75 +77,12 @@ export function ConverterWorkspace() {
toast.success(t('toast.options_reset'));
}, [format, resetOptionsForFormat, t]);
const { output, inputError, outputError, shape, parseMs } = useMemo(() => {
const start = performance.now();
if (!input.trim()) {
return { output: '', inputError: null, outputError: null, shape: null, parseMs: null };
}
const converter = getConverter(format);
if (!converter.meta.ready) {
return {
output: '',
inputError: null,
outputError: t('errors.converter_not_ready_phase', { phase: converter.meta.phase }),
shape: null,
parseMs: performance.now() - start,
};
}
if (direction === 'reverse') {
if (typeof converter.reverse !== 'function') {
return {
output: '',
inputError: null,
outputError: t('format_status.no_reverse'),
shape: null,
parseMs: performance.now() - start,
};
}
const result = converter.reverse(
{ text: input },
currentOptions as Parameters<typeof converter.reverse>[1],
);
const ms = performance.now() - start;
return result.ok
? { output: result.output, inputError: null, outputError: null, shape: null, parseMs: ms }
: { output: '', inputError: result.error, outputError: null, shape: null, parseMs: ms };
}
const parsed = parseJsonInput(input);
if (!parsed.ok) {
const msg = parsed.error === 'empty' ? null : parsed.error;
return {
output: '',
inputError: msg,
outputError: null,
shape: null,
parseMs: performance.now() - start,
};
}
const result = converter.convert(
{ data: parsed.value, rawText: input },
currentOptions as Parameters<typeof converter.convert>[1],
);
const ms = performance.now() - start;
if (result.ok) {
return {
output: result.output,
inputError: null,
outputError: null,
shape: parsed.shape,
parseMs: ms,
};
}
return {
output: '',
inputError: null,
outputError: result.error,
shape: parsed.shape,
parseMs: ms,
};
}, [input, format, currentOptions, direction, t]);
const { output, inputError, outputError, shape, parseMs } = useConversionResult(
input,
format,
direction,
currentOptions,
);
useKeyboardShortcuts([
{ key: 'k', mod: true, handler: () => setInput('') },
@@ -185,20 +90,7 @@ export function ConverterWorkspace() {
{ key: ',', mod: true, handler: () => setSettingsOpen((v) => !v) },
]);
// Flip the badge dot on the Output tab whenever output changes while the
// user is on the Input tab. Clearing happens once the user navigates over.
useEffect(() => {
if (output !== prevOutputRef.current) {
prevOutputRef.current = output;
if (output && activeTab !== 'output') {
setHasUnreadOutput(true);
}
}
}, [output, activeTab]);
useEffect(() => {
if (activeTab === 'output') setHasUnreadOutput(false);
}, [activeTab]);
const hasUnreadOutput = useOutputBadge(output, activeTab);
const inputBytes = useMemo(() => new TextEncoder().encode(input).length, [input]);
const outputBytes = useMemo(() => new TextEncoder().encode(output).length, [output]);
+15 -77
View File
@@ -1,14 +1,17 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import { Eraser, FileText, FolderOpen } from 'lucide-react';
import { ToolbarButton } from '@/components/common/ToolbarButton';
import { toast } from '@/components/ui/sonner';
import { extOf, getAllowedExtensions } from '@/lib/file-filter';
import { useFileAccept } from '@/hooks/useFileAccept';
import { editorLanguageFor } from '@/lib/editor-language';
import { extOf } from '@/lib/file-filter';
import { readFileText } from '@/lib/read-file';
import { SAMPLE_JSON } from '@/lib/sample';
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { CodeEditor, type EditorLanguage } from './CodeEditor';
import { CodeEditorLazy } from './CodeEditorLazy';
import type { Direction } from './DirectionToggle';
interface InputPanelProps {
@@ -35,49 +38,16 @@ export function InputPanel({
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragActive, setDragActive] = useState(false);
const isReverse = direction === 'reverse';
const converter = getConverter(format);
// In reverse mode the dropzone + file picker accept the format's native
// extension; in forward mode JSON is the only useful input.
const accept = useMemo(() => {
if (isReverse) {
const ext = converter.meta.extension;
return {
[converter.meta.mimeType]: [`.${ext}`],
'text/plain': ['.txt'],
};
}
return { 'application/json': ['.json'], 'text/plain': ['.txt'] };
}, [isReverse, converter.meta.mimeType, converter.meta.extension]);
const fileInputAccept = isReverse
? `.${converter.meta.extension},.txt,${converter.meta.mimeType}`
: '.json,.txt,application/json';
const { converter, isReverse, accept, fileInputAccept, allowedExtensions } = useFileAccept(
format,
direction,
);
const inputLabel = isReverse
? t('home.input_label_format', { format: t(converter.meta.labelKey) })
: t('home.input_label');
// CodeMirror language pack to use for the input. In forward mode the input
// is always JSON. In reverse, pick the closest available pack — formats
// without an official CodeMirror grammar fall back to plain text.
const editorLanguage: EditorLanguage = useMemo(() => {
if (!isReverse) return 'json';
if (format === 'yaml') return 'yaml';
if (format === 'xml' || format === 'resx') return 'xml';
if (format === 'jsonl') return 'json';
if (format === 'markdown') return 'markdown';
if (format === 'sql') return 'sql';
if (format === 'toml') return 'toml';
return 'plain';
}, [isReverse, format]);
// Allowed extensions for the single-file "Open" / drag-drop path.
// `<input accept>` is only a hint to the OS picker — re-validate in JS.
const allowedExtensions = useMemo(
() => getAllowedExtensions(isReverse ? 'reverse' : 'forward', converter.meta.extension),
[isReverse, converter.meta.extension],
);
const editorLanguage = editorLanguageFor(format, direction);
const hasAllowedExt = useCallback(
(name: string) => allowedExtensions.includes(extOf(name)),
@@ -97,7 +67,7 @@ export function InputPanel({
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
return;
}
void readFile(file).then(
void readFileText(file).then(
(text) => {
onChange(text);
toast.success(t('toast.file_loaded', { name: file.name }));
@@ -159,7 +129,7 @@ export function InputPanel({
e.target.value = '';
return;
}
void readFile(file).then(
void readFileText(file).then(
(text) => {
onChange(text);
toast.success(t('toast.file_loaded', { name: file.name }));
@@ -218,7 +188,7 @@ export function InputPanel({
</div>
<div className="relative min-h-0 flex-1">
<CodeEditor
<CodeEditorLazy
value={value}
onChange={onChange}
language={editorLanguage}
@@ -244,35 +214,3 @@ export function InputPanel({
</div>
);
}
async function readFile(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result ?? ''));
reader.onerror = () => reject(new Error(`Cannot read file: ${file.name}`));
reader.readAsText(file);
});
}
interface ToolbarButtonProps {
onClick: () => void;
label: string;
icon: React.ReactNode;
disabled?: boolean;
}
function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={label}
title={label}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
>
{icon}
<span className="hidden sm:inline">{label}</span>
</button>
);
}
+2 -24
View File
@@ -2,9 +2,10 @@ import { useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Copy, Download } from 'lucide-react';
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 {
@@ -120,26 +121,3 @@ export function OutputPanel({
</div>
);
}
interface ToolbarButtonProps {
onClick: () => void;
label: string;
icon: React.ReactNode;
disabled?: boolean;
}
function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
aria-label={label}
title={label}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
>
{icon}
<span className="hidden sm:inline">{label}</span>
</button>
);
}
+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);
});
});
+95
View File
@@ -0,0 +1,95 @@
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/components/ui/sonner';
import type { Direction } from '@/components/converter/DirectionToggle';
import type { FormatId } from '@/converters/types';
import { downloadBlob, processBatch, zipOutputs } from '@/lib/batch-processor';
import { isTauri, nativeSaveBlob } from '@/lib/tauri';
import { useBatchStore, type BatchItem } from '@/stores/batchStore';
export function useBatchActions(
format: FormatId,
direction: Direction,
options: Record<string, unknown>,
) {
const { t } = useTranslation();
const items = useBatchStore((s) => s.items);
const itemOrder = useBatchStore((s) => s.itemOrder);
const setProcessing = useBatchStore((s) => s.setProcessing);
const setAbortController = useBatchStore((s) => s.setAbortController);
const updateItem = useBatchStore((s) => s.updateItem);
const start = useCallback(async () => {
const queued = itemOrder
.map((id) => items[id])
.filter((it): it is BatchItem => !!it && it.status !== 'done' && it.status !== 'processing');
if (queued.length === 0) {
toast.info(t('batch.toast.nothing_to_process'));
return;
}
const controller = new AbortController();
setAbortController(controller);
setProcessing(true);
toast.success(t('batch.toast.started', { count: queued.length }));
try {
await processBatch(
queued,
format,
options,
{
onUpdate: (id, patch) => updateItem(id, patch),
},
controller.signal,
direction,
);
if (!controller.signal.aborted) {
toast.success(t('batch.toast.finished'));
}
} catch (err) {
toast.error(t('batch.toast.failed', { message: (err as Error).message }));
} finally {
setProcessing(false);
setAbortController(null);
}
}, [
direction,
format,
items,
itemOrder,
options,
setAbortController,
setProcessing,
t,
updateItem,
]);
const cancel = useCallback(() => {
useBatchStore.getState().abortController?.abort();
toast.info(t('batch.toast.cancelled'));
}, [t]);
const downloadZip = useCallback(async () => {
const done = itemOrder.map((id) => items[id]).filter((it): it is BatchItem => !!it);
try {
const { blob, fileCount } = await zipOutputs(done, format, direction);
const ts = new Date().toISOString().slice(0, 10);
const filename = `jsonprism-batch-${ts}.zip`;
if (isTauri()) {
const saved = await nativeSaveBlob(blob, filename);
if (saved) {
toast.success(t('batch.toast.zipped', { count: fileCount }));
}
} else {
downloadBlob(blob, filename);
toast.success(t('batch.toast.zipped', { count: fileCount }));
}
} catch (err) {
toast.error(t('batch.toast.zip_failed', { message: (err as Error).message }));
}
}, [direction, format, items, itemOrder, t]);
return { start, cancel, downloadZip };
}
+52
View File
@@ -0,0 +1,52 @@
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/components/ui/sonner';
import type { Direction } from '@/components/converter/DirectionToggle';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { filterByExtension, getAllowedExtensions } from '@/lib/file-filter';
import { useTauriDragDrop } from '@/hooks/useTauriDragDrop';
import { useBatchStore } from '@/stores/batchStore';
// Routes a multi-file drop into the batch queue (with format filtering and
// toasts) and wires the native Tauri drag-drop bridge to the same handler.
export function useBatchFileRouter(
format: FormatId,
direction: Direction,
onFilesAdded?: () => void,
): (files: File[]) => void {
const { t } = useTranslation();
const addBatchFiles = useBatchStore((s) => s.addFiles);
const handleMultiFileDrop = useCallback(
(files: File[]) => {
const allowed = getAllowedExtensions(
direction === 'reverse' ? 'reverse' : 'forward',
getConverter(format).meta.extension,
);
const { valid, wrongFormat } = filterByExtension(files, allowed);
if (wrongFormat > 0) {
toast.warning(t('batch.toast.wrong_format', { count: wrongFormat }));
}
if (valid.length === 0) return;
const result = addBatchFiles(valid);
if (result.added > 0) {
toast.success(t('batch.toast.added', { count: result.added }));
onFilesAdded?.();
}
if (result.skipped > 0) {
if (result.reason === 'duplicate') {
toast.warning(t('batch.toast.duplicate', { count: result.skipped }));
} else {
toast.warning(t('batch.toast.skipped', { count: result.skipped, max: 500 }));
}
}
},
[addBatchFiles, direction, format, t, onFilesAdded],
);
// Native OS drag-drop bridge (no-op outside Tauri).
useTauriDragDrop(handleMultiFileDrop);
return handleMultiFileDrop;
}
+85
View File
@@ -0,0 +1,85 @@
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import type { Direction } from '@/components/converter/DirectionToggle';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { parseJsonInput } from '@/lib/detect';
export function useConversionResult(
input: string,
format: FormatId,
direction: Direction,
options: Record<string, unknown>,
) {
const { t } = useTranslation();
return useMemo(() => {
const start = performance.now();
if (!input.trim()) {
return { output: '', inputError: null, outputError: null, shape: null, parseMs: null };
}
const converter = getConverter(format);
if (!converter.meta.ready) {
return {
output: '',
inputError: null,
outputError: t('errors.converter_not_ready_phase', { phase: converter.meta.phase }),
shape: null,
parseMs: performance.now() - start,
};
}
if (direction === 'reverse') {
if (typeof converter.reverse !== 'function') {
return {
output: '',
inputError: null,
outputError: t('format_status.no_reverse'),
shape: null,
parseMs: performance.now() - start,
};
}
const result = converter.reverse(
{ text: input },
options as Parameters<typeof converter.reverse>[1],
);
const ms = performance.now() - start;
return result.ok
? { output: result.output, inputError: null, outputError: null, shape: null, parseMs: ms }
: { output: '', inputError: result.error, outputError: null, shape: null, parseMs: ms };
}
const parsed = parseJsonInput(input);
if (!parsed.ok) {
const msg = parsed.error === 'empty' ? null : parsed.error;
return {
output: '',
inputError: msg,
outputError: null,
shape: null,
parseMs: performance.now() - start,
};
}
const result = converter.convert(
{ data: parsed.value, rawText: input },
options as Parameters<typeof converter.convert>[1],
);
const ms = performance.now() - start;
if (result.ok) {
return {
output: result.output,
inputError: null,
outputError: null,
shape: parsed.shape,
parseMs: ms,
};
}
return {
output: '',
inputError: null,
outputError: result.error,
shape: parsed.shape,
parseMs: ms,
};
}, [input, format, options, direction, t]);
}
+42
View File
@@ -0,0 +1,42 @@
import { useMemo } from 'react';
import type { Direction } from '@/components/converter/DirectionToggle';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { getAllowedExtensions } from '@/lib/file-filter';
export interface FileAccept {
converter: ReturnType<typeof getConverter>;
isReverse: boolean;
/** react-dropzone `accept` map: MIME type → extensions. */
accept: Record<string, string[]>;
/** Native `<input accept>` hint string. */
fileInputAccept: string;
/** Whitelist for JS-side re-validation — `<input accept>` is only a hint. */
allowedExtensions: string[];
}
export function useFileAccept(format: FormatId, direction: Direction): FileAccept {
const isReverse = direction === 'reverse';
const converter = getConverter(format);
const accept = useMemo<Record<string, string[]>>(() => {
if (isReverse) {
return {
[converter.meta.mimeType]: [`.${converter.meta.extension}`],
'text/plain': ['.txt'],
};
}
return { 'application/json': ['.json'], 'text/plain': ['.txt'] };
}, [isReverse, converter.meta.mimeType, converter.meta.extension]);
const fileInputAccept = isReverse
? `.${converter.meta.extension},.txt,${converter.meta.mimeType}`
: '.json,.txt,application/json';
const allowedExtensions = useMemo(
() => getAllowedExtensions(isReverse ? 'reverse' : 'forward', converter.meta.extension),
[isReverse, converter.meta.extension],
);
return { converter, isReverse, accept, fileInputAccept, allowedExtensions };
}
-58
View File
@@ -1,58 +0,0 @@
import { useCallback, useEffect, useState } from 'react';
/**
* React hook for persistent state in localStorage.
* Survives reload; synced across tabs via `storage` event.
*/
export function useLocalStorage<T>(
key: string,
initialValue: T,
): [T, (value: T | ((prev: T) => T)) => void] {
const read = useCallback((): T => {
if (typeof window === 'undefined') return initialValue;
try {
const raw = window.localStorage.getItem(key);
if (raw === null) return initialValue;
return JSON.parse(raw) as T;
} catch {
return initialValue;
}
}, [key, initialValue]);
const [stored, setStored] = useState<T>(read);
const setValue = useCallback(
(value: T | ((prev: T) => T)) => {
setStored((prev) => {
const next = typeof value === 'function' ? (value as (p: T) => T)(prev) : value;
try {
window.localStorage.setItem(key, JSON.stringify(next));
} catch {
/* quota errors are non-fatal */
}
return next;
});
},
[key],
);
// Cross-tab sync
useEffect(() => {
const handler = (e: StorageEvent) => {
if (e.key !== key) return;
if (e.newValue === null) {
setStored(initialValue);
return;
}
try {
setStored(JSON.parse(e.newValue) as T);
} catch {
/* ignore malformed */
}
};
window.addEventListener('storage', handler);
return () => window.removeEventListener('storage', handler);
}, [key, initialValue]);
return [stored, setValue];
}
+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;
}
+23
View File
@@ -0,0 +1,23 @@
import { useEffect, useRef, useState } from 'react';
// Tracks an "unread output" badge for the mobile Output tab: set when output
// changes while the user is on a different tab, cleared once they navigate over.
export function useOutputBadge(output: string, activeTab: 'input' | 'output'): boolean {
const [hasUnreadOutput, setHasUnreadOutput] = useState(false);
const prevOutputRef = useRef('');
useEffect(() => {
if (output !== prevOutputRef.current) {
prevOutputRef.current = output;
if (output && activeTab !== 'output') {
setHasUnreadOutput(true);
}
}
}, [output, activeTab]);
useEffect(() => {
if (activeTab === 'output') setHasUnreadOutput(false);
}, [activeTab]);
return hasUnreadOutput;
}
-2
View File
@@ -26,5 +26,3 @@ void i18n
lookupLocalStorage: 'jsonprism.lang',
},
});
export default i18n;
+49 -1
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.",
@@ -291,7 +326,20 @@
"common": {
"loading": "Loading…",
"error": "Error",
"retry": "Retry"
"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."
+2 -1
View File
@@ -291,7 +291,8 @@
"common": {
"loading": "読み込み中…",
"error": "エラー",
"retry": "再試行"
"retry": "再試行",
"scroll_to_top": "トップへ戻る"
},
"disclaimer": {
"translation": "このページの翻訳は AI 生成です。100% の正確性は保証されません。"
+49 -1
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.",
@@ -291,7 +326,20 @@
"common": {
"loading": "Đang tải…",
"error": "Lỗi",
"retry": "Thử lại"
"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%."
+2 -1
View File
@@ -291,7 +291,8 @@
"common": {
"loading": "加载中…",
"error": "错误",
"retry": "重试"
"retry": "重试",
"scroll_to_top": "回到顶部"
},
"disclaimer": {
"translation": "本页面译文由 AI 生成,不保证 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;
}
+17
View File
@@ -0,0 +1,17 @@
import type { EditorLanguage } from '@/components/converter/CodeEditor';
import type { Direction } from '@/components/converter/DirectionToggle';
import type { FormatId } from '@/converters/types';
// CodeMirror language pack for the input editor. Forward mode is always JSON.
// In reverse mode, pick the closest available pack — formats without an
// official CodeMirror grammar fall back to plain text.
export function editorLanguageFor(format: FormatId, direction: Direction): EditorLanguage {
if (direction !== 'reverse') return 'json';
if (format === 'yaml') return 'yaml';
if (format === 'xml' || format === 'resx') return 'xml';
if (format === 'jsonl') return 'json';
if (format === 'markdown') return 'markdown';
if (format === 'sql') return 'sql';
if (format === 'toml') return 'toml';
return 'plain';
}
+5
View File
@@ -0,0 +1,5 @@
export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
+8
View File
@@ -0,0 +1,8 @@
export function readFileText(file: File): Promise<string> {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result ?? ''));
reader.onerror = () => reject(new Error(`Cannot read file: ${file.name}`));
reader.readAsText(file);
});
}
+2 -1
View File
@@ -62,7 +62,7 @@ export async function nativeSaveBlob(blob: Blob, suggestedName: string): Promise
/**
* Read a file at the given native path as a UTF-8 string.
*/
export async function nativeReadText(path: string): Promise<string> {
async function nativeReadText(path: string): Promise<string> {
if (!isTauri()) {
throw new Error('nativeReadText is only available inside Tauri.');
}
@@ -131,6 +131,7 @@ export async function fileFromNativePath(path: string): Promise<File> {
/**
* Diagnostic info from the Rust side (OS, arch, app version).
* Not currently shown in the UI but useful for bug reports.
* @public
*/
export async function tauriHostInfo(): Promise<{
os: string;
+155 -148
View File
@@ -1,5 +1,7 @@
import { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { ExternalLink, Heart, Users } from 'lucide-react';
import { ScrollToTop } from '@/components/common/ScrollToTop';
import {
BlueskyIcon,
DiscordIcon,
@@ -135,170 +137,175 @@ const DEPS: DepCategory[] = [
export function About() {
const { t } = useTranslation();
const scrollRef = useRef<HTMLDivElement>(null);
return (
// Layout's <main> is `flex flex-1 min-h-0 flex-col` (height-bounded). The
// About page has many sections, so it needs its own scroll container —
// otherwise content overflows past the Footer at the bottom.
<div className="scrollbar-hide min-h-0 flex-1 overflow-y-auto">
<div className="mx-auto max-w-3xl px-4 py-10 sm:px-6 sm:py-16">
<h1 className="font-display text-spectrum mb-4 text-5xl tracking-tight italic">
{t('about.title')}
</h1>
<p className="font-display text-foreground/90 mb-8 text-2xl italic">{t('about.lead')}</p>
<div className="text-muted-foreground space-y-4 text-sm leading-relaxed">
<p>{t('about.p1')}</p>
<p>{t('about.p2')}</p>
</div>
{/* Donate */}
<section className="mt-14">
<h2 className="font-display mb-1 text-2xl tracking-tight">
<Heart className="mr-2 inline-block h-5 w-5 text-rose-400" />
{t('about.donate.title')}
</h2>
<p className="text-muted-foreground mb-4 text-sm">{t('about.donate.lead')}</p>
<ul className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
{DONATE.map((platform) => (
<li key={platform.key}>
<a
href={platform.url}
target="_blank"
rel="noreferrer"
className={cn(
'border-border/60 bg-card/40 hover:border-primary/40 hover:bg-card/80 inline-flex w-full items-center justify-between rounded-md border px-3 py-2 text-sm transition',
)}
>
<span className="text-foreground font-medium">
{t(`about.donate.${platform.key}`)}
</span>
<ExternalLink className="text-muted-foreground h-3.5 w-3.5" />
</a>
</li>
))}
</ul>
</section>
{/* Community */}
<section className="mt-14">
<h2 className="font-display mb-1 text-2xl tracking-tight">
<Users className="text-primary mr-2 inline-block h-5 w-5" />
{t('about.community.title')}
</h2>
<p className="text-muted-foreground mb-4 text-sm">{t('about.community.lead')}</p>
<ul className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
{COMMUNITY.map((platform) => (
<li key={platform.key}>
<a
href={platform.url}
target="_blank"
rel="noreferrer"
className={cn(
'border-border/60 bg-card/40 hover:border-primary/40 hover:bg-card/80 inline-flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm transition',
)}
>
<span className="text-muted-foreground inline-flex items-center gap-2">
{platform.icon}
<span className="text-foreground font-medium">
{t(`about.community.${platform.key}`)}
</span>
</span>
<ExternalLink className="text-muted-foreground h-3.5 w-3.5" />
</a>
</li>
))}
</ul>
</section>
{/* Third-party */}
<section className="mt-14">
<h2 className="font-display mb-1 text-2xl tracking-tight">
{t('about.third_party.title')}
</h2>
<p className="text-muted-foreground mb-4 text-sm">{t('about.third_party.lead')}</p>
<div className="space-y-4">
{DEPS.map((cat) => (
<div key={cat.key}>
<h3 className="text-foreground/80 mb-1 text-xs font-medium tracking-wider uppercase">
{t(`about.third_party.${cat.key}`)}
</h3>
<ul className="flex flex-wrap gap-1.5">
{cat.deps.map((dep) => (
<li key={dep.name}>
<a
href={dep.url}
target="_blank"
rel="noreferrer"
className="border-border/60 bg-card/40 hover:border-primary/40 hover:text-foreground text-muted-foreground inline-flex items-center gap-1 rounded border px-2 py-0.5 font-mono text-xs transition"
>
{dep.name}
</a>
</li>
))}
</ul>
</div>
))}
// otherwise content overflows past the Footer. The relative wrapper anchors
// the floating scroll-to-top button above the Footer.
<div className="relative flex min-h-0 flex-1 flex-col">
<div ref={scrollRef} className="scrollbar-hide min-h-0 flex-1 overflow-y-auto">
<div className="mx-auto max-w-3xl px-4 py-10 sm:px-6 sm:py-16">
<h1 className="font-display text-spectrum mb-4 text-5xl tracking-tight italic">
{t('about.title')}
</h1>
<p className="font-display text-foreground/90 mb-8 text-2xl italic">{t('about.lead')}</p>
<div className="text-muted-foreground space-y-4 text-sm leading-relaxed">
<p>{t('about.p1')}</p>
<p>{t('about.p2')}</p>
</div>
<p className="mt-4 text-sm">
<a
href={`${REPO_URL}/blob/main/THIRD-PARTY.md`}
target="_blank"
rel="noreferrer"
className="text-primary hover:underline"
>
{t('about.third_party.see_full_list')}
</a>
</p>
</section>
{/* Build info */}
<section className="mt-14">
<h2 className="font-display mb-3 text-2xl tracking-tight">{t('about.build.title')}</h2>
<dl className="border-border/60 grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 border-t pt-4 font-mono text-sm">
<dt className="text-muted-foreground">{t('about.build.version')}</dt>
<dd className="text-foreground">{__APP_VERSION__}</dd>
<dt className="text-muted-foreground">{t('about.build.commit')}</dt>
<dd className="text-foreground">
{/* Donate */}
<section className="mt-14">
<h2 className="font-display mb-1 text-2xl tracking-tight">
<Heart className="mr-2 inline-block h-5 w-5 text-rose-400" />
{t('about.donate.title')}
</h2>
<p className="text-muted-foreground mb-4 text-sm">{t('about.donate.lead')}</p>
<ul className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
{DONATE.map((platform) => (
<li key={platform.key}>
<a
href={platform.url}
target="_blank"
rel="noreferrer"
className={cn(
'border-border/60 bg-card/40 hover:border-primary/40 hover:bg-card/80 inline-flex w-full items-center justify-between rounded-md border px-3 py-2 text-sm transition',
)}
>
<span className="text-foreground font-medium">
{t(`about.donate.${platform.key}`)}
</span>
<ExternalLink className="text-muted-foreground h-3.5 w-3.5" />
</a>
</li>
))}
</ul>
</section>
{/* Community */}
<section className="mt-14">
<h2 className="font-display mb-1 text-2xl tracking-tight">
<Users className="text-primary mr-2 inline-block h-5 w-5" />
{t('about.community.title')}
</h2>
<p className="text-muted-foreground mb-4 text-sm">{t('about.community.lead')}</p>
<ul className="grid grid-cols-1 gap-2 sm:grid-cols-2 lg:grid-cols-3">
{COMMUNITY.map((platform) => (
<li key={platform.key}>
<a
href={platform.url}
target="_blank"
rel="noreferrer"
className={cn(
'border-border/60 bg-card/40 hover:border-primary/40 hover:bg-card/80 inline-flex w-full items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm transition',
)}
>
<span className="text-muted-foreground inline-flex items-center gap-2">
{platform.icon}
<span className="text-foreground font-medium">
{t(`about.community.${platform.key}`)}
</span>
</span>
<ExternalLink className="text-muted-foreground h-3.5 w-3.5" />
</a>
</li>
))}
</ul>
</section>
{/* Third-party */}
<section className="mt-14">
<h2 className="font-display mb-1 text-2xl tracking-tight">
{t('about.third_party.title')}
</h2>
<p className="text-muted-foreground mb-4 text-sm">{t('about.third_party.lead')}</p>
<div className="space-y-4">
{DEPS.map((cat) => (
<div key={cat.key}>
<h3 className="text-foreground/80 mb-1 text-xs font-medium tracking-wider uppercase">
{t(`about.third_party.${cat.key}`)}
</h3>
<ul className="flex flex-wrap gap-1.5">
{cat.deps.map((dep) => (
<li key={dep.name}>
<a
href={dep.url}
target="_blank"
rel="noreferrer"
className="border-border/60 bg-card/40 hover:border-primary/40 hover:text-foreground text-muted-foreground inline-flex items-center gap-1 rounded border px-2 py-0.5 font-mono text-xs transition"
>
{dep.name}
</a>
</li>
))}
</ul>
</div>
))}
</div>
<p className="mt-4 text-sm">
<a
href={`${REPO_URL}/commit/${__APP_COMMIT__}`}
href={`${REPO_URL}/blob/main/THIRD-PARTY.md`}
target="_blank"
rel="noreferrer"
className="hover:underline"
className="text-primary hover:underline"
>
{__APP_COMMIT__}
{t('about.third_party.see_full_list')}
</a>
</dd>
<dt className="text-muted-foreground">{t('about.build.date')}</dt>
<dd className="text-foreground">{__APP_BUILD_DATE__}</dd>
</dl>
</section>
</p>
</section>
{/* Links */}
<section className="mt-14">
<h2 className="font-display mb-3 text-2xl tracking-tight">{t('about.links.title')}</h2>
<ul className="grid grid-cols-1 gap-1 text-sm sm:grid-cols-2">
<LinkRow href={REPO_URL} label={t('about.links.repo')} />
<LinkRow href={`${REPO_URL}/issues`} label={t('about.links.issues')} />
<LinkRow href={`${REPO_URL}/discussions`} label={t('about.links.discussions')} />
<LinkRow href="https://poli0981.github.io/jsonPrism/" label={t('about.links.demo')} />
<LinkRow href={`${REPO_URL}/blob/main/LICENSE`} label={t('about.links.license')} />
</ul>
</section>
{/* Build info */}
<section className="mt-14">
<h2 className="font-display mb-3 text-2xl tracking-tight">{t('about.build.title')}</h2>
<dl className="border-border/60 grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 border-t pt-4 font-mono text-sm">
<dt className="text-muted-foreground">{t('about.build.version')}</dt>
<dd className="text-foreground">{__APP_VERSION__}</dd>
<dt className="text-muted-foreground">{t('about.build.commit')}</dt>
<dd className="text-foreground">
<a
href={`${REPO_URL}/commit/${__APP_COMMIT__}`}
target="_blank"
rel="noreferrer"
className="hover:underline"
>
{__APP_COMMIT__}
</a>
</dd>
<dt className="text-muted-foreground">{t('about.build.date')}</dt>
<dd className="text-foreground">{__APP_BUILD_DATE__}</dd>
</dl>
</section>
{/* Disclaimer */}
<section className="mt-14">
<h2 className="font-display mb-2 text-xl tracking-tight">
{t('about.disclaimer.title')}
</h2>
<p className="text-muted-foreground text-sm leading-relaxed">
{t('about.disclaimer.body')}
</p>
</section>
{/* Links */}
<section className="mt-14">
<h2 className="font-display mb-3 text-2xl tracking-tight">{t('about.links.title')}</h2>
<ul className="grid grid-cols-1 gap-1 text-sm sm:grid-cols-2">
<LinkRow href={REPO_URL} label={t('about.links.repo')} />
<LinkRow href={`${REPO_URL}/issues`} label={t('about.links.issues')} />
<LinkRow href={`${REPO_URL}/discussions`} label={t('about.links.discussions')} />
<LinkRow href="https://poli0981.github.io/jsonPrism/" label={t('about.links.demo')} />
<LinkRow href={`${REPO_URL}/blob/main/LICENSE`} label={t('about.links.license')} />
</ul>
</section>
<div className="border-border/60 text-muted-foreground mt-12 border-t pt-6 font-mono text-xs">
{t('about.version', { version: __APP_VERSION__ })}
{/* Disclaimer */}
<section className="mt-14">
<h2 className="font-display mb-2 text-xl tracking-tight">
{t('about.disclaimer.title')}
</h2>
<p className="text-muted-foreground text-sm leading-relaxed">
{t('about.disclaimer.body')}
</p>
</section>
<div className="border-border/60 text-muted-foreground mt-12 border-t pt-6 font-mono text-xs">
{t('about.version', { version: __APP_VERSION__ })}
</div>
</div>
</div>
<ScrollToTop scrollRef={scrollRef} />
</div>
);
}
+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 });
},
}));
+12
View File
@@ -198,4 +198,16 @@
)
1;
}
/* Expand the Sonner close-button hit-test radius for touch.
Visible size stays at sonner's 20px default; the ::after pseudo
gives an effective ~36–40px tap target without changing layout. */
[data-sonner-toaster] [data-close-button] {
touch-action: manipulation;
}
[data-sonner-toaster] [data-close-button]::after {
content: '';
position: absolute;
inset: -8px;
}
}
+53 -27
View File
@@ -49,38 +49,64 @@ export default defineConfig(({ mode }) => ({
build: {
target: 'es2022',
sourcemap: !isTauriContext,
// Source maps would expose full original source on the public GH Pages
// deploy (the whole dist/ is uploaded), and nothing consumes them
// (PRIVACY.md: no remote error reporting). Emit them only for local,
// non-production web builds; never for the prod web deploy or Tauri.
sourcemap: !isTauriContext && mode !== 'production',
// Vite 8 uses Rolldown + Oxc minifier by default; legacy `esbuild` requires
// installing esbuild separately.
minify: 'oxc',
rollupOptions: {
output: {
// Vite 8 / Rolldown only accepts the function form here.
manualChunks(id) {
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';
}
if (id.includes('fflate')) return 'fflate';
return undefined;
// Rolldown deprecates the `manualChunks` function form — its optimizer
// silently merges small manual chunks back together (it folded a
// `@codemirror/view` split straight back into `cm-core`).
// `advancedChunks.groups` are explicit, honored boundaries; higher
// `priority` wins when a module matches several groups.
//
// CodeMirror gotcha: a group captures its matched modules AND their deps
// recursively, so the leaf groups (`cm-kit`, `cm-langs`) would otherwise
// drag the shared core (view/state/language) in with them — that ballooned
// `cm-langs` to ~600 kB. Fix: give `cm-core` the highest cm priority so it
// claims the shared modules first, scope each cm test so it can't match
// another's packages, and put a `maxSize` on `cm-core` so Rolldown peels
// the heavy `@codemirror/view` engine into its own file. Net: every chunk
// stays under the 500 kB warning, the pieces still load together behind
// the editor's lazy boundary (same total bytes), and a stale deploy
// re-downloads only the part that moved.
advancedChunks: {
groups: [
// React core (react, react-dom, scheduler) — `[\\/]react[\\/]`
// excludes react-router / react-i18next / @uiw/react-codemirror.
{ name: 'react', priority: 100, test: /[\\/](?:react-dom|react|scheduler)[\\/]/ },
{ name: 'router', priority: 95, test: /react-router/ },
{ name: 'i18n', priority: 95, test: /i18next/ },
// `@codemirror/view` is the ~370 kB DOM/render engine — the single
// heaviest module and the reason the old `cm-core` tripped 500 kB.
// Pin it (highest cm priority) so nothing drags it elsewhere.
{ name: 'cm-view', priority: 93, test: /@codemirror[\\/]view[\\/]/ },
// The rest of the core: state + language + lezer + the @uiw wrapper
// (whose recursive deps also pull in autocomplete/commands/search/lint).
// Outranks cm-langs so the lang packs' dep capture can't steal it.
{
name: 'cm-core',
priority: 92,
test: /@codemirror[\\/](?:state|language|theme-|autocomplete|commands|search|lint)|@lezer[\\/]|@uiw[\\/]react-codemirror/,
},
{ name: 'cm-langs', priority: 90, test: /@codemirror[\\/](?:lang-|legacy-modes)/ },
// One chunk per parser library.
{ name: 'p-yaml', priority: 70, test: /js-yaml/ },
{ name: 'p-csv', priority: 70, test: /papaparse/ },
{ name: 'p-xml', priority: 70, test: /fast-xml-parser/ },
{ name: 'p-toml', priority: 70, test: /smol-toml/ },
{ name: 'p-bson', priority: 70, test: /node_modules[\\/]bson[\\/]/ },
{ name: 'p-cbor', priority: 70, test: /node_modules[\\/]cbor-x[\\/]/ },
{ name: 'p-msgpack', priority: 70, test: /node_modules[\\/]@msgpack[\\/]/ },
{ name: 'fflate', priority: 70, test: /fflate/ },
// Radix primitives + icon set.
{ name: 'ui', priority: 60, test: /(?:@radix-ui|lucide-react)/ },
],
},
},
},