13 Commits
Author SHA1 Message Date
poli0981andClaude Opus 5.5 9923c4ce17 chore: 2.2.1 — maintenance mode, Qodana and dependency refresh (#192)
The last release before JSONPrism moves to maintenance mode.

- Dependencies at their latest releases, superseding Dependabot
  #183-#191. i18next 27.1.3, react-i18next 18.0.2 and jsdom 31.0.1 are
  majors; cargo update within semver (wry 0.57.2, tauri-plugin-opener
  2.7.3); sonarqube-scan-action 8.5.0 and setup-java 6.3.0.
  THIRD-PARTY.md is re-synced with both lockfiles.
- Qodana: a new workflow runs Qodana for JS (native mode) and Qodana for
  Rust (EAP, Docker, as root with a bootstrap for the C toolchain and
  GTK/WebKit headers). Both report to Qodana Cloud.
- Qodana findings, all fixed or documented:
  - React types are imported instead of read from the UMD global.
  - XMLBuilder comes from fast-xml-builder; XMLValidator stays, with a
    documented suppression.
  - act() calls in tests are synchronous.
  - The Range geometry test stub is shared.
  - Small regex and boolean cleanups.
  - Two false positives are excluded with their reasons: a secret
    reference, and serde_json, which tauri::generate_context!() needs.
- Maintenance mode:
  - status badge and section in both READMEs;
  - the policy in CONTRIBUTING;
  - converter and translation issue templates;
  - a Scope checklist in the PR template;
  - ROADMAP Phase 11;
  - maintenance-triage.yml closes out-of-scope feature requests with a
    bilingual comment;
  - a Dependabot group for the two fast-xml packages.
- Release 2.2.1: versionCode 20201, CHANGELOG.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 18:42:33 +07:00
poli0981andClaude Opus 5.5 4bdf8ded08 docs: 2.2.0 checked on a real iPhone 14 Pro (Brave, Chrome) (#180)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:41:58 +07:00
dependabot[bot] 209a39c331 build(deps): Bump the npm-minor-patch group across 1 directory with 6 updates (#178)
Bumps the npm-minor-patch group with 6 updates in the / directory:

| Package | From | To |
| --- | --- | --- |
| [bson](https://github.com/mongodb/js-bson) | `7.3.3` | `7.3.4` |
| [i18next](https://github.com/i18next/i18next) | `26.7.1` | `26.7.2` |
| [lucide-react](https://github.com/lucide-icons/lucide/tree/HEAD/packages/lucide-react) | `1.67.0` | `1.70.0` |
| [react-i18next](https://github.com/i18next/react-i18next) | `17.1.12` | `17.1.13` |
| [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) | `8.3.5` | `8.3.6` |
| [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler) | `4.157.0` | `4.158.0` |



Updates `bson` from 7.3.3 to 7.3.4
- [Release notes](https://github.com/mongodb/js-bson/releases)
- [Changelog](https://github.com/mongodb/js-bson/blob/main/HISTORY.md)
- [Commits](https://github.com/mongodb/js-bson/compare/v7.3.3...v7.3.4)

Updates `i18next` from 26.7.1 to 26.7.2
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.7.1...v26.7.2)

Updates `lucide-react` from 1.67.0 to 1.70.0
- [Release notes](https://github.com/lucide-icons/lucide/releases)
- [Commits](https://github.com/lucide-icons/lucide/commits/1.70.0/packages/lucide-react)

Updates `react-i18next` from 17.1.12 to 17.1.13
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.1.12...v17.1.13)

Updates `vite` from 8.3.5 to 8.3.6
- [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.3.6/packages/vite)

Updates `wrangler` from 4.157.0 to 4.158.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.158.0/packages/wrangler)

---
updated-dependencies:
- dependency-name: bson
  dependency-version: 7.3.4
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: i18next
  dependency-version: 26.7.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: lucide-react
  dependency-version: 1.70.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: npm-minor-patch
- dependency-name: react-i18next
  dependency-version: 17.1.13
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: vite
  dependency-version: 8.3.6
  dependency-type: direct:development
  update-type: version-update:semver-patch
  dependency-group: npm-minor-patch
- dependency-name: wrangler
  dependency-version: 4.158.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  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-11-09 16:41:45 +07:00
dependabot[bot] e438197986 build(deps): Bump actions/setup-java (#174)
Bumps the actions group with 1 update: [actions/setup-java](https://github.com/actions/setup-java).


Updates `actions/setup-java` from 6.1.0 to 6.2.0
- [Release notes](https://github.com/actions/setup-java/releases)
- [Commits](https://github.com/actions/setup-java/compare/b843ebf9b913146b38da2eaa7aeddf76074ae1ad...77dd5b2ce225ea11469928ac317850245a74ae78)

---
updated-dependencies:
- dependency-name: actions/setup-java
  dependency-version: 6.2.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-09 16:40:41 +07:00
poli0981andClaude Opus 5.5 36f94d7b36 ci(release): build macOS on macos-15 — macos-14 images are retired (#179)
GitHub retired the macos-14 runner images on 2026-11-02; the v2.2.0 release run's macOS job was refused. Build on macos-15 (Arm64); minimumSystemVersion 12.0 keeps the macOS 12 floor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:22:09 +07:00
poli0981andClaude Opus 5.5 29d417ec93 feat: 2.2.0 — accessibility statement and fixes (#177)
ACCESSIBILITY.md (+ Vietnamese mirror) states the WCAG 2.2 AA goal, what works, a keyboard reference, what was tested, known limitations and how to report a barrier; new accessibility issue template. Fixes from an audit: skip link, focus after navigation and consent, visible focus everywhere incl. forced-colors, Esc-then-Tab hint and aria-invalid on the input editor, a quieter status bar, names that match visible labels, translated screen-reader strings, page zoom in the desktop apps. axe-core scan in CI. Docs synced (vi PRIVACY/dev_env, README credits, ROADMAP). Version 2.2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 16:04:59 +07:00
poli0981andClaude Opus 5.5 14f593c7a7 chore: 2.1.1 — dependencies to their latest releases (#170)
npm (minor/patch only): react-router 8.5.1, i18next 26.7.1,
react-i18next 17.1.12, i18next-browser-languagedetector 8.3.0,
lucide-react 1.67.0, fast-xml-parser 5.12.0, cbor-x 1.6.9,
@tauri-apps/plugin-dialog 2.8.4; dev: eslint 10.14, typescript-eslint
8.72.1, globals 17.14, vitest + coverage-v8 5.1, plugin-react 6.2.1,
tailwindcss + @tailwindcss/vite 4.3.4, knip 6.44.1, wrangler 4.157,
@types/node 26.6.6. Transitive packages refreshed; Vite and Tailwind
now share one lightningcss.

Cargo: cargo update within semver (tauri-plugin-dialog 2.8.4,
tauri-plugin-single-instance 2.5.5, wry 0.57.1, tao 0.37.2, ...).

Actions: sonarqube-scan-action 8.4.1; everything else was current.

knip 6.44 sees @testing-library/user-event, so it leaves
ignoreDependencies. THIRD-PARTY.md re-synced with the lockfiles.

minimatch < 11.0.1 (GHSA-g3hv-75wg-m249) stays: eslint and
typescript-eslint pin minimatch 10, the vulnerable path needs
optimizationLevel >= 2 and both use the default 1 on our own
config patterns.

Supersedes #163, #164, #165, #166, #167, #168, #169.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:53:47 +07:00
dependabot[bot] 0dc35a9be5 build(deps): Bump undici and wrangler (#158)
Bumps [undici](https://github.com/nodejs/undici) to 7.30.1 and updates ancestor dependency [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler). These dependencies need to be updated together.


Updates `undici` from 7.29.1 to 7.30.1
- [Release notes](https://github.com/nodejs/undici/releases)
- [Commits](https://github.com/nodejs/undici/compare/v7.29.1...v7.30.1)

Updates `wrangler` from 4.152.0 to 4.153.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/wrangler@4.153.0/packages/wrangler)

---
updated-dependencies:
- dependency-name: undici
  dependency-version: 7.30.1
  dependency-type: indirect
- dependency-name: wrangler
  dependency-version: 4.153.0
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-10-31 16:27:54 +07:00
poli0981andClaude Opus 5.5 e3d0e8b917 feat: 2.1.0 — JSONC → JSON (#161)
JSONC (JSON with comments) converts to standard JSON as a new input-only format: hand-written parser, comments and trailing commas removed at the same offsets, token-level output that keeps every number and key as written. Input-only formats in the framework (meta.inputOnly), reverse errors with line/column, JSONC editor highlighting and lint, a one-click hint in the JSON → direction, strings in four locales, docs and the 2.1.0 version bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:56:58 +07:00
poli0981andClaude Opus 5.5 b148f91635 docs: rate limits are approximate — measured on production (#159)
Cloudflare's Rate Limiting binding checks a locally cached count per edge
machine and syncs it in the background. On production one keep-alive
connection hits the limits almost exactly (120 pages, then 429s), but 300
requests on fresh parallel connections in 13 s all passed. Say so in
DEPLOYMENT.md and the rate-limit.ts header instead of "overshoot slightly",
and document a one-connection curl test for production.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 05:55:18 +07:00
poli0981andClaude Opus 5.5 72cb9a033d feat: 2.0.2 — rate limiting for the whole site (#157)
The Worker now runs first for every request except the content-hashed
bundles under /assets/ (run_worker_first: ["/*", "!/assets/*"]) and counts
it against a per-client limit before serving it:

- SITE_LIMITER: pages and public files, 120 requests / 60 s
- API_LIMITER: every /api/* request, 60 / 60 s
- VERIFY_LIMITER: /api/turnstile/verify on top, 30 / 60 s (unchanged)

Over the limit, pages get a plain-text 429 in the four UI languages and the
API a JSON 429 (rate_limited); both carry Retry-After: 60. Clients are keyed
on their IPv4 address or the /64 of their IPv6 address, never logged. Pages
still go through env.ASSETS.fetch(), so _headers, _redirects and the SPA
fallback apply as before. A failing limiter lets requests through. Previews
get their own counters (namespace_id 4204/4206).

Docs: DEPLOYMENT, PRIVACY (wording only, nothing new collected, no
re-consent), SECURITY, CONTRIBUTING, READMEs, CLAUDE.md, ROADMAP, CHANGELOG.
Version 2.0.2 (versionCode 20002).

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 05:36:02 +07:00
dependabot[bot] 6229199137 build(deps): Bump the i18n group with 2 updates
Bumps the i18n group with 2 updates: [i18next](https://github.com/i18next/i18next) and [react-i18next](https://github.com/i18next/react-i18next).


Updates `i18next` from 26.5.5 to 26.5.6
- [Release notes](https://github.com/i18next/i18next/releases)
- [Changelog](https://github.com/i18next/i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/i18next/compare/v26.5.5...v26.5.6)

Updates `react-i18next` from 17.1.1 to 17.1.3
- [Changelog](https://github.com/i18next/react-i18next/blob/master/CHANGELOG.md)
- [Commits](https://github.com/i18next/react-i18next/compare/v17.1.1...v17.1.3)

---
updated-dependencies:
- dependency-name: i18next
  dependency-version: 26.5.6
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: i18n
- dependency-name: react-i18next
  dependency-version: 17.1.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: i18n
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 13:50:09 +07:00
dependabot[bot] 9309fae1f6 build(deps-dev): Bump wrangler
Bumps the cloudflare group with 1 update: [wrangler](https://github.com/cloudflare/workers-sdk/tree/HEAD/packages/wrangler).


Updates `wrangler` from 4.151.3 to 4.152.0
- [Release notes](https://github.com/cloudflare/workers-sdk/releases)
- [Commits](https://github.com/cloudflare/workers-sdk/commits/HEAD/packages/wrangler)

---
updated-dependencies:
- dependency-name: wrangler
  dependency-version: 4.152.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
  dependency-group: cloudflare
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-10-26 13:41:20 +07:00
114 changed files with 5021 additions and 1981 deletions

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
---
name: Accessibility issue
about: Something is hard or impossible to use with a keyboard, screen reader, zoom or other assistive technology
title: '[A11Y] '
labels: ['accessibility', 'needs-triage']
assignees: []
---
<!--
Thanks for reporting a barrier. You don't need to know the cause: describe
what you tried and what happened. See ACCESSIBILITY.md for what JSONPrism
supports today and its known limitations:
https://github.com/poli0981/jsonPrism/blob/main/ACCESSIBILITY.md
Prefer not to post publicly? Email code@poli0981.dev with "Accessibility"
in the subject. Security problems go through SECURITY.md instead.
-->
## What were you trying to do?
For example: convert JSON to CSV, open a file, download the output, run a
batch, change an option, get past the consent screen.
## What happened?
What you expected, and what you got instead (for example: nothing was
announced, focus got stuck, text was unreadable at 200 % zoom).
## Steps to reproduce
1. Go to '...'
2. Press / say '...'
3. See '...'
## Your setup
- Assistive technology and version: [e.g. NVDA 2026.3, VoiceOver, TalkBack, Narrator, Dragon, screen magnifier, none]
- How you use the app: [keyboard only / screen reader / voice control / switch access / zoom or magnification / Windows contrast theme / other]
- Platform: [Web / Windows / macOS / Linux / Android]
- JSONPrism version: [e.g. 2.2.1 — see About → Build info]
- Browser (web) or OS version (apps): [e.g. Firefox on Windows 11, Safari on macOS 15, Android 15]
## How much does it block you?
- [ ] **Critical** — I can't complete the task at all
- [ ] **High** — I can, but only with a lot of effort or a workaround
- [ ] **Medium** — confusing or inconsistent, but I can finish the task
- [ ] **Low** — a minor annoyance
## Workaround
Did you find a way around it? It helps others while a fix is on the way.
## Diagnostics, recordings or screenshots
Optional. **About → Build info → Copy diagnostics** gives the version,
platform and recent log lines (check it for anything private first). A
short screen or screen-reader recording also helps.
+5 -1
View File
@@ -10,6 +10,9 @@ assignees: []
Security vulnerabilities do NOT belong in a public issue. Report them
privately through https://github.com/poli0981/jsonPrism/security/advisories/new
or by email to security@poli0981.dev.
Something hard or impossible to use with a keyboard, screen reader, zoom or
other assistive technology? Use the "Accessibility issue" template instead.
-->
## Describe the bug
@@ -42,9 +45,10 @@ What actually happened. Include the error message and target format.
## Environment
- Platform: [Web / Windows / macOS / Linux / Android]
- JSONPrism version: [e.g. 2.0.0 — see About → Build info]
- JSONPrism version: [e.g. 2.2.1 — see About → Build info]
- Browser (web) or OS version (apps): [e.g. Firefox on Windows 11, Safari on macOS 15, Ubuntu 24.04, Android 15]
- Where: [the website https://jsonprism.poli0981.dev / an installed release / a local dev build]
- Assistive technology, if any: [e.g. NVDA 2026.3, VoiceOver, keyboard only, 200 % zoom]
## Diagnostics
+4 -1
View File
@@ -1,8 +1,11 @@
blank_issues_enabled: false
contact_links:
- name: Feature ideas (maintenance mode)
url: https://github.com/poli0981/jsonPrism/discussions/categories/ideas
about: JSONPrism is in maintenance mode and takes no new features. Share ideas in Discussions, with no commitment. To add or remove a format, use the Converter request template.
- name: Questions & general discussion
url: https://github.com/poli0981/jsonPrism/discussions
about: Ask about usage, share workflows, or propose ideas before opening an issue.
about: Ask about usage or share your workflows.
- name: Security vulnerability
url: https://github.com/poli0981/jsonPrism/security/advisories/new
about: Report security issues privately via a GitHub Security Advisory, or email security@poli0981.dev. Never in a public issue.
@@ -0,0 +1,53 @@
---
name: Converter request
about: Add or remove a format, when people really need it
title: '[CONVERTER] '
labels: ['converter', 'needs-triage']
assignees: []
---
<!--
JSONPrism is in maintenance mode (CONTRIBUTING.md → Maintenance mode): it
takes no new features, but a format can still be added or removed when
there is a real need. Other ideas go to Discussions → Ideas:
https://github.com/poli0981/jsonPrism/discussions/categories/ideas
-->
## Add or remove?
- [ ] Add a format
- [ ] Remove a format
## Format
Name, file extension(s), and a link to its specification.
## Who needs it, and for what?
The real workflow this serves, or, for a removal, why the format should go.
Requests without a concrete use case are closed.
## Direction
- [ ] JSON → format
- [ ] Format → JSON
- [ ] Input only (like JSONC → JSON)
## Sample
A small input and the output you expect:
```json
{ "example": "input" }
```
```
expected output here
```
## Scope check
- [ ] It fits the "one JSON → many formats" mission
- [ ] It can run entirely on the user's device (no server)
- [ ] No format JSONPrism already has covers it
- [ ] I checked the latest build at https://jsonprism.poli0981.dev
-50
View File
@@ -1,50 +0,0 @@
---
name: Feature request
about: Suggest a new feature for JSONPrism
title: '[FEATURE] '
labels: ['enhancement', 'needs-triage']
assignees: []
---
## Problem
What problem does this feature solve? What workflow are you trying to support?
## Proposed solution
How would you like JSONPrism to handle it?
## Alternatives considered
Other approaches you thought about, and why this one fits better.
## Platform
Where would you use it? [All / Web / Windows / macOS / Linux / Android]
Version you're on: [e.g. 2.0.0 — see About → Build info]
## Sample data (if applicable)
If your feature involves a specific JSON shape, paste a sample:
```json
{ "example": "input" }
```
And the expected output:
```
expected output here
```
## Scope check
- [ ] This fits the "one JSON → many formats" core mission
- [ ] This can be done on the user's device (no server required)
- [ ] I have a real use case for this (not just hypothetical)
- [ ] I checked the latest build at https://jsonprism.poli0981.dev and it doesn't do this yet
## Additional context
Links, screenshots, references to similar tools.
+40
View File
@@ -0,0 +1,40 @@
---
name: Translation or wording issue
about: Wording that doesn't fit a culture or region, or a spelling mistake that could mislead
title: '[I18N] '
labels: ['i18n', 'needs-triage']
assignees: []
---
<!--
JSONPrism ships English, Tiếng Việt, 日本語 and 简体中文. The Japanese and
Simplified Chinese strings, and parts of the Vietnamese ones, are
AI-generated, so corrections from native speakers are very welcome.
-->
## Language
- [ ] Tiếng Việt (`vi`)
- [ ] 日本語 (`ja`)
- [ ] 简体中文 (`zh-CN`)
- [ ] English (`en`)
## Where
The page or screen, and what you were doing: for example the consent
screen, the CSV options, an error message.
## Current text
Copy the text exactly as shown, or attach a screenshot.
## Suggested text
## Why
- [ ] It doesn't fit the culture, region or usual tone
- [ ] A spelling or grammar mistake that could mislead
- [ ] The meaning is wrong (mistranslation)
- [ ] Other
Details:
+16
View File
@@ -1,6 +1,10 @@
<!--
Thanks for contributing to JSONPrism!
JSONPrism is in maintenance mode (CONTRIBUTING.md → "Maintenance mode"):
new features are out of scope, and `feat:` pull requests from outside
contributors are closed automatically.
Please fill in the sections below. PRs missing required context (no summary,
no test plan, off-topic preamble) may be closed without review.
See CONTRIBUTING.md → "Auto-ignored contributions" for what gets dismissed.
@@ -19,6 +23,17 @@ describing it in a public PR.
Closes #
## Scope
<!-- Required. Tick what this PR is. Anything else is out of scope while JSONPrism is in maintenance mode. -->
- [ ] Bug fix, broken UI/UX or accessibility fix
- [ ] Translation or wording fix
- [ ] Add or remove a converter, agreed in issue #
- [ ] Dependency update, security fix, or major language/runtime/framework upgrade
- [ ] Cloudflare / Worker change, or a fix for a website incident
- [ ] Docs or tests only
## Test plan
<!--
@@ -35,6 +50,7 @@ CI must pass before the PR can be merged.
- [ ] `npm run cf:check`
- [ ] Rust changed: `cargo fmt --check` and `cargo clippy --all-targets --locked -- -D warnings` in `src-tauri/`
- [ ] Manual smoke (describe what you clicked / loaded, and on which platform: Web / Windows / macOS / Linux / Android)
- [ ] UI changed: keyboard-only pass of what changed (visible focus, nothing stuck), accessible names in all four locales, `motion-safe:` animations, no colour-only meaning — see [ACCESSIBILITY.md](https://github.com/poli0981/jsonPrism/blob/main/ACCESSIBILITY.md#contributor-expectations). Screen reader used, if any:
## Screenshots / recordings (UI changes only)
+3
View File
@@ -45,6 +45,9 @@ updates:
patterns: ['@radix-ui/*']
cloudflare:
patterns: [wrangler, '@cloudflare/*', '@marsidev/react-turnstile']
# fast-xml-parser re-exports fast-xml-builder; keep the two in step.
xml:
patterns: [fast-xml-parser, fast-xml-builder]
npm-minor-patch:
update-types: [minor, patch]
+1 -1
View File
@@ -110,7 +110,7 @@ jobs:
- name: Scan
if: env.SONAR_TOKEN != ''
uses: SonarSource/sonarqube-scan-action@d209202bc7d53ff1cc128f7f907dac145c9d6ae9 # v8.3.0
uses: SonarSource/sonarqube-scan-action@59202af334b4ba7b5db01b701b8e79f8b3bef0f4 # v8.5.0
rust:
name: Tauri · fmt, clippy
+103
View File
@@ -0,0 +1,103 @@
name: Maintenance triage
# JSONPrism is in maintenance mode (CONTRIBUTING.md → Maintenance mode). This
# workflow closes, with a bilingual comment and the `out-of-scope` label:
# • any issue or pull request the maintainer labels `out-of-scope`;
# • when opened by an outside contributor: issues titled [FEATURE] or
# labelled `enhancement`, and pull requests titled `feat:` (any scope
# except `converter`/`converters`). The owner, members, collaborators and
# bots are skipped.
# pull_request_target runs in the base repository so it can comment on and
# close pull requests from forks. It never checks out or runs pull request
# code, and the script reads titles from the event payload itself instead of
# having untrusted text interpolated into it.
on:
issues:
types: [opened, labeled]
pull_request_target:
types: [opened, labeled]
permissions: {}
concurrency:
group: maintenance-triage-${{ github.event.issue.number || github.event.pull_request.number }}
cancel-in-progress: false
jobs:
triage:
name: Close out-of-scope requests
if: >-
(github.event.action == 'labeled' && github.event.label.name == 'out-of-scope') ||
(github.event.action == 'opened' &&
!contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'),
github.event.issue.author_association || github.event.pull_request.author_association))
runs-on: ubuntu-24.04
timeout-minutes: 5
permissions:
issues: write
pull-requests: write
steps:
- name: Close if out of scope
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
script: |
const OUT_OF_SCOPE = 'out-of-scope';
const TRUSTED = ['OWNER', 'MEMBER', 'COLLABORATOR'];
const { payload } = context;
const isPR = Boolean(payload.pull_request);
const item = payload.pull_request ?? payload.issue;
if (!item || item.state !== 'open') return;
const labels = (item.labels ?? []).map((label) => label.name);
let reason = null;
if (payload.action === 'labeled') {
if (payload.label?.name === OUT_OF_SCOPE) reason = 'labelled out-of-scope';
} else if (payload.action === 'opened') {
const trusted = TRUSTED.includes(item.author_association);
const bot = item.user?.type === 'Bot';
const title = String(item.title ?? '').trim();
if (!trusted && !bot) {
if (isPR) {
// Conventional Commits: feat:, feat(scope):, feat!: — converters stay open.
const feat = /^feat(?:\(([^)]*)\))?!?:/i.exec(title);
if (feat && !/^converters?$/i.test((feat[1] ?? '').trim())) reason = 'feat: pull request';
} else if (/^\[feature\]/i.test(title) || labels.includes('enhancement')) {
reason = 'feature request';
}
}
}
if (!reason) {
core.info(`#${item.number}: within scope, nothing to do.`);
return;
}
const ideas = 'https://github.com/poli0981/jsonPrism/discussions/categories/ideas';
const policy = 'https://github.com/poli0981/jsonPrism/blob/main/CONTRIBUTING.md#maintenance-mode';
const en = isPR ? 'pull request' : 'issue';
const vi = isPR ? 'Pull request' : 'Issue';
const body = [
'<!-- maintenance-triage -->',
'Thanks for taking the time to write this. JSONPrism is in **maintenance mode**: it still takes dependency and security updates, major runtime upgrades, fixes for bugs, UI/UX, accessibility and translations, converter additions or removals that people really need, and Cloudflare or website fixes, but no new features.',
'',
`This ${en} falls outside that scope, so it has been closed. If it is actually a bug, an accessibility or translation fix, or a converter request, reply here and the maintainer will take another look. Ideas are welcome in [Discussions → Ideas](${ideas}). The full policy is in [CONTRIBUTING.md → Maintenance mode](${policy}).`,
'',
'---',
'',
'Cảm ơn bạn đã dành thời gian. JSONPrism đang ở **giai đoạn bảo trì**: vẫn nhận cập nhật thư viện và bảo mật, nâng cấp runtime lớn, sửa lỗi, UI/UX, trợ năng (accessibility) và bản dịch, thêm hoặc bỏ converter khi thật sự có người cần, và sửa lỗi Cloudflare hay website, nhưng không thêm tính năng mới.',
'',
`${vi} này nằm ngoài phạm vi đó nên đã được đóng. Nếu thực ra đây là lỗi, sửa trợ năng hay bản dịch, hoặc yêu cầu converter, hãy trả lời tại đây để maintainer xem lại. Ý tưởng có thể gửi ở [Discussions → Ideas](${ideas}). Chính sách đầy đủ: [CONTRIBUTING.md → Maintenance mode](${policy}).`,
].join('\n');
const { owner, repo } = context.repo;
const number = item.number;
await github.rest.issues.createComment({ owner, repo, issue_number: number, body });
if (!labels.includes(OUT_OF_SCOPE)) {
await github.rest.issues.addLabels({ owner, repo, issue_number: number, labels: [OUT_OF_SCOPE] });
}
if (isPR) {
await github.rest.pulls.update({ owner, repo, pull_number: number, state: 'closed' });
} else {
await github.rest.issues.update({ owner, repo, issue_number: number, state: 'closed', state_reason: 'not_planned' });
}
core.notice(`Closed ${en} #${number} as out of scope (${reason}).`);
+149
View File
@@ -0,0 +1,149 @@
name: Qodana
# JetBrains Qodana static analysis, reported to Qodana Cloud (Ultimate licence):
# • js — Qodana for JS in native mode: the web app, the Worker, workflows and
# docs. Project "jsonprism-js-ts", secret QODANA_TOKEN_TS_JS,
# configuration in qodana.yaml.
# • rust — Qodana for Rust (Early Access, Docker only): the Tauri shell in
# src-tauri/. Project "jsonprism-rust", secret QODANA_TOKEN_RUST,
# configuration in src-tauri/qodana.yaml.
# Dependabot and fork pull requests get no secrets, so both jobs skip there.
# Results: Qodana Cloud, check annotations, a pull-request comment and the
# qodana-js / qodana-rust artifacts (SARIF and logs).
on:
push:
branches: [main]
pull_request:
branches: [main]
workflow_dispatch:
permissions: {}
concurrency:
group: qodana-${{ github.ref }}
# Only superseded PR runs are cancelled; every commit on main gets a full run.
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
env:
WRANGLER_SEND_METRICS: 'false'
jobs:
js:
name: Qodana · JS/TS
runs-on: ubuntu-24.04
timeout-minutes: 30
permissions:
contents: read
checks: write # annotations
pull-requests: write # summary comment
env:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN_TS_JS }}
steps:
- name: Skip without a token
if: env.QODANA_TOKEN == ''
run: echo "::notice::QODANA_TOKEN_TS_JS is not available to this run; skipping analysis."
- name: Checkout
if: env.QODANA_TOKEN != ''
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
# The pull request's head, not the merge commit.
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
persist-credentials: false
- name: Setup Node
if: env.QODANA_TOKEN != ''
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
cache: npm
- name: Install dependencies
if: env.QODANA_TOKEN != ''
run: npm ci --ignore-scripts --no-audit --no-fund
# worker-configuration.d.ts is generated and gitignored; without it the
# Worker's Env types don't resolve. (wrangler builds dist/ first.)
- name: Generate Worker types
if: env.QODANA_TOKEN != ''
run: npm run cf:types
- name: Qodana scan
if: env.QODANA_TOKEN != ''
uses: JetBrains/qodana-action@3e8d76ff0e0241618abd808682f426afe84bab3f # v2026.2.2
with:
args: --linter qodana-js --within-docker false
pr-mode: false
upload-result: true
artifact-name: qodana-js
primary-cache-key: qodana-2026.2-js-${{ github.ref }}-${{ github.sha }}
# A prefix, so pull requests can restore the cache saved on main.
additional-cache-key: qodana-2026.2-js-
cache-default-branch-only: true
rust:
name: Qodana · Rust (EAP)
runs-on: ubuntu-24.04
timeout-minutes: 45
permissions:
contents: read
checks: write # annotations
pull-requests: write # summary comment
env:
QODANA_TOKEN: ${{ secrets.QODANA_TOKEN_RUST }}
steps:
- name: Skip without a token
if: env.QODANA_TOKEN == ''
run: echo "::notice::QODANA_TOKEN_RUST is not available to this run; skipping analysis."
- name: Checkout
if: env.QODANA_TOKEN != ''
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
persist-credentials: false
- name: Setup Node
if: env.QODANA_TOKEN != ''
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: .nvmrc
cache: npm
- name: Install dependencies
if: env.QODANA_TOKEN != ''
run: npm ci --ignore-scripts --no-audit --no-fund
# tauri::generate_context!() embeds the icons and ../dist at compile time.
- name: Generate icons
if: env.QODANA_TOKEN != ''
run: npm run tauri:icon
- name: Build the web app
if: env.QODANA_TOKEN != ''
run: npm run build
# Docker mode mounts --repository-root, so ../dist stays visible from
# the src-tauri project directory. The container runs as root so the
# bootstrap in src-tauri/qodana.yaml can apt-get the C toolchain and
# the GTK/WebKit headers that build scripts need.
- name: Qodana scan
if: env.QODANA_TOKEN != ''
uses: JetBrains/qodana-action@3e8d76ff0e0241618abd808682f426afe84bab3f # v2026.2.2
env:
# Keep Cargo's registry in the mounted Qodana cache, which the
# action saves between runs on main.
CARGO_HOME: /data/cache/cargo
with:
args: --linter qodana-rust --repository-root . --project-dir src-tauri --user root
env-vars-to-linter: CARGO_HOME
pr-mode: false
upload-result: true
artifact-name: qodana-rust
primary-cache-key: qodana-2026.2-rust-${{ github.ref }}-${{ github.sha }}
# A prefix, so pull requests can restore the cache saved on main.
additional-cache-key: qodana-2026.2-rust-
cache-default-branch-only: true
+3 -2
View File
@@ -124,7 +124,8 @@ jobs:
runner: windows-latest
args: ''
- name: macOS (universal)
runner: macos-14
# macos-14 images were retired on 2026-11-02.
runner: macos-15
args: '--target universal-apple-darwin'
# The oldest supported Ubuntu keeps the AppImage/deb glibc floor low.
- name: Linux
@@ -195,7 +196,7 @@ jobs:
persist-credentials: false
- name: Setup Java 17
uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6.1.0
uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0
with:
distribution: temurin
java-version: '17'
+324
View File
@@ -0,0 +1,324 @@
# Accessibility
**Last reviewed**: 2026-11-09 · **Applies to**: JSONPrism 2.2.x (website, desktop and Android apps)
JSONPrism should work for everyone who needs to convert JSON, whatever
input device, screen reader, display setting or language they use. This
statement covers our goals, what works today, how it was tested, what is
known not to work yet, and how to report a barrier.
JSONPrism is a one-person project (see [DISCLAIMER.md](DISCLAIMER.md)).
This page describes honest best effort, not a certified result.
## Goals
- **Target: [WCAG 2.2](https://www.w3.org/TR/WCAG22/) level AA.** The
website and the apps share one interface, so the target covers all of
them. It is a goal, not a claim of conformance: there has been no formal
audit.
- **Priorities, in order:**
1. Every task works with the keyboard alone: converting, opening and
saving files, batch conversion, options and the consent screen.
2. Every control has a name, role and state that screen readers
announce, in the interface language.
3. Content stays readable with high contrast, zoom, light or dark
themes, reduced motion and Windows contrast themes.
- **Accessibility regressions are bugs.** They are triaged and fixed like
any other bug (see [Reporting accessibility
issues](#reporting-accessibility-issues)).
## What works today
### Keyboard
- Every interactive element is a native button, link or form control, or
a Radix UI component with built-in keyboard support. No element has a
positive `tabindex`.
- **Skip to content** is the first tab stop. After you move to another
page, focus moves to that page's content.
- Every focused control shows a visible focus indicator.
- **Dialogs and sheets** (Options, Batch, format picker):
- focus stays inside them while they are open;
- Escape closes them;
- focus then returns to the button that opened them.
- **The consent screen** keeps focus inside and must be answered; after
you accept, focus moves to the page content.
- **The input editor:** Tab indents. To leave it, press **Escape, then
Tab** (WCAG 2.1.2). The editor's screen-reader description and the
status bar both say so.
- The read-only output and the other scroll areas take focus and scroll
with the arrow and Page keys.
- **Drop zones have keyboard equivalents:** **Open** in the input panel,
**click to browse** in Batch.
### Screen readers
- **Page structure:**
- landmarks (banner, navigation, main, content info);
- one `h1` per page;
- a translated page title on every route.
- `<html lang>` follows the interface language. Each language name in the
switcher has its own `lang`.
- **The editors:**
- Both have names, such as "Input JSON" and "CSV output (read-only)".
- The input editor reports whether its content parses (`aria-invalid`).
- The input editor is described by the current error message
(`aria-describedby`).
- **Live regions announce:**
- parse errors with line and column, and conversion failures (as alerts);
- the conversion state, but not the byte counts or timing;
- batch progress and the human check;
- the offline notice and page loading;
- notifications.
- **States and shortcuts:**
- Toggle buttons expose `aria-pressed`.
- Theme choices are radio buttons, and on/off settings are switches.
- The download and options shortcuts are exposed with `aria-keyshortcuts`.
- Decorative icons are hidden from assistive technology, and icon-only
buttons have names.
- The editor's own announcements (search, replace, folding) and its
search and error panels are translated into all four interface
languages.
### Visual
- **Themes:** light, dark and system.
- Text colours were checked against 4.5:1 on their backgrounds in both
themes.
- The focus indicator uses the theme's ring colour, at 3:1 or more.
- **Reduced motion:** with `prefers-reduced-motion`, animations and
transitions are switched off, and Back to top jumps instead of scrolling.
- **Windows contrast themes** (`forced-colors`): focus, selected toggles and
switches are drawn in system colours.
- **No meaning from colour alone:**
- the status dot comes with a text state;
- batch rows have icons and text;
- the new-output dot on the narrow layout's Output tab also says "(new)".
- **Touch targets** meet WCAG 2.5.8: at least 24 × 24 CSS px, or spaced
so that a 24 px circle around each one doesn't overlap its neighbours.
### Zoom and reflow
- **Website:** browser zoom and text resizing work, and pinch-zoom is
never blocked.
- **Desktop apps:** from 2.2.0, Ctrl/⌘ + = and Ctrl/⌘ + − zoom the window.
On Windows, Ctrl + mouse wheel also works.
- **Narrow screens:** the layout reflows to 320 CSS px wide without
horizontal scrolling. It is designed for 360 × 640 and up
([tested viewports](docs/tested-viewports.md)).
### Language
The interface, including all screen-reader text, is available in English,
Tiếng Việt, 日本語 and 简体中文.
## Keyboard reference
| Keys | Where | Does |
| --- | --- | --- |
| Tab / Shift+Tab | Everywhere | Next / previous control |
| Enter on **Skip to content** | First Tab on a page | Jump to the page content |
| Ctrl+S (⌘S on macOS) | Converter | Download the output |
| Ctrl+, (⌘, on macOS) | Converter | Open Options |
| Escape | Dialog, sheet, Appearance menu | Close, and return focus to its button |
| ↑ ↓ Home End | Appearance menu | Move between items |
| ← → | Input / Output tabs (narrow screens) | Switch tab |
| Escape, then Tab | Input editor | Leave the editor (Tab alone indents) |
| Ctrl+M (Shift+Alt+M on macOS) | Input editor | Toggle "Tab moves focus" |
| Ctrl+] / Ctrl+[ (⌘] / ⌘[) | Input editor | Indent / outdent |
| Ctrl+F (⌘F), then F3 / Shift+F3 | Either editor | Search, next / previous match |
| Ctrl+Alt+G (⌘⌥G) | Either editor | Go to line |
| Ctrl+Shift+M (⌘⇧M), F8 | Input editor | Open the error list, next error |
| Alt+T | Anywhere | Focus notifications (pauses them) |
| Ctrl/⌘ + = and − | Desktop apps | Zoom in / out |
## How we test
### Tested with
| Date | Version | Platform | Method | Result |
| --- | --- | --- | --- | --- |
| 2026-11 | 2.1.1 | Windows 11: website in Edge, Brave and Firefox; Windows app (WebView2) | Narrator; keyboard only, no mouse (maintainer) | No blocking issues |
| 2026-11-09 | 2.2.0 | Chromium (development build) | Keyboard walk-through of the 2.2.0 changes: skip link, focus after navigation and consent, focus indicators | Pass |
| 2026-11-09 | 2.2.0 | iPhone 14 Pro (real device), iOS 26: production website in Brave and Chrome | Manual touch check (maintainer) | Works as expected |
| Every pull request | — | jsdom in CI | [axe-core](https://github.com/dequelabs/axe-core) on every page, the consent screen and each sheet; role and name assertions with Testing Library | Must pass |
| 2026-10-22 | 2.0.0 | Chromium device emulation, 360 × 740 to 1280 × 800, light and dark | Visual layout check | See [tested viewports](docs/tested-viewports.md) |
The automated scan runs without a real layout engine, so it can't
measure colour contrast; contrast is checked by hand.
**Not tested yet** (reports are very welcome):
- **Screen readers:** NVDA and JAWS (Windows), VoiceOver (macOS, iOS),
TalkBack (Android), Orca (Linux).
- **Voice control:** Dragon, Voice Access.
- **On real devices:** Windows contrast themes, and Android system font
size.
### Manual check before a release
1. **Keyboard only.** Work through every main flow:
- convert, open a file, download;
- run a batch to a `.zip`;
- change options, theme and language;
- pass the consent screen.
Check that focus is always visible and never stuck.
2. **Screen reader.** Use Narrator, NVDA or VoiceOver for the same flows.
Listen for names, states, errors and the conversion state.
3. **Zoom.** Check at 200 % and at 400 % in a 1280 px wide window, plus
text-only zoom where the browser offers it.
4. **Display settings.** Check with a Windows contrast theme, with reduced
motion, and in light and dark themes.
5. **Automated scan.** Run `npm test`, which includes the axe-core scan.
## Supported environments
| Surface | Engine | Assistive technology checked |
| --- | --- | --- |
| Website | Current Chrome, Edge, Brave, Firefox and Safari (engine floor: Chromium 111, WebKit of macOS 12) | Narrator with Edge, Brave and Firefox |
| Windows app | Microsoft Edge WebView2 | Narrator |
| macOS app (12+) | WKWebView | — |
| Linux app (Ubuntu 22.04+) | WebKitGTK | — |
| Android app (12+) | Android System WebView, Chromium 111+ | — |
## Known limitations
These are the barriers we know about, with workarounds where one exists.
They are tracked in [`docs/ROADMAP.md`](docs/ROADMAP.md).
1. **Long output in a screen reader's browse mode.** The editor keeps only
the visible lines in the page, so a virtual cursor can't read a long
result to the end. *Workaround:* **Copy** or **Download** the output and
read it in another app.
2. **Tab indents in the input editor.** *Workaround:* press Escape, then
Tab; or press Ctrl+M (Shift+Alt+M on macOS) to make Tab move focus.
3. **Small or short windows.**
- Below about 600 CSS px of height, the editors get very short. This
includes 400 % zoom in a 1280 px window.
- On phones, only portrait orientation is fully supported.
- Crossing 768 CSS px of width, for example by zooming, switches between
the side-by-side and tabbed layouts. The editors are recreated: your
text is kept, but focus and undo history are not.
*Workaround:* zoom to 200–300 % instead.
4. **Human check (website only).** Cloudflare Turnstile runs in a
Cloudflare frame, so its accessibility is Cloudflare's. If it fails or
takes longer than 20 seconds, **Continue without the check** appears.
5. **Notifications close after 4 seconds.** Screen readers announce them
when they appear. *Workaround:* hover them, or press Alt+T to focus and
pause them.
6. **Low non-text contrast.** Text-field and switch outlines are below
3:1 (WCAG 1.4.11). Every field is labelled, but the field boundary is
faint.
7. **Unavailable formats.** The reason a format is unavailable is in its
tooltip. Screen readers get it as the button's description, but touch
users can't see it.
8. **New tabs aren't announced.** Links that open in a new tab, or in the
system browser from the apps, don't say so.
9. **Desktop apps.** The smallest window is 800 × 560. Page zoom arrived
in 2.2.0.
10. **Android app.** It uses the WebView's default handling of system font
size and pinch-zoom, which hasn't been verified on a real device.
11. **Translations.** The Japanese and Chinese texts, including the
screen-reader texts, are AI-generated; native speakers' fixes are
welcome.
## Contributor expectations
Contributors check these for every change to the interface (see also
[CONTRIBUTING.md](CONTRIBUTING.md)):
- **Elements.** Use native elements or the components in
`src/components/ui/`. Don't put click handlers on `div` or `span`, and
don't use a positive `tabindex`.
- **Names.** Every control has an accessible name from the locale files,
in all four languages. Icon-only buttons get `aria-label`, and
decorative icons get `aria-hidden`.
- **Focus.**
- Don't use `outline-none` without a `focus-visible:` replacement.
- A scroll area that takes focus gets `role="region"` and a label.
- The only exception is an element focused from code with
`tabIndex={-1}`, such as `<main>`.
- **Motion and colour.** Animations go behind `motion-safe:`. Don't show
meaning with colour alone.
- **Announcements.** Use the existing live regions, and keep
announcements short. Don't announce text that changes on every
keystroke.
- **Testing.**
- `npm test` must pass, including the axe-core scan in
`src/app/__tests__/a11y.test.tsx`. Extend the scan for new pages and
dialogs.
- Do a keyboard-only pass of what you changed and say so in the pull
request.
- A screen-reader spot check is welcome too.
- **This file.** Update it when behaviour or a known limitation changes.
## Reporting accessibility issues
Open an issue with the **[Accessibility
issue](https://github.com/poli0981/jsonPrism/issues/new?template=accessibility.md)**
template. Include:
- what you were trying to do and what happened instead;
- your assistive technology and its version;
- the browser or app version, and your operating system.
You don't need to know the cause.
If you can't or would rather not use GitHub, email
**code@poli0981.dev** with "Accessibility" in the subject. Security
problems go through [SECURITY.md](SECURITY.md) instead.
### Severity
| Severity | Meaning | Example |
| --- | --- | --- |
| Critical | Blocks a core task, with no workaround | You can't convert, open, save or get past the consent screen with your keyboard or screen reader |
| High | Major difficulty, but a workaround exists | An error is never announced, but it shows in the output panel |
| Medium | Inconsistent or confusing, but the task is possible | A wrong or missing label; focus lands in an odd place |
| Low | Minor annoyance | Verbose announcements; an untranslated hint |
### How we respond
- We thank you and ask questions if something is unclear. We never ask
you to justify why you need an accessibility feature.
- We add the `accessibility` label, set a severity, and triage blockers
before cosmetic issues.
- We share a workaround as soon as we know one.
- When a fix is ready, we ask you to confirm it, if you are willing. Fixes
are listed in [CHANGELOG.md](CHANGELOG.md).
### Response times
This is best effort from a one-person project:
| Severity | First response | Fix released |
| --- | --- | --- |
| Critical | within 7 days | next patch release |
| High | within 14 days | next release |
| Medium / Low | within 30 days | when practical, usually the next minor release |
## Ownership and maintenance
Kokone ([@poli0981](https://github.com/poli0981)), the sole maintainer
(see [MAINTAINERS.md](MAINTAINERS.md)), owns accessibility. That covers:
- triaging reports;
- tracking them with the `accessibility` label;
- running the [manual check](#manual-check-before-a-release) before
releases;
- keeping this statement current, including its review date.
## Feedback
Suggestions for this statement are welcome as an issue or a pull request.
A [Vietnamese translation](docs/i18n/vi/ACCESSIBILITY.md) is available. If
the two differ, this English version prevails.
This statement follows the structure recommended by the Open Source Guides
([Accessibility best practices for your
project](https://opensource.guide/accessibility-best-practices-for-your-project/))
and the [Open Source Accessibility
toolkit](https://github.com/open-source-accessibility/accessibility-toolkit).
+161 -1
View File
@@ -6,7 +6,167 @@ 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".
No unreleased changes. JSONPrism is in maintenance mode: [CONTRIBUTING.md → Maintenance mode](CONTRIBUTING.md#maintenance-mode) lists what still changes.
## [2.2.1] — 2026-11-16
A maintenance release, and the start of **maintenance mode**. JSONPrism is feature-complete. From now on it gets dependency and security updates, major runtime upgrades, bug, UI/UX, accessibility and translation fixes, converter additions or removals that people really need, and Cloudflare or website fixes, but no new features. Conversions work exactly as before, nothing new is collected, and you are not asked to accept the terms again. `bundle.android.versionCode` 20201.
### Dependencies
- **npm (app):** i18next 27.1.3 and react-i18next 18.0.2 are new majors; their changed defaults don't apply here (`fallbackLng` is set, no translation is empty, no `Trans`, SSR or mocks). Also lucide-react 1.73, zustand 5.1, react-dropzone 20.2, papaparse 5.7.1, fast-xml-parser 5.12.1, `@codemirror/lint` 6.9.8 and `@tauri-apps/plugin-opener` 2.7.3.
- **npm (dev):**
- ESLint 10.15, typescript-eslint 8.72.2, eslint-plugin-react-refresh 0.5.8;
- Vite 8.3.8, `@vitejs/plugin-react` 6.3, Tailwind CSS and `@tailwindcss/vite` 4.3.5;
- Prettier 3.10.1, knip 6.45.1, wrangler 4.162;
- jsdom 31.0.1 (a new major, tests only), `@testing-library/user-event` 14.6.12.
- **Rust:** `cargo update` within semver: wry 0.57.2, tauri-plugin-opener 2.7.3 and 43 other crates.
- **GitHub Actions:** SonarSource/sonarqube-scan-action 8.5.0, actions/setup-java 6.3.0.
- `fast-xml-builder` 1.3.2 is now a direct dependency (see Fixed).
- All 414 packages have verified registry signatures, and `THIRD-PARTY.md` matches both lockfiles again.
- Supersedes Dependabot PRs #183–#191.
### Fixed
Findings from the first Qodana run. None of them is visible in the app.
- **XML builder:** the XML converter now uses `fast-xml-builder` directly. fast-xml-parser 5 deprecated its own `XMLBuilder` export, which only re-exported that package, so the output is identical.
- **React types:** imported from `react` instead of read from the global `React` namespace.
- **Tests:**
- synchronous `act()` calls no longer return a promise nobody awaits;
- the jsdom Range geometry stub is shared, and restored correctly after each file.
- **Small cleanups:** two redundant regular-expression constructs and a redundant boolean comparison.
### Project
- **Maintenance mode:**
- a status badge and section in both READMEs;
- the policy in [CONTRIBUTING.md](CONTRIBUTING.md#maintenance-mode);
- converter and translation issue templates instead of the feature request template;
- a scope checklist in the pull request template.
- **Auto-close:** `maintenance-triage.yml` closes out-of-scope feature requests with a bilingual comment.
- **Qodana:** Qodana for JS (native mode) and Qodana for Rust (Early Access) run on every push and pull request and report to Qodana Cloud.
- **Cleanup:** merged and stale branches and old worktrees were removed.
### Security
- No known vulnerability affects the app or the website.
- i18next 27.1.3 includes the fix for GHSA-q76c-gcvw-89x9. That issue needs a backend connector, which JSONPrism doesn't use.
- `npm audit` still lists minimatch < 11.0.1 (GHSA-g3hv-75wg-m249, moderate) through typescript-eslint, a development tool:
- ESLint 10.15 itself has moved to minimatch 11;
- `@typescript-eslint/typescript-estree` still requires minimatch 10, but only for typed-linting globs, which this project's ESLint config doesn't use.
## [2.2.0] — 2026-11-09
An accessibility release. JSONPrism now has an accessibility statement, [`ACCESSIBILITY.md`](ACCESSIBILITY.md), which targets WCAG 2.2 AA. The maintainer's keyboard-only and Narrator pass on 2.1.1 found no blocking issues; this release fixes the gaps an audit found beyond that pass. `bundle.android.versionCode` 20200.
### Added
- **Skip to content.** The first Tab stop on every page jumps past the header to the page content.
- **Focus follows you.**
- After you move to another page, focus moves to its content.
- After you accept the consent screen, focus moves to the page instead of being lost.
- **Back to top** returns focus to the page it scrolled.
- **Zoom in the desktop apps.** Ctrl/⌘ + = and Ctrl/⌘ + − zoom the window; on Windows, Ctrl + mouse wheel works too. This adds the `core:webview:allow-set-webview-zoom` permission, which macOS and Linux need for zooming.
- **How to leave the input editor.** Tab still indents. Screen readers now hear "press Escape, then Tab, to leave the editor", and the status bar shows the same hint on wide screens.
- **Screen-reader states for the input editor:**
- The input editor reports invalid input (`aria-invalid`).
- It is described by the current error message.
- **Download** and **Options** announce their keyboard shortcuts (`aria-keyshortcuts`).
- **Accessibility statement.** [`ACCESSIBILITY.md`](ACCESSIBILITY.md) and its [Vietnamese translation](docs/i18n/vi/ACCESSIBILITY.md) cover:
- goals;
- what works;
- a keyboard reference;
- what has been tested;
- known limitations with workarounds;
- how to report a barrier, with severity levels and response times.
The About page links the statement, and there is a new **Accessibility issue** template.
### Changed
- **Focus is always visible.**
- Controls without their own ring now get a themed outline.
- Scroll areas, the editors, the narrow-screen tab panels and the theme choices now show a ring.
- Windows contrast themes keep focus, pressed and selected states, and switches visible.
- **The status bar is quieter for screen readers.** Only the conversion state is announced, not the byte counts and timing that change on every keystroke.
- **Accessible names match what you see** (WCAG 2.5.3):
- The language buttons are named "EN English", "JA 日本語" and so on.
- **Copy** is named **Copied** while it says so.
- **The unread-output dot** on the narrow layout's Output tab is also announced, as "(new)".
- **Navigation labels** in Vietnamese, Japanese and Chinese no longer repeat the word "navigation".
- **Translations.** These now follow the interface language:
- the Home page title;
- the notification close button;
- CodeMirror's screen-reader announcements for search, replace, folding and deleted selections.
### Fixed
- **The Appearance button** no longer claims to open a menu (`aria-haspopup`). It is a disclosure for a panel.
- **The About page and the batch queue.** Their scroll areas are labelled regions, so the label is valid ARIA.
- **The format picker sheet** on phones has a description, which also removes Radix's console warning.
- **Page loading** is announced (`role="status"`), and the output panel's loading spinner is exposed as an image with a label.
### Tests
- **axe-core scan.** It covers every page, the input in an error state, the consent screen, and the Options, Batch and format-picker sheets. A guard test checks that the scan really reports violations.
- **Focus tests.** They cover the skip link, focus after navigation and after consent, and Back to top.
- **Unit tests** for the new attributes and labels.
### Docs
- **Accessibility guidance** for contributors:
- CONTRIBUTING, CLAUDE.md and the PR template have accessibility checks.
- The bug report template asks about assistive technology.
- [`docs/tested-viewports.md`](docs/tested-viewports.md) links the accessibility checks to run before a release.
- **The Vietnamese mirrors**, `docs/i18n/vi/PRIVACY.md` and `docs/i18n/vi/dev_env.md`, now describe the site-wide rate limits added in 2.0.2.
- **Other fixes:**
- The README credits match DISCLAIMER and THIRD-PARTY.
- Outdated ROADMAP notes are corrected.
- Version examples now use 2.2.0.
### Dependencies
- `axe-core` 4.14.0 (MPL-2.0), test-only; nothing new ships to users.
## [2.1.1] — 2026-11-04
A maintenance release: every dependency at its latest version, no feature or behavior change. It supersedes Dependabot PRs #163–#169. `bundle.android.versionCode` 20101.
### Dependencies
- **npm** (all minor/patch): react-router 8.5.1, i18next 26.7.1, react-i18next 17.1.12, i18next-browser-languagedetector 8.3.0, lucide-react 1.67.0, fast-xml-parser 5.12.0, cbor-x 1.6.9, `@tauri-apps/plugin-dialog` 2.8.4; dev: ESLint 10.14, typescript-eslint 8.72.1, globals 17.14, Vitest and `@vitest/coverage-v8` 5.1, `@vitejs/plugin-react` 6.2.1, Tailwind CSS and `@tailwindcss/vite` 4.3.4, knip 6.44.1, wrangler 4.157, `@types/node` 26.6.6. Transitive packages refreshed within their ranges; the lockfile is smaller because Vite and Tailwind now share one `lightningcss`. All 426 packages have verified registry signatures.
- **Rust**: `cargo update` within semver — tauri-plugin-dialog 2.8.4 (rfd 0.17), tauri-plugin-single-instance 2.5.5, wry 0.57.1, tao 0.37.2 and 26 others.
- **GitHub Actions**: SonarSource/sonarqube-scan-action 8.4.1 (scanner CLI 8.3.1). Every other action was already at its latest release.
- knip 6.44 detects `@testing-library/user-event` on its own, so it left `ignoreDependencies`.
- `THIRD-PARTY.md` lists the versions locked for 2.1.1 again; some rows had not been updated since 2.0.0.
### Security
- `npm audit` still lists minimatch < 11.0.1 (GHSA-g3hv-75wg-m249, moderate) through ESLint and typescript-eslint, which require minimatch 10 and have no release on 11 yet. It is a development-only dependency, and the amplification only runs at `optimizationLevel` 2 or higher; ESLint and typescript-eslint use the default level 1 with the glob patterns from this repository's own config. Forcing the new major with an override was rejected: minimatch 11 changes `partial` matching, which ESLint uses to decide which directories to walk.
## [2.1.0] — 2026-10-29
### Added
- **JSONC → JSON.** A new input-only format for JSON with comments, such as `tsconfig.json`, VS Code `settings.json`, `.code-workspace` and `deno.jsonc` files. Pick **JSONC** in the **→ JSON** direction, paste or drop `.jsonc` and `.json` files (batches included), and get standard JSON back: `//` and `/* */` comments and trailing commas are removed. Values are copied token by token rather than through JavaScript numbers, so integers beyond 2^53, `1.0`, `1e3`, duplicate keys and `__proto__` come out exactly as written. Output layout: 2 spaces (default), 4 spaces, tab or minified. The parser is hand-written and runs on your device; there is no new dependency.
- **"This looks like JSONC" hint.** In the JSON → direction, when the input fails only because of comments or trailing commas, the input panel offers **Convert JSONC → JSON**, which switches the direction and format in one click.
- The JSONC input editor highlights comments and marks errors in the gutter at the same line and column the converter reports.
### Changed
- Converting back to JSON can now report the line and column of an error. JSONC uses it, so its errors show `Ln …, Col …` like JSON input errors do.
- The JSONC chip is disabled in the JSON → direction with an "Input only" note. Switching to JSON → while JSONC is selected moves to JSONL.
## [2.0.2] — 2026-10-27
### Added
- **Rate limiting for the whole website, not just the human check.** The Worker now runs first for every request except the content-hashed bundles under `/assets/` (`run_worker_first: ["/*", "!/assets/*"]`) and counts it against a per-client limit before serving it: pages and public files 120 requests a minute (`SITE_LIMITER`, about 40 page loads), every `/api/*` request 60 a minute (`API_LIMITER`), and `/api/turnstile/verify` keeps its own 30 a minute on top. Over the limit, pages get a plain-text `429 Too Many Requests` in English, Vietnamese, Japanese and Chinese, and the API gets `{"ok":false,"error":"rate_limited"}`; both carry `Retry-After: 60`. Clients are keyed on their IPv4 address or the /64 network of their IPv6 address, which is never logged. Pages are still served through the assets binding, so the security headers, the old-path redirects and the SPA fallback are unchanged. If the limiter itself fails, requests go through rather than taking the site down. Preview deployments get their own counters.
### Changed
- The Privacy Policy describes the rate limit for page requests too. Nothing new is collected, so you are not asked to accept it again.
## [2.0.1] — 2026-10-22
+28 -6
View File
@@ -4,16 +4,29 @@ Guidance for Claude (and other AI assistants) working on this repository.
## Project context
**JSONPrism** converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back. Conversion always runs on the user's device. It ships as:
**JSONPrism** converts one JSON input into 12 formats (JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack) and parses six of them (JSONL, CSV, TSV, YAML, TOML, RESX) back, plus the input-only JSONC → JSON. Conversion always runs on the user's device. It ships as:
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets + a tiny `/api/*` Worker), deployed by Cloudflare Workers Builds on every push to `main`;
- a web app at <https://jsonprism.poli0981.dev>, served by the Cloudflare Worker `jsonprism` (static assets behind a tiny Worker that rate limits requests and answers `/api/*`), deployed by Cloudflare Workers Builds on every push to `main`;
- native apps built with Tauri 2: Windows, macOS, Linux and Android (sideload APK).
GitHub Pages (`poli0981.github.io/jsonPrism`) now only redirects to the new domain.
The maintainer is **Kokone** ([@poli0981](https://github.com/poli0981)). Audience: the developer community on the open-source Discord server plus YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
**Current release**: 2.0.0. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
**Current release**: 2.2.1. See [`docs/ROADMAP.md`](docs/ROADMAP.md) for what is next.
**Status: maintenance mode** (since 2.2.1). Don't propose new features. Every change must fall under the policy in [`CONTRIBUTING.md` → Maintenance mode](CONTRIBUTING.md#maintenance-mode):
- dependency updates;
- security fixes (a CVE rated high or critical, a serious runtime issue);
- major language, runtime or framework upgrades;
- bug, UI/UX and accessibility fixes;
- adding or removing a converter when there is a real need;
- translation fixes;
- Cloudflare/Worker changes;
- website incidents.
`.github/workflows/maintenance-triage.yml` closes out-of-scope issues and pull requests (label `out-of-scope`).
## Stack — exact versions matter
@@ -33,7 +46,7 @@ Do not propose downgrading or "modernizing" to deprecated patterns.
## Web platform (Cloudflare)
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback; only `/api/*` runs the Worker (`run_worker_first`). Bindings: `ASSETS`, `VERIFY_LIMITER` (rate limit), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
- `wrangler.jsonc`: static assets from `dist/` with SPA fallback. Every request except the hashed `/assets/*` bundles runs the Worker first (`run_worker_first`): it rate limits per client (`worker/rate-limit.ts`), then passes pages to `env.ASSETS.fetch()` (which still applies `_headers`, `_redirects` and the SPA fallback) or answers `/api/*`. Bindings: `ASSETS`, `SITE_LIMITER` / `API_LIMITER` / `VERIFY_LIMITER` (rate limits; each needs a preview twin with its own `namespace_id` under `previews`), var `ALLOWED_HOSTNAMES`, secret `TURNSTILE_SECRET` (dashboard; locally `.dev.vars`, copied from `.dev.vars.example`).
- `worker/index.ts` may only have a **default export** — workerd treats every named export of the entry module as an entrypoint and refuses to start. Put shared code in other modules (`worker/verify.ts`, `worker/turnstile.ts`, `worker/http.ts`).
- Worker logs are structured (`logEvent`) and must never contain IPs, tokens or user content.
- `public/_headers` holds the CSP and security headers; `public/_redirects` maps the old `/jsonPrism/*` paths. Adding any third-party script, style, font or connection means updating the CSP there (and the Tauri CSP in `tauri.conf.json` if it applies to the apps).
@@ -87,6 +100,15 @@ The same React UI runs in the browser and in Tauri (desktop + Android).
- **Tailwind class order**: rely on `prettier-plugin-tailwindcss`; never hand-sort.
- **Don't fight the theme system**. Use the tokens (`--color-prism-*`, `--color-success`, `--color-warning`, `bg-background`, …), which have separate light and dark values. No hard-coded hex. Animations go behind `motion-safe:`.
- **i18n everything user-facing** in all four locales: `en.json`, `vi.json`, `ja.json`, `zh-CN.json` (`src/i18n/__tests__/locales.test.ts` enforces key parity). Libraries return error *codes*; components translate them.
- **Accessibility** (target WCAG 2.2 AA; see [`ACCESSIBILITY.md`](ACCESSIBILITY.md)). There is no `eslint-plugin-jsx-a11y` (it doesn't support ESLint 10); the axe-core scan in `src/app/__tests__/a11y.test.tsx` is the automated check, so extend it for new pages and dialogs.
- **Elements:** native elements or the Radix-based `ui/` components only. No click handlers on `div`/`span`, no positive `tabIndex`.
- **Names:** every control has an accessible name from i18n. Icon-only buttons get `aria-label` and decorative icons `aria-hidden`. The name starts with the visible label (WCAG 2.5.3).
- **Focus:**
- Never `outline-none` without a `focus-visible:ring-*` replacement; the one exception is an element focused only from code with `tabIndex={-1}`, like `<main>`.
- A focusable scroll area needs `role="region"` and an `aria-label`.
- Move focus with `focusMain()` (`src/lib/focus.ts`) when content is replaced.
- **Announcements:** use the existing live regions (input error, output alert, status-bar state, batch chips, toasts). Never announce text that changes on every keystroke.
- **Docs:** a behaviour change or new known limitation updates `ACCESSIBILITY.md` and its Vietnamese mirror.
- **Logging**: use `createLogger(scope)` from `src/lib/logger.ts`, not `console.*` (ESLint warns). Logs stay in memory and feed About → Copy diagnostics; never log user content.
- **Heavy work off the main thread**: conversions of large inputs and batch jobs go through `src/lib/convert-client.ts` (Web Worker); keep `convert-worker.ts` free of DOM access.
@@ -118,7 +140,7 @@ If you find yourself wanting another top-level folder, stop and reconsider.
## Adding a new converter — checklist
1. Create `src/converters/myformat.ts` exporting `myFormatConverter`.
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, and `binary` for byte formats). Return errors as values.
2. Implement `Converter<MyFormatOptions>`, including `meta.extension` (plus `altExtensions` for aliases such as `yml`, `binary` for byte formats, and `inputOnly` for formats that only convert to JSON, like JSONC — their `convert()` returns an error). Return errors as values.
3. Add the ID to the `FormatId` union in `src/converters/types.ts`.
4. Register it in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`).
5. Add `formats.myformat` (and any option labels) to all four locale files.
@@ -148,7 +170,7 @@ npm run build # verify production output
npm run preview:cf # the real Cloudflare setup on http://localhost:8787
```
CI (`.github/workflows/ci.yml`) also runs `format:check`, `knip`, coverage, `cf:check`, SonarQube Cloud and `cargo fmt`/`clippy`. The maintainer typically uses **WebStorm** (JetBrains license), so Prettier and ESLint run on save.
CI (`.github/workflows/ci.yml`) also runs `format:check`, `knip`, coverage, `cf:check`, SonarQube Cloud and `cargo fmt`/`clippy`. `.github/workflows/qodana.yml` runs Qodana for JS (native mode, `qodana.yaml`) and Qodana for Rust (Early Access, Docker, `src-tauri/qodana.yaml`) with the `QODANA_TOKEN_TS_JS` and `QODANA_TOKEN_RUST` secrets; both jobs skip without their token. The maintainer typically uses **WebStorm** (JetBrains license), so Prettier and ESLint run on save.
## Communication preferences
+99 -12
View File
@@ -2,6 +2,44 @@
Thanks for considering a contribution! JSONPrism is an open-source project under Apache License 2.0.
## Maintenance mode
Since 2.2.1 (November 2026) JSONPrism is in **maintenance mode**. It is
feature-complete and stays maintained, but it doesn't grow new features.
These changes are still accepted:
1. **Dependency updates** on a regular schedule (weekly, grouped by
Dependabot).
2. **Security fixes**, as soon as possible: a dependency with a high or
critical CVE, or a serious security issue in a runtime such as Node.js.
3. **Major upgrades** of a language, runtime or framework, for example
Node 24 → 26 or TypeScript 6 → 7.
4. **Issues and pull requests** that:
- add or remove a converter when people really need it (open a
[converter request](#converter-requests) first);
- fix a bug, a broken UI/UX or an accessibility barrier.
5. **Language fixes**: wording that doesn't fit a culture or region, and
spelling mistakes that could mislead (see [Translations](#translations)).
6. **Cloudflare / Worker** changes when the platform changes significantly.
7. **Website incidents** such as DDoS or bot spam.
Anything else is out of scope, new features in particular, unless the
maintainer judges one genuinely necessary.
- The [maintenance triage workflow](.github/workflows/maintenance-triage.yml)
closes feature issues and `feat:` pull requests from outside contributors
automatically. It also closes anything the maintainer labels
`out-of-scope`.
- Feature ideas are welcome in
[Discussions → Ideas](https://github.com/poli0981/jsonPrism/discussions/categories/ideas),
with no commitment.
- If your issue or pull request was closed by mistake, reply to it and the
maintainer will take another look.
Releases ship only when one of these changes needs one, for example a
security fix for the desktop and Android apps. The website keeps deploying
from `main`.
## Prerequisites
| Tool | Version | Notes |
@@ -54,14 +92,26 @@ npm run tauri:android:dev # Android emulator or device
Run `npm run tauri:icon` and `npm run build` first: the Rust build
embeds the generated icons and `dist/`.
The **Qodana** workflow (Qodana for JS and Qodana for Rust) needs
Qodana Cloud tokens, so it skips on pull requests from forks. The
maintainer reviews its findings before merging.
2. **Match the project style.** Read [`CLAUDE.md`](CLAUDE.md) for the
non-negotiable code conventions (converter shape, error handling, i18n
requirements). For tool versions, `package.json` and this file are
authoritative.
3. **Keep PRs focused.** One feature or one fix per PR. Refactors as separate PRs.
3. **Keep the UI accessible.** For any UI change:
- Do a keyboard-only pass of what you changed: focus is visible and never stuck.
- Give every control an accessible name in all four locales.
- Put animations behind `motion-safe:`.
- Extend the axe-core scan in `src/app/__tests__/a11y.test.tsx` when you add a page or dialog.
4. **Fill in the [PR template](.github/PULL_REQUEST_TEMPLATE.md)**: what
[`ACCESSIBILITY.md`](ACCESSIBILITY.md#contributor-expectations) has the full list.
4. **Keep PRs focused.** One feature or one fix per PR. Refactors as separate PRs.
5. **Fill in the [PR template](.github/PULL_REQUEST_TEMPLATE.md)**: what
changed, why, how you tested it, screenshots if UI, and whether AI
tools helped.
@@ -117,16 +167,20 @@ Cloudflare's runtime and is not bound by this rule.
## Cloudflare Worker (web build)
The website is served by a Cloudflare Worker configured in
[`wrangler.jsonc`](wrangler.jsonc). Only `/api/*` runs Worker code;
everything else is static files from `dist/`. The code lives in
[`wrangler.jsonc`](wrangler.jsonc). Every request except the hashed bundles
under `/assets/` runs the Worker first: it applies a per-client rate limit,
then serves pages from `dist/` through the `ASSETS` binding or answers
`/api/*`. The code lives in
[`worker/`](worker/):
| File | Role |
|---|---|
| `worker/index.ts` | Router. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
| `worker/index.ts` | Router: rate limit, then the `ASSETS` binding for pages or the API handlers. The entry module must only have a **default export**: workerd treats named exports as entrypoints. |
| `worker/rate-limit.ts` | Per-client limits (`SITE_LIMITER`, `API_LIMITER`), IPv4 / IPv6-/64 keys, 429 responses |
| `worker/env.ts` | The bindings and variables the Worker reads |
| `worker/verify.ts` | `POST /api/turnstile/verify`: same-origin check, JSON only, body size cap, rate limit |
| `worker/turnstile.ts` | Cloudflare siteverify call: timeout, one retry, hostname / action / age checks |
| `worker/http.ts` | JSON responses with strict headers, structured logs |
| `worker/http.ts` | JSON and plain-text responses with strict headers, structured logs |
Worker logs must never contain IP addresses, tokens or user content.
@@ -166,21 +220,45 @@ Use the [Bug Report](https://github.com/poli0981/jsonPrism/issues/new?template=b
Security vulnerabilities never go in a public issue. See [SECURITY.md](SECURITY.md).
### Feature requests
### Accessibility issues
Use the [Feature Request](https://github.com/poli0981/jsonPrism/issues/new?template=feature_request.md) template. We prioritize features that:
Something hard or impossible to use with a keyboard, screen reader, zoom or other assistive technology? Use the [Accessibility issue](https://github.com/poli0981/jsonPrism/issues/new?template=accessibility.md) template. You don't need to know the cause. [ACCESSIBILITY.md](ACCESSIBILITY.md) covers:
- what is supported and tested;
- the known limitations;
- how reports are triaged.
Fixes for those limitations are welcome.
### Converter requests
A format can still be added or removed when people really need it. Open a
[Converter request](https://github.com/poli0981/jsonPrism/issues/new?template=converter_request.md)
first and describe the workflow it serves. A pull request that adds a
converter without an agreed request may be closed. A new converter must:
- Fit the "one JSON → many formats" core mission
- Run entirely on the user's device (conversion never touches a server)
- Have a clear use case from a real workflow
### Feature ideas
New features are out of scope while JSONPrism is in
[maintenance mode](#maintenance-mode). Share ideas in
[Discussions → Ideas](https://github.com/poli0981/jsonPrism/discussions/categories/ideas):
they are read, but nothing is scheduled.
### Translations
Currently bundled: **English** (`en`), **Tiếng Việt** (`vi`), **日本語**
(`ja`), **简体中文** (`zh-CN`). The Japanese and Simplified Chinese
locales, and parts of the Vietnamese one, are AI-generated and not
professionally reviewed; see [DISCLAIMER.md](DISCLAIMER.md).
Native-speaker corrections are very welcome.
Native-speaker corrections are very welcome. Wording that reads wrong for
a culture or region, or a spelling mistake that could mislead, counts as a
bug: report it with the
[Translation or wording issue](https://github.com/poli0981/jsonPrism/issues/new?template=translation.md)
template, or fix it in a pull request.
Every user-facing string goes through i18next, so a new or changed string
means editing **all four** files in `src/i18n/locales/`. The parity test
@@ -189,7 +267,10 @@ when a locale is missing a key or has an extra one, changes a
`{{variable}}`, or leaves a value empty. If you aren't confident in a
translation, say so in the PR.
To add a new language:
A new language counts as a new feature, so while JSONPrism is in
[maintenance mode](#maintenance-mode), ask in
[Discussions → Ideas](https://github.com/poli0981/jsonPrism/discussions/categories/ideas)
before you start. The steps stay here for reference. To add a new language:
1. Copy `src/i18n/locales/en.json` to `src/i18n/locales/<locale>.json` and translate every value (keep `{{variables}}` unchanged)
2. Import it in `src/i18n/index.ts` and add it to `resources` and `SUPPORTED_LANGUAGES`
@@ -200,11 +281,13 @@ To add a new language:
### Adding a new converter
See the **"Adding a new converter — checklist"** section in [`CLAUDE.md`](CLAUDE.md).
Start with a [converter request](#converter-requests). Once it is agreed,
follow the **"Adding a new converter — checklist"** section in
[`CLAUDE.md`](CLAUDE.md).
Briefly:
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values)
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>` (pure, errors as values; an input-only format such as JSONC sets `meta.inputOnly`)
2. Add the ID to `FormatId` in `types.ts` and register the converter in `registry.ts`
3. Add `formats.myformat` labels to all four locales
4. Add tests in `src/converters/__tests__/` (`contract.test.ts` already runs every registered converter against the errors-as-values contract)
@@ -233,6 +316,10 @@ Prefixes: `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `build`
To keep the maintainer's review queue manageable, the following are
closed without review:
- **New features outside the [maintenance scope](#maintenance-mode).**
Feature issues and `feat:` pull requests from outside contributors are
closed automatically. Other out-of-scope items are closed with the
`out-of-scope` label.
- **PRs with suspicious code.** If a diff looks like obfuscated/minified
code, hidden network calls, or subtly tampered third-party files, it
will be flagged. If CodeQL or Dependabot also flag it, the contributor
+4 -3
View File
@@ -1,6 +1,6 @@
# Disclaimer
**Last updated**: 2026-10-22
**Last updated**: 2026-11-09
## Project status
@@ -28,7 +28,7 @@ Apache 2.0 disclaimer-of-warranty clause applies in full.
This project openly uses AI tools during development:
- **Claude Chat** and **Claude Code** — Claude Opus 4.7 and 4.8 for the 1.x
releases, Claude Opus 5.5 for 2.0 — used for drafting code,
releases, Claude Opus 5.5 for 2.x — used for drafting code,
refactoring, writing tests and documentation, generating translations
and reviewing changes.
- All AI-generated code is reviewed by the maintainer before it is merged.
@@ -59,7 +59,8 @@ do not depend on these services.
without checking it.
- Do not assume that a round trip JSON → format → JSON is byte-perfect for
lossy formats. Only JSONL, CSV, TSV, YAML, TOML and RESX convert back
to JSON at all.
to JSON at all. JSONC → JSON removes comments and trailing commas, so
they are not kept.
- Pin a specific JSONPrism version if you depend on its behaviour; future
releases may change defaults.
+13 -1
View File
@@ -8,6 +8,10 @@ JSONPrism is co-authored with AI tooling — see [DISCLAIMER.md](DISCLAIMER.md)
for details. The maintainer is the single point of human review for every
merged PR.
Since 2.2.1 the project is in **maintenance mode**: no new features, only
the changes listed in
[CONTRIBUTING.md → Maintenance mode](CONTRIBUTING.md#maintenance-mode).
## Responsibilities
- **Code review** — reviews and merges every PR, including AI-assisted
@@ -20,13 +24,21 @@ merged PR.
Cloudflare Workers Builds.
- **Translations review** — the AI-generated Japanese and Simplified
Chinese strings and the partly AI-generated Vietnamese ones.
- **Accessibility** — triages reports labelled `accessibility`, runs the
manual checks before a release and keeps
[ACCESSIBILITY.md](ACCESSIBILITY.md) current.
- **Community** — issues, Discussions and the Discord server, and
enforcement of the [Code of Conduct](CODE_OF_CONDUCT.md). Vulnerability
reports are triaged as described in [SECURITY.md](SECURITY.md).
- **Triage** — keeps issues and pull requests within the maintenance
scope, closing the rest with the `out-of-scope` label (the triage
workflow posts the explanation).
## Contact
- Bug reports & feature requests: [GitHub Issues](https://github.com/poli0981/jsonPrism/issues)
- Bug reports, translation fixes and converter requests: [GitHub Issues](https://github.com/poli0981/jsonPrism/issues)
- Feature ideas (no commitment while in maintenance mode): [Discussions → Ideas](https://github.com/poli0981/jsonPrism/discussions/categories/ideas)
- Accessibility barriers: the [Accessibility issue](https://github.com/poli0981/jsonPrism/issues/new?template=accessibility.md) template, or [code@poli0981.dev](mailto:code@poli0981.dev) — see [ACCESSIBILITY.md](ACCESSIBILITY.md)
- Discussion / Q&A: [GitHub Discussions](https://github.com/poli0981/jsonPrism/discussions)
- Community chat: [Discord](https://discord.gg/2aNR3aVt)
- Project, maintainer & Code of Conduct: [code@poli0981.dev](mailto:code@poli0981.dev)
+8 -7
View File
@@ -35,13 +35,14 @@ Privacy questions and requests: **privacy@poli0981.dev**.
Cloudflare, Inc. serves the website and processes the data every web
request carries (IP address, user agent, requested URL, time, TLS details)
to deliver pages and protect the service against abuse. JSONPrism's own
server code handles only the human-check API (`/api/turnstile/verify`)
and a health check. For that API it records structured events — outcome,
HTTP status, the Cloudflare data centre code, duration and Turnstile error
codes — in Cloudflare Workers Logs, kept for 7 days. These events never
contain IP addresses, Turnstile tokens or anything you convert. The API is
rate limited per client by Cloudflare; the client key is not stored by
JSONPrism.
server code answers only the human-check API (`/api/turnstile/verify`) and
a health check, and counts page and API requests against a per-client rate
limit before serving them. It records structured events — outcome, HTTP
status, the Cloudflare data centre code, duration, Turnstile error codes
and refused over-limit requests — in Cloudflare Workers Logs, kept for 7
days. These events never contain IP addresses, Turnstile tokens or anything
you convert. The rate-limit counters are kept by Cloudflare, keyed on your
IP address (for IPv6, its /64 network); JSONPrism does not store the key.
### Human check (website)
+49 -18
View File
@@ -6,7 +6,9 @@
One JSON input. Multi-target formats. Fully on your device.
[![Status: maintenance mode](https://img.shields.io/badge/status-maintenance_mode-yellow.svg)](#project-status)
[![CI](https://github.com/poli0981/jsonPrism/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/jsonPrism/actions/workflows/ci.yml)
[![Qodana](https://github.com/poli0981/jsonPrism/actions/workflows/qodana.yml/badge.svg)](https://github.com/poli0981/jsonPrism/actions/workflows/qodana.yml)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=poli0981_jsonPrism&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=poli0981_jsonPrism)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
@@ -18,24 +20,37 @@ One JSON input. Multi-target formats. Fully on your device.
JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into many target formats — like white light through a prism. **Conversion runs entirely on your device** — in the browser, the desktop app or the Android app — so your data never leaves it.
## Project status
**Maintenance mode** since 2.2.1 (November 2026). JSONPrism is feature-complete, and it stays maintained:
- dependency updates on a regular schedule, and fast fixes for high or critical CVEs and serious runtime security issues;
- major language, runtime and framework upgrades (for example Node 24 → 26, TypeScript 6 → 7);
- bug, UI/UX and accessibility fixes, and adding or removing a converter when people really need it;
- translation fixes: wording that doesn't fit a culture or region, and spelling mistakes that could mislead;
- changes the Cloudflare or Worker platform forces, and website incidents such as DDoS or bot spam.
New features are not planned, except the rare one that is genuinely necessary. Feature issues and pull requests outside this list are closed automatically. The full policy is in [CONTRIBUTING.md](CONTRIBUTING.md#maintenance-mode).
## Target formats
| Format | Extension | Status | Reverse (→ JSON) |
| ----------------- | ----------- | ------------- | ---------------- |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| CSV | `.csv` | ✅ Phase 1 | ✅ |
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
| XML | `.xml` | ✅ Phase 2 | — |
| TOML | `.toml` | ✅ Phase 2 | ✅ |
| Markdown table | `.md` | ✅ Phase 2 | — |
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
| BSON | `.bson` | ✅ Phase 4 | — |
| CBOR | `.cbor` | ✅ Phase 4 | — |
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
| Format | Extension | Status | Reverse (→ JSON) |
| ------------------ | ----------------- | --------- | ---------------- |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| JSONC (input only) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (only) |
| CSV | `.csv` | ✅ Phase 1 | ✅ |
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
| XML | `.xml` | ✅ Phase 2 | — |
| TOML | `.toml` | ✅ Phase 2 | ✅ |
| Markdown table | `.md` | ✅ Phase 2 | — |
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
| BSON | `.bson` | ✅ Phase 4 | — |
| CBOR | `.cbor` | ✅ Phase 4 | — |
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
Twelve formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
Twelve target formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also convert back to JSON; in that direction `.ndjson`, `.tab` and `.yml` files are accepted too. **JSONC** (JSON with comments: `tsconfig.json`, VS Code settings) is input only: it turns `.jsonc` and `.json` files into plain JSON, dropping comments and trailing commas while keeping every value, number and key exactly as written. Paste JSONC in the JSON → direction and the app offers to switch. SQL `INSERT` speaks standard SQL, PostgreSQL, MySQL, SQLite and MSSQL. BSON, CBOR and MessagePack are binary: the output panel shows them as base64 or hex text, and downloads are real binary files.
## Features
@@ -61,6 +76,19 @@ Twelve formats. Six of them — JSONL, CSV, TSV, YAML, TOML and RESX — also co
Details: [`PRIVACY.md`](PRIVACY.md).
## Accessibility
JSONPrism aims for **WCAG 2.2 AA** on the website and in the apps:
- **Keyboard:** everything works with the keyboard alone, with a skip link and a visible focus indicator.
- **Screen readers:** controls have names, and errors and state changes are announced, in all four languages.
- **Display:** light, dark or system theme with text at 4.5:1 or better, plus support for reduced motion and Windows contrast themes.
- **Zoom:** works on the website, and in the desktop apps with Ctrl/⌘ + = and −.
The maintainer tests it with Narrator and the keyboard alone, and every pull request runs an axe-core scan.
Known limitations and how to report a barrier: [`ACCESSIBILITY.md`](ACCESSIBILITY.md).
## Tech stack
- **Vite 8** + **React 19.3** + **TypeScript 7** (native compiler; the `typescript` dependency is a TS 6 alias kept only for typescript-eslint)
@@ -70,7 +98,7 @@ Details: [`PRIVACY.md`](PRIVACY.md).
- **i18next** for translations, **Zustand** for state, **React Router 8** for routing, **Sonner** for toasts
- **Vitest** + Testing Library for tests
- **Node.js 26** for the toolchain
- **Cloudflare Workers** hosts the web app (static assets plus a small Worker for `/api/*`)
- **Cloudflare Workers** hosts the web app (static assets behind a small Worker that rate limits requests and serves `/api/*`)
- **Tauri 2.12** for the desktop (Windows, macOS, Linux) and Android apps
## Quick start
@@ -295,6 +323,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
};
```
An input-only format (like JSONC) sets `meta.inputOnly: true`, implements `reverse()`, and has `convert()` return an error; the UI then disables it in the JSON → direction.
Then add the id to the `FormatId` union in `src/converters/types.ts`, register the converter in `src/converters/registry.ts` (`CONVERTERS` and `ALL_FORMATS`), and add its label keys to all four files in `src/i18n/locales/` — a parity test fails when a locale is missing a key.
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full phase plan.
@@ -325,6 +355,7 @@ Bug reports and feature requests belong in [GitHub Issues](https://github.com/po
| [`PRIVACY.md`](PRIVACY.md) | What stays on your device, and the web-only Cloudflare services (hosting, Turnstile, Web Analytics). |
| [`TERMS.md`](TERMS.md) | ToS / EULA — acceptable use, license inheritance, user data ownership. |
| [`SECURITY.md`](SECURITY.md) | How to report vulnerabilities; response SLAs. |
| [`ACCESSIBILITY.md`](ACCESSIBILITY.md) | Accessibility goals (WCAG 2.2 AA), what's tested, known limitations, how to report a barrier. |
| [`DISCLAIMER.md`](DISCLAIMER.md) | One-person + AI-assisted project; no warranty. |
| [`THIRD-PARTY.md`](THIRD-PARTY.md) | Every dependency: version, license, link. |
| [`MAINTAINERS.md`](MAINTAINERS.md) | Who's responsible for what. |
@@ -350,8 +381,8 @@ Hang out, ask questions, or follow updates:
Substantial parts of JSONPrism's code, tests, translations, and docs
were drafted with AI assistance: **Claude Chat** and **Claude Code
(Opus 4.7, 1M context)** for v1.x, and **Claude Code (Opus 5.5)** for
v2.0.0. See [DISCLAIMER.md](DISCLAIMER.md) for the full AI-assist
(Opus 4.7 and 4.8)** for v1.x, and **Claude Code (Opus 5.5)** for
v2.x. See [DISCLAIMER.md](DISCLAIMER.md) for the full AI-assist
disclosure. The Japanese and Simplified Chinese translations, and parts
of the Vietnamese one, are AI-generated and best-effort; contributions
from native speakers are welcomed.
+49 -18
View File
@@ -6,7 +6,9 @@
Một JSON đầu vào. Đa định dạng đích. Chạy hoàn toàn trên thiết bị của bạn.
[![Status: maintenance mode](https://img.shields.io/badge/status-maintenance_mode-yellow.svg)](#trạng-thái-dự-án)
[![CI](https://github.com/poli0981/jsonPrism/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/jsonPrism/actions/workflows/ci.yml)
[![Qodana](https://github.com/poli0981/jsonPrism/actions/workflows/qodana.yml/badge.svg)](https://github.com/poli0981/jsonPrism/actions/workflows/qodana.yml)
[![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=poli0981_jsonPrism&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=poli0981_jsonPrism)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
@@ -18,24 +20,37 @@ Một JSON đầu vào. Đa định dạng đích. Chạy hoàn toàn trên thi
JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu vào và phân tách ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính. **Việc chuyển đổi diễn ra hoàn toàn trên thiết bị của bạn** — trong trình duyệt, app desktop hay app Android — nên dữ liệu không bao giờ rời khỏi máy.
## Trạng thái dự án
**Đang ở giai đoạn bảo trì** từ bản 2.2.1 (tháng 11/2026). JSONPrism đã đủ tính năng và vẫn được duy trì:
- cập nhật thư viện định kỳ; vá nhanh các CVE mức high trở lên và lỗ hổng bảo mật nghiêm trọng của runtime;
- nâng cấp lớn ngôn ngữ, runtime, framework (ví dụ Node 24 → 26, TypeScript 6 → 7);
- sửa lỗi, lỗi UI/UX và trợ năng (accessibility); thêm hoặc bỏ converter khi thật sự có người cần;
- sửa bản dịch: câu chữ không hợp văn hoá hay giọng địa phương, lỗi chính tả dễ gây hiểu nhầm;
- thay đổi do Cloudflare hoặc nền tảng Worker bắt buộc, và sự cố website như DDoS hay bot spam.
Không thêm tính năng mới, trừ trường hợp hiếm thật sự cần thiết. Issue và pull request đề xuất tính năng ngoài danh sách trên sẽ tự động bị đóng. Chính sách đầy đủ ở [CONTRIBUTING.md](CONTRIBUTING.md#maintenance-mode) (tiếng Anh).
## Định dạng hỗ trợ
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
| ----------------- | ------------ | -------------- | ------------ |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| CSV | `.csv` | ✅ Phase 1 | ✅ |
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
| XML | `.xml` | ✅ Phase 2 | — |
| TOML | `.toml` | ✅ Phase 2 | ✅ |
| Bảng Markdown | `.md` | ✅ Phase 2 | — |
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
| BSON | `.bson` | ✅ Phase 4 | — |
| CBOR | `.cbor` | ✅ Phase 4 | — |
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
| Định dạng | Phần mở rộng | Trạng thái | Đảo (→ JSON) |
| ------------------- | ----------------- | ---------- | ----------------- |
| JSONL | `.jsonl` | ✅ Phase 1 | ✅ |
| JSONC (chỉ đầu vào) | `.jsonc`, `.json` | ✅ 2.1.0 | ✅ (chỉ chiều này) |
| CSV | `.csv` | ✅ Phase 1 | ✅ |
| TSV | `.tsv` | ✅ Phase 1 | ✅ |
| YAML | `.yaml` | ✅ Phase 1 | ✅ |
| XML | `.xml` | ✅ Phase 2 | — |
| TOML | `.toml` | ✅ Phase 2 | ✅ |
| Bảng Markdown | `.md` | ✅ Phase 2 | — |
| SQL `INSERT` | `.sql` | ✅ Phase 2 | — |
| RESX (.NET) | `.resx` | ✅ Phase 3 | ✅ |
| BSON | `.bson` | ✅ Phase 4 | — |
| CBOR | `.cbor` | ✅ Phase 4 | — |
| MessagePack | `.msgpack` | ✅ Phase 4 | — |
Tổng cộng 12 định dạng. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
Tổng cộng 12 định dạng đích. Sáu trong số đó — JSONL, CSV, TSV, YAML, TOML và RESX — còn chuyển ngược được về JSON; ở chiều này app cũng nhận file `.ndjson`, `.tab` và `.yml`. **JSONC** (JSON có comment: `tsconfig.json`, settings của VS Code) là định dạng chỉ-đầu-vào: biến file `.jsonc` và `.json` thành JSON thuần, bỏ comment và dấu phẩy thừa nhưng giữ nguyên mọi giá trị, con số và key như bạn viết. Dán JSONC ở chiều JSON → thì app sẽ gợi ý chuyển sang. SQL `INSERT` hỗ trợ SQL chuẩn, PostgreSQL, MySQL, SQLite và MSSQL. BSON, CBOR và MessagePack là định dạng nhị phân: panel output hiển thị chúng dưới dạng text base64 hoặc hex, còn file tải về là binary thật.
## Tính năng
@@ -61,6 +76,19 @@ Tổng cộng 12 định dạng. Sáu trong số đó — JSONL, CSV, TSV, YAML,
Chi tiết: [`PRIVACY.md`](PRIVACY.md).
## Trợ năng (Accessibility)
JSONPrism hướng tới **WCAG 2.2 AA** trên website lẫn các app:
- **Bàn phím:** mọi thao tác dùng được chỉ bằng bàn phím, có skip link và chỉ báo focus rõ ràng.
- **Trình đọc màn hình:** control có tên, lỗi và thay đổi trạng thái được đọc lên, đủ bốn ngôn ngữ.
- **Hiển thị:** theme sáng, tối hoặc theo hệ thống với chữ tương phản từ 4.5:1, hỗ trợ giảm chuyển động và contrast theme của Windows.
- **Phóng to:** dùng được trên website, và trong app desktop bằng Ctrl/⌘ + = và −.
Maintainer kiểm thử bằng Narrator và chỉ dùng bàn phím, mỗi pull request đều chạy bài quét axe-core.
Hạn chế đã biết và cách báo rào cản: [`ACCESSIBILITY.md`](ACCESSIBILITY.md) ([bản tiếng Việt](docs/i18n/vi/ACCESSIBILITY.md)).
## Tech stack
- **Vite 8** + **React 19.3** + **TypeScript 7** (compiler native; dependency `typescript` là alias TS 6, chỉ giữ lại cho typescript-eslint)
@@ -70,7 +98,7 @@ Chi tiết: [`PRIVACY.md`](PRIVACY.md).
- **i18next** cho dịch thuật, **Zustand** cho state, **React Router 8** cho routing, **Sonner** cho toast
- **Vitest** + Testing Library cho test
- **Node.js 26** cho toolchain
- **Cloudflare Workers** host bản web (static assets kèm một Worker nhỏ cho `/api/*`)
- **Cloudflare Workers** host bản web (static assets phía sau một Worker nhỏ giới hạn tần suất request và phục vụ `/api/*`)
- **Tauri 2.12** cho app desktop (Windows, macOS, Linux) và Android
## Bắt đầu nhanh
@@ -295,6 +323,8 @@ export const myFormatConverter: Converter<MyFormatOptions> = {
};
```
Định dạng chỉ-đầu-vào (như JSONC) đặt `meta.inputOnly: true`, cài `reverse()`, còn `convert()` trả lỗi; UI sẽ disable nó ở chiều JSON →.
Sau đó thêm id vào union `FormatId` trong `src/converters/types.ts`, đăng ký converter trong `src/converters/registry.ts` (`CONVERTERS` và `ALL_FORMATS`), và thêm label key vào cả bốn file trong `src/i18n/locales/` — test parity sẽ fail nếu một ngôn ngữ thiếu key.
Xem [`docs/ROADMAP.md`](docs/ROADMAP.md) để biết kế hoạch phase đầy đủ.
@@ -325,6 +355,7 @@ Báo bug và đề xuất tính năng vui lòng gửi qua [GitHub Issues](https:
| [`PRIVACY.md`](PRIVACY.md) | Những gì ở lại trên thiết bị, và các dịch vụ Cloudflare chỉ dùng cho website (hosting, Turnstile, Web Analytics). |
| [`TERMS.md`](TERMS.md) | ToS / EULA — acceptable use, kế thừa giấy phép, quyền sở hữu dữ liệu. |
| [`SECURITY.md`](SECURITY.md) | Cách report vulnerability, SLA. |
| [`ACCESSIBILITY.md`](ACCESSIBILITY.md) · [`docs/i18n/vi/ACCESSIBILITY.md`](docs/i18n/vi/ACCESSIBILITY.md) | Mục tiêu trợ năng (WCAG 2.2 AA), những gì đã kiểm thử, hạn chế đã biết, cách báo rào cản. |
| [`DISCLAIMER.md`](DISCLAIMER.md) | Project 1 người + AI-assisted, không bảo hành. |
| [`THIRD-PARTY.md`](THIRD-PARTY.md) | Mỗi dependency: version, giấy phép, link. |
| [`MAINTAINERS.md`](MAINTAINERS.md) | Ai chịu trách nhiệm gì. |
@@ -349,8 +380,8 @@ Trò chuyện, hỏi đáp, hoặc theo dõi cập nhật:
## Ghi nhận
Phần lớn code, test, bản dịch và tài liệu của JSONPrism được draft với
sự hỗ trợ của AI: **Claude Chat** và **Claude Code (Opus 4.7, 1M
context)** cho v1.x, **Claude Code (Opus 5.5)** cho v2.0.0. Xem
sự hỗ trợ của AI: **Claude Chat** và **Claude Code (Opus 4.7 và
4.8)** cho v1.x, **Claude Code (Opus 5.5)** cho v2.x. Xem
[DISCLAIMER.md](DISCLAIMER.md) để biết chi tiết về AI-assist. Bản dịch
tiếng Nhật, tiếng Trung giản thể và một phần bản tiếng Việt do AI tạo,
chất lượng ở mức best-effort — rất hoan nghênh đóng góp từ người bản ngữ.
+9 -3
View File
@@ -11,6 +11,11 @@ website always runs the latest code on `main`.
| 2.x | ✅ |
| < 2.0 | ❌ |
JSONPrism has been in
[maintenance mode](CONTRIBUTING.md#maintenance-mode) since 2.2.1. That
doesn't change this policy: security fixes keep shipping, and a dependency
with a high or critical CVE is fixed as soon as possible.
## Reporting a vulnerability
**Please do not open a public GitHub Issue for security reports.**
@@ -50,8 +55,9 @@ website's edge configuration.
In scope:
- `src/` — the React app, converters and batch processor.
- `worker/` — the Cloudflare Worker (`/api/turnstile/verify`,
`/api/health`): origin checks, rate limiting, request validation.
- `worker/` — the Cloudflare Worker (per-client rate limits for the whole
site, `/api/turnstile/verify`, `/api/health`): rate limiting, origin
checks, request validation.
- Website edge configuration: `public/_headers` (CSP and security
headers), `public/_redirects`, `wrangler.jsonc`.
- `src-tauri/` — the Rust shell, capabilities, file-system scope and CSP.
@@ -77,7 +83,7 @@ attestations generated in GitHub Actions:
```bash
sha256sum -c SHA256SUMS.txt --ignore-missing
gh attestation verify JSONPrism_2.0.0_x64-setup.exe --repo poli0981/jsonPrism
gh attestation verify JSONPrism_2.2.1_x64-setup.exe --repo poli0981/jsonPrism
```
The desktop installers are not yet code-signed, so Windows SmartScreen
+37 -35
View File
@@ -3,7 +3,7 @@
JSONPrism is built on top of open-source libraries. This page lists each
direct dependency declared in [`package.json`](package.json) and
[`src-tauri/Cargo.toml`](src-tauri/Cargo.toml), the exact version used by
**JSONPrism 2.0.0**, the upstream license, and a link to the project. It
**JSONPrism 2.2.1**, the upstream license, and a link to the project. It
also lists the third-party services the website uses.
Versions are the ones locked in [`package-lock.json`](package-lock.json)
@@ -24,8 +24,8 @@ copyright and license notices. This file is a starting point.
|---|---|---|---|
| `react` | 19.3.1 | MIT | [react.dev](https://react.dev/) |
| `react-dom` | 19.3.1 | MIT | [react.dev](https://react.dev/) |
| `react-router` | 8.5.0 | MIT | [reactrouter.com](https://reactrouter.com/) |
| `tailwindcss` (devDep) | 4.3.3 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `react-router` | 8.5.1 | MIT | [reactrouter.com](https://reactrouter.com/) |
| `tailwindcss` (devDep) | 4.3.5 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `tw-animate-css` (devDep) | 1.4.0 | MIT | [github.com/Wombosvideo/tw-animate-css](https://github.com/Wombosvideo/tw-animate-css) |
| `tailwind-merge` | 3.7.0 | MIT | [github.com/dcastil/tailwind-merge](https://github.com/dcastil/tailwind-merge) |
| `class-variance-authority` | 0.7.1 | Apache-2.0 | [cva.style](https://cva.style/) |
@@ -34,9 +34,9 @@ copyright and license notices. This file is a starting point.
| `@radix-ui/react-slot` | 1.5.0 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `@radix-ui/react-switch` | 1.4.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `@radix-ui/react-tabs` | 1.2.1 | MIT | [radix-ui.com](https://www.radix-ui.com/) |
| `lucide-react` | 1.61.0 | ISC | [lucide.dev](https://lucide.dev/) |
| `lucide-react` | 1.73.0 | ISC | [lucide.dev](https://lucide.dev/) |
| `sonner` | 2.0.8 | MIT | [sonner.emilkowal.ski](https://sonner.emilkowal.ski/) |
| `react-dropzone` | 20.1.4 | MIT | [react-dropzone.js.org](https://react-dropzone.js.org/) |
| `react-dropzone` | 20.2.0 | MIT | [react-dropzone.js.org](https://react-dropzone.js.org/) |
The component patterns under `src/components/ui/` are generated from
**[shadcn/ui](https://ui.shadcn.com/)** (MIT) — copied into the repo, not
@@ -57,19 +57,20 @@ build-time packages whose generated CSS ships in the bundle.
| `@codemirror/lang-markdown` | 6.5.2 | MIT | [codemirror.net](https://codemirror.net/) |
| `@codemirror/lang-sql` | 6.10.0 | MIT | [codemirror.net](https://codemirror.net/) |
| `@codemirror/legacy-modes` | 6.5.5 | MIT | [codemirror.net](https://codemirror.net/) |
| `@codemirror/lint` | 6.9.7 | MIT | [codemirror.net](https://codemirror.net/) |
| `@codemirror/lint` | 6.9.8 | MIT | [codemirror.net](https://codemirror.net/) |
| `@lezer/highlight` | 1.2.5 | MIT | [lezer.codemirror.net](https://lezer.codemirror.net/) |
## Parsers / serialization
| Package | Version | License | Link |
|---|---|---|---|
| `papaparse` | 5.7.0 | MIT | [papaparse.com](https://www.papaparse.com/) |
| `papaparse` | 5.7.1 | MIT | [papaparse.com](https://www.papaparse.com/) |
| `js-yaml` | 5.5.0 | MIT | [github.com/nodeca/js-yaml](https://github.com/nodeca/js-yaml) |
| `smol-toml` | 1.9.1 | BSD-3-Clause | [github.com/squirrelchat/smol-toml](https://github.com/squirrelchat/smol-toml) |
| `fast-xml-parser` | 5.11.2 | MIT | [github.com/NaturalIntelligence/fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) |
| `bson` | 7.3.3 | Apache-2.0 | [github.com/mongodb/js-bson](https://github.com/mongodb/js-bson) |
| `cbor-x` | 1.6.8 | MIT | [github.com/kriszyp/cbor-x](https://github.com/kriszyp/cbor-x) |
| `fast-xml-parser` | 5.12.1 | MIT | [github.com/NaturalIntelligence/fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) |
| `fast-xml-builder` | 1.3.2 | MIT | [github.com/NaturalIntelligence/fast-xml-builder](https://github.com/NaturalIntelligence/fast-xml-builder) |
| `bson` | 7.3.4 | Apache-2.0 | [github.com/mongodb/js-bson](https://github.com/mongodb/js-bson) |
| `cbor-x` | 1.6.9 | MIT | [github.com/kriszyp/cbor-x](https://github.com/kriszyp/cbor-x) |
| `@msgpack/msgpack` | 3.1.3 | ISC | [msgpack.org](https://msgpack.org/) |
| `fflate` | 0.8.3 | MIT | [github.com/101arrowz/fflate](https://github.com/101arrowz/fflate) |
@@ -77,17 +78,17 @@ build-time packages whose generated CSS ships in the bundle.
| Package | Version | License | Link |
|---|---|---|---|
| `zustand` | 5.0.16 | MIT | [github.com/pmndrs/zustand](https://github.com/pmndrs/zustand) |
| `i18next` | 26.5.5 | MIT | [i18next.com](https://www.i18next.com/) |
| `react-i18next` | 17.1.1 | MIT | [react.i18next.com](https://react.i18next.com/) |
| `i18next-browser-languagedetector` | 8.2.1 | MIT | [github.com/i18next/i18next-browser-languageDetector](https://github.com/i18next/i18next-browser-languageDetector) |
| `zustand` | 5.1.0 | MIT | [github.com/pmndrs/zustand](https://github.com/pmndrs/zustand) |
| `i18next` | 27.1.3 | MIT | [i18next.com](https://www.i18next.com/) |
| `react-i18next` | 18.0.2 | MIT | [react.i18next.com](https://react.i18next.com/) |
| `i18next-browser-languagedetector` | 8.3.0 | MIT | [github.com/i18next/i18next-browser-languageDetector](https://github.com/i18next/i18next-browser-languageDetector) |
## Cloudflare (web build)
| Package | Version | License | Link |
|---|---|---|---|
| `@marsidev/react-turnstile` | 1.6.3 | MIT | [github.com/marsidev/react-turnstile](https://github.com/marsidev/react-turnstile) |
| `wrangler` (devDep) | 4.151.3 | MIT OR Apache-2.0 | [github.com/cloudflare/workers-sdk](https://github.com/cloudflare/workers-sdk) |
| `wrangler` (devDep) | 4.162.0 | MIT OR Apache-2.0 | [github.com/cloudflare/workers-sdk](https://github.com/cloudflare/workers-sdk) |
`@marsidev/react-turnstile` renders the Turnstile widget on the website
only. `wrangler` runs, type-checks and deploys the Worker in `worker/`.
@@ -99,9 +100,9 @@ The services themselves are covered under
| Package | Version | License | Link |
|---|---|---|---|
| `@tauri-apps/api` | 2.12.4 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-dialog` | 2.8.3 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-dialog` | 2.8.4 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-fs` | 2.7.1 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-opener` | 2.7.2 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/plugin-opener` | 2.7.3 | MIT OR Apache-2.0 | [tauri.app](https://tauri.app/) |
| `@tauri-apps/cli` (devDep) | 2.12.4 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
### Rust crates (`src-tauri/Cargo.lock`)
@@ -110,10 +111,10 @@ The services themselves are covered under
|---|---|---|---|
| `tauri` | 2.12.5 | Apache-2.0 OR MIT | [crates.io/crates/tauri](https://crates.io/crates/tauri) |
| `tauri-build` (build dependency) | 2.7.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-build](https://crates.io/crates/tauri-build) |
| `tauri-plugin-dialog` | 2.8.3 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
| `tauri-plugin-dialog` | 2.8.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
| `tauri-plugin-fs` | 2.7.1 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-fs](https://crates.io/crates/tauri-plugin-fs) |
| `tauri-plugin-opener` | 2.7.2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-opener](https://crates.io/crates/tauri-plugin-opener) |
| `tauri-plugin-single-instance` (desktop only) | 2.5.4 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
| `tauri-plugin-opener` | 2.7.3 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-opener](https://crates.io/crates/tauri-plugin-opener) |
| `tauri-plugin-single-instance` (desktop only) | 2.5.5 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
| `serde` | 1.0.229 | MIT OR Apache-2.0 | [serde.rs](https://serde.rs/) |
| `serde_json` | 1.0.154 | MIT OR Apache-2.0 | [github.com/serde-rs/json](https://github.com/serde-rs/json) |
@@ -124,28 +125,29 @@ shipped in the app.
| Package | Version | License | Link |
|---|---|---|---|
| `vite` | 8.3.5 | MIT | [vite.dev](https://vite.dev/) |
| `@vitejs/plugin-react` | 6.1.2 | MIT | [github.com/vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react) |
| `@tailwindcss/vite` | 4.3.3 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `vite` | 8.3.8 | MIT | [vite.dev](https://vite.dev/) |
| `@vitejs/plugin-react` | 6.3.0 | MIT | [github.com/vitejs/vite-plugin-react](https://github.com/vitejs/vite-plugin-react) |
| `@tailwindcss/vite` | 4.3.5 | MIT | [tailwindcss.com](https://tailwindcss.com/) |
| `@typescript/native` (alias of `typescript@^7`) | 7.0.2 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
| `typescript` (alias of `@typescript/typescript6`, wraps TypeScript 6.0.3) | 6.0.2 | Apache-2.0 | [typescriptlang.org](https://www.typescriptlang.org/) |
| `eslint` | 10.13.0 | MIT | [eslint.org](https://eslint.org/) |
| `eslint` | 10.15.0 | MIT | [eslint.org](https://eslint.org/) |
| `@eslint/js` | 10.0.1 | MIT | [eslint.org](https://eslint.org/) |
| `typescript-eslint` | 8.72.0 | MIT | [typescript-eslint.io](https://typescript-eslint.io/) |
| `typescript-eslint` | 8.72.2 | MIT | [typescript-eslint.io](https://typescript-eslint.io/) |
| `eslint-plugin-react-hooks` | 7.1.1 | MIT | [github.com/facebook/react](https://github.com/facebook/react) |
| `eslint-plugin-react-refresh` | 0.5.7 | MIT | [github.com/ArnaudBarre/eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) |
| `globals` | 17.13.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
| `prettier` | 3.9.10 | MIT | [prettier.io](https://prettier.io/) |
| `eslint-plugin-react-refresh` | 0.5.8 | MIT | [github.com/ArnaudBarre/eslint-plugin-react-refresh](https://github.com/ArnaudBarre/eslint-plugin-react-refresh) |
| `globals` | 17.14.0 | MIT | [github.com/sindresorhus/globals](https://github.com/sindresorhus/globals) |
| `prettier` | 3.10.1 | MIT | [prettier.io](https://prettier.io/) |
| `prettier-plugin-tailwindcss` | 0.8.1 | MIT | [github.com/tailwindlabs/prettier-plugin-tailwindcss](https://github.com/tailwindlabs/prettier-plugin-tailwindcss) |
| `knip` | 6.42.1 | ISC | [knip.dev](https://knip.dev/) |
| `vitest` | 5.0.5 | MIT | [vitest.dev](https://vitest.dev/) |
| `@vitest/coverage-v8` | 5.0.5 | MIT | [vitest.dev](https://vitest.dev/) |
| `jsdom` | 30.1.3 | MIT | [github.com/jsdom/jsdom](https://github.com/jsdom/jsdom) |
| `knip` | 6.45.1 | ISC | [knip.dev](https://knip.dev/) |
| `vitest` | 5.1.0 | MIT | [vitest.dev](https://vitest.dev/) |
| `@vitest/coverage-v8` | 5.1.0 | MIT | [vitest.dev](https://vitest.dev/) |
| `jsdom` | 31.0.1 | MIT | [github.com/jsdom/jsdom](https://github.com/jsdom/jsdom) |
| `@testing-library/react` | 16.3.3 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/dom` | 10.4.2 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/jest-dom` | 7.0.1 | MIT | [testing-library.com](https://testing-library.com/) |
| `@testing-library/user-event` | 14.6.8 | MIT | [testing-library.com](https://testing-library.com/) |
| `@types/node` | 26.6.5 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@testing-library/user-event` | 14.6.12 | MIT | [testing-library.com](https://testing-library.com/) |
| `axe-core` | 4.14.0 | MPL-2.0 | [github.com/dequelabs/axe-core](https://github.com/dequelabs/axe-core) |
| `@types/node` | 26.6.6 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/papaparse` | 5.5.2 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/react` | 19.3.0 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
| `@types/react-dom` | 19.3.0 | MIT | [github.com/DefinitelyTyped/DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) |
@@ -192,7 +194,7 @@ of the project.
Substantial portions of JSONPrism's code, tests, translations, and docs
were drafted with AI assistance from Anthropic: **Claude Chat** +
**Claude Code** with Claude Opus 4.7 and 4.8 for the 1.x releases, and
**Claude Code** with Claude Opus 5.5 for 2.0.0. The Japanese and Simplified
**Claude Code** with Claude Opus 5.5 for 2.x. The Japanese and Simplified
Chinese translations, and parts of the Vietnamese one, are AI-generated.
The maintainer reviews every change before it is merged. See
[DISCLAIMER.md](DISCLAIMER.md).
+87 -15
View File
@@ -19,16 +19,23 @@ in [dev_env.md](dev_env.md), Tauri details in [TAURI-NOTES.md](TAURI-NOTES.md).
```
browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
├─ /api/* → worker/index.ts ──► Turnstile siteverify
└─ everything → static assets from dist/
else (_headers, _redirects, SPA fallback to index.html)
├─ /assets/* → static assets from dist/ (hashed bundles, no Worker)
└─ everything → worker/index.ts: per-client rate limit, then
else ├─ /api/* → answered here ──► Turnstile siteverify
└─ pages → ASSETS binding: dist/ with _headers,
_redirects, SPA fallback to index.html
```
- One Cloudflare Worker, **`jsonprism`** (Workers Paid plan), configured in
`wrangler.jsonc`.
- **Static assets**: the Vite build in `dist/`, served by Workers Static Assets
with `not_found_handling: "single-page-application"`.
- **Worker code** runs only for `/api/*` (`run_worker_first: ["/api/*"]`).
- **Worker code** runs first for every request except `/assets/*`
(`run_worker_first: ["/*", "!/assets/*"]`). It counts the request against a
per-client [rate limit](#rate-limiting), hands pages and public files to the
`ASSETS` binding — which still applies `_headers`, `_redirects` and the SPA
fallback — and answers `/api/*` itself. `/assets/*` holds the content-hashed
bundles, most of each page load, and stays on the Worker-free path.
Conversion never happens on the server.
| Route | Code | Response |
@@ -39,8 +46,9 @@ browser ──► jsonprism.poli0981.dev (Cloudflare Worker "jsonprism")
- `worker/index.ts` may only have a default export: workerd treats every named
export of the entry module as an entrypoint. Put helpers in other modules.
- API responses set their own headers (`worker/http.ts`: `no-store`,
`nosniff`, `default-src 'none'`); assets get theirs from `public/_headers`.
- Responses the Worker builds itself (API answers, 429s) set their own headers
(`worker/http.ts`: `no-store`, `nosniff`, `default-src 'none'`); pages and
assets get theirs from `public/_headers`.
- The Worker has its own `tsconfig.worker.json`; its runtime and binding types
come from `npm run cf:types` (`wrangler types` → gitignored
`worker-configuration.d.ts`).
@@ -78,8 +86,8 @@ after the branch (`<branch>-jsonprism.<subdomain>.workers.dev` when workers.dev
is enabled) and reports it on the pull request.
- Previews inherit no production vars or bindings. `wrangler.jsonc` → `previews`
declares them again: a separate rate-limit counter (`namespace_id` 4202) and
an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
declares them again: separate rate-limit counters (`namespace_id` 4202, 4204,
4206) and an empty `ALLOWED_HOSTNAMES`. Any binding added at the top level needs a
preview-safe twin there, or `wrangler preview` fails with "missing a
`previews` block".
- Previews get no `TURNSTILE_SECRET` (set one with
@@ -117,7 +125,7 @@ is enabled) and reports it on the pull request.
| --- | --- | --- |
| `TURNSTILE_SECRET` | Secret | Worker → **Settings → Variables and Secrets**, or `npx wrangler secret put TURNSTILE_SECRET`. Never in the repo. |
| `ALLOWED_HOSTNAMES` | Variable | `wrangler.jsonc` → `vars`: comma-separated hostnames a Turnstile token may be issued on. |
| `VERIFY_LIMITER` | Binding | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
| `SITE_LIMITER`, `API_LIMITER`, `VERIFY_LIMITER` | Bindings | `wrangler.jsonc` → `ratelimits` — see [Rate limiting](#rate-limiting). |
- Plain variables added in the dashboard are replaced by `wrangler.jsonc` `vars`
on every deploy (`keep_vars` is off); secrets are kept. The sitekey needs no
@@ -216,13 +224,50 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
## Rate limiting
- Binding `VERIFY_LIMITER` (`ratelimits` in `wrangler.jsonc`, `namespace_id`
`4201`): 30 requests per 60 s per client, keyed on `CF-Connecting-IP`. The IP
is only the key; it is never logged.
- Over the limit → 429 `rate_limited` with `Retry-After: 60`. The app treats
that as "check unavailable" and lets the user continue.
- To change it, edit `simple.limit` / `simple.period` and deploy. Keep
Three [Rate Limiting bindings](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
(`ratelimits` in `wrangler.jsonc`), applied in `worker/rate-limit.ts`:
| Binding | Counts | Limit | `namespace_id` (production / preview) |
| --- | --- | --- | --- |
| `SITE_LIMITER` | pages and public files: everything outside `/api/` and `/assets/` | 120 requests / 60 s | 4205 / 4206 |
| `API_LIMITER` | every `/api/*` request | 60 requests / 60 s | 4203 / 4204 |
| `VERIFY_LIMITER` | `/api/turnstile/verify`, on top of `API_LIMITER` | 30 requests / 60 s | 4201 / 4202 |
- The key is the client's IPv4 address, or the /64 network of an IPv6 address
(one subscriber usually holds a whole /64), from `CF-Connecting-IP`. It is
only the key; it is never logged.
- A page load makes about three counted requests (`index.html`,
`theme-init.js`, `favicon.svg`); the hashed bundles under `/assets/` are not
counted. 120 per minute is about 40 page loads a minute from one address.
- Over the limit: pages get a plain-text 429 in the four UI languages, the API
gets a JSON 429 `{"ok":false,"error":"rate_limited"}`; both carry
`Retry-After: 60` and `Cache-Control: no-store`. The app treats a 429 from
the verify endpoint as "check unavailable" and lets the user continue.
- The limits are approximate. Counts are kept per Cloudflare data centre, and
each edge machine checks a locally cached count that syncs in the
background. Measured on production (2026-10-27): on one keep-alive
connection they hold almost exactly (120 pages, then 429s), but 300
requests on fresh parallel connections in 13 s all passed, because they
spread over many machines before the counts caught up. They throttle
browsers, crawlers and simple scripts; a strict cap would need a Durable
Object or a WAF rule (below).
- If the limiter itself fails the request goes through (`ratelimit.error` in
the logs): a broken counter must not take the site down.
- Every request that reaches the Worker is billed as a Worker request,
refused ones included. The limits keep floods off the API and slow scrapers;
volumetric attacks are Cloudflare's DDoS protection's job, in front of the
Worker. For a zone-level limit that also covers `/assets/*` and runs before
the Worker, add a WAF rate limiting rule for the hostname in the dashboard
(**Security → WAF → Rate limiting rules**).
- To change a limit, edit `simple.limit` / `simple.period` (10 or 60 s) for
production and its twin under `previews`, then deploy. Keep every
`namespace_id` unique within the Cloudflare account.
- To see it work locally, run `npm run preview:cf` and then
`for i in $(seq 70); do curl -s -o /dev/null -w '%{http_code}\n' http://localhost:8787/api/health; done | sort | uniq -c`
— 60 × 200, then 429s for the rest of the minute. Against production, send
the burst over one connection so it reaches one machine, e.g.
`curl -s -w '%{http_code}\n' $(printf -- '-o /dev/null https://jsonprism.poli0981.dev/api/health %.0s' $(seq 100)) | sort | uniq -c`
(this throttles your own address for a minute).
## Workers Logs
@@ -235,6 +280,9 @@ Vite copies `public/` into `dist/`; Workers Static Assets applies `_headers` and
Outcomes: `verified`, `rejected`, `bad-origin`, `bad-method`,
`bad-content-type`, `too-large`, `rate-limited`, `bad-json`, `bad-token`,
`misconfigured`, `unavailable`.
- Rate limiting writes `{"event":"ratelimit.exceeded","scope":"site"|"api","colo":…}`
for each refused request, and `ratelimit.error` with a `detail` if the
limiter binding fails.
- Never log IPs, tokens or user content (`logEvent()` in `worker/http.ts`).
Source maps are not uploaded (`upload_source_maps: false`).
@@ -306,6 +354,30 @@ after a rollback or a dashboard change.
(`sonar.qualitygate.wait=false`).
- CodeQL runs through GitHub's default setup (no workflow file).
## Qodana
- Workflow `qodana.yml` ("Qodana") runs on every push to `main`, every pull
request to `main`, and by hand. Results go to Qodana Cloud (Ultimate
licence). They also come back as check annotations, a pull-request
comment and the `qodana-js` / `qodana-rust` artifacts (SARIF and logs).
- **Job `js`**: Qodana for JS in native mode (`--within-docker false`).
- Runs on Node 26 with the runner's `node_modules`; `npm run cf:types`
runs first so the Worker's types resolve.
- Config `qodana.yaml`, Cloud project `jsonprism-js-ts`, secret
`QODANA_TOKEN_TS_JS`.
- **Job `rust`**: Qodana for Rust, Early Access, Docker only
(`jetbrains/qodana-rust:2026.2-eap`).
- `src-tauri/` is the project directory and the repository root is
mounted. The job builds `dist/` and the icons first, because
`tauri::generate_context!()` embeds them.
- Config `src-tauri/qodana.yaml`, Cloud project `jsonprism-rust`, secret
`QODANA_TOKEN_RUST`.
- Both jobs skip without their token (Dependabot and fork pull requests).
Findings are reported, not enforced: there is no quality gate.
- If the licence lapses, the jobs fail at the licence check, but only in
this workflow; CI and the Discord notifier are unaffected. Renew the
licence, or delete the two secrets so the jobs skip.
## Releases (desktop + Android)
The web app ships continuously from `main`; tags are for the desktop and
+108 -6
View File
@@ -4,7 +4,9 @@ This document is the **single source of truth** for what's done, what's next, an
Update it as work lands — keep the project status honest.
**Current release: v2.0.0 (2026-10-22).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
**Status: maintenance mode since v2.2.1 (2026-11-16).** No new features; see [Phase 11](#phase-11--maintenance-mode-) for what is still done.
**Current release: v2.2.1 (2026-11-16).** The web app runs at https://jsonprism.poli0981.dev (Cloudflare Workers); desktop and Android builds are on [GitHub Releases](https://github.com/poli0981/jsonPrism/releases).
---
@@ -83,8 +85,8 @@ Goal: make the four working converters production-quality and the UX delightful
- [x] Keyboard shortcuts: ⌘/Ctrl+K (clear), ⌘/Ctrl+S (download) — *⌘/Ctrl+K removed in 2.0.0: it clashed with the browser's search shortcut*
- [x] Status bar showing: input bytes, output bytes, parse time, shortcut hints
- [x] Shape detection hint (scalar / object / array / flat-object / array-of-objects)
- [x] Disabled-format chips show "P2"/"P3" badge with tooltip
- [x] Cmd/Ctrl+, to open settings — *deferred at the time; added in a later 1.x release*
- [x] Disabled-format chips show "P2"/"P3" badge with tooltip — *badges retired once every format shipped; a disabled chip now explains why in its tooltip*
- [x] Cmd/Ctrl+, to open settings — *deferred at the time; added in 2.0.0*
### Deliverable
@@ -178,7 +180,7 @@ Split into three sub-phases for digestibility.
8/9 formats production-ready. Batch up to 500 files. Desktop builds for Windows / macOS / Linux. JSONPrism becomes a "real" tool, not just a website.
**Currently at Phase 2A — only RESX (Phase 3) remains as a stub.**
*Written during Phase 2A, when only RESX (Phase 3) was still a stub; Phase 3 has since shipped.*
---
@@ -243,7 +245,7 @@ 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`).
- [x] Scroll-to-top button on the long, scrollbar-hidden About page (respects `prefers-reduced-motion`). — *since 2.0.0 the scrollbar shows unless **Appearance → Hide scrollbars** is on; since 2.2.0 the button hands focus back to the page*
---
@@ -263,7 +265,7 @@ Compliance + reliability + first-paint performance. No converter behavior change
## Phase 7 — Android (sideload APK) 🔜
**Status**: in progress — the APK has shipped with every release since v1.7.0 (2026-06-16); only the real-device checks below remain.
**Status**: in progress — the APK has shipped with every release since v1.7.0 (2026-06-16); only the real-device checks below remain, handled as maintenance since 2.2.1.
Goal: ship JSONPrism as an Android app users sideload from a `.apk`. Same React UI, no behavior change to the converters. **Minimum Android 12 (API 31)** — older devices are blocked by the OS.
@@ -302,6 +304,7 @@ A platform release: a new home for the web app, a human check and analytics conf
- [x] Web app served by the Cloudflare Worker `jsonprism` (Workers Static Assets, SPA fallback) at **https://jsonprism.poli0981.dev**; config in `wrangler.jsonc`, operations in [`docs/DEPLOYMENT.md`](DEPLOYMENT.md)
- [x] Cloudflare Workers Builds deploys every push to `main`; the GitHub Pages deploy workflow and `public/404.html` are gone
- [x] `/api/*` Worker in `worker/`: `POST /api/turnstile/verify` (same-origin only, 4 KB body cap, 30 requests / 60 s rate limit) and `GET /api/health`; structured Workers Logs without IPs, tokens or user content
- [x] 2.0.2: per-client rate limits for the whole site — the Worker runs first for everything except the hashed `/assets/*` bundles; pages 120 / 60 s, API 60 / 60 s, verify 30 / 60 s; IPv6 keyed on its /64; 429 with `Retry-After`
- [x] Static headers in `public/_headers` (CSP, HSTS, COOP, Permissions-Policy, immutable `/assets/*`), `/jsonPrism/*` → 301 in `public/_redirects`, `robots.txt`, `sitemap.xml`, `.well-known/security.txt`, Open Graph image
- [x] GitHub Pages keeps only a path-preserving redirect to the new domain (`pages-redirect.yml`, run by hand)
- [x] `production-smoke.yml` waits for each pushed commit to go live, then checks headers, routes, redirects and the API
@@ -352,8 +355,106 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
---
## Phase 9 — 2.1.0: JSONC → JSON ✅
**Status**: complete (shipped in v2.1.0, 2026-10-29)
The most common "this isn't valid JSON" paste — config files with comments — now converts in one step.
- [x] `src/converters/jsonc.ts`: hand-written, no dependency. Comments and trailing commas become spaces at the same offsets (error line/column match the input), `JSON.parse` validates, then a token-level printer lays the result out without building JS values — big integers, number spelling, duplicate and `__proto__` keys survive. Iterative, with an output-size guard for pathological nesting.
- [x] Input-only formats: `ConverterMeta.inputOnly`; the chip is disabled in the JSON → direction, switching to JSON → falls back to JSONL, and a stored input-only format opens in → JSON.
- [x] Reverse errors carry an optional line/column (`ConversionFailure`), shown like JSON input errors.
- [x] JSONC input editor: legacy JSON mode for comment highlighting plus a linter that shares the converter's parser.
- [x] JSON → input that is valid JSONC gets a one-click "Convert JSONC → JSON" hint.
- [x] Accepts `.jsonc` and `.json` (plus `.txt`) in the single-file and batch flows; strings in all four locales.
- [x] 2.1.1 (2026-11-04): every npm, Cargo and GitHub Actions dependency at its latest release within the current majors; `THIRD-PARTY.md` re-synced with the lockfiles
### Deliverable
13 chips — 12 target formats plus JSONC as an input. **932 tests in 94 files.**
---
## Phase 10 — 2.2.0: Accessibility ✅
**Status**: complete (shipped in v2.2.0, 2026-11-09)
The release adds an accessibility statement and fixes the gaps that an audit against WCAG 2.2 AA found. The maintainer's keyboard-only and Narrator pass on 2.1.1 found no blockers; these fixes cover what that pass didn't reach.
- [x] **Docs and process:**
- [`ACCESSIBILITY.md`](../ACCESSIBILITY.md) and its [Vietnamese mirror](i18n/vi/ACCESSIBILITY.md): goals, what works, keyboard reference, tested-with table, supported environments, known limitations, contributor expectations, and reporting with severity levels and response times.
- An accessibility issue template and a PR checklist item.
- Rules in CONTRIBUTING and CLAUDE.md.
- [x] **Focus:**
- A skip link.
- Focus moves to `<main>` after a navigation and after the consent gate.
- Visible focus everywhere: a global `:focus-visible` outline, and inset rings on scroll areas and the editors.
- In Windows contrast themes (`forced-colors`), focus, the pressed or selected state, and switches stay visible.
- [x] **Input editor:** an "Escape, then Tab" hint (screen-reader description and status bar), and `aria-invalid` with `aria-describedby` pointing at the current error.
- [x] **Screen readers:**
- Only the status bar's state is a live region.
- The language buttons and Copy have names that start with their visible labels.
- Download and Options expose `aria-keyshortcuts`.
- The unread-output dot has text.
- The format-picker sheet has a description.
- Loading has `role="status"`.
- Back to top hands focus back to the content.
- [x] **Translated screen-reader strings:**
- the toast close button;
- CodeMirror's search, replace, fold and delete announcements;
- the Home page title.
Navigation labels no longer repeat "navigation".
- [x] **Desktop apps:** page zoom with Ctrl/⌘ + = and − (`zoomHotkeysEnabled`, with the `core:webview:allow-set-webview-zoom` permission).
- [x] **Automated check:** an axe-core scan of every page, the consent gate and each sheet runs in `npm test`. The About page links the statement.
### Deliverable
An accessibility statement backed by tests. **949 tests in 95 files.**
---
## Phase 11 — Maintenance mode 📋
**Status**: ongoing since v2.2.1 (2026-11-16)
JSONPrism is feature-complete. From 2.2.1 on it is maintained, not extended: no new features unless one is judged genuinely necessary. The accepted changes, and how out-of-scope issues and pull requests are closed, are in [CONTRIBUTING.md → Maintenance mode](../CONTRIBUTING.md#maintenance-mode).
What 2.2.1 set up for it:
- [x] **Policy:**
- a status section and badge in both READMEs;
- the policy in CONTRIBUTING;
- converter and translation issue templates (the feature-request template is gone);
- a scope checklist in the pull request template.
- [x] **Auto-close:** `maintenance-triage.yml` closes, with a bilingual comment:
- feature issues and `feat:` pull requests from outside contributors;
- anything the maintainer labels `out-of-scope`.
- [x] **Qodana:** Qodana for JS (native mode) and Qodana for Rust (Early Access) on every push and pull request, reported to Qodana Cloud.
- [x] **Dependencies:** every dependency at its latest release, including i18next 27, react-i18next 18 and jsdom 31.
Earlier work still open, now handled as maintenance:
- the Android real-device checks (Phase 7);
- the accessibility follow-ups below.
---
## Beyond — Ideas (no commitment)
**Frozen while JSONPrism is in maintenance mode.** An item moves only if it falls under the [maintenance policy](../CONTRIBUTING.md#maintenance-mode), for example a security need or a converter people really need.
### Accessibility follow-ups
These are tracked as known limitations in [`ACCESSIBILITY.md`](../ACCESSIBILITY.md#known-limitations).
- **Non-text contrast:** text-field and switch outlines at 3:1 (WCAG 1.4.11).
- **Android:** follow the system font size and allow pinch-zoom in the WebView; a TalkBack pass on a real device.
- **More screen readers:** NVDA, VoiceOver and Orca passes, and Windows contrast themes checked on real hardware.
- **Layout switch:** keep editor focus and undo history when the layout changes at 768 px.
- **New tabs:** announce links that open a new tab or the system browser.
- **Long output:** a way to read it in a screen reader's browse mode, such as a plain-text view.
### Deferred from 2.0.0
- **Lazy-load non-English locales** — about 20 KB gzip off the first load
@@ -364,6 +465,7 @@ JSONPrism 2.0.0 on its own domain, with the human check and analytics confined t
- **End-to-end tests** — Playwright (web), tauri-driver (desktop)
- **JSON tools** — JSON Schema, JSONPath and diff features
- **More formats** — INI, `.env`, Java `.properties`, Excel `.xlsx`
- **JSONC as input for every target** — accept comments in the JSON → direction (e.g. `tsconfig.json` straight to YAML) instead of converting to JSON first; changes the strict `parseJsonInput` contract, so it needs its own design
- **Streaming NDJSON** for very large files
- **Community translation workflow** (ja and zh-CN are AI-translated today)
- **Drop the TypeScript 6 alias** once TypeScript 7 ships an API that typescript-eslint supports
+18 -1
View File
@@ -60,6 +60,7 @@ intentionally narrow (trimmed in 2.0.0):
| Permission | Why |
| --- | --- |
| `core:default` | Tauri's core set (app, event, path, window, webview, …), including the `tauri://drag-drop` events. |
| `core:webview:allow-set-webview-zoom` | Page zoom (2.2.0). On macOS and Linux, `zoomHotkeysEnabled` injects a script that zooms with Ctrl/⌘ + = and − through this command. On Windows, WebView2's own zoom controls are used. |
| `opener:default` | Opens `https://` and `mailto:` links in the system browser / mail app via `openUrl`. Works on Android, where the shell plugin's `open()` has no URL handler. |
| `dialog:allow-open`, `dialog:allow-save` | Native open / save dialogs only — no message, ask or confirm dialogs. |
| `fs:default` | The fs plugin's baseline: the app's own data directories; denies the webview data folder. |
@@ -100,6 +101,18 @@ default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'
external blocking script rather than an inline one, so neither CSP needs
`'unsafe-inline'` for scripts (the reason is spelled out in `index.html`).
## Page zoom
`app.windows[0].zoomHotkeysEnabled` is `true` since 2.2.0. It is off by default in Tauri, and before 2.2.0 the desktop apps could only scale with the OS display setting (WCAG 1.4.4 Resize Text).
| Platform | Behaviour |
| --- | --- |
| Windows | Sets WebView2's `IsZoomControlEnabled`: Ctrl + = / − and Ctrl + mouse wheel both work. |
| macOS, Linux | Tauri injects a script for Ctrl/⌘ + = / −, in 20 % steps from 20 % to 1000 %. It calls `set_webview_zoom`, so it needs the permission above. |
| Android | Not supported by Tauri. Pinch-zoom and text size follow the system WebView defaults; see the known limitations in [`ACCESSIBILITY.md`](../ACCESSIBILITY.md#known-limitations). |
The zoom level isn't saved between launches.
## Consent gate
The first-launch Consent Gate (License, Terms, Privacy Policy, Disclaimer)
@@ -144,7 +157,11 @@ Gatekeeper warnings on first launch. Signing is on the roadmap.
draft; it refuses when the release is already published. (Parallel
"find or create" calls used to race and split assets across drafts.)
3. **desktop** — matrix: Windows (`windows-latest`), macOS universal
(`macos-14`, `--target universal-apple-darwin`), Linux (`ubuntu-22.04`).
(`macos-15`, Arm64, `--target universal-apple-darwin`), Linux (`ubuntu-22.04`).
GitHub retired the `macos-14` images on 2026-11-02; the v2.2.0 macOS job
was refused with "configuration … is not supported" and rebuilt on
`macos-15`. `minimumSystemVersion` 12.0 keeps the macOS 12 floor whatever
the runner's version.
Each builds with `tauri-apps/tauri-action` v1 and uploads into the draft.
4. **android** — Java 17 (Temurin), SDK platform 36 + NDK `27.2.12479018`,
Rust Android targets; signs with the release keystore from secrets and
+1 -1
View File
@@ -56,7 +56,7 @@ npm run preview:cf # wrangler dev on http://localhost:8787 (builds
- `.dev.vars` holds the Worker secret `TURNSTILE_SECRET` for local runs. It is
gitignored; never put the production secret in it.
- `npm run preview:cf` serves `dist/` the way production does (`_headers`,
`_redirects`, SPA fallback) together with the `/api/*` Worker. On localhost
`_redirects`, SPA fallback) behind the Worker (rate limits, `/api/*`). On localhost
the app uses Cloudflare's test sitekey, so the Consent Gate's Turnstile check
passes on its own.
- `npm run cf:types` — regenerates `worker-configuration.d.ts` (gitignored)
+322
View File
@@ -0,0 +1,322 @@
> **Lưu ý:** Đây là bản dịch tiếng Việt chỉ mang tính tham khảo. Nếu có
> bất kỳ khác biệt nào giữa bản dịch này và
> [bản gốc tiếng Anh](../../../ACCESSIBILITY.md), bản tiếng Anh được ưu
> tiên áp dụng.
# Trợ năng (Accessibility)
**Rà soát lần cuối**: 2026-11-09 · **Áp dụng cho**: JSONPrism 2.2.x (website, ứng dụng desktop và Android)
JSONPrism muốn ai cần chuyển đổi JSON cũng dùng được, bất kể họ dùng
thiết bị nhập nào, trình đọc màn hình nào, thiết lập hiển thị hay ngôn
ngữ nào. Tài liệu này nêu mục tiêu, những gì đang hoạt động, cách đã kiểm
thử, những gì còn chưa ổn và cách báo một rào cản.
JSONPrism do một người duy trì (xem [DISCLAIMER.md](../../../DISCLAIMER.md)).
Đây là nỗ lực thành thật hết mức có thể, không phải kết quả được chứng nhận.
## Mục tiêu
- **Đích: [WCAG 2.2](https://www.w3.org/TR/WCAG22/) mức AA.** Website và
các ứng dụng dùng chung một giao diện, nên mục tiêu áp dụng cho tất cả.
Đây là mục tiêu, không phải tuyên bố đã đạt chuẩn: chưa có đợt audit
chính thức nào.
- **Ưu tiên, theo thứ tự:**
1. Mọi việc đều làm được chỉ bằng bàn phím: chuyển đổi, mở và lưu tệp,
chuyển đổi hàng loạt (batch), tuỳ chọn và màn hình đồng ý điều khoản.
2. Mọi control đều có tên, vai trò và trạng thái để trình đọc màn hình
đọc được, bằng ngôn ngữ của giao diện.
3. Nội dung luôn dễ đọc khi tăng độ tương phản, phóng to, dùng theme
sáng hoặc tối, giảm chuyển động hoặc bật contrast theme của Windows.
- **Lỗi hồi quy về trợ năng là bug.** Chúng được phân loại và sửa như mọi
bug khác (xem [Báo lỗi trợ năng](#báo-lỗi-trợ-năng)).
## Những gì đang hoạt động
### Bàn phím
- Mọi phần tử tương tác đều là nút, liên kết hay control form gốc của
HTML, hoặc component Radix UI có sẵn hỗ trợ bàn phím. Không phần tử nào
có `tabindex` dương.
- **Bỏ qua, tới nội dung chính** (skip link) là điểm dừng Tab đầu tiên.
Khi bạn chuyển sang trang khác, focus chuyển vào nội dung của trang đó.
- Control nào đang có focus cũng hiện chỉ báo focus.
- **Hộp thoại và sheet** (Tuỳ chọn, Batch, chọn định dạng):
- focus nằm gọn bên trong khi chúng đang mở;
- Escape đóng chúng;
- sau đó focus quay về nút đã mở chúng.
- **Màn hình đồng ý** giữ focus bên trong và phải được trả lời; sau khi
bạn đồng ý, focus chuyển vào nội dung trang.
- **Ô nhập (editor):** Tab dùng để thụt lề. Để rời khỏi editor, nhấn
**Esc rồi Tab** (WCAG 2.1.2). Mô tả cho trình đọc màn hình và thanh
trạng thái đều ghi điều này.
- Ô kết quả chỉ đọc và các vùng cuộn khác nhận được focus và cuộn bằng
phím mũi tên, Page Up/Down.
- **Vùng kéo thả có cách tương đương bằng bàn phím:** **Mở** ở ô nhập,
**click để duyệt…** trong Batch.
### Trình đọc màn hình
- **Cấu trúc trang:**
- landmark (banner, điều hướng, nội dung chính, chân trang);
- mỗi trang một `h1`;
- tiêu đề trang đã dịch cho mọi route.
- `<html lang>` theo ngôn ngữ giao diện. Mỗi tên ngôn ngữ trong bộ chuyển
ngôn ngữ có `lang` riêng.
- **Các editor:**
- Cả hai đều có tên, ví dụ "JSON đầu vào" và "Kết quả CSV (chỉ đọc)".
- Ô nhập báo nội dung có hợp lệ hay không (`aria-invalid`).
- Ô nhập được mô tả bằng thông báo lỗi hiện tại (`aria-describedby`).
- **Live region đọc lên:**
- lỗi phân tích kèm dòng và cột, và lỗi chuyển đổi (dạng cảnh báo);
- trạng thái chuyển đổi, nhưng không đọc số byte hay thời gian;
- tiến độ batch và bước xác minh con người;
- thông báo mất mạng và trạng thái đang tải trang;
- các thông báo (notification).
- **Trạng thái và phím tắt:**
- Nút bật/tắt có `aria-pressed`.
- Lựa chọn theme là radio, các thiết lập bật/tắt là switch.
- Phím tắt tải về và mở tuỳ chọn được khai báo bằng `aria-keyshortcuts`.
- Icon trang trí được ẩn khỏi công nghệ hỗ trợ, nút chỉ có icon đều có tên.
- Các thông báo riêng của editor (tìm kiếm, thay thế, thu gọn) cùng bảng
tìm kiếm và bảng lỗi đã được dịch sang cả bốn ngôn ngữ giao diện.
### Hiển thị
- **Theme:** sáng, tối và theo hệ thống.
- Màu chữ đã được kiểm tra đạt 4.5:1 so với nền ở cả hai theme.
- Chỉ báo focus dùng màu ring của theme, tương phản từ 3:1 trở lên.
- **Giảm chuyển động:** khi bật `prefers-reduced-motion`, hiệu ứng động và
chuyển cảnh bị tắt, nút Về đầu trang nhảy thẳng thay vì cuộn mượt.
- **Contrast theme của Windows** (`forced-colors`): focus, nút đang được
chọn và switch được vẽ bằng màu hệ thống.
- **Không truyền tải ý nghĩa chỉ bằng màu:**
- chấm trạng thái luôn đi kèm chữ;
- các dòng trong batch có icon và chữ;
- chấm báo có kết quả mới trên tab Kết quả (bố cục hẹp) còn kèm chữ "(mới)".
- **Vùng chạm** đạt WCAG 2.5.8: tối thiểu 24 × 24 CSS px, hoặc cách nhau
đủ để vòng tròn 24 px quanh mỗi vùng không chồng lên vùng bên cạnh.
### Phóng to và dàn lại bố cục
- **Website:** phóng to của trình duyệt và tăng cỡ chữ đều dùng được,
không bao giờ chặn pinch-zoom.
- **Ứng dụng desktop:** từ 2.2.0, Ctrl/⌘ + = và Ctrl/⌘ + − phóng to, thu
nhỏ cửa sổ. Trên Windows dùng được cả Ctrl + con lăn chuột.
- **Màn hình hẹp:** bố cục dàn lại tới bề rộng 320 CSS px mà không cần
cuộn ngang. Bố cục được thiết kế cho 360 × 640 trở lên
([các viewport đã kiểm thử](../../tested-viewports.md)).
### Ngôn ngữ
Giao diện, kể cả mọi đoạn chữ dành cho trình đọc màn hình, có tiếng Anh,
tiếng Việt, tiếng Nhật và tiếng Trung giản thể.
## Bảng phím tắt
| Phím | Ở đâu | Tác dụng |
| --- | --- | --- |
| Tab / Shift+Tab | Mọi nơi | Control tiếp theo / trước đó |
| Enter trên **Bỏ qua, tới nội dung chính** | Lần Tab đầu tiên của trang | Nhảy tới nội dung trang |
| Ctrl+S (⌘S trên macOS) | Trang chuyển đổi | Tải kết quả về |
| Ctrl+, (⌘, trên macOS) | Trang chuyển đổi | Mở Tuỳ chọn |
| Esc | Hộp thoại, sheet, menu Giao diện | Đóng, focus quay về nút đã mở |
| ↑ ↓ Home End | Menu Giao diện | Di chuyển giữa các mục |
| ← → | Tab Đầu vào / Kết quả (màn hình hẹp) | Chuyển tab |
| Esc rồi Tab | Ô nhập | Rời editor (chỉ Tab thì thụt lề) |
| Ctrl+M (Shift+Alt+M trên macOS) | Ô nhập | Bật/tắt chế độ "Tab chuyển focus" |
| Ctrl+] / Ctrl+[ (⌘] / ⌘[) | Ô nhập | Thụt lề / bỏ thụt lề |
| Ctrl+F (⌘F), rồi F3 / Shift+F3 | Cả hai editor | Tìm, kết quả tiếp / trước |
| Ctrl+Alt+G (⌘⌥G) | Cả hai editor | Đến dòng |
| Ctrl+Shift+M (⌘⇧M), F8 | Ô nhập | Mở danh sách lỗi, lỗi tiếp theo |
| Alt+T | Mọi nơi | Focus vào thông báo (tạm dừng chúng) |
| Ctrl/⌘ + = và − | Ứng dụng desktop | Phóng to / thu nhỏ |
## Cách kiểm thử
### Đã kiểm thử với
| Ngày | Phiên bản | Nền tảng | Cách kiểm | Kết quả |
| --- | --- | --- | --- | --- |
| 2026-11 | 2.1.1 | Windows 11: website trên Edge, Brave và Firefox; ứng dụng Windows (WebView2) | Narrator; chỉ bàn phím, không dùng chuột (maintainer) | Không có lỗi chặn |
| 2026-11-09 | 2.2.0 | Chromium (bản development) | Đi bằng bàn phím qua các thay đổi của 2.2.0: skip link, focus sau khi chuyển trang và sau màn hình đồng ý, chỉ báo focus | Đạt |
| 2026-11-09 | 2.2.0 | iPhone 14 Pro (máy thật), iOS 26: website production trên Brave và Chrome | Kiểm tra thủ công bằng cảm ứng (maintainer) | Hoạt động đúng |
| Mỗi pull request | — | jsdom trong CI | [axe-core](https://github.com/dequelabs/axe-core) trên mọi trang, màn hình đồng ý và từng sheet; kiểm tra vai trò và tên bằng Testing Library | Bắt buộc đạt |
| 2026-10-22 | 2.0.0 | Giả lập thiết bị trên Chromium, từ 360 × 740 tới 1280 × 800, sáng và tối | Kiểm tra bố cục bằng mắt | Xem [các viewport đã kiểm thử](../../tested-viewports.md) |
Bài quét tự động chạy không có engine layout thật nên không đo được độ
tương phản màu; độ tương phản được kiểm tra thủ công.
**Chưa kiểm thử** (rất mong nhận báo cáo):
- **Trình đọc màn hình:** NVDA và JAWS (Windows), VoiceOver (macOS, iOS),
TalkBack (Android), Orca (Linux).
- **Điều khiển bằng giọng nói:** Dragon, Voice Access.
- **Trên thiết bị thật:** contrast theme của Windows, cỡ chữ hệ thống trên
Android.
### Kiểm tra thủ công trước khi phát hành
1. **Chỉ bàn phím.** Đi qua mọi luồng chính:
- chuyển đổi, mở tệp, tải về;
- chạy một batch ra tệp `.zip`;
- đổi tuỳ chọn, theme và ngôn ngữ;
- qua màn hình đồng ý.
Kiểm tra focus luôn nhìn thấy và không bao giờ bị kẹt.
2. **Trình đọc màn hình.** Dùng Narrator, NVDA hoặc VoiceOver cho các
luồng trên. Nghe tên, trạng thái, lỗi và trạng thái chuyển đổi.
3. **Phóng to.** Kiểm tra ở 200 % và 400 % trong cửa sổ rộng 1280 px, cùng
chế độ chỉ phóng to chữ nếu trình duyệt có.
4. **Thiết lập hiển thị.** Kiểm tra với contrast theme của Windows, với
giảm chuyển động, và ở theme sáng lẫn tối.
5. **Quét tự động.** Chạy `npm test`, lệnh này bao gồm bài quét axe-core.
## Môi trường hỗ trợ
| Bề mặt | Engine | Công nghệ hỗ trợ đã kiểm |
| --- | --- | --- |
| Website | Chrome, Edge, Brave, Firefox và Safari bản hiện hành (engine tối thiểu: Chromium 111, WebKit của macOS 12) | Narrator với Edge, Brave và Firefox |
| Ứng dụng Windows | Microsoft Edge WebView2 | Narrator |
| Ứng dụng macOS (12+) | WKWebView | — |
| Ứng dụng Linux (Ubuntu 22.04+) | WebKitGTK | — |
| Ứng dụng Android (12+) | Android System WebView, Chromium 111+ | — |
## Hạn chế đã biết
Đây là các rào cản đã biết, kèm cách khắc phục tạm nếu có. Chúng được
theo dõi trong [`docs/ROADMAP.md`](../../ROADMAP.md).
1. **Kết quả dài khi trình đọc màn hình ở chế độ duyệt (browse mode).**
Editor chỉ giữ trong trang các dòng đang hiển thị, nên con trỏ ảo không
đọc được hết một kết quả dài. *Cách khắc phục:* **Sao chép** hoặc **Tải
về** kết quả rồi đọc bằng ứng dụng khác.
2. **Tab thụt lề trong ô nhập.** *Cách khắc phục:* nhấn Esc rồi Tab; hoặc
nhấn Ctrl+M (Shift+Alt+M trên macOS) để Tab chuyển focus.
3. **Cửa sổ nhỏ hoặc thấp.**
- Khi chiều cao dưới khoảng 600 CSS px, các editor trở nên rất thấp,
kể cả khi phóng to 400 % trong cửa sổ rộng 1280 px.
- Trên điện thoại, chỉ chiều dọc được hỗ trợ đầy đủ.
- Khi bề rộng vượt qua mốc 768 CSS px, ví dụ do phóng to, bố cục chuyển
giữa dạng hai cột và dạng tab. Các editor được tạo lại: chữ của bạn
vẫn còn, nhưng focus và lịch sử hoàn tác (undo) thì không.
*Cách khắc phục:* phóng to ở mức 200–300 %.
4. **Xác minh con người (chỉ trên website).** Cloudflare Turnstile chạy
trong một khung của Cloudflare, nên khả năng truy cập của nó thuộc về
Cloudflare. Nếu bước này lỗi hoặc quá 20 giây, nút **Tiếp tục không xác
minh** sẽ hiện ra.
5. **Thông báo tự đóng sau 4 giây.** Trình đọc màn hình đọc chúng ngay khi
xuất hiện. *Cách khắc phục:* rê chuột lên, hoặc nhấn Alt+T để focus và
tạm dừng chúng.
6. **Tương phản phi văn bản thấp.** Viền ô nhập và switch dưới 3:1
(WCAG 1.4.11). Ô nào cũng có nhãn, nhưng đường viền mờ.
7. **Định dạng không dùng được.** Lý do một định dạng không dùng được nằm
trong tooltip. Trình đọc màn hình nhận được nó dưới dạng mô tả của nút,
nhưng người dùng màn hình cảm ứng không xem được.
8. **Không báo khi mở tab mới.** Các liên kết mở tab mới, hoặc mở trình
duyệt hệ thống từ ứng dụng, không nói điều đó.
9. **Ứng dụng desktop.** Cửa sổ nhỏ nhất là 800 × 560. Phóng to trang mới
có từ 2.2.0.
10. **Ứng dụng Android.** Ứng dụng dùng cách xử lý mặc định của WebView
với cỡ chữ hệ thống và pinch-zoom, chưa được kiểm chứng trên thiết bị
thật.
11. **Bản dịch.** Chữ tiếng Nhật và tiếng Trung, kể cả chữ dành cho trình
đọc màn hình, do AI tạo; rất hoan nghênh người bản ngữ sửa.
## Yêu cầu với người đóng góp
Người đóng góp kiểm tra các điểm sau với mọi thay đổi giao diện (xem thêm
[CONTRIBUTING.md](../../../CONTRIBUTING.md)):
- **Phần tử.** Dùng phần tử HTML gốc hoặc các component trong
`src/components/ui/`. Không gắn click handler cho `div` hay `span`, không
dùng `tabindex` dương.
- **Tên.** Mọi control đều có tên accessible lấy từ các file locale, đủ cả
bốn ngôn ngữ. Nút chỉ có icon có `aria-label`, icon trang trí có
`aria-hidden`.
- **Focus.**
- Không dùng `outline-none` nếu không có thứ thay thế dạng `focus-visible:`.
- Vùng cuộn nhận focus phải có `role="region"` và nhãn.
- Ngoại lệ duy nhất là phần tử được focus từ code với `tabIndex={-1}`,
như `<main>`.
- **Chuyển động và màu.** Hiệu ứng động đặt sau `motion-safe:`. Không
truyền tải ý nghĩa chỉ bằng màu.
- **Thông báo.** Dùng các live region có sẵn, giữ thông báo ngắn gọn.
Không đọc lên đoạn chữ thay đổi sau mỗi lần gõ phím.
- **Kiểm thử.**
- `npm test` phải đạt, kể cả bài quét axe-core trong
`src/app/__tests__/a11y.test.tsx`. Mở rộng bài quét khi thêm trang hay
hộp thoại mới.
- Tự đi bằng bàn phím qua phần mình thay đổi và ghi lại trong pull request.
- Kiểm tra nhanh bằng trình đọc màn hình thì càng tốt.
- **Tài liệu này.** Cập nhật khi hành vi hoặc một hạn chế đã biết thay đổi.
## Báo lỗi trợ năng
Mở issue bằng template **[Accessibility
issue](https://github.com/poli0981/jsonPrism/issues/new?template=accessibility.md)**,
kèm theo:
- bạn định làm gì và chuyện gì đã xảy ra;
- công nghệ hỗ trợ bạn dùng và phiên bản;
- phiên bản trình duyệt hoặc ứng dụng, và hệ điều hành.
Bạn không cần biết nguyên nhân.
Nếu không thể hoặc không muốn dùng GitHub, hãy email
**code@poli0981.dev**, tiêu đề có chữ "Accessibility". Vấn đề bảo mật đi
theo [SECURITY.md](../../../SECURITY.md).
### Mức độ
| Mức độ | Ý nghĩa | Ví dụ |
| --- | --- | --- |
| Critical | Chặn một việc chính, không có cách khắc phục | Không thể chuyển đổi, mở, lưu tệp hoặc qua màn hình đồng ý bằng bàn phím hay trình đọc màn hình |
| High | Rất khó khăn nhưng có cách khắc phục | Lỗi không bao giờ được đọc lên, nhưng có hiện trong ô kết quả |
| Medium | Không nhất quán hoặc gây khó hiểu, nhưng vẫn làm được | Nhãn sai hoặc thiếu; focus rơi vào chỗ lạ |
| Low | Phiền nhỏ | Đọc lên quá dài dòng; một gợi ý chưa được dịch |
### Cách chúng tôi phản hồi
- Cảm ơn bạn và hỏi lại nếu có gì chưa rõ. Không bao giờ yêu cầu bạn giải
thích vì sao bạn cần một tính năng trợ năng.
- Gắn nhãn `accessibility`, đặt mức độ, ưu tiên lỗi chặn trước lỗi về
hình thức.
- Chia sẻ cách khắc phục tạm ngay khi biết.
- Khi có bản sửa, nhờ bạn xác nhận nếu bạn sẵn lòng. Các bản sửa được ghi
trong [CHANGELOG.md](../../../CHANGELOG.md).
### Thời gian phản hồi
Đây là nỗ lực hết mức có thể của một dự án một người:
| Mức độ | Phản hồi đầu tiên | Phát hành bản sửa |
| --- | --- | --- |
| Critical | trong vòng 7 ngày | bản patch kế tiếp |
| High | trong vòng 14 ngày | bản phát hành kế tiếp |
| Medium / Low | trong vòng 30 ngày | khi có thể, thường là bản minor kế tiếp |
## Trách nhiệm và duy trì
Kokone ([@poli0981](https://github.com/poli0981)), maintainer duy nhất
(xem [MAINTAINERS.md](../../../MAINTAINERS.md)), chịu trách nhiệm về trợ
năng, gồm:
- phân loại báo cáo;
- theo dõi chúng bằng nhãn `accessibility`;
- chạy [bước kiểm tra thủ công](#kiểm-tra-thủ-công-trước-khi-phát-hành)
trước khi phát hành;
- giữ tài liệu này luôn cập nhật, kể cả ngày rà soát.
## Góp ý
Mọi góp ý cho tài liệu này đều được hoan nghênh qua issue hoặc pull request.
Cấu trúc tài liệu theo khuyến nghị của Open Source Guides
([Accessibility best practices for your
project](https://opensource.guide/accessibility-best-practices-for-your-project/))
và [Open Source Accessibility
toolkit](https://github.com/open-source-accessibility/accessibility-toolkit).
[English](../../../ACCESSIBILITY.md)
+9 -7
View File
@@ -47,13 +47,15 @@ Cloudflare, Inc. phục vụ trang web và xử lý dữ liệu mà mọi yêu c
tin TLS) để cung cấp các trang và bảo vệ dịch vụ trước hành vi lạm dụng.
Phần mã phía máy chủ của riêng JSONPrism chỉ xử lý API xác minh con người
(`/api/turnstile/verify`) và một điểm kiểm tra tình trạng hoạt động
(health check). Với API đó, phần mã này ghi lại các sự kiện có cấu trúc —
kết quả, trạng thái HTTP, mã trung tâm dữ liệu của Cloudflare, thời lượng
và mã lỗi Turnstile — vào Cloudflare Workers Logs, được lưu giữ trong 7
ngày. Các sự kiện này không bao giờ chứa địa chỉ IP, token Turnstile hay
bất cứ nội dung nào bạn chuyển đổi. API này được Cloudflare giới hạn tần
suất truy cập (rate limit) theo từng máy khách; JSONPrism không lưu trữ
khoá máy khách (client key).
(health check), đồng thời tính các yêu cầu tới trang và API vào giới hạn
tần suất truy cập (rate limit) theo từng máy khách trước khi phục vụ.
Phần mã này ghi lại các sự kiện có cấu trúc — kết quả, trạng thái HTTP,
mã trung tâm dữ liệu của Cloudflare, thời lượng, mã lỗi Turnstile và các
yêu cầu bị từ chối vì vượt giới hạn — vào Cloudflare Workers Logs, được
lưu giữ trong 7 ngày. Các sự kiện này không bao giờ chứa địa chỉ IP, token
Turnstile hay bất cứ nội dung nào bạn chuyển đổi. Bộ đếm giới hạn tần
suất do Cloudflare lưu giữ, theo khoá là địa chỉ IP của bạn (với IPv6 là
mạng /64 của địa chỉ đó); JSONPrism không lưu trữ khoá này.
### Xác minh con người (trang web)
+1 -1
View File
@@ -58,7 +58,7 @@ npm run preview:cf # wrangler dev tại http://localhost:8787 (t
- `.dev.vars` chứa secret `TURNSTILE_SECRET` của Worker khi chạy local. File
này đã được gitignore; tuyệt đối không đưa secret production vào đây.
- `npm run preview:cf` phục vụ `dist/` giống hệt production (`_headers`,
`_redirects`, SPA fallback) cùng với Worker `/api/*`. Trên localhost app
`_redirects`, SPA fallback) phía sau Worker (rate limit, `/api/*`). Trên localhost app
dùng sitekey test của Cloudflare, nên bước kiểm tra Turnstile trong Consent
Gate tự pass.
- `npm run cf:types` — tạo lại `worker-configuration.d.ts` (đã gitignore) sau
+16
View File
@@ -10,6 +10,16 @@ Status legend:
Recommended minimum viewport: **360 × 640**. Phones in landscape orientation are best-effort — see [recommendation](#recommendation).
## v2.2.0 check (2026-11-09)
The maintainer checked the production website (https://jsonprism.poli0981.dev) on a real phone.
| Device | Viewport | Browsers | Status | Notes |
| --- | --- | --- | --- | --- |
| iPhone 14 Pro (iOS 26) | 393 × 852 | Brave, Chrome | ✅ | Real device; everything works as expected |
The accessibility checks for this release are recorded in [`ACCESSIBILITY.md` → Tested with](../ACCESSIBILITY.md#tested-with).
## v2.0.0 check (2026-10-22)
Chromium device emulation against the production build served by `wrangler dev` (`npm run preview:cf`), in the light and the dark theme at each size.
@@ -68,5 +78,11 @@ Also checked in this round:
3. Pick a device from the dropdown or set a custom viewport.
4. Verify on the Home page: Header navigation visible, Input/Output Tabs accessible, FormatPicker trigger fits, no horizontal scroll on `<body>`.
5. Repeat in light and dark (Appearance menu), pass the Consent Gate (the Turnstile test key passes on its own), and check the console for CSP violations.
6. Run the accessibility checks in [`ACCESSIBILITY.md` → Manual check before a release](../ACCESSIBILITY.md#manual-check-before-a-release):
- keyboard only;
- a screen reader;
- 200 % and 400 % zoom;
- a Windows contrast theme;
- reduced motion.
Test results contributed by the maintainer. PRs welcome to expand the matrix.
+3 -3
View File
@@ -18,11 +18,11 @@
<title>JSONPrism · Disperse JSON into 12 formats</title>
<meta
name="description"
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, and six of them back to JSON. Conversion runs on your device; batch up to 500 files."
content="JSONPrism converts JSON to JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR and MessagePack, reads six of them back, and turns JSONC (JSON with comments) into plain JSON. Conversion runs on your device; batch up to 500 files."
/>
<meta
name="keywords"
content="JSON converter, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
content="JSON converter, JSONC to JSON, JSONL, NDJSON, CSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT, BSON, CBOR, MessagePack, batch, offline"
/>
<!-- Updated per route by Layout (useCanonicalUrl). -->
<link rel="canonical" href="https://jsonprism.poli0981.dev/" />
@@ -33,7 +33,7 @@
<meta property="og:title" content="JSONPrism — Disperse JSON into 12 formats" />
<meta
property="og:description"
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible. Runs on your device."
content="A refracting tool for developers: one JSON input, twelve target formats, six of them reversible, plus JSONC to JSON. Runs on your device."
/>
<meta property="og:url" content="https://jsonprism.poli0981.dev/" />
<meta property="og:image" content="https://jsonprism.poli0981.dev/og-image.png" />
+1 -1
View File
@@ -3,7 +3,7 @@
"entry": ["src/lib/convert-worker.ts"],
"project": ["src/**/*.{ts,tsx,css}", "worker/**/*.ts"],
"ignore": ["src/components/ui/**"],
"ignoreDependencies": ["@radix-ui/react-slot", "@testing-library/user-event"],
"ignoreDependencies": ["@radix-ui/react-slot"],
"rules": {
"types": "off"
}
+954 -1250
View File
File diff suppressed because it is too large. Load diff
+34 -32
View File
@@ -1,9 +1,9 @@
{
"name": "jsonprism",
"private": true,
"version": "2.0.1",
"version": "2.2.1",
"type": "module",
"description": "Disperse JSON into 12 formats (six convert back) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
"description": "Disperse JSON into 12 formats (six convert back, plus JSONC → JSON) — JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown, SQL, BSON, CBOR, MessagePack. Conversion runs locally in your browser or desktop app.",
"author": "poli0981 <code@poli0981.dev> (https://github.com/poli0981)",
"license": "Apache-2.0",
"homepage": "https://jsonprism.poli0981.dev",
@@ -50,7 +50,7 @@
"@codemirror/lang-yaml": "^6.1.3",
"@codemirror/language": "^6.13.1",
"@codemirror/legacy-modes": "^6.5.5",
"@codemirror/lint": "^6.9.7",
"@codemirror/lint": "^6.9.8",
"@codemirror/state": "^6.7.6",
"@codemirror/view": "^6.43.15",
"@fontsource-variable/geist": "^5.3.0",
@@ -63,60 +63,62 @@
"@radix-ui/react-switch": "^1.4.1",
"@radix-ui/react-tabs": "^1.2.1",
"@tauri-apps/api": "^2.12.4",
"@tauri-apps/plugin-dialog": "^2.8.3",
"@tauri-apps/plugin-dialog": "^2.8.4",
"@tauri-apps/plugin-fs": "^2.7.1",
"@tauri-apps/plugin-opener": "^2.7.2",
"@tauri-apps/plugin-opener": "^2.7.3",
"@uiw/react-codemirror": "^4.25.12",
"bson": "^7.3.3",
"cbor-x": "^1.6.8",
"bson": "^7.3.4",
"cbor-x": "^1.6.9",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"fast-xml-parser": "^5.11.2",
"fast-xml-builder": "^1.3.2",
"fast-xml-parser": "^5.12.1",
"fflate": "^0.8.3",
"i18next": "^26.5.5",
"i18next-browser-languagedetector": "^8.2.1",
"i18next": "^27.1.3",
"i18next-browser-languagedetector": "^8.3.0",
"js-yaml": "^5.5.0",
"lucide-react": "^1.61.0",
"papaparse": "^5.7.0",
"lucide-react": "^1.73.0",
"papaparse": "^5.7.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-dropzone": "^20.1.4",
"react-i18next": "^17.1.1",
"react-router": "^8.5.0",
"react-dropzone": "^20.2.0",
"react-i18next": "^18.0.2",
"react-router": "^8.5.1",
"smol-toml": "^1.9.1",
"sonner": "^2.0.8",
"tailwind-merge": "^3.7.0",
"zustand": "^5.0.16"
"zustand": "^5.1.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.3.3",
"@tailwindcss/vite": "^4.3.5",
"@tauri-apps/cli": "^2.12.4",
"@testing-library/dom": "^10.4.2",
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@testing-library/user-event": "^14.6.8",
"@types/node": "^26.6.5",
"@testing-library/user-event": "^14.6.12",
"@types/node": "^26.6.6",
"@types/papaparse": "^5.5.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@typescript/native": "npm:typescript@^7.0.2",
"@vitejs/plugin-react": "^6.1.2",
"@vitest/coverage-v8": "^5.0.5",
"eslint": "^10.13.0",
"@vitejs/plugin-react": "^6.3.0",
"@vitest/coverage-v8": "^5.1.0",
"axe-core": "^4.14.0",
"eslint": "^10.15.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7",
"globals": "^17.13.0",
"jsdom": "^30.1.3",
"knip": "^6.42.1",
"prettier": "^3.9.10",
"eslint-plugin-react-refresh": "^0.5.8",
"globals": "^17.14.0",
"jsdom": "^31.0.1",
"knip": "^6.45.1",
"prettier": "^3.10.1",
"prettier-plugin-tailwindcss": "^0.8.1",
"tailwindcss": "^4.3.3",
"tailwindcss": "^4.3.5",
"tw-animate-css": "^1.4.0",
"typescript": "npm:@typescript/typescript6@^6.0.2",
"typescript-eslint": "^8.72.0",
"vite": "^8.3.5",
"vitest": "^5.0.5",
"wrangler": "^4.151.3"
"typescript-eslint": "^8.72.2",
"vite": "^8.3.8",
"vitest": "^5.1.0",
"wrangler": "^4.162.0"
}
}
+27
View File
@@ -0,0 +1,27 @@
# Qodana for JS/TS: Qodana Cloud project "jsonprism-js-ts".
# Runs in native mode from .github/workflows/qodana.yml (job "js").
# The Tauri shell has its own configuration in src-tauri/qodana.yaml.
version: '1.0'
linter: qodana-js
profile:
name: qodana.recommended
exclude:
- name: All
paths:
# Build output, caches and generated files
- .wrangler
- coverage
- dist
- node_modules
- package-lock.json
- worker-configuration.d.ts
# Generated by the shadcn CLI; not edited by hand (see CLAUDE.md)
- src/components/ui
# Analysed by Qodana for Rust (src-tauri/qodana.yaml)
- src-tauri
# The webhook there is a ${{ secrets.… }} reference, not a hard-coded secret.
- name: HardcodedPasswords
paths:
- .github/workflows/notify-release-pipeline.yml
+365 -280
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "jsonprism"
version = "2.0.1"
version = "2.2.1"
description = "Disperse JSON into many formats."
authors = ["poli0981 <code@poli0981.dev>"]
license = "Apache-2.0"
@@ -23,6 +23,8 @@ tauri-plugin-dialog = "2"
tauri-plugin-fs = "2"
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
# Not referenced in src/, but the code tauri::generate_context!() expands to
# uses ::serde_json, so it has to stay a direct dependency.
serde_json = "1"
# Desktop-only: prevent multiple JSONPrism windows / processes when the user
+2 -1
View File
@@ -1,10 +1,11 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "JSONPrism main window: native open/save dialogs, reading files the user picks or drops, writing where they choose to save, and opening links in the system browser. Picked and dropped paths are added to the fs scope at runtime; the static scope only covers common folders.",
"description": "JSONPrism main window: native open/save dialogs, reading files the user picks or drops, writing where they choose to save, opening links in the system browser, and page zoom (Ctrl/Cmd + and -). Picked and dropped paths are added to the fs scope at runtime; the static scope only covers common folders.",
"windows": ["main"],
"permissions": [
"core:default",
"core:webview:allow-set-webview-zoom",
"opener:default",
"dialog:allow-open",
"dialog:allow-save",
+4 -4
View File
@@ -6,12 +6,12 @@
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/v2.0.1/LICENSE\par
https://github.com/poli0981/jsonPrism/blob/v2.2.1/LICENSE\par
\par
Your use is also governed by the following documents (version 2.0, effective 2026-10-22):\par
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.0.1/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.0.1/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.0.1/DISCLAIMER.md\par
\bullet\tab Terms of Service (EULA): https://github.com/poli0981/jsonPrism/blob/v2.2.1/TERMS.md\par
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/v2.2.1/PRIVACY.md\par
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/v2.2.1/DISCLAIMER.md\par
\par
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. The desktop app converts everything on your device and makes no network requests of its own.\par
\par
+33
View File
@@ -0,0 +1,33 @@
# Qodana for Rust (Early Access): Qodana Cloud project "jsonprism-rust".
# Runs in Docker from .github/workflows/qodana.yml (job "rust"), with this
# folder as the project directory and the repository root mounted, so
# tauri::generate_context!() can read ../dist.
version: '1.0'
linter: qodana-rust
# The image ships Rust but no C toolchain or GTK/WebKit headers, so build
# scripts and proc macros can't compile ("linker `cc` not found") and the
# analysis is incomplete. Install what the CI `rust` job installs. This needs
# the container to run as root (--user root in the workflow).
bootstrap: >-
apt-get update -qq &&
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends
build-essential pkg-config libssl-dev libgtk-3-dev libwebkit2gtk-4.1-dev
profile:
name: qodana.recommended
exclude:
- name: All
paths:
# Generated by `tauri android init` and the Android build
- gen
# Generated by `npm run tauri:icon`
- icons
- target
# serde_json looks unused from src/, but the code tauri::generate_context!()
# expands to uses ::serde_json, and removing it breaks the build (see the
# comment in Cargo.toml).
- name: CargoUnusedDependency
paths:
- Cargo.toml
+3 -2
View File
@@ -22,6 +22,7 @@
"fullscreen": false,
"transparent": false,
"dragDropEnabled": true,
"zoomHotkeysEnabled": true,
"theme": null
}
],
@@ -42,7 +43,7 @@
],
"category": "DeveloperTool",
"shortDescription": "Disperse JSON into many formats",
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back, entirely on your machine.",
"longDescription": "JSONPrism is a refracting tool for developers. It takes a single JSON input and disperses it into twelve formats — JSONL, CSV, TSV, YAML, XML, TOML, .NET RESX, Markdown table, SQL INSERT, BSON, CBOR and MessagePack — and parses six of them back (plus JSONC into plain JSON), entirely on your machine.",
"copyright": "Copyright (c) 2026 poli0981",
"publisher": "poli0981",
"homepage": "https://jsonprism.poli0981.dev",
@@ -78,7 +79,7 @@
},
"android": {
"minSdkVersion": 31,
"versionCode": 20001
"versionCode": 20201
}
},
"plugins": {
+161
View File
@@ -0,0 +1,161 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router';
import '@/i18n';
import { App } from '../App';
import { axeViolations } from '@/test/axe';
import { stubRangeGeometry } from '@/test/range-geometry';
import { useConsentStore } from '@/stores/consentStore';
import { useWorkspaceStore } from '@/stores/workspaceStore';
vi.mock('@/lib/analytics', () => ({ loadWebAnalytics: vi.fn(() => false) }));
stubRangeGeometry();
beforeEach(() => {
// axe probes <canvas> for icon fonts; jsdom only logs "not implemented".
vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(null);
});
function renderApp(path = '/') {
const user = userEvent.setup();
render(
<MemoryRouter initialEntries={[path]}>
<App />
</MemoryRouter>,
);
return user;
}
/**
* Waits for the real CodeMirror editor, which loads as its own chunk. Until
* then a plain <textarea> with the same name stands in, so match on the
* editor's content element, not just the role and name.
*/
async function findInputEditor() {
return waitFor(
() => {
const editor = screen.getByRole('textbox', { name: 'Input JSON' });
expect(editor).toHaveClass('cm-content');
return editor;
},
{ timeout: 10_000 },
);
}
beforeEach(() => {
useConsentStore.setState({ accepted: true, humanVerified: true });
useWorkspaceStore.setState({
input: '[{"id":1,"name":"Ada"}]',
format: 'csv',
direction: 'forward',
optionsByFormat: {},
});
});
afterEach(() => {
vi.restoreAllMocks();
document.documentElement.classList.remove('dark');
});
describe('axe-core scan', () => {
it('reports real violations (guards against a scan that checks nothing)', async () => {
render(
<main>
<button type="button">
<svg aria-hidden="true" />
</button>
</main>,
);
// This bare render also lacks a <title>; the app pages always have one.
expect(await axeViolations()).toEqual(
expect.arrayContaining([
expect.stringMatching(/^button-name \(critical\)/),
expect.stringMatching(/^document-title/),
]),
);
});
it('finds no violations on the converter page', async () => {
renderApp('/');
const editor = await findInputEditor();
expect(editor).toHaveAccessibleDescription(/To leave the editor, press Escape, then Tab/);
expect(await axeViolations()).toEqual([]);
});
it('finds no violations while the input does not parse', async () => {
useWorkspaceStore.setState({ input: '{"broken": ' });
renderApp('/');
const editor = await findInputEditor();
await waitFor(() => expect(editor).toHaveAttribute('aria-invalid', 'true'));
expect(await axeViolations()).toEqual([]);
});
it.each([
['/about', 'About JSONPrism'],
['/no/such/page', 'Page not found'],
['/error/403', 'Forbidden'],
])('finds no violations on %s', async (path, heading) => {
renderApp(path);
await screen.findByRole('heading', { level: 1, name: heading });
expect(await axeViolations()).toEqual([]);
});
it('finds no violations with the consent gate open', async () => {
useConsentStore.setState({ accepted: false });
renderApp('/');
await screen.findByRole('dialog', { name: 'Before you start' });
expect(await axeViolations()).toEqual([]);
});
it.each([
['Options', /options/i],
['Batch', /batch/i],
[/Target format/, /Target format/],
])('finds no violations with the %s sheet open', async (trigger, dialogName) => {
const user = renderApp('/');
await findInputEditor();
await user.click(screen.getByRole('button', { name: trigger }));
const dialog = await screen.findByRole('dialog', { name: dialogName });
expect(dialog).toHaveAccessibleDescription();
expect(await axeViolations()).toEqual([]);
});
});
describe('focus management', () => {
it('starts with a skip link that moves focus to the main content', async () => {
const user = renderApp('/about');
await screen.findByRole('heading', { level: 1, name: 'About JSONPrism' });
await user.tab();
const skip = screen.getByRole('link', { name: 'Skip to content' });
expect(skip).toHaveFocus();
await user.keyboard('{Enter}');
expect(screen.getByRole('main')).toHaveFocus();
// The next Tab continues inside the page, not back in the header.
await user.tab();
expect(
within(screen.getByRole('main')).getByRole('region', { name: 'About JSONPrism' }),
).toHaveFocus();
});
it('moves focus to the main content after navigating', async () => {
const user = renderApp('/about');
await screen.findByRole('heading', { level: 1, name: 'About JSONPrism' });
await user.click(screen.getByRole('link', { name: 'Convert' }));
await findInputEditor();
expect(screen.getByRole('main')).toHaveFocus();
});
it('continues in the main content once the consent gate closes', async () => {
useConsentStore.setState({ accepted: false });
const user = renderApp('/about');
await screen.findByRole('dialog', { name: 'Before you start' });
await user.click(screen.getByRole('checkbox', { name: /I have read and agree/ }));
await user.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(screen.getByRole('main')).toHaveFocus());
});
});
+6
View File
@@ -9,6 +9,7 @@ import {
DialogTitle,
} from '@/components/ui/dialog';
import { HumanCheck } from '@/components/common/HumanCheck';
import { focusMain } from '@/lib/focus';
import { legalDocUrl } from '@/lib/links';
import { isTurnstileEnabled } from '@/lib/turnstile';
import { useConsentStore } from '@/stores/consentStore';
@@ -47,6 +48,11 @@ export function ConsentGate({ children }: { children: ReactNode }) {
onEscapeKeyDown={(e) => e.preventDefault()}
onPointerDownOutside={(e) => e.preventDefault()}
onInteractOutside={(e) => e.preventDefault()}
// The gate has no trigger to return to, so Radix would leave focus
// on <body>; continue in the page content instead.
onCloseAutoFocus={(e) => {
if (focusMain()) e.preventDefault();
}}
className="max-w-md"
>
{/* Tauri builds never run the human check, so the bundler drops it there. */}
+2 -1
View File
@@ -27,7 +27,8 @@ export function LanguageSwitcher() {
type="button"
lang={lang.code}
aria-pressed={current === lang.code}
aria-label={lang.name}
// Starts with the visible code so voice control ("click JA") works (WCAG 2.5.3).
aria-label={`${lang.label} ${lang.name}`}
title={lang.name}
onClick={() => change(lang.code)}
className={cn(
+5 -2
View File
@@ -5,8 +5,11 @@ import { LoaderCircle } from 'lucide-react';
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" />
<div
role="status"
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" aria-hidden />
<span className="text-sm">{t('common.loading')}</span>
</div>
);
+5 -2
View File
@@ -1,11 +1,11 @@
import { useEffect, useState } from 'react';
import { useEffect, useState, type RefObject } 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>;
scrollRef: RefObject<HTMLDivElement | null>;
/** Reveal the button once the container is scrolled past this many pixels. */
threshold?: number;
}
@@ -28,6 +28,9 @@ export function ScrollToTop({ scrollRef, threshold = 320 }: ScrollToTopProps) {
if (!el) return;
const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
el.scrollTo({ top: 0, behavior: reduceMotion ? 'auto' : 'smooth' });
// The button hides at the top; hand focus to the content it scrolled
// (a focusable region) rather than leaving it on a hidden control.
if (el.tabIndex >= 0) el.focus({ preventScroll: true });
};
return (
+6 -1
View File
@@ -1,12 +1,15 @@
import type { ReactNode } from 'react';
import { cn } from '@/lib/utils';
interface ToolbarButtonProps {
onClick: () => void;
label: string;
icon: React.ReactNode;
icon: ReactNode;
disabled?: boolean;
/** Shown instead of `label` (visually) without changing the accessible name. */
visibleLabel?: string;
/** `aria-keyshortcuts` value, e.g. "Control+S". */
keyShortcuts?: string;
className?: string;
}
@@ -21,6 +24,7 @@ export function ToolbarButton({
icon,
disabled,
visibleLabel,
keyShortcuts,
className,
}: ToolbarButtonProps) {
return (
@@ -29,6 +33,7 @@ export function ToolbarButton({
onClick={onClick}
disabled={disabled}
aria-label={label}
aria-keyshortcuts={keyShortcuts}
title={label}
className={cn(
'group text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring inline-flex min-h-8 items-center gap-1.5 rounded-md px-2 text-xs transition outline-none focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-40',
@@ -17,11 +17,12 @@ describe('LanguageSwitcher', () => {
const group = screen.getByRole('group', { name: 'Language' });
const buttons = within(group).getAllByRole('button');
expect(buttons.map((b) => b.textContent)).toEqual(['EN', 'VI', 'JA', 'ZH']);
expect(within(group).getByRole('button', { name: 'English' })).toHaveAttribute(
expect(within(group).getByRole('button', { name: 'EN English' })).toHaveAttribute(
'aria-pressed',
'true',
);
expect(within(group).getByRole('button', { name: '日本語' })).toHaveAttribute('lang', 'ja');
// Names start with the visible code (WCAG 2.5.3) and add the native name.
expect(within(group).getByRole('button', { name: 'JA 日本語' })).toHaveAttribute('lang', 'ja');
expect(screen.getByRole('combobox', { name: 'Language' })).toHaveValue('en');
});
@@ -29,14 +30,14 @@ describe('LanguageSwitcher', () => {
const user = userEvent.setup();
render(<LanguageSwitcher />);
await user.click(screen.getByRole('button', { name: 'Tiếng Việt' }));
await user.click(screen.getByRole('button', { name: 'VI Tiếng Việt' }));
expect(i18n.resolvedLanguage).toBe('vi');
expect(document.documentElement.lang).toBe('vi');
expect(screen.getByRole('button', { name: 'Tiếng Việt' })).toHaveAttribute(
expect(screen.getByRole('button', { name: 'VI Tiếng Việt' })).toHaveAttribute(
'aria-pressed',
'true',
);
expect(screen.getByRole('button', { name: 'English' })).toHaveAttribute(
expect(screen.getByRole('button', { name: 'EN English' })).toHaveAttribute(
'aria-pressed',
'false',
);
@@ -51,7 +52,7 @@ describe('LanguageSwitcher', () => {
expect(i18n.resolvedLanguage).toBe('zh-CN');
expect(document.documentElement.lang).toBe('zh-CN');
expect(screen.getByRole('combobox')).toHaveValue('zh-CN');
expect(screen.getByRole('button', { name: '简体中文' })).toHaveAttribute(
expect(screen.getByRole('button', { name: 'ZH 简体中文' })).toHaveAttribute(
'aria-pressed',
'true',
);
@@ -68,6 +69,9 @@ describe('LanguageSwitcher', () => {
</I18nextProvider>,
);
expect(screen.getByRole('combobox')).toHaveValue('en');
expect(screen.getByRole('button', { name: 'English' })).toHaveAttribute('aria-pressed', 'true');
expect(screen.getByRole('button', { name: 'EN English' })).toHaveAttribute(
'aria-pressed',
'true',
);
});
});
@@ -6,7 +6,8 @@ import { RouteFallback } from '../RouteFallback';
describe('RouteFallback', () => {
it('shows a translated loading indicator while a route chunk streams in', () => {
const { container } = render(<RouteFallback />);
expect(screen.getByText('Loading…')).toBeInTheDocument();
expect(screen.getByRole('status')).toHaveTextContent('Loading…');
expect(container.querySelector('svg')).toHaveClass('animate-spin');
expect(container.querySelector('svg')).toHaveAttribute('aria-hidden', 'true');
});
});
@@ -99,6 +99,18 @@ describe('ScrollToTop', () => {
expect(scroll).toHaveBeenCalledWith({ top: 0, behavior });
});
it('hands focus to a focusable container instead of the button it hides', async () => {
const user = userEvent.setup();
stubReducedMotion(true);
render(<ScrollArea initialScroll={1000} />);
const scroller = screen.getByTestId('scroller');
scroller.tabIndex = 0;
Object.defineProperty(scroller, 'scrollTo', { configurable: true, value: vi.fn() });
await user.click(screen.getByRole('button', { name: 'Back to top' }));
expect(scroller).toHaveFocus();
});
it('does nothing without a scroll container', async () => {
const user = userEvent.setup();
const matchMedia = stubReducedMotion(false);
+4 -3
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef } from 'react';
import { useCallback, useEffect, useRef, type ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone, type FileRejection } from 'react-dropzone';
import { useShallow } from 'zustand/react/shallow';
@@ -144,7 +144,7 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
}
};
const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const onFileInputChange = (e: ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files ?? []);
e.target.value = '';
if (files.length > 0) handleAddFiles(files);
@@ -250,8 +250,9 @@ export function BatchPanel({ format, direction, options, open, onOpenChange }: B
{/* Queue list */}
<div
className="flex-1 [scrollbar-gutter:stable] overflow-y-auto px-6 pb-3"
className="focus-visible:ring-ring flex-1 [scrollbar-gutter:stable] overflow-y-auto px-6 pb-3 outline-none focus-visible:ring-2 focus-visible:ring-inset"
tabIndex={0} // NOSONAR(S6845): scrollable region; keyboard users need focus to scroll it
role="region"
aria-label={t('batch.queue_label')}
>
{totalCount === 0 ? (
+67 -9
View File
@@ -1,4 +1,4 @@
import { useMemo } from 'react';
import { useId, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import CodeMirror, {
EditorState,
@@ -12,15 +12,18 @@ import { xml } from '@codemirror/lang-xml';
import { markdown } from '@codemirror/lang-markdown';
import { sql } from '@codemirror/lang-sql';
import { HighlightStyle, StreamLanguage, syntaxHighlighting } from '@codemirror/language';
import { json as jsonStream } from '@codemirror/legacy-modes/mode/javascript';
import { toml } from '@codemirror/legacy-modes/mode/toml';
import { lintGutter, linter, type Diagnostic } from '@codemirror/lint';
import { tags as t } from '@lezer/highlight';
import { parseJsonInput } from '@/lib/detect';
import { parseJsonc } from '@/converters/jsonc';
import type { ConversionFailure } from '@/converters/types';
import { parseJsonInput, type ParseFailure } from '@/lib/detect';
import { useTheme } from '@/lib/theme';
import { cn } from '@/lib/utils';
export type EditorLanguage =
'json' | 'jsonl' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
'json' | 'jsonl' | 'jsonc' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
export interface CodeEditorProps {
value: string;
@@ -31,6 +34,10 @@ export interface CodeEditorProps {
placeholder?: string;
/** Accessible name for the editable region (screen readers). */
ariaLabel?: string;
/** Space-separated ids of elements that describe the editor (hints, errors). */
ariaDescribedBy?: string;
/** Marks the content invalid, e.g. while the input doesn't parse. */
ariaInvalid?: boolean;
}
/**
@@ -76,15 +83,23 @@ const yieldFileDrops = EditorView.domEventHandlers({
const LINT_LIMIT_CHARS = 2_000_000;
const MAX_JSONL_DIAGNOSTICS = 100;
type Check = (text: string) => { ok: true } | ParseFailure | ConversionFailure;
/**
* Lints `text` (starting at document offset `start`) with the converter's own
* parser, so the editor and the conversion agree — a leading byte-order mark
* is fine, and error positions match on every engine. Blank text is a
* prompt, not an error.
*/
function parseDiagnostic(view: EditorView, text: string, start: number): Diagnostic | null {
const result = parseJsonInput(text);
if (result.ok || result.error === 'empty') return null;
function parseDiagnostic(
view: EditorView,
text: string,
start: number,
check: Check = parseJsonInput,
): Diagnostic | null {
if (!text.trim()) return null;
const result = check(text);
if (result.ok) return null;
const { doc } = view.state;
let from = start;
if (result.line !== undefined && result.column !== undefined) {
@@ -100,6 +115,17 @@ const jsonLint = linter((view) => {
return diagnostic ? [diagnostic] : [];
});
// @lezer/json has no comment tokens, so JSONC uses the legacy JSON mode, which
// highlights them. It calls true/false/null "atom"; colour them like JSON's.
const jsoncLanguage = StreamLanguage.define({ ...jsonStream, tokenTable: { atom: t.bool } });
// JSONC: comments and trailing commas are fine; the rest must be JSON.
const jsoncLint = linter((view) => {
if (view.state.doc.length > LINT_LIMIT_CHARS) return [];
const diagnostic = parseDiagnostic(view, view.state.doc.toString(), 0, parseJsonc);
return diagnostic ? [diagnostic] : [];
});
// JSONL: every non-blank line is its own JSON document.
const jsonlLint = linter((view) => {
const { doc } = view.state;
@@ -134,6 +160,8 @@ function languageExtensions(language: EditorLanguage, readOnly: boolean) {
return readOnly ? [json()] : [json(), lintGutter(), jsonLint];
case 'jsonl':
return readOnly ? [json()] : [json(), lintGutter(), jsonlLint];
case 'jsonc':
return readOnly ? [jsoncLanguage] : [jsoncLanguage, lintGutter(), jsoncLint];
case 'yaml':
return [yaml()];
case 'xml':
@@ -149,7 +177,9 @@ function languageExtensions(language: EditorLanguage, readOnly: boolean) {
}
}
// English phrases used by CodeMirror's search panel, folding and lint UI.
// English phrases used by CodeMirror's search panel, folding and lint UI, and
// in what it announces to screen readers (search, replace, folding, deletion).
// `$` is CodeMirror's placeholder for a number; translations keep it.
const PHRASE_KEYS: Record<string, string> = {
Find: 'find',
Replace: 'replace',
@@ -170,6 +200,15 @@ const PHRASE_KEYS: Record<string, string> = {
unfold: 'unfold',
Diagnostics: 'diagnostics',
'No diagnostics': 'no_diagnostics',
'Folded lines': 'folded_lines',
'Unfolded lines': 'unfolded_lines',
to: 'to',
'current match': 'current_match',
'on line': 'on_line',
'replaced match on line $': 'replaced_match_on_line',
'replaced $ matches': 'replaced_matches',
'Selection deleted': 'selection_deleted',
'Control character': 'control_character',
};
export function CodeEditor({
@@ -180,10 +219,15 @@ export function CodeEditor({
className,
placeholder,
ariaLabel,
ariaDescribedBy,
ariaInvalid = false,
}: CodeEditorProps) {
const { resolvedTheme } = useTheme();
const { t: translate, i18n } = useTranslation();
const wrap = value.length < WRAP_LIMIT_CHARS;
// Tab indents in the editable editor (WCAG 2.1.2: say how to leave it).
const tabHintId = useId();
const describedBy = [readOnly ? undefined : tabHintId, ariaDescribedBy].filter(Boolean).join(' ');
const phrases = useMemo(() => {
const entries = Object.entries(PHRASE_KEYS).map(([phrase, key]) => [
@@ -241,8 +285,15 @@ export function CodeEditor({
'.cm-placeholder': {
color: 'var(--muted-foreground)',
},
// Focus ring drawn inside the editor: the wrapper clips overflow.
'&.cm-focused': {
outline: 'none',
outline: '2px solid var(--color-ring)',
outlineOffset: '-2px',
},
// The read-only output focuses its scroller, not the content.
'.cm-scroller:focus-visible': {
outline: '2px solid var(--color-ring)',
outlineOffset: '-2px',
},
},
{ dark: isDark },
@@ -255,15 +306,22 @@ export function CodeEditor({
phrases,
EditorView.contentAttributes.of({
...(ariaLabel ? { 'aria-label': ariaLabel } : {}),
...(describedBy ? { 'aria-describedby': describedBy } : {}),
...(ariaInvalid ? { 'aria-invalid': 'true' } : {}),
...(readOnly ? { 'aria-readonly': 'true' } : {}),
}),
...(readOnly ? [focusableScroller(ariaLabel)] : []),
theme,
];
}, [ariaLabel, language, phrases, readOnly, resolvedTheme, wrap]);
}, [ariaInvalid, ariaLabel, describedBy, language, phrases, readOnly, resolvedTheme, wrap]);
return (
<div className={cn('h-full overflow-hidden', className)}>
{!readOnly && (
<span id={tabHintId} className="sr-only">
{translate('editor.tab_hint')}
</span>
)}
<CodeMirror
// The wrapper div this component renders must fill the panel too, or
// `height="100%"` has nothing to resolve against: the editor grows to
+5 -1
View File
@@ -20,6 +20,8 @@ function EditorFallback({
readOnly = false,
className,
ariaLabel,
ariaDescribedBy,
ariaInvalid = false,
}: CodeEditorProps) {
return (
<div className={cn('h-full overflow-hidden', className)}>
@@ -29,8 +31,10 @@ function EditorFallback({
spellCheck={false}
placeholder={placeholder}
aria-label={ariaLabel}
aria-describedby={ariaDescribedBy}
aria-invalid={ariaInvalid || undefined}
onChange={onChange ? (e) => onChange(e.target.value) : undefined}
className="text-foreground placeholder:text-muted-foreground h-full w-full resize-none bg-transparent px-4 py-3 font-mono text-[13px] leading-[1.6] outline-none"
className="text-foreground placeholder:text-muted-foreground focus-visible:ring-ring h-full w-full resize-none bg-transparent px-4 py-3 font-mono text-[13px] leading-[1.6] outline-none focus-visible:ring-2 focus-visible:ring-inset"
/>
</div>
);
@@ -23,6 +23,8 @@ import { StatusBar, type ConversionState } from './StatusBar';
import { BatchPanel } from './BatchPanel';
const REVERSIBLE_FALLBACKS: FormatId[] = ['jsonl', 'csv', 'yaml', 'toml', 'resx'];
/** Where the JSON → direction lands when the current format is input-only. */
const FORWARD_FALLBACK: FormatId = 'jsonl';
export function ConverterWorkspace() {
const { t } = useTranslation();
@@ -74,16 +76,24 @@ export function ConverterWorkspace() {
(next: Direction) => {
setDirection(next);
// If the current format doesn't support the new direction, switch to one that does.
if (next === 'reverse' && typeof getConverter(format).reverse !== 'function') {
const converter = getConverter(format);
if (next === 'reverse' && typeof converter.reverse !== 'function') {
const fallback = REVERSIBLE_FALLBACKS.find(
(id) => typeof getConverter(id).reverse === 'function',
);
if (fallback) setFormat(fallback);
}
if (next === 'forward' && converter.meta.inputOnly) setFormat(FORWARD_FALLBACK);
},
[format, setDirection, setFormat],
);
// Offered by the input panel when JSON → fails on text that is valid JSONC.
const readAsJsonc = useCallback(() => {
setDirection('reverse');
setFormat('jsonc');
}, [setDirection, setFormat]);
const currentOptions = useMemo(
() => storedOptions ?? { ...getConverter(format).defaultOptions },
[format, storedOptions],
@@ -130,6 +140,7 @@ export function ConverterWorkspace() {
format={format}
direction={direction}
onMultiFileDrop={handleMultiFileDrop}
onReadAsJsonc={readAsJsonc}
/>
);
const outputPanel = (
@@ -193,10 +204,14 @@ export function ConverterWorkspace() {
<TabsTrigger value="output" className="relative">
{t('home.tab_output')}
{hasUnreadOutput && (
<span
aria-hidden
className="bg-primary absolute top-1 right-1 h-1.5 w-1.5 rounded-full"
/>
<>
<span
aria-hidden
className="bg-primary absolute top-1 right-1 h-1.5 w-1.5 rounded-full"
/>
{/* The dot alone is visual; say it in the tab's name too. */}{' '}
<span className="sr-only">{t('home.output_unread')}</span>
</>
)}
</TabsTrigger>
</TabsList>
@@ -204,14 +219,14 @@ export function ConverterWorkspace() {
<TabsContent
value="input"
forceMount
className="min-h-0 flex-1 data-[state=inactive]:hidden"
className="focus-visible:ring-ring min-h-0 flex-1 focus-visible:ring-2 focus-visible:ring-inset data-[state=inactive]:hidden"
>
{inputPanel}
</TabsContent>
<TabsContent
value="output"
forceMount
className="min-h-0 flex-1 data-[state=inactive]:hidden"
className="focus-visible:ring-ring min-h-0 flex-1 focus-visible:ring-2 focus-visible:ring-inset data-[state=inactive]:hidden"
>
{outputPanel}
</TabsContent>
+23 -8
View File
@@ -1,7 +1,14 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ChevronDown } from 'lucide-react';
import { Sheet, SheetContent, SheetHeader, SheetTitle, SheetTrigger } from '@/components/ui/sheet';
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet';
import { ALL_FORMATS, getConverter } from '@/converters/registry';
import type { Direction, FormatId } from '@/converters/types';
import type { JsonShape } from '@/lib/detect';
@@ -13,7 +20,10 @@ interface FormatPickerProps {
onChange: (id: FormatId) => void;
/** Drives the subtle highlight ring on suggested chips. */
shape?: JsonShape | null;
/** When reverse, formats without a reverse() implementation are disabled. */
/**
* When reverse, formats without a reverse() implementation are disabled;
* when forward, input-only formats (JSONC) are.
*/
direction?: Direction;
}
@@ -30,7 +40,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
return (
<>
{/* Mobile: compact Sheet trigger — saves ~50-80px of toolbar height when
the 12 chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
the chip grid would otherwise wrap to 2-3 rows on narrow viewports. */}
<Sheet open={sheetOpen} onOpenChange={setSheetOpen}>
<SheetTrigger asChild>
<button
@@ -49,6 +59,9 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
>
<SheetHeader>
<SheetTitle>{t('home.format_picker_label')}</SheetTitle>
<SheetDescription className="sr-only">
{t('home.format_picker_description')}
</SheetDescription>
</SheetHeader>
<div
className="grid grid-cols-2 gap-1.5 p-4 pt-2 sm:grid-cols-3"
@@ -70,7 +83,7 @@ export function FormatPicker({ value, onChange, shape, direction = 'forward' }:
</SheetContent>
</Sheet>
{/* Desktop: 12 chips inline. */}
{/* Desktop: every chip inline. */}
<div
className="hidden flex-wrap gap-1 md:flex"
role="group"
@@ -101,8 +114,9 @@ interface FormatChipProps {
expanded?: boolean;
}
function chipStatus(noReverse: boolean, suggested: boolean, dimmed: boolean) {
function chipStatus(noReverse: boolean, inputOnly: boolean, suggested: boolean, dimmed: boolean) {
if (noReverse) return 'no_reverse';
if (inputOnly) return 'input_only';
if (suggested) return 'suggested';
return dimmed ? 'not_suggested' : 'ready';
}
@@ -113,9 +127,10 @@ function FormatChip({ id, value, onChange, shape, direction, expanded }: FormatC
const active = value === id;
const suggested = direction === 'forward' && shape ? isFormatSuggested(id, shape) : false;
const noReverse = direction === 'reverse' && typeof c.reverse !== 'function';
const enabled = c.meta.ready && !noReverse;
const dimmed = direction === 'forward' && !!shape && !suggested && c.meta.ready;
const status = chipStatus(noReverse, suggested, dimmed);
const inputOnly = direction === 'forward' && c.meta.inputOnly === true;
const enabled = c.meta.ready && !noReverse && !inputOnly;
const dimmed = direction === 'forward' && !!shape && !suggested && enabled;
const status = chipStatus(noReverse, inputOnly, suggested, dimmed);
return (
<button
+36 -3
View File
@@ -1,12 +1,14 @@
import { useCallback, useRef, useState } from 'react';
import { useCallback, useId, useMemo, useRef, useState, type ChangeEvent } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone, type FileRejection } from 'react-dropzone';
import { Eraser, FileText, FolderOpen } from 'lucide-react';
import { Eraser, FileText, FolderOpen, MessageSquareCode } from 'lucide-react';
import { ToolbarButton } from '@/components/common/ToolbarButton';
import { toast } from '@/components/ui/sonner';
import { parseJsonc } from '@/converters/jsonc';
import { extensionsFor } from '@/converters/registry';
import type { Direction, FormatId } from '@/converters/types';
import { useFileAccept } from '@/hooks/useFileAccept';
import { WORKER_THRESHOLD_CHARS } from '@/lib/convert-client';
import { editorLanguageFor } from '@/lib/editor-language';
import { errorMessage } from '@/lib/errors';
import { extOf } from '@/lib/file-filter';
@@ -28,6 +30,8 @@ interface InputPanelProps {
direction: Direction;
/** Called when 2+ files are dropped — workspace routes them into batch. */
onMultiFileDrop?: (files: File[]) => void;
/** Switches to JSONC → JSON; offered when JSON → fails on valid JSONC. */
onReadAsJsonc?: () => void;
}
export function InputPanel({
@@ -39,10 +43,12 @@ export function InputPanel({
format,
direction,
onMultiFileDrop,
onReadAsJsonc,
}: InputPanelProps) {
const { t } = useTranslation();
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragActive, setDragActive] = useState(false);
const errorId = useId();
const { converter, isReverse, accept, fileInputAccept, allowedExtensions } = useFileAccept(
format,
@@ -150,12 +156,19 @@ export function InputPanel({
}
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = '';
if (file) loadFile(file);
};
// Comments or trailing commas make JSON → fail; if that is all that is wrong,
// offer JSONC. Inputs this big convert in the worker, so skip the extra parse.
const looksLikeJsonc = useMemo(
() => !isReverse && !!error && value.length < WORKER_THRESHOLD_CHARS && parseJsonc(value).ok,
[error, isReverse, value],
);
const showOverlay = isDragActive || dragActive;
const position =
errorLine != null
@@ -204,6 +217,7 @@ export function InputPanel({
</div>
<div
id={errorId}
role="status"
aria-live="polite"
className={cn(
@@ -219,12 +233,31 @@ export function InputPanel({
) : null}
</div>
{looksLikeJsonc && onReadAsJsonc && (
<div className="border-border/70 flex flex-wrap items-center justify-between gap-x-3 gap-y-1 border-b px-3 py-1 text-xs">
<span className="text-muted-foreground">{t('home.jsonc_hint')}</span>
<button
type="button"
onClick={onReadAsJsonc}
className="group border-primary/40 text-foreground hover:bg-primary/10 focus-visible:ring-ring inline-flex min-h-6 items-center gap-1.5 rounded-md border px-2 font-mono font-medium transition outline-none focus-visible:ring-2"
>
<MessageSquareCode
className="h-3.5 w-3.5 transition-transform motion-safe:group-hover:-rotate-6"
aria-hidden
/>
{t('home.jsonc_switch')}
</button>
</div>
)}
<div className="relative min-h-0 flex-1">
<CodeEditorLazy
value={value}
onChange={onChange}
language={editorLanguageFor(format, direction)}
ariaLabel={inputLabel}
ariaDescribedBy={errorId}
ariaInvalid={!!error}
placeholder={
isReverse
? t('home.input_placeholder_format', {
+5 -2
View File
@@ -5,6 +5,7 @@ import { toast } from '@/components/ui/sonner';
import { ToolbarButton } from '@/components/common/ToolbarButton';
import { getConverter } from '@/converters/registry';
import type { Direction, FormatId } from '@/converters/types';
import { ariaModShortcut } from '@/hooks/useKeyboardShortcuts';
import { decodeBytes, type Encoding } from '@/lib/bytes';
import { downloadBlob } from '@/lib/download';
import { outputLanguageFor } from '@/lib/editor-language';
@@ -115,6 +116,7 @@ export function OutputPanel({
{pending && (
<LoaderCircle
className="text-primary h-3.5 w-3.5 motion-safe:animate-spin"
role="img"
aria-label={t('common.loading')}
/>
)}
@@ -122,8 +124,8 @@ export function OutputPanel({
<div className="flex items-center gap-0.5">
<ToolbarButton
onClick={() => void handleCopy()}
label={t('home.copy')}
visibleLabel={copied ? t('home.copied') : t('home.copy')}
// The name follows the visible label (WCAG 2.5.3).
label={copied ? t('home.copied') : t('home.copy')}
icon={
copied ? (
<Check className="text-success motion-safe:animate-pop h-3.5 w-3.5" />
@@ -136,6 +138,7 @@ export function OutputPanel({
<ToolbarButton
onClick={() => void handleDownload()}
label={t('home.download')}
keyShortcuts={ariaModShortcut('S')}
icon={<Download className="motion-safe:group-hover:animate-bob h-3.5 w-3.5" />}
disabled={disabled}
/>
@@ -12,6 +12,7 @@ import {
import { Switch } from '@/components/ui/switch';
import { getConverter } from '@/converters/registry';
import type { FormatId, OptionSchemaField } from '@/converters/types';
import { ariaModShortcut } from '@/hooks/useKeyboardShortcuts';
import { cn } from '@/lib/utils';
interface SettingsPanelProps {
@@ -48,6 +49,7 @@ export function SettingsPanel({
<SheetTrigger asChild>
<button
type="button"
aria-keyshortcuts={ariaModShortcut(',')}
className="group text-muted-foreground hover:bg-muted hover:text-foreground border-border bg-card/60 inline-flex min-h-8 items-center gap-1.5 rounded-md border px-2.5 text-xs transition"
>
<Settings2
+13 -4
View File
@@ -27,10 +27,14 @@ export function StatusBar({ state, inputBytes, outputBytes, ms, precisionLoss }:
return (
<div className="border-border/70 text-muted-foreground flex items-center justify-between gap-3 border-t px-3 py-1 font-mono text-[11px]">
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5" aria-live="polite">
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-0.5">
<span className="inline-flex items-center gap-1.5">
<span aria-hidden className={cn('h-1.5 w-1.5 rounded-full', DOT_TONE[state])} />
<span className="text-foreground">{t(`status.state.${state}`)}</span>
{/* Only the state is announced; sizes and timing change on every
keystroke and would flood screen readers. */}
<span className="text-foreground" aria-live="polite">
{t(`status.state.${state}`)}
</span>
</span>
<span>
{t('status.in')} <span className="text-foreground">{formatBytes(inputBytes)}</span>
@@ -54,14 +58,19 @@ export function StatusBar({ state, inputBytes, outputBytes, ms, precisionLoss }:
<span>UTF-8</span>
<Shortcut keys={`${modKey()}+S`} label={t('shortcut.download')} />
<Shortcut keys={`${modKey()}+,`} label={t('shortcut.settings')} />
<Shortcut
keys="Esc, Tab"
label={t('shortcut.leave_editor')}
className="hidden lg:inline-flex"
/>
</div>
</div>
);
}
function Shortcut({ keys, label }: { keys: string; label: string }) {
function Shortcut({ keys, label, className }: { keys: string; label: string; className?: string }) {
return (
<span className="inline-flex items-center gap-1">
<span className={cn('inline-flex items-center gap-1', className)}>
<kbd className="kbd">{keys}</kbd>
<span>{label}</span>
</span>
@@ -1,4 +1,4 @@
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { act, createEvent, fireEvent, render } from '@testing-library/react';
import { EditorView } from '@codemirror/view';
import { diagnosticCount, forceLinting } from '@codemirror/lint';
@@ -7,28 +7,10 @@ import '@/i18n';
import { parseJsonInput } from '@/lib/detect';
import { editorLanguageFor } from '@/lib/editor-language';
import { ThemeProvider, type Theme } from '@/lib/theme';
import { stubRangeGeometry } from '@/test/range-geometry';
import { CodeEditor, type CodeEditorProps, type EditorLanguage } from '../CodeEditor';
// jsdom has no layout engine; CodeMirror measures text ranges to draw the
// cursor and selection layers. Empty geometry is enough for these tests.
const emptyRect = { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 };
const rangeGeometry = ['getClientRects', 'getBoundingClientRect'] as const;
const originalGeometry = rangeGeometry.map((key) =>
Object.getOwnPropertyDescriptor(Range.prototype, key),
);
beforeAll(() => {
Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
Range.prototype.getBoundingClientRect = () => ({ ...emptyRect, toJSON: () => emptyRect });
});
afterAll(() => {
rangeGeometry.forEach((key, i) => {
const original = originalGeometry[i];
if (original) Object.defineProperty(Range.prototype, key, original);
else Reflect.deleteProperty(Range.prototype, key);
});
});
stubRangeGeometry();
afterEach(async () => {
await i18n.changeLanguage('en');
@@ -111,6 +93,24 @@ describe('CodeEditor — editable', () => {
typeInto(view, '{}');
expect(view.state.doc.toString()).toBe('{}');
});
it('says how to leave the editor and links the error description (WCAG 2.1.2)', () => {
const { content, rerender } = renderEditor({
value: '{',
ariaLabel: 'Input JSON',
ariaDescribedBy: 'input-error',
ariaInvalid: true,
});
const [hintId, errorId] = content.getAttribute('aria-describedby')!.split(' ');
expect(document.getElementById(hintId!)).toHaveTextContent(
'Tab indents. To leave the editor, press Escape, then Tab.',
);
expect(errorId).toBe('input-error');
expect(content).toHaveAttribute('aria-invalid', 'true');
rerender({ value: '{}', ariaLabel: 'Input JSON', ariaDescribedBy: 'input-error' });
expect(content).not.toHaveAttribute('aria-invalid');
});
});
describe('CodeEditor — sizing', () => {
@@ -141,6 +141,8 @@ describe('CodeEditor — read-only', () => {
expect(scroller).toHaveAttribute('role', 'region');
expect(scroller).toHaveAttribute('aria-label', 'YAML output (read-only)');
expect(content).toHaveAttribute('aria-label', 'YAML output (read-only)');
// Nothing to indent, so no "leave the editor" hint.
expect(content).not.toHaveAttribute('aria-describedby');
expect(container.querySelector('.cm-lineNumbers')).not.toBeNull();
expect(container.querySelector('.cm-activeLine')).toBeNull();
expect(container.querySelector('.cm-gutter-lint')).toBeNull();
@@ -156,6 +158,7 @@ describe('CodeEditor — languages', () => {
it.each<[EditorLanguage, string | null]>([
['json', 'json'],
['jsonl', 'json'],
['jsonc', 'json'],
['yaml', 'yaml'],
['xml', 'xml'],
['markdown', 'markdown'],
@@ -218,6 +221,26 @@ describe('CodeEditor — JSON linting', () => {
});
});
describe('CodeEditor — JSONC linting', () => {
const language = editorLanguageFor('jsonc', 'reverse');
it('accepts comments and trailing commas', async () => {
const { view } = renderEditor({
value: '{\n // note\n "a": [1, 2,], /* more */\n}',
language,
});
expect(await lintNow(view)).toBe(0);
});
it('flags JSONC errors where the converter does', async () => {
const { view } = renderEditor({ value: '{\n "a": 1 /* open\n}', language });
expect(await lintNow(view)).toBe(1);
typeInto(view, '');
expect(await lintNow(view)).toBe(0);
});
});
describe('CodeEditor — behaviour', () => {
it('leaves file drops to the surrounding dropzone', async () => {
const { content, view } = renderEditor({ value: 'keep' });
@@ -1,9 +1,10 @@
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import '@/i18n';
import type { CodeEditorProps } from '@/components/converter/CodeEditor';
import type * as CodeEditorModule from '@/components/converter/CodeEditor';
import { ThemeProvider } from '@/lib/theme';
import { stubRangeGeometry } from '@/test/range-geometry';
import { CodeEditorLazy } from '../CodeEditorLazy';
// The real editor module, behind a switch that simulates a failed chunk load.
@@ -24,22 +25,7 @@ vi.mock('@/components/converter/CodeEditor', async (importOriginal) => {
};
});
const emptyRect = { x: 0, y: 0, width: 0, height: 0, top: 0, right: 0, bottom: 0, left: 0 };
const originalGetClientRects = Object.getOwnPropertyDescriptor(Range.prototype, 'getClientRects');
beforeAll(() => {
// jsdom has no layout; CodeMirror measures ranges for the cursor layer.
Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
Range.prototype.getBoundingClientRect = () => ({ ...emptyRect, toJSON: () => emptyRect });
});
afterAll(() => {
if (originalGetClientRects) {
Object.defineProperty(Range.prototype, 'getClientRects', originalGetClientRects);
} else {
Reflect.deleteProperty(Range.prototype, 'getClientRects');
}
Reflect.deleteProperty(Range.prototype, 'getBoundingClientRect');
});
stubRangeGeometry();
afterEach(() => {
chunk.broken = false;
@@ -195,6 +195,39 @@ describe('ConverterWorkspace — direction', () => {
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'csv' });
expect(inputBox()).toBeInTheDocument();
});
it('converts JSONC back to JSON and places errors in the original text', () => {
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
render(<ConverterWorkspace />);
type('{\n // comment\n "a": [1, 2,],\n}', 'Input JSONC');
expect(outputBox('JSON output (read-only)')).toHaveValue('{\n "a": [\n 1,\n 2\n ]\n}');
type('{\n /* comment */\n "a": 1\n "b": 2\n}', 'Input JSONC');
expect(screen.getByRole('status')).toHaveTextContent(/^Ln 4, Col 3/);
expect(screen.getByText('error')).toBeInTheDocument();
});
it('leaves an input-only format when switching to JSON →', async () => {
const user = userEvent.setup();
useWorkspaceStore.setState({ format: 'jsonc', direction: 'reverse' });
render(<ConverterWorkspace />);
await user.click(screen.getByRole('button', { name: 'JSON →' }));
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'forward', format: 'jsonl' });
expect(within(chips()).getByRole('button', { name: 'JSONC' })).toBeDisabled();
});
it('offers to read JSON with comments as JSONC', async () => {
const user = userEvent.setup();
render(<ConverterWorkspace />);
type('[1, /* two */ 2]');
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
expect(useWorkspaceStore.getState()).toMatchObject({ direction: 'reverse', format: 'jsonc' });
expect(inputBox('Input JSONC')).toHaveValue('[1, /* two */ 2]');
expect(outputBox('JSON output (read-only)')).toHaveValue('[\n 1,\n 2\n]');
});
});
describe('ConverterWorkspace — options', () => {
@@ -346,6 +379,8 @@ describe('ConverterWorkspace — mobile layout', () => {
type('[{"a":1}]');
expect(badgeOn(outputTab)).toBe(true);
// The dot is visual only; the tab's name says it too.
expect(outputTab).toHaveAccessibleName('Output (new)');
await user.click(outputTab);
expect(outputTab).toHaveAttribute('aria-selected', 'true');
@@ -7,6 +7,7 @@ import { FormatPicker } from '../FormatPicker';
const LABELS: Record<FormatId, string> = {
jsonl: 'JSONL',
jsonc: 'JSONC',
csv: 'CSV',
tsv: 'TSV',
yaml: 'YAML',
@@ -34,7 +35,7 @@ describe('FormatPicker — inline chips', () => {
render(<FormatPicker value="yaml" onChange={() => {}} />);
const buttons = within(inlineGroup()).getAllByRole('button');
expect(buttons.map((b) => b.textContent)).toEqual(Object.values(LABELS));
for (const button of buttons) {
for (const button of buttons.filter((b) => b.textContent !== 'JSONC')) {
expect(button).toHaveAttribute(
'aria-pressed',
button.textContent === 'YAML' ? 'true' : 'false',
@@ -44,6 +45,23 @@ describe('FormatPicker — inline chips', () => {
}
});
it('disables input-only formats going forward', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(<FormatPicker value="jsonl" onChange={onChange} shape="object" />);
expect(chip('jsonc')).toBeDisabled();
expect(chip('jsonc')).toHaveAttribute(
'title',
'Input only: converts to JSON in the → JSON direction',
);
// Disabled, not "not suggested": no dashed border.
expect(chip('jsonc')).not.toHaveClass('border-dashed');
await user.click(chip('jsonc'));
expect(onChange).not.toHaveBeenCalled();
});
it('reports the picked format', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
@@ -84,8 +102,9 @@ describe('FormatPicker — inline chips', () => {
expect(chip(format)).toBeDisabled();
expect(chip(format)).toHaveAttribute('title', 'Reverse parse not supported for this format');
}
for (const format of ['jsonl', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
for (const format of ['jsonl', 'jsonc', 'csv', 'tsv', 'yaml', 'toml', 'resx'] as const) {
expect(chip(format)).toBeEnabled();
expect(chip(format)).toHaveAttribute('title', 'Ready');
}
await user.click(chip('xml'));
@@ -107,7 +126,7 @@ describe('FormatPicker — compact sheet (mobile)', () => {
await user.click(screen.getByRole('button', { name: /Target format\s*JSONL/ }));
const dialog = await screen.findByRole('dialog', { name: 'Target format' });
const sheetGroup = within(dialog).getByRole('group', { name: 'Target format' });
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(12);
expect(within(sheetGroup).getAllByRole('button')).toHaveLength(13);
expect(chip('jsonl', sheetGroup)).toHaveAttribute('aria-pressed', 'true');
expect(chip('yaml', sheetGroup)).toHaveAttribute('title', 'Suggested for the detected shape');
@@ -40,6 +40,7 @@ interface PanelProps {
format?: FormatId;
direction?: Direction;
onMultiFileDrop?: (files: File[]) => void;
onReadAsJsonc?: () => void;
}
function renderPanel(props: PanelProps = {}) {
@@ -54,6 +55,7 @@ function renderPanel(props: PanelProps = {}) {
format={props.format ?? 'csv'}
direction={props.direction ?? 'forward'}
{...(props.onMultiFileDrop ? { onMultiFileDrop: props.onMultiFileDrop } : {})}
{...(props.onReadAsJsonc ? { onReadAsJsonc: props.onReadAsJsonc } : {})}
/>,
);
const root = utils.container.firstElementChild as HTMLElement;
@@ -113,6 +115,15 @@ describe('InputPanel — layout', () => {
);
});
it('highlights and accepts JSONC going back', () => {
const { fileInput } = renderPanel({ format: 'jsonc', direction: 'reverse' });
expect(screen.getByRole('textbox', { name: 'Input JSONC' })).toHaveAttribute(
'data-language',
'jsonc',
);
expect(fileInput).toHaveAttribute('accept', '.jsonc,.json,.txt,application/jsonc');
});
it('passes edits straight through', () => {
const { onChange } = renderPanel();
fireEvent.change(screen.getByRole('textbox', { name: 'Input JSON' }), {
@@ -174,6 +185,38 @@ describe('InputPanel — error banner', () => {
});
});
describe('InputPanel — JSONC hint', () => {
const jsonc = '{\n // compiler options\n "strict": true,\n}';
const error = "Expected property name or '}' in JSON";
it('offers JSONC → JSON when the JSON error is only comments or trailing commas', async () => {
const user = userEvent.setup();
const onReadAsJsonc = vi.fn();
renderPanel({ value: jsonc, error, onReadAsJsonc });
expect(
screen.getByText('This looks like JSONC — JSON with comments or trailing commas.'),
).toBeInTheDocument();
await user.click(screen.getByRole('button', { name: 'Convert JSONC → JSON' }));
expect(onReadAsJsonc).toHaveBeenCalledOnce();
});
it.each<[string, PanelProps]>([
['the input is valid', { value: jsonc, error: null }],
['the text is not valid JSONC either', { value: '{"a": }', error }],
['already converting back', { value: jsonc, error, direction: 'reverse', format: 'jsonc' }],
['the input is too big to check here', { value: jsonc + ' '.repeat(256 * 1024), error }],
])('stays hidden when %s', (_case, props) => {
renderPanel({ ...props, onReadAsJsonc: vi.fn() });
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
});
it('stays hidden without a handler', () => {
renderPanel({ value: jsonc, error });
expect(screen.queryByRole('button', { name: 'Convert JSONC → JSON' })).not.toBeInTheDocument();
});
});
describe('InputPanel — file picker (web)', () => {
it('opens the hidden file input', async () => {
const user = userEvent.setup();
@@ -52,9 +52,17 @@ afterEach(() => {
Reflect.deleteProperty(navigator, 'clipboard');
});
const copyButton = () => screen.getByRole('button', { name: 'Copy' });
// The name follows the visible label: "Copy", then "Copied" for a moment.
const copyButton = () => screen.getByRole('button', { name: /^Cop(y|ied)$/ });
const downloadButton = () => screen.getByRole('button', { name: 'Download' });
/** Advances the fake timers inside act(); the block body keeps act() synchronous. */
function advance(ms: number) {
act(() => {
vi.advanceTimersByTime(ms);
});
}
async function lastDownloaded(): Promise<{ blob: Blob; name: string; bytes: number[] }> {
const [blob, name] = vi.mocked(downloadBlob).mock.lastCall!;
return { blob, name, bytes: [...new Uint8Array(await blob.arrayBuffer())] };
@@ -132,8 +140,9 @@ describe('OutputPanel — copy', () => {
expect(writeText).toHaveBeenCalledWith(CSV);
expect(toast.success).toHaveBeenCalledWith('Copied CSV to clipboard');
// The visible label flips; the accessible name stays "Copy".
// The visible label and the accessible name flip together.
expect(copyButton()).toHaveTextContent('Copied');
expect(copyButton()).toHaveAccessibleName('Copied');
});
it('reverts the "Copied" label after a moment, restarting on each copy', async () => {
@@ -143,12 +152,12 @@ describe('OutputPanel — copy', () => {
await act(async () => fireEvent.click(copyButton()));
expect(copyButton()).toHaveTextContent('Copied');
act(() => vi.advanceTimersByTime(1000));
advance(1000);
await act(async () => fireEvent.click(copyButton()));
act(() => vi.advanceTimersByTime(1000));
advance(1000);
expect(copyButton()).toHaveTextContent('Copied');
act(() => vi.advanceTimersByTime(500));
advance(500);
expect(copyButton()).toHaveTextContent('Copy');
expect(copyButton()).not.toHaveTextContent('Copied');
});
@@ -32,6 +32,12 @@ describe('StatusBar', () => {
expect(live).toHaveAttribute('aria-live', 'polite');
});
it('keeps sizes and timing out of the live region (they change on every keystroke)', () => {
renderBar({ state: 'ok', inputBytes: 2048, ms: 1.5 });
expect(screen.getByText('2.0 KB').closest('[aria-live]')).toBeNull();
expect(screen.getByText(/ ms$/).closest('[aria-live]')).toBeNull();
});
it('shows input and output sizes in human units', () => {
renderBar({ inputBytes: 2048, outputBytes: 3 * 1024 * 1024 });
expect(screen.getByText('2.0 KB')).toBeInTheDocument();
+9 -4
View File
@@ -1,4 +1,10 @@
import { useEffect, useId, useRef, useState } from 'react';
import {
useEffect,
useId,
useRef,
useState,
type KeyboardEvent as ReactKeyboardEvent,
} from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Monitor, Moon, SlidersHorizontal, Sun } from 'lucide-react';
import { Switch } from '@/components/ui/switch';
@@ -53,7 +59,7 @@ export function AppearanceMenu() {
};
}, [open]);
const onPanelKeyDown = (e: React.KeyboardEvent<HTMLDivElement>) => {
const onPanelKeyDown = (e: ReactKeyboardEvent<HTMLDivElement>) => {
if (e.key !== 'ArrowDown' && e.key !== 'ArrowUp' && e.key !== 'Home' && e.key !== 'End') return;
const items = Array.from(
panelRef.current?.querySelectorAll<HTMLElement>('[data-menu-item]') ?? [],
@@ -80,7 +86,6 @@ export function AppearanceMenu() {
onClick={() => setOpen((v) => !v)}
className="group text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:ring-ring inline-flex h-9 w-9 items-center justify-center rounded-md transition outline-none focus-visible:ring-2"
aria-label={t('appearance.title')}
aria-haspopup="true"
aria-expanded={open}
aria-controls={open ? panelId : undefined}
>
@@ -111,7 +116,7 @@ export function AppearanceMenu() {
data-menu-item
onClick={() => setTheme(value)}
className={cn(
'hover:bg-muted focus-visible:bg-muted flex min-h-9 w-full items-center gap-2 rounded-md px-2 text-left text-sm outline-none',
'hover:bg-muted focus-visible:bg-muted focus-visible:ring-ring flex min-h-9 w-full items-center gap-2 rounded-md px-2 text-left text-sm outline-none focus-visible:ring-2 focus-visible:ring-inset',
active && 'text-primary',
)}
>
+2 -1
View File
@@ -1,3 +1,4 @@
import type { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { BlueskyIcon, DiscordIcon, XIcon } from '@/components/common/SocialIcons';
@@ -44,7 +45,7 @@ export function Footer() {
interface SocialLinkProps {
href: string;
label: string;
icon: React.ReactNode;
icon: ReactNode;
}
function SocialLink({ href, label, icon }: SocialLinkProps) {
+2 -1
View File
@@ -1,3 +1,4 @@
import type { ReactNode } from 'react';
import { Link, NavLink } from 'react-router';
import { useTranslation } from 'react-i18next';
import { GithubIcon } from '@/components/common/SocialIcons';
@@ -50,7 +51,7 @@ export function Header() {
interface NavItemProps {
to: string;
end?: boolean;
children: React.ReactNode;
children: ReactNode;
}
function NavItem({ to, end, children }: NavItemProps) {
+37 -2
View File
@@ -1,8 +1,10 @@
import { Suspense, useEffect } from 'react';
import { Suspense, useEffect, useRef } from 'react';
import { Outlet, useLocation } from 'react-router';
import { useTranslation } from 'react-i18next';
import { ChunkErrorBoundary } from '@/components/common/ChunkErrorBoundary';
import { OfflineBanner } from '@/components/common/OfflineBanner';
import { RouteFallback } from '@/components/common/RouteFallback';
import { focusMain, MAIN_ID } from '@/lib/focus';
import { SITE_URL } from '@/lib/links';
import { Header } from './Header';
import { Footer } from './Footer';
@@ -23,15 +25,48 @@ function useCanonicalUrl(pathname: string) {
}, [pathname]);
}
/**
* After an in-app navigation, moves focus to `<main>` so keyboard and
* screen-reader users continue in the new page instead of on the link they
* left behind. The first render keeps the browser's default focus.
*/
function useFocusMainOnNavigate(pathname: string) {
const previous = useRef(pathname);
useEffect(() => {
if (previous.current === pathname) return;
previous.current = pathname;
focusMain({ preventScroll: true });
}, [pathname]);
}
export function Layout() {
const { t } = useTranslation();
const { pathname } = useLocation();
useCanonicalUrl(pathname);
useFocusMainOnNavigate(pathname);
return (
<div className="flex h-dvh flex-col">
{/* First tab stop. Focuses <main> directly, so the URL gets no #hash
and the router never sees a navigation. */}
<a
href={`#${MAIN_ID}`}
onClick={(e) => {
e.preventDefault();
focusMain();
}}
// `not-sr-only` resets padding, so the focused padding is set after it.
className="bg-background text-foreground border-border sr-only z-50 rounded-md border text-sm font-medium shadow-lg focus:not-sr-only focus:fixed focus:top-2 focus:left-2 focus:px-3 focus:py-2"
>
{t('nav.skip_to_content')}
</a>
<Header />
<OfflineBanner />
<main className="flex min-h-0 flex-1 flex-col pr-[env(safe-area-inset-right)] pl-[env(safe-area-inset-left)]">
<main
id={MAIN_ID}
tabIndex={-1}
className="flex min-h-0 flex-1 flex-col pr-[env(safe-area-inset-right)] pl-[env(safe-area-inset-left)] outline-none"
>
{/* Boundary catches a failed route chunk (e.g. stale deploy) and keeps
the header/footer; keyed by path so navigating away recovers.
Suspense shows the loader while the chunk streams in. */}
@@ -36,7 +36,8 @@ afterEach(() => {
describe('AppearanceMenu', () => {
it('opens a labelled panel and focuses the current theme', async () => {
const user = renderMenu();
expect(trigger()).toHaveAttribute('aria-haspopup', 'true');
// A disclosure, not a menu: no aria-haspopup.
expect(trigger()).not.toHaveAttribute('aria-haspopup');
expect(trigger()).toHaveAttribute('aria-expanded', 'false');
expect(trigger()).not.toHaveAttribute('aria-controls');
expect(queryPanel()).not.toBeInTheDocument();
+1
View File
@@ -14,6 +14,7 @@ export function Toaster(props: ToasterProps) {
closeButton
containerAriaLabel={t('common.notifications')}
toastOptions={{
closeButtonAriaLabel: t('common.close_notification'),
classNames: {
toast:
'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:font-sans',
@@ -37,6 +37,12 @@ const ADVERSARIAL_TEXT = [
'\u0000\u0001\u0002',
'key = = value',
'<root><data name="x"><value>1</value></data></root>',
// JSONC-shaped: comments, stray commas, a string cut off mid-escape.
'/*',
'//',
'[,]',
'{"a": 1,} // ok',
'"\\',
];
describe('converter contract', () => {
+178
View File
@@ -0,0 +1,178 @@
import { describe, expect, it } from 'vitest';
import type { ConversionResult } from '../types';
import { jsoncConverter, parseJsonc } from '../jsonc';
type Indent = (typeof jsoncConverter.defaultOptions)['indent'];
function reverse(text: string, indent: Indent = '2'): ConversionResult {
return jsoncConverter.reverse!({ text }, { indent });
}
function ok(result: ConversionResult): string {
if (!result.ok) throw new Error(`expected ok, got error: ${result.error}`);
return result.output;
}
function fail(result: ConversionResult) {
if (result.ok) throw new Error(`expected an error, got output: ${result.output.slice(0, 200)}`);
return result;
}
describe('jsoncConverter — comments', () => {
it('removes line and block comments', () => {
const text = `// leading
{
"a": 1, // trailing
/* block */ "b": [true, /* inline */ null]
}
/* end */`;
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: 1, b: [true, null] });
});
it('ends a line comment at CR or LF and keeps the rest', () => {
expect(JSON.parse(ok(reverse('[1, // one\r\n2, // two\r3]')))).toEqual([1, 2, 3]);
});
it('keeps comment-like text inside strings', () => {
const text = '{"url": "http://example.com/*x*/", "path": "C:\\\\dir\\\\", "q": "a\\"//b"} // c';
expect(JSON.parse(ok(reverse(text)))).toEqual({
url: 'http://example.com/*x*/',
path: 'C:\\dir\\',
q: 'a"//b',
});
});
it('reports an unterminated block comment where it starts', () => {
const result = fail(reverse('{\n "a": 1 /* open\n}'));
expect(result.error).toMatch(/Unterminated block comment/);
expect(result).toMatchObject({ line: 2, column: 10 });
});
it('rejects input that only has comments', () => {
expect(fail(reverse('// nothing\n/* here */')).error).toMatch(/No JSON value/);
expect(fail(reverse('')).error).toMatch(/No JSON value/);
});
it('reports an unterminated string, even with comments after it', () => {
expect(fail(reverse('["abc\n// x\n"]'))).toMatchObject({ line: 1 });
expect(fail(reverse('["abc // x'))).toMatchObject({ line: 1 });
});
it('leaves a lone slash for JSON.parse to reject', () => {
expect(fail(reverse('[1 / 2]')).error.length).toBeGreaterThan(0);
});
});
describe('jsoncConverter — trailing commas', () => {
it('removes trailing commas in objects, arrays and nested containers', () => {
const text = '{"a": [1, 2,], "b": {"c": 3,},}';
expect(JSON.parse(ok(reverse(text)))).toEqual({ a: [1, 2], b: { c: 3 } });
});
it('removes a trailing comma with comments and line breaks before the bracket', () => {
const text = '[\n "x", // last item\n /* nothing more */\n]';
expect(JSON.parse(ok(reverse(text)))).toEqual(['x']);
});
it.each(['[,]', '{,}', '[1,,2]', '[1,,]', '{"a":,}'])('still rejects %s', (text) => {
expect(fail(reverse(text)).error.length).toBeGreaterThan(0);
});
});
describe('jsoncConverter — errors line up with the input', () => {
it('reports a JSON error at its line and column despite earlier comments', () => {
const text = '/* a\n b */\n{\n "a": 1 // ok\n "b": 2\n}';
expect(fail(reverse(text))).toMatchObject({ line: 5, column: 3 });
});
it('counts columns in UTF-16 code units, like the editor', () => {
const text = '/* 🎮 */ [1 2]';
expect(fail(reverse(text))).toMatchObject({ line: 1, column: 13 });
});
it('accepts a byte-order mark', () => {
expect(ok(reverse('\uFEFF// bom\n[1]'))).toBe('[\n 1\n]');
});
});
describe('jsoncConverter — output keeps values exactly', () => {
it('copies number literals verbatim', () => {
const output = ok(reverse('[12345678901234567890, 1.0, 1e3, -0, 0.1e-7]', 'minify'));
expect(output).toBe('[12345678901234567890,1.0,1e3,-0,0.1e-7]');
});
it('keeps duplicate and __proto__ keys', () => {
const output = ok(reverse('{"a": 1, "a": 2, "__proto__": {"x": 1}}', 'minify'));
expect(output).toBe('{"a":1,"a":2,"__proto__":{"x":1}}');
});
it('collapses empty containers, comments inside included', () => {
expect(ok(reverse('{ /* nothing */ "a": [ ], "b": { // none\n } }'))).toBe(
'{\n "a": [],\n "b": {}\n}',
);
});
it('formats scalars at the root', () => {
expect(ok(reverse('/* answer */ 42'))).toBe('42');
expect(ok(reverse('"text" // c'))).toBe('"text"');
});
});
describe('jsoncConverter — layout', () => {
const text = '{"a": [1, {"b": null}], "c": "d"} // c';
it.each<[Indent, string]>([
['2', '{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}'],
[
'4',
'{\n "a": [\n 1,\n {\n "b": null\n }\n ],\n "c": "d"\n}',
],
['tab', '{\n\t"a": [\n\t\t1,\n\t\t{\n\t\t\t"b": null\n\t\t}\n\t],\n\t"c": "d"\n}'],
['minify', '{"a":[1,{"b":null}],"c":"d"}'],
])('indent %s', (indent, expected) => {
expect(ok(reverse(text, indent))).toBe(expected);
});
it('handles deep nesting without recursion', () => {
const depth = 10_000;
const text = '['.repeat(depth) + '/* deep */' + ']'.repeat(depth);
const output = ok(reverse(text, 'minify'));
expect(output).toBe('['.repeat(depth - 1) + '[]' + ']'.repeat(depth - 1));
});
it('refuses pretty output that would be enormous', () => {
const depth = 50_000;
const text = '['.repeat(depth) + '1' + ']'.repeat(depth);
expect(fail(reverse(text)).error).toMatch(/too large/);
});
});
describe('jsoncConverter — contract', () => {
it('is input-only and has no forward pass', () => {
expect(jsoncConverter.meta.inputOnly).toBe(true);
const result = jsoncConverter.convert({ data: { a: 1 } }, jsoncConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('accepts .jsonc and .json files', () => {
expect(jsoncConverter.meta.extension).toBe('jsonc');
expect(jsoncConverter.meta.altExtensions).toEqual(['json']);
});
});
describe('parseJsonc', () => {
it('returns JSON text at the same offsets as the input', () => {
const text = '{"a": 1, /* c */ "b": [2,],} // end';
const result = parseJsonc(text);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.json).toHaveLength(text.length);
expect(result.json).toBe(`{"a": 1, ${' '.repeat(7)} "b": [2 ] } ${' '.repeat(6)}`);
expect(JSON.parse(result.json)).toEqual({ a: 1, b: [2] });
});
it('returns plain JSON unchanged', () => {
const text = '{"a": [1, 2]}';
expect(parseJsonc(text)).toEqual({ ok: true, json: text });
});
});
+11 -4
View File
@@ -3,11 +3,12 @@ import { ALL_FORMATS, CONVERTERS, getConverter } from '../registry';
import type { FormatId } from '../types';
describe('converter registry', () => {
it('exposes all 12 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(12);
it('exposes all 13 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(13);
expect(new Set(ALL_FORMATS)).toEqual(
new Set<FormatId>([
'jsonl',
'jsonc',
'csv',
'tsv',
'yaml',
@@ -42,7 +43,7 @@ describe('converter registry', () => {
}
});
it('all 12 converters are marked ready', () => {
it('all 13 converters are marked ready', () => {
for (const id of ALL_FORMATS) {
expect(getConverter(id).meta.ready).toBe(true);
}
@@ -50,7 +51,13 @@ describe('converter registry', () => {
it('phase metadata covers all expected phases', () => {
const phases = ALL_FORMATS.map((id) => getConverter(id).meta.phase);
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack.
// P1 jsonl/csv/tsv/yaml, P2 xml/toml/markdown/sql, P3 resx, P4 bson/cbor/msgpack/jsonc.
expect(new Set(phases)).toEqual(new Set([1, 2, 3, 4]));
});
it('only JSONC is input-only, and it parses back to JSON', () => {
const inputOnly = ALL_FORMATS.filter((id) => getConverter(id).meta.inputOnly);
expect(inputOnly).toEqual(['jsonc']);
expect(typeof getConverter('jsonc').reverse).toBe('function');
});
});
+295
View File
@@ -0,0 +1,295 @@
import type { ConversionFailure, Converter } from './types';
import { errorPosition, offsetToLineColumn } from '@/lib/detect';
import { errorMessage } from '@/lib/errors';
type JsoncIndent = '2' | '4' | 'tab' | 'minify';
interface JsoncOptions {
/** Layout of the JSON output; `minify` puts it on one line. */
indent: JsoncIndent;
}
const INDENT_UNITS: Record<JsoncIndent, string | null> = {
'2': ' ',
'4': ' ',
tab: '\t',
minify: null,
};
/**
* Formatted output beyond this many characters is refused: deep nesting makes
* indentation grow quadratically, and engines cap strings near 2^29.
*/
const MAX_OUTPUT_CHARS = 2 ** 28;
const QUOTE = 0x22;
const SLASH = 0x2f;
const STAR = 0x2a;
const BACKSLASH = 0x5c;
const COMMA = 0x2c;
const COLON = 0x3a;
const LF = 0x0a;
const CR = 0x0d;
const OPEN_BRACE = 0x7b;
const CLOSE_BRACE = 0x7d;
const OPEN_BRACKET = 0x5b;
const CLOSE_BRACKET = 0x5d;
/** Characters that end a number or `true`/`false`/`null` literal. */
const DELIMITERS = ' \t\r\n{}[],:';
function isJsonWhitespace(c: number): boolean {
return c === 0x20 || c === 0x09 || c === LF || c === CR;
}
/**
* Index just past the string literal opening at `start`. An unterminated
* string stops at the end of its line; JSON.parse reports it later.
*/
function skipString(text: string, start: number): number {
let i = start + 1;
while (i < text.length) {
const c = text.charCodeAt(i);
if (c === QUOTE) return i + 1;
if (c === LF || c === CR) return i;
i += c === BACKSLASH ? 2 : 1;
}
return text.length;
}
function skipWhitespace(text: string, start: number): number {
let i = start;
while (i < text.length && isJsonWhitespace(text.charCodeAt(i))) i++;
return i;
}
/**
* End of the comment starting at `start`: `start` itself when there is no
* comment there, -1 for a block comment that never closes.
*/
function commentEnd(text: string, start: number): number {
const next = text.charCodeAt(start + 1);
if (next === SLASH) {
let i = start + 2;
while (i < text.length && text.charCodeAt(i) !== LF && text.charCodeAt(i) !== CR) i++;
return i;
}
if (next === STAR) {
const close = text.indexOf('*/', start + 2);
return close < 0 ? -1 : close + 2;
}
return start;
}
/**
* Replaces every comment with spaces, keeping line breaks, so offsets — and
* the line/column of any later JSON error — still match the user's text.
* Returns the offset of an unterminated block comment instead.
*/
function blankComments(text: string): string | number {
const parts: string[] = [];
let copied = 0;
let i = 0;
while (i < text.length) {
const c = text.charCodeAt(i);
if (c === QUOTE) {
i = skipString(text, i);
continue;
}
const end = c === SLASH ? commentEnd(text, i) : i;
if (end < 0) return i;
if (end === i) {
i++;
continue;
}
parts.push(text.slice(copied, i), text.slice(i, end).replace(/[^\r\n]/g, ' '));
copied = end;
i = end;
}
if (copied === 0) return text;
parts.push(text.slice(copied));
return parts.join('');
}
/** A comma after `[`, `{`, `,` or `:` is a syntax error, never a trailing comma. */
function followsValue(previous: number): boolean {
return (
previous !== OPEN_BRACKET && previous !== OPEN_BRACE && previous !== COMMA && previous !== COLON
);
}
/** Replaces each comma that directly precedes `]` or `}` with a space. */
function blankTrailingCommas(json: string): string {
const commas: number[] = [];
let pending = -1;
let previous = OPEN_BRACKET;
let i = 0;
while (i < json.length) {
const c = json.charCodeAt(i);
if (isJsonWhitespace(c)) {
i++;
continue;
}
if (pending >= 0 && (c === CLOSE_BRACKET || c === CLOSE_BRACE)) commas.push(pending);
pending = c === COMMA && followsValue(previous) ? i : -1;
previous = c;
i = c === QUOTE ? skipString(json, i) : i + 1;
}
if (commas.length === 0) return json;
const parts: string[] = [];
let copied = 0;
for (const at of commas) {
parts.push(json.slice(copied, at), ' ');
copied = at + 1;
}
parts.push(json.slice(copied));
return parts.join('');
}
function failAt(error: string, text: string, offset: number): ConversionFailure {
return { ok: false, error, ...offsetToLineColumn(text, offset) };
}
/**
* Turns JSONC into plain JSON text at the same offsets: comments and trailing
* commas become spaces, then JSON.parse validates the rest. Shared by the
* converter and the input editor's linter so both report the same errors.
*/
export function parseJsonc(text: string): { ok: true; json: string } | ConversionFailure {
// JSON.parse rejects a byte-order mark; a space keeps the offsets.
const source = text.charCodeAt(0) === 0xfeff ? ' ' + text.slice(1) : text;
const uncommented = blankComments(source);
if (typeof uncommented === 'number') {
return failAt('Unterminated block comment: add the closing */.', source, uncommented);
}
const json = blankTrailingCommas(uncommented);
if (skipWhitespace(json, 0) === json.length) {
return { ok: false, error: 'No JSON value: the input is empty or only has comments.' };
}
try {
JSON.parse(json);
return { ok: true, json };
} catch (err) {
const message = errorMessage(err);
const position = errorPosition(message, json);
return position ? { ok: false, error: message, ...position } : { ok: false, error: message };
}
}
/** End of the string, number or literal token starting at `start`. */
function valueEnd(json: string, start: number): number {
if (json.charCodeAt(start) === QUOTE) return skipString(json, start);
let i = start + 1;
while (i < json.length && !DELIMITERS.includes(json[i]!)) i++;
return i;
}
/**
* Lays out valid JSON token by token. Tokens are copied verbatim — numbers
* keep every digit, duplicate and `__proto__` keys survive — because no JS
* value is built. Iterative, so deep nesting cannot overflow the stack.
* Returns null when the output would be too large.
*/
function reprint(json: string, unit: string | null): string | null {
const out: string[] = [];
const colon = unit === null ? ':' : ': ';
// Line breaks slice one shared indent string instead of repeating per line.
let indent = '';
const newline = (depth: number): string => {
if (unit === null) return '';
const width = depth * unit.length;
if (indent.length < width) indent = unit.repeat(depth * 2);
return '\n' + indent.slice(0, width);
};
let size = 0;
let depth = 0;
let i = skipWhitespace(json, 0);
while (i < json.length) {
const ch = json[i]!;
let end = i + 1;
let piece: string;
switch (ch) {
case '{':
case '[': {
const next = skipWhitespace(json, end);
if (json[next] === (ch === '{' ? '}' : ']')) {
piece = ch + json[next];
end = next + 1;
} else {
depth++;
piece = ch + newline(depth);
}
break;
}
case '}':
case ']':
depth--;
piece = newline(depth) + ch;
break;
case ',':
piece = ',' + newline(depth);
break;
case ':':
piece = colon;
break;
default:
end = valueEnd(json, i);
piece = json.slice(i, end);
}
size += piece.length;
if (size > MAX_OUTPUT_CHARS) return null;
out.push(piece);
i = skipWhitespace(json, end);
}
return out.join('');
}
/**
* JSONC (JSON with Comments — tsconfig.json, VS Code settings) → JSON. An
* input-only format: JSON is already valid JSONC, so there is no forward pass.
*/
export const jsoncConverter: Converter<JsoncOptions> = {
meta: {
id: 'jsonc',
labelKey: 'formats.jsonc',
extension: 'jsonc',
// Most JSONC files are named .json (tsconfig.json, settings.json).
altExtensions: ['json'],
mimeType: 'application/jsonc',
phase: 4,
ready: true,
inputOnly: true,
},
defaultOptions: { indent: '2' },
optionSchema: [
{
type: 'enum',
key: 'indent',
labelKey: 'options.jsonc.indent',
descriptionKey: 'options.jsonc.indent_desc',
choices: [
{ value: '2', labelKey: 'options.jsonc.indent_2' },
{ value: '4', labelKey: 'options.jsonc.indent_4' },
{ value: 'tab', labelKey: 'options.jsonc.indent_tab' },
{ value: 'minify', labelKey: 'options.jsonc.indent_minify' },
],
},
],
convert() {
return {
ok: false,
error: 'JSONC is an input format: switch the direction to → JSON to convert it.',
};
},
reverse({ text }, { indent }) {
const parsed = parseJsonc(text);
if (!parsed.ok) return parsed;
const output = reprint(parsed.json, INDENT_UNITS[indent]);
return output === null
? {
ok: false,
error: 'The formatted JSON is too large (very deep nesting). Choose "Minified".',
}
: { ok: true, output };
},
};
+3
View File
@@ -1,6 +1,7 @@
import type { ConversionInput, ConversionResult, Converter, FormatId, ReverseInput } from './types';
import { errorMessage } from '@/lib/errors';
import { jsonlConverter } from './jsonl';
import { jsoncConverter } from './jsonc';
import { csvConverter, tsvConverter } from './csv';
import { yamlConverter } from './yaml';
import { xmlConverter } from './xml';
@@ -15,6 +16,7 @@ import { msgpackConverter } from './msgpack';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const CONVERTERS: Record<FormatId, Converter<any>> = {
jsonl: jsonlConverter,
jsonc: jsoncConverter,
csv: csvConverter,
tsv: tsvConverter,
yaml: yamlConverter,
@@ -30,6 +32,7 @@ export const CONVERTERS: Record<FormatId, Converter<any>> = {
export const ALL_FORMATS: FormatId[] = [
'jsonl',
'jsonc',
'csv',
'tsv',
'yaml',
+3
View File
@@ -1,3 +1,5 @@
// XMLValidator is deprecated in fast-xml-parser 5 (see the note in xml.ts).
// noinspection JSDeprecatedSymbols
import { XMLParser, XMLValidator } from 'fast-xml-parser';
import type { Converter } from './types';
import { errorMessage } from '@/lib/errors';
@@ -194,6 +196,7 @@ export const resxConverter: Converter<ResxOptions> = {
if (/<!DOCTYPE/i.test(text)) {
return { ok: false, error: 'Not a RESX file: DOCTYPE declarations are not supported.' };
}
// noinspection JSDeprecatedSymbols
const validation = XMLValidator.validate(text);
if (validation !== true) {
return {
+15 -1
View File
@@ -9,6 +9,7 @@
export type FormatId =
| 'jsonl'
| 'jsonc'
| 'csv'
| 'tsv'
| 'yaml'
@@ -43,6 +44,11 @@ export interface ConverterMeta {
* for display, but downloads decode back to raw bytes via the MIME type.
*/
binary?: boolean;
/**
* Input-only formats (JSONC) only convert *to* JSON: `convert()` returns an
* error and the UI disables them in the JSON → direction.
*/
inputOnly?: boolean;
}
export interface ConversionInput {
@@ -57,7 +63,15 @@ export interface ReverseInput {
sourceName?: string;
}
export type ConversionResult = { ok: true; output: string } | { ok: false; error: string };
export interface ConversionFailure {
ok: false;
error: string;
/** 1-based position of an input syntax error, when the parser knows it. */
line?: number;
column?: number;
}
export type ConversionResult = { ok: true; output: string } | ConversionFailure;
/**
* Schema describing a single option field, used by the settings UI
+10 -2
View File
@@ -1,4 +1,11 @@
import { XMLBuilder, XMLValidator } from 'fast-xml-parser';
// Default import: the package's typings also declare a named `Builder`, but
// its ES module only has the default export.
import XMLBuilder from 'fast-xml-builder';
// fast-xml-parser 5 deprecates XMLValidator in favour of the separate
// fast-xml-validator package, which would bundle a second XML parser. The
// built-in validator stays until fast-xml-parser removes it.
// noinspection JSDeprecatedSymbols
import { XMLValidator } from 'fast-xml-parser';
import type { Converter } from './types';
import { errorMessage } from '@/lib/errors';
import { defineOwn } from '@/lib/json';
@@ -186,7 +193,8 @@ export const xmlConverter: Converter<XmlOptions> = {
// `{"@_enabled": true}` must become enabled="true", not a bare attribute.
suppressBooleanAttributes: false,
});
const xml = builder.build({ [rootName]: body }) as string;
const xml = builder.build({ [rootName]: body });
// noinspection JSDeprecatedSymbols
const validation = XMLValidator.validate(xml);
if (validation !== true) {
return {
@@ -150,7 +150,9 @@ describe('useBatchActions.start', () => {
return '[2]';
},
});
act(() => useBatchStore.getState().addFiles([slow]));
act(() => {
useBatchStore.getState().addFiles([slow]);
});
let second!: Promise<void>;
act(() => {
second = result.current.start();
@@ -71,6 +71,13 @@ function okOutcome(output: string, ms = 12): TimedOutcome {
const big = (marker: string) =>
JSON.stringify({ marker, blob: 'x'.repeat(WORKER_THRESHOLD_CHARS) });
/** Advances the fake timers inside act(); the block body keeps act() synchronous. */
function advance(ms: number) {
act(() => {
vi.advanceTimersByTime(ms);
});
}
describe('useConversionResult — small inputs (main thread)', () => {
it('is idle for empty or blank input', () => {
const { result, rerender } = setup();
@@ -162,6 +169,18 @@ describe('useConversionResult — small inputs (main thread)', () => {
expect(result.current.inputErrorColumn).toBeNull();
});
it('surfaces the position of a JSONC error', () => {
const { result } = setup({
input: '[\n 1, /* two */\n 2 3\n]',
format: 'jsonc',
direction: 'reverse',
options: { indent: '2' },
});
expect(result.current.inputError).toEqual(expect.any(String));
expect(result.current.inputErrorLine).toBe(3);
expect(result.current.inputErrorColumn).toBe(5);
});
it('re-converts when the options change', () => {
const { result, rerender } = setup({
input: '[{"a":1}]',
@@ -209,10 +228,10 @@ describe('useConversionResult — large inputs (worker)', () => {
const { result } = setup({ input, format: 'yaml', options: { indent: 2 } });
expect(result.current).toMatchObject({ output: '', pending: true });
act(() => vi.advanceTimersByTime(199));
advance(199);
expect(client.convertLive).not.toHaveBeenCalled();
act(() => vi.advanceTimersByTime(1));
advance(1);
expect(client.convertLive).toHaveBeenCalledTimes(1);
expect(client.convertLive).toHaveBeenCalledWith<[ConversionRequest]>({
text: input,
@@ -235,10 +254,10 @@ describe('useConversionResult — large inputs (worker)', () => {
client.convertLive.mockReturnValue(new Promise(() => {}));
const { rerender } = setup({ input: big('1') });
for (const marker of ['2', '3', '4']) {
act(() => vi.advanceTimersByTime(100));
advance(100);
rerender({ input: big(marker), format: 'csv', direction: 'forward', options: CSV_OPTIONS });
}
act(() => vi.advanceTimersByTime(200));
advance(200);
expect(client.convertLive).toHaveBeenCalledTimes(1);
expect(client.convertLive.mock.calls[0]![0]).toMatchObject({ text: big('4') });
});
@@ -248,14 +267,14 @@ describe('useConversionResult — large inputs (worker)', () => {
const second = deferred();
client.convertLive.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);
const { result, rerender } = setup({ input: big('a') });
act(() => vi.advanceTimersByTime(200));
advance(200);
await act(async () => first.resolve(okOutcome('A')));
expect(result.current).toMatchObject({ output: 'A', pending: false });
rerender({ input: big('b'), format: 'csv', direction: 'forward', options: CSV_OPTIONS });
expect(result.current).toMatchObject({ output: 'A', pending: true });
act(() => vi.advanceTimersByTime(200));
advance(200);
await act(async () => second.resolve(okOutcome('B')));
expect(result.current).toMatchObject({ output: 'B', pending: false });
});
@@ -265,10 +284,10 @@ describe('useConversionResult — large inputs (worker)', () => {
const fresh = deferred();
client.convertLive.mockReturnValueOnce(stale.promise).mockReturnValueOnce(fresh.promise);
const { result, rerender } = setup({ input: big('old') });
act(() => vi.advanceTimersByTime(200));
advance(200);
rerender({ input: big('new'), format: 'csv', direction: 'forward', options: CSV_OPTIONS });
act(() => vi.advanceTimersByTime(200));
advance(200);
await act(async () => stale.resolve(okOutcome('OLD')));
expect(result.current).toMatchObject({ output: '', pending: true });
@@ -280,7 +299,7 @@ describe('useConversionResult — large inputs (worker)', () => {
const run = deferred();
client.convertLive.mockReturnValueOnce(run.promise);
const { result } = setup({ input: big('a') });
act(() => vi.advanceTimersByTime(200));
advance(200);
await act(async () => run.reject(new Error('The conversion ran out of resources.')));
expect(result.current).toMatchObject({
@@ -294,7 +313,7 @@ describe('useConversionResult — large inputs (worker)', () => {
const run = deferred();
client.convertLive.mockReturnValueOnce(run.promise);
const { result } = setup({ input: big('a') });
act(() => vi.advanceTimersByTime(200));
advance(200);
await act(async () => run.reject(new SupersededError()));
expect(result.current).toMatchObject({ output: '', outputError: null, pending: true });
@@ -322,7 +341,7 @@ describe('useConversionResult — large inputs (worker)', () => {
for (const [outcome, expected] of outcomes) {
client.convertLive.mockResolvedValueOnce(outcome);
const { result, unmount } = setup({ input: big('k') });
act(() => vi.advanceTimersByTime(200));
advance(200);
await act(async () => {});
expect(result.current).toMatchObject({ ...expected, pending: false });
unmount();
@@ -333,7 +352,7 @@ describe('useConversionResult — large inputs (worker)', () => {
const run = deferred();
client.convertLive.mockReturnValueOnce(run.promise);
const { unmount, renders } = setup({ input: big('a') });
act(() => vi.advanceTimersByTime(200));
advance(200);
unmount();
const count = renders.length;
await act(async () => run.resolve(okOutcome('late')));
@@ -343,7 +362,7 @@ describe('useConversionResult — large inputs (worker)', () => {
it('cancels the pending timer when the input shrinks below the threshold', () => {
const { result, rerender } = setup({ input: big('a'), format: 'jsonl', options: {} });
rerender({ input: '[{"a":1}]', format: 'jsonl', direction: 'forward', options: {} });
act(() => vi.advanceTimersByTime(1000));
advance(1000);
expect(client.convertLive).not.toHaveBeenCalled();
expect(result.current).toMatchObject({ output: '{"a":1}\n', pending: false });
});
@@ -34,6 +34,15 @@ describe('useFileAccept', () => {
expect(result.allowedExtensions).toEqual(['yaml', 'yml', 'txt']);
});
it('accepts .jsonc and .json files for JSONC going back', () => {
const result = accept('jsonc', 'reverse');
expect(result.accept).toEqual({
'application/jsonc': ['.jsonc', '.json'],
'text/plain': ['.txt'],
});
expect(result.allowedExtensions).toEqual(['jsonc', 'json', 'txt']);
});
it('keys the dropzone map by the format MIME type', () => {
const result = accept('jsonl', 'reverse');
expect(result.accept).toEqual({
@@ -1,6 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { renderHook } from '@testing-library/react';
import { useKeyboardShortcuts } from '../useKeyboardShortcuts';
import { ariaModShortcut, useKeyboardShortcuts } from '../useKeyboardShortcuts';
function press(init: KeyboardEventInit) {
const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init });
@@ -54,3 +54,14 @@ describe('useKeyboardShortcuts', () => {
expect(second).toHaveBeenCalledTimes(1);
});
});
describe('ariaModShortcut', () => {
it('names Control on Windows and Linux, Meta on macOS', () => {
const platform = vi.spyOn(navigator, 'platform', 'get');
platform.mockReturnValue('Win32');
expect(ariaModShortcut('S')).toBe('Control+S');
platform.mockReturnValue('MacIntel');
expect(ariaModShortcut(',')).toBe('Meta+,');
platform.mockRestore();
});
});
+5
View File
@@ -63,3 +63,8 @@ export function useKeyboardShortcuts(shortcuts: ShortcutDef[]): void {
export function modKey(): 'Cmd' | 'Ctrl' {
return isMac() ? 'Cmd' : 'Ctrl';
}
/** `aria-keyshortcuts` value for Mod+`key` ("Control+S", or "Meta+S" on macOS). */
export function ariaModShortcut(key: string): string {
return `${isMac() ? 'Meta' : 'Control'}+${key}`;
}
+38 -9
View File
@@ -7,7 +7,8 @@
"about": "About",
"github": "GitHub",
"label": "Main",
"home_brand": "JSONPrism home"
"home_brand": "JSONPrism home",
"skip_to_content": "Skip to content"
},
"home": {
"input_label": "Input JSON",
@@ -33,10 +34,16 @@
"title_rest": "JSON.",
"copied": "Copied",
"error_position": "Ln {{line}}, Col {{column}}",
"output_aria": "{{format}} output (read-only)"
"jsonc_hint": "This looks like JSONC — JSON with comments or trailing commas.",
"jsonc_switch": "Convert JSONC → JSON",
"output_aria": "{{format}} output (read-only)",
"document_title": "JSONPrism · Disperse JSON into 12 formats",
"format_picker_description": "Choose a format. Formats that don't work in the current direction are disabled.",
"output_unread": "(new)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +60,8 @@
"ready": "Ready",
"suggested": "Suggested for the detected shape",
"not_suggested": "Not suggested for the detected shape",
"no_reverse": "Reverse parse not supported for this format"
"no_reverse": "Reverse parse not supported for this format",
"input_only": "Input only: converts to JSON in the → JSON direction"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +74,14 @@
"pretty": "Pretty-print each line",
"pretty_desc": "Canonical JSONL is single-line. Enable for human-readable multi-line records."
},
"jsonc": {
"indent": "Output layout",
"indent_desc": "Comments and trailing commas are removed; values, numbers and key order stay exactly as written.",
"indent_2": "2 spaces",
"indent_4": "4 spaces",
"indent_tab": "Tab",
"indent_minify": "Minified"
},
"csv": {
"header": "Include header row",
"header_desc": "Emit the first row as column names derived from object keys.",
@@ -179,7 +195,8 @@
},
"shortcut": {
"download": "Download",
"settings": "Settings"
"settings": "Settings",
"leave_editor": "Leave editor"
},
"settings": {
"title": "Options",
@@ -292,7 +309,7 @@
"about": {
"title": "About JSONPrism",
"lead": "A refracting tool for developers.",
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
"p1": "JSONPrism takes a single JSON input and disperses it into many target formats — like white light through a prism — and parses six of them back, plus JSONC (JSON with comments) into plain JSON. Conversion runs entirely on your device, so the data you paste or drop never leaves it.",
"p2": "Built with React 19, TypeScript 7, Vite 8, Tailwind CSS v4 and shadcn/ui. The web version is served by Cloudflare Workers; the desktop and Android apps are built with Tauri 2. Source on GitHub.",
"version": "Version {{version}}",
"donate": {
@@ -345,7 +362,8 @@
"discussions": "Discussions",
"demo": "Web app",
"license": "License (Apache 2.0)",
"releases": "Releases & downloads"
"releases": "Releases & downloads",
"accessibility": "Accessibility statement"
},
"disclaimer": {
"title": "Disclaimer",
@@ -373,7 +391,8 @@
"loading": "Loading…",
"scroll_to_top": "Back to top",
"close": "Close",
"notifications": "Notifications"
"notifications": "Notifications",
"close_notification": "Close notification"
},
"consent": {
"title": "Before you start",
@@ -443,7 +462,17 @@
"folded_code": "folded code",
"unfold": "unfold",
"diagnostics": "Diagnostics",
"no_diagnostics": "No diagnostics"
}
"no_diagnostics": "No diagnostics",
"folded_lines": "Folded lines",
"unfolded_lines": "Unfolded lines",
"to": "to",
"current_match": "current match",
"on_line": "on line",
"replaced_match_on_line": "replaced match on line $",
"replaced_matches": "replaced $ matches",
"selection_deleted": "Selection deleted",
"control_character": "Control character"
},
"tab_hint": "Tab indents. To leave the editor, press Escape, then Tab."
}
}
+39 -10
View File
@@ -6,8 +6,9 @@
"home": "変換",
"about": "概要",
"github": "GitHub",
"label": "メインナビゲーション",
"home_brand": "JSONPrism ホーム"
"label": "メイン",
"home_brand": "JSONPrism ホーム",
"skip_to_content": "本文へスキップ"
},
"home": {
"input_label": "JSON 入力",
@@ -33,10 +34,16 @@
"title_rest": "JSON。",
"copied": "コピー済み",
"error_position": "{{line}} 行 {{column}} 列",
"output_aria": "{{format}} の出力(読み取り専用)"
"jsonc_hint": "JSONC(コメントや末尾カンマを含む JSON)のようです。",
"jsonc_switch": "JSONC → JSON に変換",
"output_aria": "{{format}} の出力(読み取り専用)",
"document_title": "JSONPrism · JSON を 12 形式に変換",
"format_picker_description": "形式を選択します。現在の方向で使えない形式は無効になっています。",
"output_unread": "(新規)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +60,8 @@
"ready": "利用可能",
"suggested": "検出されたデータ形状に適しています",
"not_suggested": "検出されたデータ形状には推奨されません",
"no_reverse": "この形式は逆方向のパースに対応していません"
"no_reverse": "この形式は逆方向のパースに対応していません",
"input_only": "入力専用:→ JSON の方向で JSON に変換します"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +74,14 @@
"pretty": "各行を整形して出力",
"pretty_desc": "標準の JSONL は 1 行 1 レコードです。人間が読みやすい複数行を希望する場合に有効化。"
},
"jsonc": {
"indent": "出力レイアウト",
"indent_desc": "コメントと末尾のカンマを取り除きます。値・数値・キーの順序は書かれたとおりに保たれます。",
"indent_2": "スペース 2 つ",
"indent_4": "スペース 4 つ",
"indent_tab": "タブ",
"indent_minify": "最小化"
},
"csv": {
"header": "ヘッダー行を含める",
"header_desc": "オブジェクトのキーから生成した列名を最初の行に出力します。",
@@ -179,7 +195,8 @@
},
"shortcut": {
"download": "ダウンロード",
"settings": "設定"
"settings": "設定",
"leave_editor": "エディターから出る"
},
"settings": {
"title": "オプション",
@@ -259,7 +276,7 @@
"about": {
"title": "JSONPrism について",
"lead": "開発者のための分光ツール。",
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
"p1": "JSONPrism はひとつの JSON 入力を、プリズムを通る白色光のように多くの形式へ分光し、そのうち 6 形式は JSON に戻すこともできます。JSONC(コメント付き JSON)も通常の JSON に変換できます。変換はすべて端末上で行われるため、貼り付けたりドロップしたデータが外部に出ることはありません。",
"p2": "React 19、TypeScript 7、Vite 8、Tailwind CSS v4、shadcn/ui で構築。Web 版は Cloudflare Workers で配信され、デスクトップ版と Android 版は Tauri 2 で構築されています。ソースは GitHub にあります。",
"version": "バージョン {{version}}",
"donate": {
@@ -312,7 +329,8 @@
"discussions": "ディスカッション",
"demo": "Web アプリ",
"license": "ライセンス (Apache 2.0)",
"releases": "リリースとダウンロード"
"releases": "リリースとダウンロード",
"accessibility": "アクセシビリティ方針"
},
"disclaimer": {
"title": "免責事項",
@@ -340,7 +358,8 @@
"loading": "読み込み中…",
"scroll_to_top": "トップへ戻る",
"close": "閉じる",
"notifications": "通知"
"notifications": "通知",
"close_notification": "通知を閉じる"
},
"social": {
"discord": "Discord",
@@ -443,7 +462,17 @@
"folded_code": "折りたたまれたコード",
"unfold": "展開",
"diagnostics": "診断",
"no_diagnostics": "診断なし"
}
"no_diagnostics": "診断なし",
"folded_lines": "行を折りたたみました",
"unfolded_lines": "行を展開しました",
"to": "〜",
"current_match": "現在の一致",
"on_line": "行",
"replaced_match_on_line": "$ 行目の一致を置換しました",
"replaced_matches": "$ 件の一致を置換しました",
"selection_deleted": "選択範囲を削除しました",
"control_character": "制御文字"
},
"tab_hint": "Tab キーでインデントします。エディターから出るには、Esc を押してから Tab を押します。"
}
}
+39 -10
View File
@@ -6,8 +6,9 @@
"home": "Chuyển đổi",
"about": "Giới thiệu",
"github": "GitHub",
"label": "Điều hướng chính",
"home_brand": "Trang chủ JSONPrism"
"label": "Chính",
"home_brand": "Trang chủ JSONPrism",
"skip_to_content": "Bỏ qua, tới nội dung chính"
},
"home": {
"input_label": "JSON đầu vào",
@@ -33,10 +34,16 @@
"title_rest": "JSON.",
"copied": "Đã chép",
"error_position": "Dòng {{line}}, Cột {{column}}",
"output_aria": "Kết quả {{format}} (chỉ đọc)"
"jsonc_hint": "Có vẻ đây là JSONC — JSON có comment hoặc dấu phẩy thừa.",
"jsonc_switch": "Chuyển JSONC → JSON",
"output_aria": "Kết quả {{format}} (chỉ đọc)",
"document_title": "JSONPrism · Chuyển JSON sang 12 định dạng",
"format_picker_description": "Chọn một định dạng. Định dạng không dùng được theo chiều hiện tại sẽ bị tắt.",
"output_unread": "(mới)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +60,8 @@
"ready": "Sẵn sàng",
"suggested": "Gợi ý cho shape phát hiện được",
"not_suggested": "Không gợi ý cho shape phát hiện được",
"no_reverse": "Format này không hỗ trợ parse ngược"
"no_reverse": "Format này không hỗ trợ parse ngược",
"input_only": "Chỉ làm đầu vào: chuyển sang JSON ở chiều → JSON"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +74,14 @@
"pretty": "Pretty-print mỗi dòng",
"pretty_desc": "JSONL chuẩn là một dòng một record. Bật cái này nếu muốn dạng dễ đọc nhiều dòng."
},
"jsonc": {
"indent": "Bố cục output",
"indent_desc": "Comment và dấu phẩy thừa bị bỏ; giá trị, số và thứ tự key giữ nguyên như bạn viết.",
"indent_2": "2 dấu cách",
"indent_4": "4 dấu cách",
"indent_tab": "Tab",
"indent_minify": "Thu gọn (minify)"
},
"csv": {
"header": "Bao gồm dòng header",
"header_desc": "Phát ra dòng đầu tiên là tên cột lấy từ key của object.",
@@ -179,7 +195,8 @@
},
"shortcut": {
"download": "Tải về",
"settings": "Tuỳ chọn"
"settings": "Tuỳ chọn",
"leave_editor": "Rời trình soạn thảo"
},
"settings": {
"title": "Tuỳ chọn",
@@ -292,7 +309,7 @@
"about": {
"title": "Về JSONPrism",
"lead": "Một công cụ tán sắc cho developer.",
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
"p1": "JSONPrism nhận một đầu vào JSON và tán nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính — và đọc ngược được sáu trong số đó, cùng với JSONC (JSON có comment) thành JSON thuần. Mọi chuyển đổi chạy hoàn toàn trên thiết bị của bạn, nên dữ liệu bạn dán hoặc thả vào không bao giờ rời khỏi máy.",
"p2": "Xây dựng với React 19, TypeScript 7, Vite 8, Tailwind CSS v4 và shadcn/ui. Bản web chạy trên Cloudflare Workers; ứng dụng desktop và Android được xây dựng bằng Tauri 2. Mã nguồn trên GitHub.",
"version": "Phiên bản {{version}}",
"donate": {
@@ -345,7 +362,8 @@
"discussions": "Thảo luận",
"demo": "Ứng dụng web",
"license": "Giấy phép (Apache 2.0)",
"releases": "Bản phát hành & tải về"
"releases": "Bản phát hành & tải về",
"accessibility": "Tuyên bố trợ năng (accessibility)"
},
"disclaimer": {
"title": "Lưu ý",
@@ -373,7 +391,8 @@
"loading": "Đang tải…",
"scroll_to_top": "Về đầu trang",
"close": "Đóng",
"notifications": "Thông báo"
"notifications": "Thông báo",
"close_notification": "Đóng thông báo"
},
"consent": {
"title": "Trước khi bắt đầu",
@@ -443,7 +462,17 @@
"folded_code": "mã đã thu gọn",
"unfold": "mở rộng",
"diagnostics": "Chẩn đoán",
"no_diagnostics": "Không có chẩn đoán"
}
"no_diagnostics": "Không có chẩn đoán",
"folded_lines": "Đã thu gọn các dòng",
"unfolded_lines": "Đã mở rộng các dòng",
"to": "đến",
"current_match": "kết quả khớp hiện tại",
"on_line": "ở dòng",
"replaced_match_on_line": "đã thay kết quả khớp ở dòng $",
"replaced_matches": "đã thay $ kết quả khớp",
"selection_deleted": "Đã xoá vùng chọn",
"control_character": "Ký tự điều khiển"
},
"tab_hint": "Phím Tab dùng để thụt lề. Để rời trình soạn thảo, nhấn Esc rồi nhấn Tab."
}
}
+39 -10
View File
@@ -6,8 +6,9 @@
"home": "转换",
"about": "关于",
"github": "GitHub",
"label": "主导航",
"home_brand": "JSONPrism 首页"
"label": "主要",
"home_brand": "JSONPrism 首页",
"skip_to_content": "跳到主要内容"
},
"home": {
"input_label": "JSON 输入",
@@ -33,10 +34,16 @@
"title_rest": "JSON。",
"copied": "已复制",
"error_position": "第 {{line}} 行,第 {{column}} 列",
"output_aria": "{{format}} 输出(只读)"
"jsonc_hint": "这看起来是 JSONC——带注释或尾随逗号的 JSON。",
"jsonc_switch": "转换 JSONC → JSON",
"output_aria": "{{format}} 输出(只读)",
"document_title": "JSONPrism · 将 JSON 转换为 12 种格式",
"format_picker_description": "选择一种格式。当前方向下不可用的格式已禁用。",
"output_unread": "(新)"
},
"formats": {
"jsonl": "JSONL",
"jsonc": "JSONC",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
@@ -53,7 +60,8 @@
"ready": "可用",
"suggested": "适用于检测到的数据形状",
"not_suggested": "不推荐用于检测到的数据形状",
"no_reverse": "此格式不支持反向解析"
"no_reverse": "此格式不支持反向解析",
"input_only": "仅作输入:在 → JSON 方向转换为 JSON"
},
"direction": {
"forward": "JSON →",
@@ -66,6 +74,14 @@
"pretty": "美化每一行",
"pretty_desc": "标准 JSONL 为每条记录一行。如需多行人类可读输出,请启用此项。"
},
"jsonc": {
"indent": "输出布局",
"indent_desc": "移除注释和尾随逗号;值、数字和键的顺序保持原样。",
"indent_2": "2 个空格",
"indent_4": "4 个空格",
"indent_tab": "制表符",
"indent_minify": "压缩"
},
"csv": {
"header": "包含表头行",
"header_desc": "以对象键作为列名输出第一行。",
@@ -179,7 +195,8 @@
},
"shortcut": {
"download": "下载",
"settings": "设置"
"settings": "设置",
"leave_editor": "离开编辑器"
},
"settings": {
"title": "选项",
@@ -259,7 +276,7 @@
"about": {
"title": "关于 JSONPrism",
"lead": "为开发者打造的分光工具。",
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
"p1": "JSONPrism 将一个 JSON 输入分解为多种目标格式——就像白光穿过棱镜——其中六种格式还能转换回 JSON,JSONC(带注释的 JSON)也能转为标准 JSON。所有转换都在你的设备上完成,你粘贴或拖入的数据绝不会离开设备。",
"p2": "基于 React 19、TypeScript 7、Vite 8、Tailwind CSS v4 和 shadcn/ui 构建。网页版由 Cloudflare Workers 提供服务;桌面版和 Android 版使用 Tauri 2 构建。源代码托管在 GitHub。",
"version": "版本 {{version}}",
"donate": {
@@ -312,7 +329,8 @@
"discussions": "讨论区",
"demo": "网页版",
"license": "许可证 (Apache 2.0)",
"releases": "版本与下载"
"releases": "版本与下载",
"accessibility": "无障碍声明"
},
"disclaimer": {
"title": "免责声明",
@@ -340,7 +358,8 @@
"loading": "加载中…",
"scroll_to_top": "回到顶部",
"close": "关闭",
"notifications": "通知"
"notifications": "通知",
"close_notification": "关闭通知"
},
"social": {
"discord": "Discord",
@@ -443,7 +462,17 @@
"folded_code": "已折叠代码",
"unfold": "展开",
"diagnostics": "诊断",
"no_diagnostics": "无诊断"
}
"no_diagnostics": "无诊断",
"folded_lines": "已折叠行",
"unfolded_lines": "已展开行",
"to": "至",
"current_match": "当前匹配",
"on_line": "位于行",
"replaced_match_on_line": "已替换第 $ 行的匹配",
"replaced_matches": "已替换 $ 处匹配",
"selection_deleted": "已删除选区",
"control_character": "控制字符"
},
"tab_hint": "Tab 键用于缩进。要离开编辑器,请先按 Esc,再按 Tab。"
}
}
+10
View File
@@ -62,6 +62,16 @@ describe('runConversion', () => {
).toBe('input-error');
});
it('passes a reverse error position through when the parser knows it', () => {
const { outcome } = runConversion({
text: '// config\n{"a": 1 "b": 2}',
format: 'jsonc',
direction: 'reverse',
options: { indent: '2' },
});
expect(outcome).toMatchObject({ kind: 'input-error', line: 2, column: 9 });
});
it('flags precision loss on huge integers', () => {
const { outcome } = runConversion({
text: '{"id": 12345678901234567890}',
@@ -6,6 +6,7 @@ import { editorLanguageFor, outputLanguageFor } from '../editor-language';
/** Expected CodeMirror language for text written in each format. */
const FORMAT_LANGUAGE: Record<FormatId, string> = {
jsonl: 'jsonl',
jsonc: 'jsonc',
csv: 'plain',
tsv: 'plain',
yaml: 'yaml',
+1 -1
View File
@@ -33,5 +33,5 @@ export function saveConsent(consent: StoredConsent): void {
}
export function isConsentValid(consent: StoredConsent | null): boolean {
return !!consent && consent.accepted === true && consent.version === CONSENT_VERSION;
return !!consent && consent.accepted && consent.version === CONSENT_VERSION;
}
+15 -9
View File
@@ -71,15 +71,21 @@ function convertOnce({
if (direction === 'reverse') {
if (typeof converter.reverse !== 'function') return { kind: 'no-reverse' };
const result = safeReverse(converter, { text, ...(sourceName ? { sourceName } : {}) }, options);
return result.ok
? {
kind: 'ok',
output: result.output,
shape: null,
precisionLoss: false,
outputBytes: utf8ByteLength(result.output),
}
: { kind: 'input-error', message: result.error };
if (!result.ok) {
return {
kind: 'input-error',
message: result.error,
...(result.line !== undefined ? { line: result.line } : {}),
...(result.column !== undefined ? { column: result.column } : {}),
};
}
return {
kind: 'ok',
output: result.output,
shape: null,
precisionLoss: false,
outputBytes: utf8ByteLength(result.output),
};
}
const parsed = parseCached(text);
+1 -1
View File
@@ -92,7 +92,7 @@ export function errorPosition(
return offsetToLineColumn(text, offset);
}
function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
export function offsetToLineColumn(text: string, offset: number): { line: number; column: number } {
let line = 1;
let column = 1;
const end = Math.min(offset, text.length);
+2
View File
@@ -11,6 +11,8 @@ function languageOfFormat(format: FormatId): EditorLanguage {
return 'xml';
case 'jsonl':
return 'jsonl';
case 'jsonc':
return 'jsonc';
case 'markdown':
return 'markdown';
case 'sql':
+14
View File
@@ -0,0 +1,14 @@
/** `id` of the page's `<main>` landmark — the skip link and route changes move focus there. */
export const MAIN_ID = 'main';
/**
* Moves keyboard focus to the `<main>` landmark (it has `tabIndex={-1}`), so
* the next Tab continues inside the page content and screen readers start
* reading there. Returns `false` when the landmark isn't mounted.
*/
export function focusMain(options: FocusOptions = {}): boolean {
const main = document.getElementById(MAIN_ID);
if (!main) return false;
main.focus(options);
return true;
}
+10 -5
View File
@@ -1,4 +1,4 @@
import { useRef, useState } from 'react';
import { useRef, useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, ClipboardCopy, ExternalLink, Heart, Mail, ShieldCheck, Users } from 'lucide-react';
import { ScrollToTop } from '@/components/common/ScrollToTop';
@@ -18,7 +18,7 @@ import { tauriHostInfo } from '@/lib/tauri';
interface CommunityPlatform {
key: 'discord' | 'x' | 'bluesky' | 'mastodon' | 'telegram' | 'youtube';
url: string;
icon: React.ReactNode;
icon: ReactNode;
}
const COMMUNITY: CommunityPlatform[] = [
@@ -163,8 +163,9 @@ export function About() {
<div
ref={scrollRef}
tabIndex={0} // NOSONAR(S6845): scrollable region; keyboard users need focus to scroll it
role="region"
aria-label={t('about.title')}
className="min-h-0 flex-1 overflow-y-auto outline-none"
className="focus-visible:ring-ring min-h-0 flex-1 overflow-y-auto outline-none focus-visible:ring-2 focus-visible:ring-inset"
>
<div className="mx-auto max-w-3xl px-4 py-10 sm:px-6 sm:py-14">
<p className="label-mono mb-2">{t('about.kicker')}</p>
@@ -329,6 +330,10 @@ export function About() {
<LinkRow href={SITE_URL} label={t('about.links.demo')} />
<LinkRow href={`${REPO_URL}/releases`} label={t('about.links.releases')} />
<LinkRow href={legalDocUrl('LICENSE')} label={t('about.links.license')} />
<LinkRow
href={legalDocUrl('ACCESSIBILITY.md')}
label={t('about.links.accessibility')}
/>
</ul>
</Section>
@@ -354,9 +359,9 @@ function Section({
title,
children,
}: {
icon?: React.ReactNode;
icon?: ReactNode;
title: string;
children: React.ReactNode;
children: ReactNode;
}) {
return (
<section className="mt-12">
+2
View File
@@ -6,6 +6,8 @@ export function Home() {
return (
<div className="mx-auto flex min-h-0 w-full max-w-screen-2xl flex-1 flex-col gap-3 px-3 py-3 sm:gap-4 sm:px-6 sm:py-5">
{/* React 19 hoists this into <head>, ahead of index.html's English title. */}
<title>{t('home.document_title')}</title>
<header className="flex flex-col gap-1.5 md:flex-row md:items-end md:justify-between md:gap-6">
<div>
<p className="label-mono mb-1">{t('home.kicker')}</p>
+1 -1
View File
@@ -172,7 +172,7 @@ describe('Copy diagnostics', () => {
'',
'Recent log:',
]);
expect(lines[6]).toMatch(/^\d{4}-\d{2}-\d{2}T\S+ WARN \[convert\] Slow conversion 1200$/);
expect(lines[6]).toMatch(/^\d{4}-\d{2}-\d{2}T\S+ WARN \[convert] Slow conversion 1200$/);
expect(success).toHaveBeenCalledWith('Diagnostics copied — paste them into your bug report.');
expect(copyButton().querySelector('svg')).toHaveClass('lucide-check');
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more