demo basic

This commit is contained in:
poli0981 committed 2026-05-13 09:43:37 +07:00
1 parent e4cdfc3bec
commit fb506baba2
101 files changed
+15319

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
+49
View File
@@ -0,0 +1,49 @@
---
name: Bug report
about: Report a bug in JSONPrism
title: '[BUG] '
labels: ['bug', 'needs-triage']
assignees: []
---
## Describe the bug
A clear description of what the bug is.
## To reproduce
1. Go to '...'
2. Paste this JSON: '...'
3. Pick format '...'
4. See error
## Sample JSON
Please provide a **minimal** JSON sample that triggers the bug:
```json
{ "your": "sample here" }
```
## Expected behavior
What you expected to happen.
## Actual behavior
What actually happened. Include the error message and target format.
## Environment
- Browser: [e.g. Chrome 130, Firefox 132, Safari 18]
- OS: [e.g. Windows 11, macOS 15, Ubuntu 24.04]
- JSONPrism version: [e.g. 0.1.0 — check the footer]
- Is this on the hosted version (poli0981.github.io/jsonprism/) or local dev?
## Screenshots
If applicable, attach screenshots.
## Additional context
Anything else relevant.
+43
View File
@@ -0,0 +1,43 @@
---
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.
## 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 client-side (no server required)
- [ ] I have a real use case for this (not just hypothetical)
## Additional context
Links, screenshots, references to similar tools.
+59
View File
@@ -0,0 +1,59 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
permissions:
contents: read
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
build:
name: Lint, typecheck, build
runs-on: ubuntu-latest
timeout-minutes: 10
strategy:
matrix:
node-version: [22.x]
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node ${{ matrix.node-version }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- name: Install dependencies
run: npm ci --no-audit --no-fund
- name: Format check
run: npm run format:check
- name: Lint
run: npm run lint
- name: Typecheck
run: npm run typecheck
- name: Test
run: npm test
- name: Build
run: npm run build
- name: Upload build artifact
uses: actions/upload-artifact@v4
with:
name: dist
path: dist
retention-days: 7
+61
View File
@@ -0,0 +1,61 @@
name: Deploy to GitHub Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
name: Build
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Node 22
uses: actions/setup-node@v4
with:
node-version: 22.x
cache: npm
- name: Install dependencies
run: npm ci --no-audit --no-fund
- name: Build
run: npm run build
# SPA fallback so deep links (/jsonprism/about) work on GH Pages.
- name: Copy index.html → 404.html
run: cp dist/index.html dist/404.html
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v3
with:
path: dist
deploy:
name: Deploy
needs: build
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
+92
View File
@@ -0,0 +1,92 @@
name: Release Tauri bundles
on:
push:
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: write
jobs:
build:
name: Build · ${{ matrix.platform.name }}
runs-on: ${{ matrix.platform.runner }}
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
platform:
- name: Windows
runner: windows-latest
args: ''
- name: macOS (Apple Silicon)
runner: macos-14
args: '--target aarch64-apple-darwin'
- name: macOS (Intel)
runner: macos-13
args: '--target x86_64-apple-darwin'
- name: Linux
runner: ubuntu-22.04
args: ''
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Install Linux build dependencies
if: matrix.platform.runner == 'ubuntu-22.04'
run: |
sudo apt-get update
sudo apt-get install -y \
libwebkit2gtk-4.1-dev \
libappindicator3-dev \
librsvg2-dev \
patchelf \
libssl-dev \
libgtk-3-dev
- name: Setup Node 22
uses: actions/setup-node@v4
with:
node-version: 22.x
cache: npm
- name: Setup Rust (stable)
uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.platform.runner == 'macos-14' && 'aarch64-apple-darwin' || matrix.platform.runner == 'macos-13' && 'x86_64-apple-darwin' || '' }}
- name: Cache Cargo build artifacts
uses: swatinem/rust-cache@v2
with:
workspaces: './src-tauri -> target'
- name: Install npm dependencies
run: npm ci --no-audit --no-fund
- name: Generate icons (Linux & macOS)
if: matrix.platform.runner != 'windows-latest'
run: npm run tauri:icon
- name: Generate icons (Windows)
if: matrix.platform.runner == 'windows-latest'
run: npm run tauri:icon
shell: pwsh
- name: Build, sign, and create release
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tagName: ${{ github.ref_name }}
releaseName: 'JSONPrism ${{ github.ref_name }}'
releaseBody: |
Native desktop builds for Windows, macOS, and Linux.
See the [CHANGELOG](https://github.com/poli0981/jsonprism/blob/main/CHANGELOG.md) for what's new.
releaseDraft: true
prerelease: false
args: ${{ matrix.platform.args }}
+45
View File
@@ -0,0 +1,45 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/settings.json
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Env
.env
.env.local
.env.*.local
!.env.example
# Tauri (Phase 2C)
src-tauri/target
src-tauri/Cargo.lock
src-tauri/gen
src-tauri/icons/*.png
src-tauri/icons/*.ico
src-tauri/icons/*.icns
# Test artifacts
coverage
.nyc_output
.claude/
+1
View File
@@ -0,0 +1 @@
22
+6
View File
@@ -0,0 +1,6 @@
dist
node_modules
pnpm-lock.yaml
package-lock.json
yarn.lock
src/components/ui
+11
View File
@@ -0,0 +1,11 @@
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"useTabs": false,
"arrowParens": "always",
"endOfLine": "lf",
"plugins": ["prettier-plugin-tailwindcss"]
}
+166
View File
@@ -0,0 +1,166 @@
# Changelog
All notable changes to JSONPrism are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
Project is feature-complete for the original Phase 0–3 plan. Future work tracked in `docs/ROADMAP.md` under "Beyond Phase 3".
## [1.0.0] — 2026-05-12
### Added — Phase 3: RESX + i18n migration
- **RESX converter** (`.resx`) — hand-rolled XML output byte-aligned with Visual Studio's editor. 9/9 formats now production-ready.
- Accepts flat string-to-string objects: `{ "Key": "value", ... }`
- Supports the `{ value, _comment }` shape per entry; emits both `<value>` and `<comment>` elements
- Options: `commentKey` (default `_comment`), `includeSchema`, `sortKeys`
- Full RESX 2.0 schema header + `resmimetype` / `version` / `reader` / `writer` resheaders
- Proper XML escaping: `&`, `<`, `>` in text; quotes in `name=` attributes
- Rejects nested objects (the only valid use of nesting is the `{ value, _comment }` shape)
- **Smart format suggestions** — picker now highlights formats matching the detected JSON shape with a subtle ring:
- `flat-object` → RESX surfaces first
- `array-of-objects` → CSV/TSV/Markdown/SQL/JSONL
- `object` → YAML/TOML/XML
- `array` → JSONL/YAML/XML
- `scalar` → YAML
- **Migration tutorial** (`docs/RESX-MIGRATION.md`) — step-by-step guide for taking i18next JSON locales into .NET RESX, with batch flow, Visual Studio verification, comment support, and a worked example using PhantomMAC's 30+ locale files
### Status
**JSONPrism reaches 1.0.** All 9 formats production-ready; web + desktop; bilingual; 110+ tests.
### Tests
- **15+ new tests**: RESX converter (escaping, comment shape, sort order, error paths, Visual Studio byte-match), suggestions module
- Total tests: **115+**
## [0.5.0] — 2026-05-12
### Added — Phase 2C: Tauri 2 desktop wrapper
- **`src-tauri/` Rust workspace** with Tauri 2.x: `Cargo.toml`, `tauri.conf.json`, `src/lib.rs`, `src/main.rs`, `build.rs`
- **App identifier**: `com.kokone.jsonprism`
- **Bundle targets**: Windows (MSI via WiX + NSIS installer), macOS (DMG, min 12.0), Linux (AppImage + deb)
- **Window config**: 1280×820 default, 800×560 minimum, drag-drop enabled, theme follows system
- **CSP locked down** to: self + Google Fonts (existing fonts) + IPC channel only
- **Tauri 2 plugin integration**: `plugin-dialog`, `plugin-fs`, `plugin-os`, `plugin-shell`
- **Capability file** (`capabilities/default.json`) scoped to `$HOME`, `$DOCUMENT`, `$DOWNLOAD`, `$DESKTOP`
- **Custom Rust command `host_info`** exposes OS / arch / app version for diagnostics
- **Frontend Tauri bridge** (`src/lib/tauri.ts`): `isTauri()`, `nativeOpenFiles()`, `nativeSaveBlob()`, `nativeReadText()`, `fileFromNativePath()`, `tauriHostInfo()`
- **Native drag-drop hook** (`useTauriDragDrop`) listens to `tauri://drag-drop` events and feeds File objects into the existing batch store
- **InputPanel + BatchPanel** branch on `isTauri()`: native dialogs in Tauri, web inputs in browser
- **Single source of truth**: same React UI, same converters, same tests — only I/O boundaries branch
- **Vite config Tauri-aware**: detects `TAURI_ENV_PLATFORM`, switches base to `/`, skips clearing screen, respects `TAURI_DEV_HOST` for mobile dev
- **Icon source** (`src-tauri/icons/icon.svg`, 1024×1024) — generates all platform icons via `npm run tauri:icon`
- **GitHub Actions release workflow** (`.github/workflows/release.yml`): matrix-builds Windows, macOS (Apple Silicon + Intel), Linux on `v*` tag push; creates draft GitHub release
### Dependencies
- Added `@tauri-apps/api`, `@tauri-apps/plugin-dialog`, `@tauri-apps/plugin-fs`, `@tauri-apps/plugin-os`, `@tauri-apps/plugin-shell` (^2.0.0 each)
- Added `@tauri-apps/cli` (devDep)
### New npm scripts
- `tauri:dev` — runs Tauri window in dev mode with HMR
- `tauri:build` — produces the platform's native bundle
- `tauri:icon` — generates all platform icons from `src-tauri/icons/icon.svg`
## [0.4.0] — 2026-05-12
### Added — Phase 2B: Batch processing
- **Multi-file queue** — drop up to **500 JSON files** at once for parallel conversion to any ready format
- **Batch panel** (Sheet drawer) — per-file status (queued / processing / done / error), inline drop zone, per-row remove
- **Cooperative scheduling** — yields to the UI between files via `requestIdleCallback` with `setTimeout(0)` fallback, so the browser stays responsive on large queues
- **Per-file error isolation** — broken JSON or converter errors don't stop the rest of the batch; each failure is surfaced inline
- **AbortController-based cancellation** — Cancel button stops the run mid-batch
- **`.zip` export** via **fflate** (~8KB gzipped, much smaller than JSZip), with automatic filename collision handling (`data.csv`, `data_2.csv`, …)
- **Smart drop routing in input panel** — single file goes into the editor, 2+ files auto-open the batch panel and queue them
- **Zustand `batchStore`** — `Record<string, BatchItem>` + `itemOrder` for O(1) per-item updates without re-rendering the whole list
- **Trigger pill in toolbar** shows current queue size
### Tests
- **20+ new Vitest tests** covering `batchStore` mutations, `processBatch` cooperative scheduling and abort, `zipOutputs` round-trip (decode and verify contents), filename uniquification
- Total tests: **100+**
### Dependencies
- Added `fflate ^0.8.2` (zip)
## [0.3.0] — 2026-05-12
### Added — Phase 2A: four new converters
- **XML converter** via fast-xml-parser. Options: `indent`, `rootName`, `itemName`, `declaration`. Supports attributes via the `@_` key prefix convention.
- **TOML converter** via smol-toml. Option: `sortKeys` (recursive). Rejects non-object roots with a clear error.
- **Markdown table converter** (hand-rolled). Options: `alignment` (left/center/right/none), `escapePipes`. Newlines in cells become `<br>` per GFM.
- **SQL INSERT converter** (hand-rolled). Options: `tableName`, `dialect` (standard/postgres/mysql/sqlite/mssql), `multiRow`, `chunkSize`, `includeCreate`. Per-dialect identifier quoting, value escaping, and `CREATE TABLE` type inference.
### Tests
- **45+ new Vitest tests** across XML, TOML, Markdown, and SQL converters (helpers tested in isolation: `quoteIdentifier`, `formatSqlValue`, `inferSqlType`)
- Round-trip tests for XML (via `XMLParser`) and TOML (via `parse`)
- Per-dialect SQL coverage (5 dialects × value types)
- Total Vitest tests: **80+**
### Changed
- All 8 user-visible converters now report `ready: true`. RESX remains Phase 3.
- `xml.ts`, `toml.ts`, `markdown.ts`, `sql.ts` are no longer stubs.
## [0.2.0] — 2026-05-12
### Added — Phase 1 polish
- **CodeMirror 6** input editor with JSON syntax highlighting and parse-error linting
- **Settings panel** (Sheet drawer) auto-generated from each converter's `optionSchema`
- **Per-format options exposed** in the UI:
- JSONL: `pretty` toggle
- CSV/TSV: `header` toggle, `newline` (LF/CRLF), `nestedStrategy` (json/flatten)
- YAML: `indent` (2–8), `quoteStyle` (auto/single/double)
- **Settings persist** to `localStorage` per format; survive reload and tabs
- **File handling**: drag-drop + "Open" button for single `.json` / `.txt` files
- **Sonner toasts** for copy success, download, file load, options reset, errors
- **Keyboard shortcuts**: `Cmd/Ctrl+K` clear input, `Cmd/Ctrl+S` download output
- **Status bar** showing input/output byte counts, parse time, and shortcut hints
- **Shape detection hint** above the format picker (scalar / object / array / flat-object / array-of-objects)
- **Format selection persists** to localStorage
- **Tests**: 35+ Vitest tests covering all Phase 1 converters, registry, shape detection, options storage
### Changed
- `Converter<TOptions>` interface now requires `optionSchema: ReadonlyArray<OptionSchemaField<TOptions>>`
- YAML `indent` option changed from `2 | 4` literal to `number` (range 2–8 via integer schema)
- Stub converters (XML/TOML/Markdown/SQL/RESX) declare empty `optionSchema: []` to satisfy the interface
- `InputPanel` and `OutputPanel` updated to use `CodeEditor` and toast notifications
### Developer experience
- **Vitest** + `@testing-library/react` + `jsdom` configured
- `npm test`, `npm run test:watch`, `npm run test:coverage` scripts
- CI runs tests between typecheck and build
## [0.1.0] — 2026-05-12
### Added — Phase 0 scaffold
- Project scaffold with Vite 6 + React 19 + TypeScript 5.7 strict
- Tailwind CSS v4 setup using `@theme inline` syntax
- "Prism Spectrum" theme with violet / cyan / amber / rose accents
- Dark + light theme with system preference detection
- Bilingual interface (English + Vietnamese) via i18next
- React Router v7 with `/` and `/about` routes
- Converter framework: `Converter<TOptions>` interface, registry, shape detection
- **Phase 1 working converters**: JSONL, CSV, TSV, YAML
- **Phase 2 stubs with implementation plans**: XML, TOML, Markdown table, SQL INSERT
- **Phase 3 stub**: RESX (.NET resources)
- UI: header with brand mark, hero, format picker, side-by-side input/output panels
- Copy + download actions with proper MIME types
- shadcn/ui configuration (`components.json`)
- GitHub Actions CI workflow (format, lint, typecheck, build)
- GitHub Actions deploy workflow → GitHub Pages
- Apache License 2.0
- Full documentation: `README.md` (EN + VI), `CLAUDE.md`, `CONTRIBUTING.md`, `docs/ROADMAP.md`
+124
View File
@@ -0,0 +1,124 @@
# CLAUDE.md
Guidance for Claude (and other AI assistants) working on this repository.
## Project context
**JSONPrism** is a client-side JSON converter web app. Single JSON input → many formats (JSONL, CSV, TSV, YAML, XML, TOML, RESX, Markdown table, SQL INSERT). Deployed to GitHub Pages; later wrapped in Tauri 2 as a desktop app.
The maintainer is **Kokone** ([@poli0981](https://github.com/poli0981)). Audience: developer community on the open-source Discord server + YouTube viewers who watch indie/visual-novel gameplay and occasionally want a quick devtool.
**Project phase**: Phase 0 scaffold complete. Phase 1 polishes the four working converters and adds CodeMirror. Phase 2 implements XML/TOML/Markdown/SQL and the Tauri build. Phase 3 implements RESX.
## Stack — exact versions matter
- **Node.js** 22.x LTS (minimum 22.0.0; enforced in `package.json` `engines`)
- **React** 19.x (uses new JSX transform, `use()` hook, ref-as-prop)
- **TypeScript** 5.7+ (strict mode; `verbatimModuleSyntax`; `erasableSyntaxOnly`)
- **Vite** 6.x (ES2022 target, `@tailwindcss/vite` plugin)
- **Tailwind CSS** v4 (new `@theme inline` syntax in CSS, NOT `tailwind.config.ts`)
- **shadcn/ui** New York style, neutral base, configured in `components.json`
- **ESLint** v9 flat config + `typescript-eslint` v8
- **Prettier** 3.x with `prettier-plugin-tailwindcss`
Do not propose downgrading or "modernizing" to deprecated patterns.
## Tauri 2 desktop wrapper
JSONPrism is shipped as both a web app (GitHub Pages) and a native desktop app (Tauri 2 bundles). The same React UI runs in both contexts.
**Runtime detection**: `isTauri()` from `src/lib/tauri.ts` is the single source of truth. The web bundle never imports Tauri modules statically — they're behind dynamic imports gated by `isTauri()` so tree-shaking keeps web builds clean.
**When to branch on `isTauri()`**:
- File dialogs: web uses hidden `<input type="file">`; Tauri uses `plugin-dialog`
- Save .zip: web uses Blob URL download; Tauri uses native save dialog + `plugin-fs.writeFile`
- Drag-drop from File Explorer / Finder: web uses `react-dropzone`; Tauri uses `tauri://drag-drop` event via `useTauriDragDrop`
**Don't branch on `isTauri()`** for things that work in both: clipboard, in-memory operations, the converters themselves. Keep the Tauri-specific code at the I/O boundary.
**Adding a new Tauri-only command**: declare in `src-tauri/src/lib.rs` with `#[tauri::command]`, register in `invoke_handler!`, expose a typed wrapper in `src/lib/tauri.ts` using `invoke()`. Update the capability JSON if it needs new permissions.
**Icon updates**: edit `src-tauri/icons/icon.svg` (1024×1024 canvas) then run `npm run tauri:icon`. The generated PNG/ICO/ICNS files are gitignored — CI regenerates them per build.
**Permission model**: Tauri 2 uses capability files. Edits to `src-tauri/capabilities/default.json` change which APIs the main window can call. Default capability already grants dialog, fs (scoped to `$HOME`, `$DOCUMENT`, `$DOWNLOAD`, `$DESKTOP`), os, and shell:open.
**Bundling**: `npm run tauri:build` produces the platform bundle of whatever OS you're on. For cross-platform releases, push a `v*` tag — `.github/workflows/release.yml` matrix-builds for Windows, macOS Intel/ARM, and Linux.
**Velopack note**: PhantomMAC uses Velopack for `.exe` deltas; JSONPrism uses Tauri's native bundler instead. Don't mix the two — Tauri's bundler produces `.msi` + `.exe` (NSIS) for Windows which covers the same ground.
## Code style — non-negotiable
- **Pure functions for converters**. Each converter is a pure, synchronous module implementing the `Converter<TOptions>` interface in `src/converters/types.ts`. No I/O, no DOM access, no global state.
- **Errors as values**. Converters return `{ ok: true, output } | { ok: false, error }`. Never throw across converter boundaries.
- **No `any`**. Use `unknown` for JSON values and narrow with type guards. The only sanctioned `any` is in `registry.ts` for the heterogeneous record type — keep it there.
- **Type-only imports**: `import type { Converter } from './types'`. Enforced by ESLint rule `consistent-type-imports`.
- **Use the `@/*` path alias** for imports inside `src/`. Don't write `../../lib/utils`.
- **Tailwind class order**: rely on `prettier-plugin-tailwindcss` — never hand-sort.
- **Don't fight the theme system**. Use the CSS variables (`--color-prism-*`, `bg-background`, etc.) instead of hard-coded hex.
- **i18n everything user-facing**. Hard-coded English strings in components are a bug. Add to both `en.json` and `vi.json`.
## File layout — where things go
```
src/
├── app/ # Top-level App component + routes
├── components/
│ ├── ui/ # shadcn components — generated by CLI, don't hand-edit
│ ├── layout/ # Header, Footer, theme/language toggles
│ ├── converter/ # The workspace UI
│ └── common/ # Reusable bits not specific to converters
├── converters/ # ONE file per format. Self-contained.
├── hooks/ # React hooks
├── i18n/ # i18next setup + locales
├── lib/ # Pure utilities: detect, theme, sample, utils
├── pages/ # Route components
└── styles/ # globals.css ONLY — no per-component CSS files
```
If you find yourself wanting to add a new top-level folder, stop and reconsider.
## Adding a new converter — checklist
1. Create `src/converters/myformat.ts` exporting `myFormatConverter` (camelCase).
2. Implement the `Converter<MyFormatOptions>` interface. Return errors as values.
3. Add the format ID to the `FormatId` union in `src/converters/types.ts`.
4. Register in `src/converters/registry.ts` (both `CONVERTERS` and `ALL_FORMATS`).
5. Add `formats.myformat` label to BOTH `src/i18n/locales/en.json` AND `src/i18n/locales/vi.json`.
6. If introducing a new parsing library, add it to `vite.config.ts` `manualChunks.parsers` so it splits cleanly.
7. Update the format table in `README.md` and `README.vi.md`.
8. Update `docs/ROADMAP.md` to mark the phase done.
9. Write unit tests (Phase 1+ when Vitest lands).
## Pitfalls observed in the wild
- **Don't put options inside the converter call signature**. Options are passed separately so the UI can introspect `defaultOptions` to render a settings panel.
- **Don't use `JSON.parse` directly in components**. Always go through `parseJsonInput` in `src/lib/detect.ts` so error positions surface uniformly.
- **CSV nested values**: stringify nested objects as JSON by default (`nestedStrategy: 'json'`). The `flatten` strategy is alpha — keep it but don't make it default.
- **YAML force-quoting**: js-yaml's `forceQuotes` only works in conjunction with `quotingType`. Leaving one undefined produces unquoted output. Tested.
- **GitHub Pages basename**: production builds use base `/jsonprism/`. The router uses `import.meta.env.PROD` to switch basename. Do not hard-code.
- **Tailwind v4 dark mode**: uses the new `@custom-variant dark (&:is(.dark *));` syntax. The `.dark` class on `<html>` triggers all dark-mode variants. Don't add `darkMode: 'class'` configs — that's v3 syntax.
## Commands the maintainer actually runs
```bash
npm run dev # 99% of the time
npm run typecheck # before pushing
npm run lint # CI does this anyway
npm run build # to verify production output
```
Format check happens automatically via Prettier in CI. The maintainer typically uses **WebStorm** (JetBrains license), so Prettier and ESLint run on save.
## Communication preferences
- Reply in **Vietnamese** unless the maintainer writes in English.
- Be direct. Skip unnecessary preamble.
- When proposing changes, show the diff or full file; don't just describe.
- Match the file-naming and patterns already established (`*Converter`, `useFoo`, kebab-case for files, PascalCase for components).
- The maintainer dislikes excessive emoji; reserve them for status indicators in docs (✅ 🔜 📋).
- When unsure between two equally-valid approaches, pick one and explain briefly — don't ask which the maintainer prefers unless it's a meaningful tradeoff.
## Roadmap reference
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the canonical phase plan. Update it as work lands.
+98
View File
@@ -0,0 +1,98 @@
# Contributing to JSONPrism
Thanks for considering a contribution! JSONPrism is an open-source project under Apache License 2.0.
## Quick start
```bash
git clone https://github.com/poli0981/jsonprism.git
cd jsonprism
npm install
npm run dev
```
Open <http://localhost:5173>.
## Before opening a PR
1. **Run the checks locally**:
```bash
npm run format
npm run lint
npm run typecheck
npm run build
```
CI runs all four. If any fails, your PR can't be merged.
2. **Match the project style.** Read [`CLAUDE.md`](CLAUDE.md) for non-negotiable conventions (converter shape, error handling, i18n requirements).
3. **Keep PRs focused.** One feature or one fix per PR. Refactors as separate PRs.
4. **Write a clear PR description**: what changed, why, screenshots if UI.
## Ways to contribute
### 🐛 Bug reports
Use the [Bug Report](https://github.com/poli0981/jsonprism/issues/new?template=bug_report.md) template. Include:
- Browser + OS
- Steps to reproduce
- Sample JSON that triggers the bug (minimal, please)
- Expected vs actual output
### 💡 Feature requests
Use the [Feature Request](https://github.com/poli0981/jsonprism/issues/new?template=feature_request.md) template. We prioritize features that:
- Fit the "one JSON → many formats" core mission
- Don't require server-side processing (we're client-only by design)
- Have a clear use case from a real workflow
### 🌍 Translations
Currently bundled: **English** and **Tiếng Việt**. To add a new language:
1. Copy `src/i18n/locales/en.json` to `src/i18n/locales/<your-locale>.json`
2. Translate every value
3. Register in `src/i18n/index.ts`
4. Add to the `supportedLngs` array
5. Add the language to `LanguageSwitcher.tsx`
6. Open a PR
### ➕ Adding a new converter
See the **"Adding a new converter — checklist"** section in [`CLAUDE.md`](CLAUDE.md).
Briefly:
1. New file `src/converters/myformat.ts` implementing `Converter<TOptions>`
2. Register in `registry.ts` and `types.ts`
3. Add i18n labels (EN + VI minimum)
4. Update README format tables
5. Mark roadmap entry done
## Commit messages
We follow a relaxed version of [Conventional Commits](https://www.conventionalcommits.org):
```
feat(converter): add TOML converter with smol-toml
fix(csv): escape pipes in cell values
docs: clarify Tauri build steps
chore(deps): bump react to 19.1
```
Prefixes: `feat`, `fix`, `docs`, `refactor`, `test`, `chore`, `style`.
## Code of Conduct
Be kind. Assume good faith. Disagreements about technical choices are fine; personal attacks are not.
Reports to the maintainer via GitHub (DM or email on profile).
## License
By contributing, you agree your contributions will be licensed under [Apache License 2.0](LICENSE).
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for describing the origin of the Work and
reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may accept and charge a
fee for acceptance of support, warranty, indemnity, or other liability
obligations and/or rights consistent with this License. However, in
accepting such obligations, You may act only on Your own behalf
and on Your sole responsibility, not on behalf of any other
Contributor, and only if You agree to indemnify, defend, and hold
each Contributor harmless for any liability incurred by, or claims
asserted against, such Contributor by reason of your accepting any
such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 Kokone (https://github.com/poli0981)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+191
View File
@@ -0,0 +1,191 @@
<div align="center">
# JSONPrism
**Disperse JSON into many formats.**
One JSON input. Eight target formats. Fully in your browser.
[![CI](https://github.com/poli0981/jsonprism/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/jsonprism/actions/workflows/ci.yml)
[![Deploy](https://github.com/poli0981/jsonprism/actions/workflows/deploy.yml/badge.svg)](https://github.com/poli0981/jsonprism/actions/workflows/deploy.yml)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[Live demo](https://poli0981.github.io/jsonprism/) · [Tiếng Việt](README.vi.md) · [Roadmap](docs/ROADMAP.md)
</div>
---
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. **Everything runs client-side**, so your data never leaves your device.
## Target formats
| Format | Extension | Status |
| ----------------- | --------- | ------------- |
| 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 |
## Features
- **Client-side only** — no server, no telemetry, no upload. Your JSON stays in your browser.
- **Batch processing** — up to 500 files at once (Phase 2).
- **Smart shape detection** — recognizes flat objects, arrays of objects, scalars; suggests the best target format.
- **Per-format options** — pretty-print, indentation, dialect (for SQL), alignment (for Markdown), and more.
- **Dark + light themes** — Prism Spectrum palette with violet / cyan / amber / rose accents.
- **EN + VI** — bilingual interface out of the box. More languages welcome.
- **Tauri desktop build** — drag-and-drop file workflow, offline-first (Phase 2 milestone).
## Tech stack
- **Vite 6** + **React 19** + **TypeScript 5.7**
- **Tailwind CSS v4** + **shadcn/ui** (New York style, neutral base)
- **CodeMirror 6** for the input editor (Phase 1 polish)
- **PapaParse**, **js-yaml**, **smol-toml**, **fast-xml-parser** for parsing/serialization
- **i18next** for translations, **Zustand** for state, **Sonner** for toasts
- **Tauri 2** wrapper (Phase 2)
## Quick start
**Requirements**: Node.js **22 LTS** or newer.
```bash
git clone https://github.com/poli0981/jsonprism.git
cd jsonprism
npm install
npm run dev # http://localhost:5173
```
## Desktop app (Tauri 2)
JSONPrism also ships as a native desktop app via Tauri 2. The app uses the same React UI, with native OS dialogs and drag-drop hooked into the existing batch flow.
**Additional requirements**:
- **Rust toolchain** (`rustup`) with the stable channel
- **Platform build deps**:
- **Windows**: Visual Studio Build Tools (C++ workload) + WebView2 (preinstalled on Windows 11)
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
- **Linux**: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf`, `libssl-dev`
**Generate icons once** (uses Tauri's CLI to render the SVG to PNG/ICO/ICNS):
```bash
npm run tauri:icon
```
**Run in dev mode** (Vite + Tauri window with hot reload):
```bash
npm run tauri:dev
```
**Build native bundles**:
```bash
npm run tauri:build
```
Output:
- Windows → `src-tauri/target/release/bundle/msi/*.msi` + `nsis/*-setup.exe`
- macOS → `src-tauri/target/release/bundle/dmg/*.dmg` + `macos/*.app`
- Linux → `src-tauri/target/release/bundle/appimage/*.AppImage` + `deb/*.deb`
**Automated releases**: pushing a `v*` tag triggers `.github/workflows/release.yml`, which builds for all platforms in parallel and creates a draft GitHub release.
### Scripts
| Script | What it does |
| --------------------- | --------------------------------------------- |
| `npm run dev` | Start Vite dev server with HMR |
| `npm run build` | Production build to `dist/` |
| `npm run preview` | Preview the built site locally |
| `npm run lint` | Run ESLint |
| `npm run lint:fix` | Run ESLint with autofix |
| `npm run typecheck` | TypeScript type-check, no emit |
| `npm run format` | Format with Prettier |
| `npm run format:check`| Check formatting (CI uses this) |
### shadcn/ui components
The `components.json` is preconfigured. Add components on demand:
```bash
npx shadcn@latest add button input textarea tabs select card dialog sheet \
dropdown-menu switch badge progress tooltip sonner resizable
```
## Architecture
```
src/
├── app/ # Router + global providers
├── components/
│ ├── ui/ # shadcn components (added on demand)
│ ├── layout/ # Header, Footer, ThemeToggle
│ ├── converter/ # Workspace, panels, format picker
│ └── common/ # ErrorBoundary, LanguageSwitcher
├── converters/ # One module per target format
│ ├── types.ts # Converter interface
│ ├── registry.ts # Lookup table
│ └── *.ts # Per-format implementations
├── hooks/ # Custom hooks
├── i18n/ # Translations (en, vi)
├── lib/ # detect, theme, utils, sample
├── pages/ # Home, About
├── styles/ # globals.css (Tailwind + theme tokens)
└── main.tsx
```
### Adding a new format
Each format is a self-contained module implementing the `Converter` interface:
```ts
import type { Converter } from './types';
interface MyFormatOptions {
indent: 2 | 4;
}
export const myFormatConverter: Converter<MyFormatOptions> = {
meta: {
id: 'myformat',
labelKey: 'formats.myformat',
extension: 'myf',
mimeType: 'application/x-myformat',
phase: 1,
ready: true,
},
defaultOptions: { indent: 2 },
convert({ data }, options) {
try {
const output = serialize(data, options);
return { ok: true, output };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
```
Then register it in `src/converters/registry.ts` and add label keys to `src/i18n/locales/*.json`.
See [`docs/ROADMAP.md`](docs/ROADMAP.md) for the full phase plan.
## Contributing
Pull requests welcome — please read [`CONTRIBUTING.md`](CONTRIBUTING.md) first.
For bug reports and feature requests, use [GitHub Issues](https://github.com/poli0981/jsonprism/issues).
## License
[Apache License 2.0](LICENSE) — © 2026 Kokone.
+191
View File
@@ -0,0 +1,191 @@
<div align="center">
# JSONPrism
**Tán sắc JSON ra nhiều định dạng.**
Một JSON đầu vào. Tám định dạng đích. Chạy hoàn toàn trong trình duyệt.
[![CI](https://github.com/poli0981/jsonprism/actions/workflows/ci.yml/badge.svg)](https://github.com/poli0981/jsonprism/actions/workflows/ci.yml)
[![Deploy](https://github.com/poli0981/jsonprism/actions/workflows/deploy.yml/badge.svg)](https://github.com/poli0981/jsonprism/actions/workflows/deploy.yml)
[![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[Bản demo](https://poli0981.github.io/jsonprism/) · [English](README.md) · [Lộ trình](docs/ROADMAP.md)
</div>
---
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. **Mọi thứ chạy client-side**, dữ liệu của bạn không bao giờ rời khỏi máy.
## Định dạng hỗ trợ
| Định dạng | Phần mở rộng | Trạng thái |
| ----------------- | ------------ | -------------- |
| 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 |
## Tính năng
- **Chạy hoàn toàn client-side** — không server, không telemetry, không upload. JSON của bạn ở lại trong trình duyệt.
- **Xử lý batch** — tới 500 file cùng lúc (Phase 2).
- **Phát hiện shape thông minh** — nhận diện flat object, mảng object, scalar; gợi ý format đích phù hợp.
- **Tuỳ chọn theo từng format** — pretty-print, indentation, dialect (SQL), alignment (Markdown), v.v.
- **Theme sáng/tối** — bảng màu Prism Spectrum với violet / cyan / amber / rose.
- **Đa ngôn ngữ EN + VI** — sẵn sàng từ ngày đầu. Hoan nghênh thêm ngôn ngữ khác.
- **Bản desktop Tauri** — drag-and-drop file, hoạt động offline (mốc Phase 2).
## Tech stack
- **Vite 6** + **React 19** + **TypeScript 5.7**
- **Tailwind CSS v4** + **shadcn/ui** (style New York, base neutral)
- **CodeMirror 6** cho editor đầu vào (Phase 1 polish)
- **PapaParse**, **js-yaml**, **smol-toml**, **fast-xml-parser** để parse/serialize
- **i18next** cho dịch thuật, **Zustand** cho state, **Sonner** cho toast
- **Tauri 2** wrapper (Phase 2)
## Bắt đầu nhanh
**Yêu cầu**: Node.js **22 LTS** trở lên.
```bash
git clone https://github.com/poli0981/jsonprism.git
cd jsonprism
npm install
npm run dev # http://localhost:5173
```
## Bản desktop (Tauri 2)
JSONPrism cũng có bản desktop native qua Tauri 2. App dùng cùng React UI, với dialog OS native và drag-drop tích hợp vào batch flow hiện có.
**Yêu cầu thêm**:
- **Rust toolchain** (`rustup`) với channel stable
- **Build deps theo platform**:
- **Windows**: Visual Studio Build Tools (workload C++) + WebView2 (cài sẵn trên Windows 11)
- **macOS**: Xcode Command Line Tools (`xcode-select --install`)
- **Linux**: `libwebkit2gtk-4.1-dev`, `libappindicator3-dev`, `librsvg2-dev`, `patchelf`, `libssl-dev`
**Generate icon một lần** (dùng Tauri CLI render SVG ra PNG/ICO/ICNS):
```bash
npm run tauri:icon
```
**Chạy dev mode** (Vite + Tauri window có hot reload):
```bash
npm run tauri:dev
```
**Build bundle native**:
```bash
npm run tauri:build
```
Output:
- Windows → `src-tauri/target/release/bundle/msi/*.msi` + `nsis/*-setup.exe`
- macOS → `src-tauri/target/release/bundle/dmg/*.dmg` + `macos/*.app`
- Linux → `src-tauri/target/release/bundle/appimage/*.AppImage` + `deb/*.deb`
**Release tự động**: push tag `v*` sẽ trigger `.github/workflows/release.yml`, build cho tất cả platform song song và tạo draft GitHub release.
### Các script
| Script | Chức năng |
| --------------------- | ---------------------------------------- |
| `npm run dev` | Chạy Vite dev server với HMR |
| `npm run build` | Build production vào `dist/` |
| `npm run preview` | Xem trước bản build trên máy local |
| `npm run lint` | Chạy ESLint |
| `npm run lint:fix` | Chạy ESLint với autofix |
| `npm run typecheck` | Type-check TypeScript, không emit |
| `npm run format` | Format bằng Prettier |
| `npm run format:check`| Kiểm tra format (CI dùng cái này) |
### Components shadcn/ui
`components.json` đã được cấu hình sẵn. Thêm component theo nhu cầu:
```bash
npx shadcn@latest add button input textarea tabs select card dialog sheet \
dropdown-menu switch badge progress tooltip sonner resizable
```
## Kiến trúc
```
src/
├── app/ # Router + providers
├── components/
│ ├── ui/ # shadcn components (thêm theo nhu cầu)
│ ├── layout/ # Header, Footer, ThemeToggle
│ ├── converter/ # Workspace, panels, format picker
│ └── common/ # ErrorBoundary, LanguageSwitcher
├── converters/ # Một module cho mỗi định dạng đích
│ ├── types.ts # Interface Converter
│ ├── registry.ts # Bảng tra cứu
│ └── *.ts # Cài đặt theo từng format
├── hooks/ # Custom hooks
├── i18n/ # Dịch thuật (en, vi)
├── lib/ # detect, theme, utils, sample
├── pages/ # Home, About
├── styles/ # globals.css (Tailwind + theme tokens)
└── main.tsx
```
### Thêm định dạng mới
Mỗi format là một module độc lập, cài đặt interface `Converter`:
```ts
import type { Converter } from './types';
interface MyFormatOptions {
indent: 2 | 4;
}
export const myFormatConverter: Converter<MyFormatOptions> = {
meta: {
id: 'myformat',
labelKey: 'formats.myformat',
extension: 'myf',
mimeType: 'application/x-myformat',
phase: 1,
ready: true,
},
defaultOptions: { indent: 2 },
convert({ data }, options) {
try {
const output = serialize(data, options);
return { ok: true, output };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
```
Sau đó đăng ký nó trong `src/converters/registry.ts` và thêm label key vào `src/i18n/locales/*.json`.
Xem [`docs/ROADMAP.md`](docs/ROADMAP.md) để biết kế hoạch phase đầy đủ.
## Đóng góp
Welcome pull request — vui lòng đọc [`CONTRIBUTING.md`](CONTRIBUTING.md) trước.
Báo bug hoặc đề xuất tính năng tại [GitHub Issues](https://github.com/poli0981/jsonprism/issues).
## Giấy phép
[Apache License 2.0](LICENSE) — © 2026 Kokone.
+21
View File
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/styles/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
+229
View File
@@ -0,0 +1,229 @@
# Migrating i18next JSON to .NET RESX
This guide walks you through converting i18next-style locale files (used by JSONPrism's frontend, YTDescGen, the F2P Tracker, and most React projects) into .NET RESX resource files (used by AutoClickForge, PhantomMAC, and other WPF / Avalonia / WinForms projects).
It's the canonical workflow for keeping a single source-of-truth translation across your web and desktop projects.
---
## The problem
Most JS/TS projects ship translations as namespaced JSON:
```json
{
"app": {
"name": "PhantomMAC",
"tagline": "Randomize your MAC address"
},
"buttons": {
"ok": "OK",
"cancel": "Cancel"
}
}
```
.NET projects expect RESX:
```xml
<data name="app.name" xml:space="preserve">
<value>PhantomMAC</value>
</data>
<data name="buttons.ok" xml:space="preserve">
<value>OK</value>
</data>
```
Two mismatches:
1. **Shape**: i18next allows arbitrary nesting; RESX requires a flat string-to-string map.
2. **Key convention**: web typically uses `dot.separated.paths` already; native .NET sometimes uses `PascalCase`. JSONPrism doesn't impose either — preserve whatever you have.
---
## Step 1 — Flatten nested JSON
JSONPrism's RESX converter rejects nested objects by design (RESX has no concept of nesting). You need a flat object first.
If your translations are nested, flatten them with a one-liner. Save this as `flatten.mjs`:
```js
import { readFileSync, writeFileSync } from 'node:fs';
function flatten(obj, prefix = '', out = {}) {
for (const [k, v] of Object.entries(obj)) {
const key = prefix ? `${prefix}.${k}` : k;
if (v !== null && typeof v === 'object' && !Array.isArray(v)) {
flatten(v, key, out);
} else {
out[key] = typeof v === 'string' ? v : JSON.stringify(v);
}
}
return out;
}
const input = JSON.parse(readFileSync(process.argv[2], 'utf8'));
writeFileSync(process.argv[3], JSON.stringify(flatten(input), null, 2));
console.log(`Flattened to ${process.argv[3]}`);
```
Run it:
```bash
node flatten.mjs strings.en.json strings.en.flat.json
node flatten.mjs strings.vi.json strings.vi.flat.json
```
You now have flat objects like:
```json
{
"app.name": "PhantomMAC",
"app.tagline": "Randomize your MAC address",
"buttons.ok": "OK",
"buttons.cancel": "Cancel"
}
```
---
## Step 2 — Convert to RESX with JSONPrism
### Option A — Single file via the web UI
1. Open JSONPrism (web or desktop)
2. Drop or paste `strings.en.flat.json` into the input panel
3. The format picker highlights **RESX** (a flat object is its native shape)
4. Click **RESX**
5. (Optional) Open the settings panel — enable **Sort entries alphabetically** if you want stable diffs
6. Click **Download** → you get `output.resx`
7. Rename to match your .NET project convention, e.g. `Strings.resx` or `Resources.resx`
### Option B — Batch convert all locales at once
1. Drop **all** your flattened locale files into the input area at the same time (2+ files automatically open the batch panel)
2. Pick **RESX** in the format picker
3. Click **Process** in the batch panel
4. Click **Download .zip**
The output zip contains one `.resx` per input file, with the locale segment preserved:
```
strings.en.flat.json → strings.en.flat.resx
strings.vi.flat.json → strings.vi.flat.resx
strings.ja.flat.json → strings.ja.flat.resx
```
Rename to the .NET convention `Resources.en.resx`, `Resources.vi.resx`, etc. before dropping into your project.
---
## Step 3 — Verify in Visual Studio
1. Drop the generated `.resx` into your .NET project's resources folder
2. Open in Visual Studio — the .resx editor should display every key/value as a flat table
3. Build the project — if VS regenerates a `Resources.Designer.cs` automatically, you'll have strongly-typed access:
```csharp
var greeting = Resources.app_name; // "PhantomMAC"
```
The default tooling replaces `.` with `_` in the property name.
4. Round-trip check: save the file from Visual Studio's editor; the diff against JSONPrism's output should be minimal (whitespace at most). If you see structural diffs, file an issue with the input JSON.
---
## Adding comments
If your translators need context, use the `{ value, _comment }` shape:
```json
{
"app.name": "PhantomMAC",
"buttons.ok": { "value": "OK", "_comment": "Confirmation dialog primary action" }
}
```
JSONPrism emits both `<value>` and `<comment>` elements. The comment column shows up in Visual Studio's .resx editor and is preserved through `ResXResourceWriter`.
Change the comment key in the settings panel if your convention is different (e.g. `note`, `description`).
---
## Round-trip safety notes
- **Special characters**: `&`, `<`, `>` are XML-escaped automatically in values; `"` is also escaped in `name=` attributes. You don't need to pre-escape.
- **Whitespace**: `<data>` elements get `xml:space="preserve"`, so leading/trailing spaces in values survive.
- **Empty values**: `null` and `undefined` in JSON become empty `<value></value>` elements.
- **Numbers and booleans**: coerced to their string representation (`true`, `false`, `42`). If you want explicit nullability, wrap in a string in your source JSON.
- **Schema header**: JSONPrism emits the standard RESX 2.0 schema. Visual Studio expects this — leave the **Include xsd:schema header** option on unless you're diffing manually.
---
## Reverse direction (RESX → JSON)
JSONPrism doesn't do this — it's a one-way "JSON → many formats" tool. If you need RESX → JSON for round-tripping, the simplest path is a small .NET console app using `ResXResourceReader`:
```csharp
using System.Resources;
using System.Text.Json;
var dict = new Dictionary<string, string>();
using var reader = new ResXResourceReader("Resources.en.resx");
foreach (System.Collections.DictionaryEntry entry in reader)
{
dict[(string)entry.Key] = entry.Value?.ToString() ?? "";
}
File.WriteAllText("strings.en.flat.json", JsonSerializer.Serialize(dict, new JsonSerializerOptions { WriteIndented = true }));
```
Run once after editing in Visual Studio's editor, then your JS project sees the changes.
---
## CI integration sketch
If you maintain translations in `strings.*.json` and your .NET project under the same monorepo:
```yaml
# .github/workflows/sync-resx.yml
name: Sync RESX from JSON
on:
push:
paths:
- 'locales/strings.*.json'
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22.x
- name: Flatten locales
run: |
for f in locales/strings.*.json; do
node scripts/flatten.mjs "$f" "$f.flat"
done
# Then either:
# a) use a CLI build of JSONPrism (Phase 4 idea), or
# b) commit the .flat.json and have a separate workflow open JSONPrism manually
```
A CLI version of JSONPrism is on the "Beyond Phase 3" wishlist in `docs/ROADMAP.md`. Until then, batch through the web/desktop UI manually when locales change.
---
## Worked example: PhantomMAC
PhantomMAC has 30+ locale files maintained as `.resx` originally. Going forward:
1. Maintain the canonical source as JSON (easier for translators using web tools like Crowdin or Lokalise)
2. On release, flatten + batch-convert through JSONPrism into `Resources.<locale>.resx`
3. Drop into the .NET project, commit
4. Visual Studio rebuilds the strongly-typed `Resources.Designer.cs`
The same approach works for AutoClickForge (~85 files, EN/VI) and any future MVVM project you scaffold.
+244
View File
@@ -0,0 +1,244 @@
# JSONPrism Roadmap
This document is the **single source of truth** for what's done, what's next, and why.
Update it as work lands — keep the project status honest.
---
## Phase 0 — Scaffold ✅
**Status**: complete (2026-05-12)
**Duration**: ~1 day
Foundation: build tooling, app shell, converter framework, four working converters, full docs.
What landed:
- Vite 6 + React 19 + TypeScript 5.7 strict
- Tailwind v4 + shadcn-ready theme tokens
- Routing, theming, i18n (EN + VI), error boundary
- Converter interface + registry + shape detection
- Working: JSONL, CSV, TSV, YAML
- Stubs with detailed plans: XML, TOML, Markdown, SQL, RESX
- CI + GH Pages deploy workflows
- Full documentation suite
---
## Phase 1 — Polish & Foundations ✅
**Status**: complete (2026-05-12)
**Actual**: ~1 day
Goal: make the four working converters production-quality and the UX delightful enough to share publicly.
### Tasks
#### 1.1 Editor upgrade
- [x] Replace `<textarea>` input with **CodeMirror 6** + `@codemirror/lang-json`
- [x] Line numbers + active-line highlight
- [x] Folding for nested structures
- [x] Theme: custom Prism Spectrum tokens applied to lezer highlight tags
- [x] Parse-error linting (visible gutter markers)
- [ ] Output panel uses CodeMirror in read-only mode with format-specific syntax — *deferred to Phase 2 (needs per-format language packages: yaml, xml, sql)*
#### 1.2 Settings panel
- [x] Side sheet (Radix Dialog) that opens per-converter options
- [x] Form widgets auto-generated from `optionSchema`: Switch, segmented enum, number input, text input
- [x] Settings persist to localStorage per format
- [x] "Reset to defaults" button with toast confirmation
#### 1.3 Per-format options exposed in UI
- [x] JSONL: pretty toggle
- [x] CSV/TSV: header toggle, newline (LF/CRLF), nested strategy (json/flatten)
- [x] YAML: indent (2–8), quote style
#### 1.4 File handling
- [x] Drag-drop a single `.json` file onto the input panel
- [x] "Open file…" button via hidden file input
- [x] Drop overlay with Prism Spectrum styling
- [ ] Auto-detect file encoding — *non-issue; FileReader uses UTF-8 by default and modern editors don't emit BOM*
#### 1.5 Notifications
- [x] Sonner toast for: copy success/failure, download started, file loaded/failed, options reset
- [x] Dismissible, bottom-right, dark/light aware via ThemeProvider integration
#### 1.6 Testing
- [x] Vitest + @testing-library/react + jsdom configured
- [x] Unit tests for all Phase 1 converters (happy path + edge cases): 35+ tests
- [x] Tests for `parseJsonInput`, `detectShape`, `options-storage`
- [x] CI runs tests between typecheck and build
#### 1.7 Polish
- [x] Keyboard shortcuts: ⌘/Ctrl+K (clear), ⌘/Ctrl+S (download)
- [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
- [ ] Cmd/Ctrl+, to open settings — *deferred; Sheet trigger handles its own keyboard nav via Radix*
### Deliverable
A polished, single-file converter UX with four production-grade converters. Ready to demo publicly and share in the Discord open-source server. **35+ unit tests passing**.
---
## Phase 2 — Four more formats + batch + Tauri
Split into three sub-phases for digestibility.
### Phase 2A — Four new converters ✅
**Status**: complete (2026-05-12)
**Actual**: ~1 day
#### XML converter
- [x] `fast-xml-parser` `XMLBuilder` integration
- [x] Configurable root element name, item name, declaration, indent
- [x] Attribute convention: keys starting with `@_` become attributes
- [x] Array handling: each item wrapped with `itemName` element when array is root
- [x] XML declaration prepended conditionally
- [x] 8 unit tests including round-trip via `XMLParser`
#### TOML converter
- [x] `smol-toml` `stringify` integration
- [x] Rejects non-object roots (array, scalar, null) with clear error
- [x] `sortKeys` option, recursive
- [x] Nested tables emitted naturally via smol-toml
- [x] 7 unit tests including round-trip via `parse`
#### Markdown table converter
- [x] Hand-rolled, zero deps
- [x] Header row from union of all object keys (preserve insertion order)
- [x] Alignment markers per column (left/center/right/none)
- [x] Pipe escaping in cell values
- [x] Newlines → `<br>` per GFM
- [x] Nested values JSON-stringified
- [x] 11 unit tests
#### SQL INSERT converter
- [x] Hand-rolled, zero deps
- [x] Dialect support: standard / postgres / mysql / sqlite / mssql
- [x] Identifier quoting per dialect (double-quote / backtick / bracket) with proper escaping
- [x] Value escaping per dialect (booleans differ across all 5)
- [x] Multi-row INSERT with configurable chunk size
- [x] Optional `CREATE TABLE` inference from first row's types
- [x] Missing keys across rows → `NULL`
- [x] 19 unit tests (helpers + integration; 5 dialects × value types)
### Phase 2B — Batch processing ✅
**Status**: complete (2026-05-12)
**Actual**: ~1 day
- [x] Drag-drop multiple files onto a dropzone (`react-dropzone`)
- [x] Batch queue panel showing: filename, size, status (queued/processing/done/error), output size
- [x] Hard limit: 500 files (`BATCH_MAX_FILES`)
- [x] Process in chunks to keep UI responsive (`requestIdleCallback` with `setTimeout(0)` fallback)
- [x] "Download all (.zip)" via **fflate** (chosen over JSZip for ~12× smaller bundle)
- [x] Per-file error display without blocking the rest of the queue
- [x] AbortController-based cancellation
- [x] Smart drop routing: 1 file → editor, 2+ files → batch panel auto-opens
- [x] Zustand store with item map + display order for O(1) per-item updates
- [x] Filename collision handling in the zip
- [x] 20+ unit tests including round-trip zip decode
### Phase 2C — Tauri 2 desktop wrapper ✅
**Status**: complete (2026-05-12)
**Actual**: ~1 day
- [x] `src-tauri/` scaffold with Tauri 2.x (`Cargo.toml`, `tauri.conf.json`, `lib.rs`)
- [x] Tauri serves Vite-built `dist/`; dev mode runs Vite + Tauri window with HMR
- [x] Native file open/save dialogs via `plugin-dialog` + `plugin-fs`
- [x] OS drag-drop integration via `tauri://drag-drop` events (hook: `useTauriDragDrop`)
- [x] App icons: SVG source committed (`src-tauri/icons/icon.svg`), generated formats via `npm run tauri:icon`
- [x] Bundle targets: Windows (MSI + NSIS `.exe`), macOS (DMG + .app, min 12.0), Linux (AppImage + deb)
- [x] CSP and capability file locked down (scoped to user dirs only)
- [x] Custom Rust command `host_info` for diagnostics
- [x] GitHub Actions release workflow (matrix: Windows / macOS ARM / macOS Intel / Linux); draft release on `v*` tag
- [x] Vite config detects Tauri context and adjusts base path + dev server
- [x] Frontend `isTauri()` runtime gate keeps web bundle free of Tauri imports (tree-shaken)
- [x] `Velopack` skipped — using Tauri's native bundler (avoids the two-tool overhead PhantomMAC has)
### Deliverable (full Phase 2)
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.**
---
## Phase 3 — RESX & i18n integration ✅
**Status**: complete (2026-05-12)
**Actual**: ~1 day
Goal: ship the .NET RESX converter and integrate with existing AutoClickForge / PhantomMAC localization workflows.
### Tasks
#### 3.1 RESX converter
- [x] Hand-rolled XML output (skip fast-xml-parser; the template is too rigid)
- [x] Standard RESX 2.0 header with `xsd:schema` + 4 `resheader` elements (resmimetype, version, reader, writer)
- [x] Input contract: flat object `{ "Key": "value" }`; nested objects → reject with helpful error
- [x] Optional `_comment` key (configurable via `commentKey` option) → emits `<comment>` element on the `<data>`
- [x] XML escaping for text content (&, <, >) and attribute context (quotes)
- [x] Number and boolean coercion to string
- [x] Null/undefined coerced to empty string
- [x] `sortKeys` option for stable diffs across locale files
- [x] `includeSchema` option (Visual Studio expects schema; tests verify byte-exact match)
- [x] 17 unit tests covering schema, comment shape, escaping, sort order, error paths
#### 3.2 Smart UI for the RESX use case
- [x] Format picker highlights suggested formats based on `detectShape` output via subtle ring
- [x] Flat-object detection surfaces RESX first in the suggestion list
- [x] Batch processor preserves locale segment in filenames: `strings.vi.json` → `strings.vi.resx`
#### 3.3 Documentation
- [x] `docs/RESX-MIGRATION.md` — tutorial: i18next JSON → .NET RESX, with flatten script, batch flow, Visual Studio verification, comment support, CI sketch
- [x] Cross-link with PhantomMAC / AutoClickForge i18n docs in the worked example
### Deliverable
**9/9 formats production-ready.** RESX integration documented as a real migration path between i18next-based web projects and .NET WPF projects. JSONPrism reaches **1.0**.
---
## Beyond Phase 3 — Ideas (no commitment)
- **JSON → Excel (.xlsx)** via SheetJS — possible if Markdown/CSV doesn't cover the use case
- **Reverse direction** (other format → JSON): different mental model; might warrant a sibling app
- **Schema inference**: emit JSON Schema, TypeScript types, or Go structs from sample JSON
- **CLI version**: same converter modules, exposed as a Node CLI for CI pipelines
- **VS Code extension**: surface the converters in the editor command palette
- **Sharing**: hash-based shareable URLs (`#data=...`) for sample inputs (privacy: opt-in only)
These are deliberately deferred — Phase 1–3 first.
---
## Tracking
Update this file when:
- A task is completed (mark it `- [x]` and add a date if significant)
- An estimate changes meaningfully
- The phase plan changes (and explain why in the commit message)
- A new phase is added to the "Beyond" section
The goal: anyone reading this should be able to answer **"What's the current state of JSONPrism?"** in 30 seconds.
+36
View File
@@ -0,0 +1,36 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';
export default tseslint.config(
{ ignores: ['dist', 'node_modules', 'src/components/ui/**'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2022,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
'@typescript-eslint/no-unused-vars': [
'warn',
{ argsIgnorePattern: '^_', varsIgnorePattern: '^_' },
],
'@typescript-eslint/consistent-type-imports': [
'error',
{ prefer: 'type-imports', fixStyle: 'inline-type-imports' },
],
},
},
);
+32
View File
@@ -0,0 +1,32 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="dark light" />
<meta name="theme-color" content="#0a0b14" />
<meta name="description" content="JSONPrism — disperse JSON into many formats. Convert to JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL. Fully client-side, batch up to 500 files." />
<meta name="keywords" content="JSON, converter, JSONL, YAML, CSV, XML, TOML, RESX, Markdown, SQL, batch, offline" />
<!-- Open Graph -->
<meta property="og:title" content="JSONPrism — Disperse JSON into many formats" />
<meta property="og:description" content="A refracting tool for developers. One JSON input, eight target formats, fully in-browser." />
<meta property="og:type" content="website" />
<!-- Fonts: Instrument Serif (display) + Geist (body) + JetBrains Mono (code) -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Geist:wght@300;400;500;600;700&family=Instrument+Serif:ital@0;1&family=JetBrains+Mono:wght@400;500;700&display=swap"
rel="stylesheet"
/>
<title>JSONPrism · Disperse JSON</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+7102
View File
File diff suppressed because it is too large. Load diff
+97
View File
@@ -0,0 +1,97 @@
{
"name": "jsonprism",
"private": true,
"version": "1.0.0",
"type": "module",
"description": "Disperse JSON into many formats — JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL — fully client-side.",
"author": "poli0981 <https://github.com/poli0981>",
"license": "Apache-2.0",
"homepage": "https://poli0981.github.io/jsonprism/",
"repository": {
"type": "git",
"url": "https://github.com/poli0981/jsonprism.git"
},
"engines": {
"node": ">=22.0.0"
},
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write \"src/**/*.{ts,tsx,css,md,json}\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx,css,md,json}\"",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:watch": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest run --coverage",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"tauri:build": "tauri build",
"tauri:icon": "tauri icon src-tauri/icons/icon.svg"
},
"dependencies": {
"@codemirror/lang-json": "^6.0.0",
"@codemirror/language": "^6.10.0",
"@codemirror/lint": "^6.8.0",
"@codemirror/state": "^6.4.0",
"@codemirror/view": "^6.34.0",
"@lezer/highlight": "^1.2.0",
"@radix-ui/react-dialog": "^1.1.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
"@tauri-apps/api": "^2.0.0",
"@tauri-apps/plugin-dialog": "^2.0.0",
"@tauri-apps/plugin-fs": "^2.0.0",
"@tauri-apps/plugin-os": "^2.0.0",
"@tauri-apps/plugin-shell": "^2.0.0",
"@uiw/react-codemirror": "^4.23.0",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
"fast-xml-parser": "^5.8.0",
"fflate": "^0.8.2",
"i18next": "^23.0.0",
"i18next-browser-languagedetector": "^8.0.0",
"js-yaml": "^4.1.0",
"lucide-react": "^0.460.0",
"papaparse": "^5.4.0",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-dropzone": "^14.3.0",
"react-i18next": "^15.0.0",
"react-router-dom": "^7.0.0",
"smol-toml": "^1.3.0",
"sonner": "^1.7.0",
"tailwind-merge": "^2.5.0",
"zustand": "^5.0.0"
},
"devDependencies": {
"@eslint/js": "^9.15.0",
"@tailwindcss/vite": "^4.0.0",
"@tauri-apps/cli": "^2.0.0",
"@testing-library/jest-dom": "^6.6.0",
"@testing-library/react": "^16.1.0",
"@testing-library/user-event": "^14.5.0",
"@types/js-yaml": "^4.0.0",
"@types/node": "^22.0.0",
"@types/papaparse": "^5.3.0",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@vitejs/plugin-react": "^4.3.0",
"@vitest/coverage-v8": "^4.1.6",
"eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.0",
"jsdom": "^25.0.0",
"prettier": "^3.4.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"tailwindcss": "^4.0.0",
"tw-animate-css": "^1.2.0",
"typescript": "^5.7.0",
"typescript-eslint": "^8.15.0",
"vite": "^6.0.0",
"vitest": "^4.1.6"
}
}
+11
View File
@@ -0,0 +1,11 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" fill="none">
<!-- Incoming white ray -->
<line x1="2" y1="32" x2="22" y2="32" stroke="#f5f5f5" stroke-width="3" stroke-linecap="round" />
<!-- Prism triangle -->
<path d="M22 12 L46 32 L22 52 Z" fill="#0a0b14" stroke="#f5f5f5" stroke-width="2.5" stroke-linejoin="round" />
<!-- Dispersed rays -->
<line x1="46" y1="32" x2="62" y2="20" stroke="#a78bfa" stroke-width="2.5" stroke-linecap="round" />
<line x1="46" y1="32" x2="62" y2="28" stroke="#22d3ee" stroke-width="2.5" stroke-linecap="round" />
<line x1="46" y1="32" x2="62" y2="36" stroke="#f59e0b" stroke-width="2.5" stroke-linecap="round" />
<line x1="46" y1="32" x2="62" y2="44" stroke="#ec4899" stroke-width="2.5" stroke-linecap="round" />
</svg>

After

Width:  |  Height:  |  Size: 782 B

+13
View File
@@ -0,0 +1,13 @@
/target/
/gen/schemas/
Cargo.lock
# Icon binaries are generated from icon.svg via `npm run tauri:icon`.
# Comment these out and commit the binaries if your CI doesn't run the generation step.
icons/32x32.png
icons/128x128.png
icons/128x128@2x.png
icons/icon.icns
icons/icon.ico
icons/Square*.png
icons/StoreLogo.png
+38
View File
@@ -0,0 +1,38 @@
[package]
name = "jsonprism"
version = "1.0.0"
description = "Disperse JSON into many formats."
authors = ["Kokone <https://github.com/poli0981>"]
license = "Apache-2.0"
repository = "https://github.com/poli0981/jsonprism"
edition = "2021"
rust-version = "1.77"
# Disable the default `main.rs` binary lookup; we want a library + bin.
[lib]
name = "jsonprism_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-dialog = "2"
tauri-plugin-fs = "2"
tauri-plugin-os = "2"
tauri-plugin-shell = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
[features]
# this feature is used for production builds or when `devUrl` points to the
# filesystem and the built-in dev server is disabled.
custom-protocol = ["tauri/custom-protocol"]
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"
strip = true
+3
View File
@@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}
+28
View File
@@ -0,0 +1,28 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Default permissions for the JSONPrism main window.",
"windows": ["main"],
"permissions": [
"core:default",
"core:event:allow-listen",
"core:event:allow-unlisten",
"core:webview:default",
"core:window:default",
"core:window:allow-set-title",
"shell:allow-open",
"os:default",
"dialog:default",
"dialog:allow-open",
"dialog:allow-save",
"dialog:allow-message",
"fs:default",
"fs:allow-read-text-file",
"fs:allow-write-text-file",
"fs:allow-write-file",
{
"identifier": "fs:scope",
"allow": ["$HOME/**", "$DOCUMENT/**", "$DOWNLOAD/**", "$DESKTOP/**"]
}
]
}
+46
View File
@@ -0,0 +1,46 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" fill="none">
<!-- Background: deep midnight gradient -->
<defs>
<radialGradient id="bg" cx="50%" cy="40%" r="70%">
<stop offset="0%" stop-color="#1a1530" />
<stop offset="100%" stop-color="#0a0b14" />
</radialGradient>
<linearGradient id="ray-v" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#a78bfa" stop-opacity="0.95" />
<stop offset="100%" stop-color="#a78bfa" stop-opacity="0.7" />
</linearGradient>
<linearGradient id="ray-c" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#22d3ee" stop-opacity="0.95" />
<stop offset="100%" stop-color="#22d3ee" stop-opacity="0.7" />
</linearGradient>
<linearGradient id="ray-a" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#f59e0b" stop-opacity="0.95" />
<stop offset="100%" stop-color="#f59e0b" stop-opacity="0.7" />
</linearGradient>
<linearGradient id="ray-r" x1="0" y1="0" x2="1" y2="0">
<stop offset="0%" stop-color="#ec4899" stop-opacity="0.95" />
<stop offset="100%" stop-color="#ec4899" stop-opacity="0.7" />
</linearGradient>
</defs>
<!-- Rounded square base (macOS app icon look) -->
<rect width="1024" height="1024" rx="200" fill="url(#bg)" />
<!-- Incoming white ray -->
<line x1="60" y1="512" x2="360" y2="512" stroke="#f5f5f5" stroke-width="40" stroke-linecap="round" />
<!-- Prism triangle -->
<path
d="M360 192 L760 512 L360 832 Z"
fill="rgba(245,245,245,0.04)"
stroke="#f5f5f5"
stroke-width="36"
stroke-linejoin="round"
/>
<!-- Dispersed rays -->
<line x1="760" y1="512" x2="980" y2="320" stroke="url(#ray-v)" stroke-width="36" stroke-linecap="round" />
<line x1="760" y1="512" x2="980" y2="440" stroke="url(#ray-c)" stroke-width="36" stroke-linecap="round" />
<line x1="760" y1="512" x2="980" y2="584" stroke="url(#ray-a)" stroke-width="36" stroke-linecap="round" />
<line x1="760" y1="512" x2="980" y2="704" stroke="url(#ray-r)" stroke-width="36" stroke-linecap="round" />
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

+48
View File
@@ -0,0 +1,48 @@
use serde::Serialize;
use tauri::Manager;
/// Metadata about the host system — useful for diagnostics and UI hints.
/// Exposed to the frontend via the `host_info` command.
#[derive(Serialize)]
struct HostInfo {
os: String,
arch: String,
family: String,
app_version: String,
}
#[tauri::command]
fn host_info() -> HostInfo {
HostInfo {
os: std::env::consts::OS.to_string(),
arch: std::env::consts::ARCH.to_string(),
family: std::env::consts::FAMILY.to_string(),
app_version: env!("CARGO_PKG_VERSION").to_string(),
}
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_dialog::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_os::init())
.invoke_handler(tauri::generate_handler![host_info])
.setup(|app| {
// Surface the main window once it's ready — avoids the
// "blank window flash" some platforms exhibit on cold start.
#[cfg(any(target_os = "macos", target_os = "windows"))]
if let Some(window) = app.get_webview_window("main") {
let _ = window.show();
let _ = window.set_focus();
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
{
let _ = app;
}
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running JSONPrism");
}
+6
View File
@@ -0,0 +1,6 @@
// Prevents an extra console window on Windows in release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
jsonprism_lib::run();
}
+84
View File
@@ -0,0 +1,84 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "JSONPrism",
"version": "1.0.0",
"identifier": "com.kokone.jsonprism",
"build": {
"beforeDevCommand": "npm run dev",
"beforeBuildCommand": "npm run build",
"devUrl": "http://localhost:5173",
"frontendDist": "../dist"
},
"app": {
"windows": [
{
"title": "JSONPrism · Disperse JSON",
"width": 1280,
"height": 820,
"minWidth": 800,
"minHeight": 560,
"decorations": true,
"resizable": true,
"fullscreen": false,
"transparent": false,
"dragDropEnabled": true,
"theme": null
}
],
"security": {
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost https://fonts.googleapis.com https://fonts.gstatic.com"
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"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 many target formats — JSONL, CSV/TSV, YAML, XML, TOML, Markdown, SQL INSERT — fully on your machine.",
"copyright": "Copyright (c) 2026 Kokone",
"publisher": "Kokone",
"homepage": "https://github.com/poli0981/jsonprism",
"windows": {
"wix": {
"language": "en-US"
},
"nsis": {
"displayLanguageSelector": false,
"installerIcon": "icons/icon.ico",
"installMode": "perMachine",
"languages": ["English", "Vietnamese"]
},
"certificateThumbprint": null,
"digestAlgorithm": "sha256",
"timestampUrl": ""
},
"macOS": {
"minimumSystemVersion": "12.0",
"exceptionDomain": "",
"frameworks": [],
"files": {},
"providerShortName": null,
"signingIdentity": null
},
"linux": {
"appimage": {
"bundleMediaFramework": false
},
"deb": {
"depends": []
}
}
},
"plugins": {
"fs": {
"requireLiteralLeadingDot": false
}
}
}
+23
View File
@@ -0,0 +1,23 @@
import { Route, Routes } from 'react-router-dom';
import { ThemeProvider } from '@/lib/theme';
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
import { Layout } from '@/components/layout/Layout';
import { Toaster } from '@/components/ui/sonner';
import { Home } from '@/pages/Home';
import { About } from '@/pages/About';
export function App() {
return (
<ThemeProvider defaultTheme="system">
<ErrorBoundary>
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="about" element={<About />} />
</Route>
</Routes>
<Toaster />
</ErrorBoundary>
</ThemeProvider>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { Component, type ErrorInfo, type ReactNode } from 'react';
interface Props {
children: ReactNode;
fallback?: ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false, error: null };
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
override componentDidCatch(error: Error, info: ErrorInfo): void {
// eslint-disable-next-line no-console
console.error('JSONPrism error boundary caught:', error, info);
}
override render(): ReactNode {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div className="bg-background text-foreground flex min-h-screen items-center justify-center p-8">
<div className="border-border bg-card max-w-md rounded-lg border p-6">
<h1 className="font-display mb-2 text-2xl">Something refracted unexpectedly.</h1>
<p className="text-muted-foreground mb-4 text-sm">
{this.state.error?.message ?? 'Unknown error.'}
</p>
<button
type="button"
onClick={() => window.location.reload()}
className="bg-primary text-primary-foreground hover:opacity-90 rounded-md px-4 py-2 text-sm font-medium transition"
>
Reload
</button>
</div>
</div>
);
}
return this.props.children;
}
}
@@ -0,0 +1,32 @@
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
const LANGUAGES = [
{ code: 'en', label: 'EN' },
{ code: 'vi', label: 'VI' },
] as const;
export function LanguageSwitcher() {
const { i18n } = useTranslation();
const current = i18n.resolvedLanguage ?? 'en';
return (
<div className="border-border/60 flex items-center gap-0.5 rounded-md border p-0.5">
{LANGUAGES.map((lang) => (
<button
key={lang.code}
type="button"
onClick={() => void i18n.changeLanguage(lang.code)}
className={cn(
'rounded px-2 py-0.5 text-xs font-medium transition',
current === lang.code
? 'bg-muted text-foreground'
: 'text-muted-foreground hover:text-foreground',
)}
>
{lang.label}
</button>
))}
</div>
);
}
+448
View File
@@ -0,0 +1,448 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import {
Download,
FileStack,
FolderOpen,
Loader2,
Play,
StopCircle,
Trash2,
} from 'lucide-react';
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet';
import { toast } from '@/components/ui/sonner';
import { useBatchStore, BATCH_MAX_FILES, type BatchItem } from '@/stores/batchStore';
import { processBatch, zipOutputs, downloadBlob } from '@/lib/batch-processor';
import { isTauri, nativeOpenFiles, nativeSaveBlob, fileFromNativePath } from '@/lib/tauri';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { cn } from '@/lib/utils';
interface BatchPanelProps {
format: FormatId;
options: Record<string, unknown>;
open: boolean;
onOpenChange: (open: boolean) => void;
/** Filenames added via this trigger button are also routed into the queue. */
onAddExternalFiles?: (files: File[]) => void;
}
export function BatchPanel({ format, options, open, onOpenChange }: BatchPanelProps) {
const { t } = useTranslation();
const items = useBatchStore((s) => s.items);
const itemOrder = useBatchStore((s) => s.itemOrder);
const processing = useBatchStore((s) => s.processing);
const addFiles = useBatchStore((s) => s.addFiles);
const removeItem = useBatchStore((s) => s.removeItem);
const clear = useBatchStore((s) => s.clear);
const setProcessing = useBatchStore((s) => s.setProcessing);
const setAbortController = useBatchStore((s) => s.setAbortController);
const updateItem = useBatchStore((s) => s.updateItem);
const resetStatuses = useBatchStore((s) => s.resetStatuses);
const fileInputRef = useRef<HTMLInputElement>(null);
const totalCount = itemOrder.length;
const doneCount = itemOrder.filter((id) => items[id]?.status === 'done').length;
const errorCount = itemOrder.filter((id) => items[id]?.status === 'error').length;
const queuedCount = itemOrder.filter((id) => items[id]?.status === 'queued').length;
const handleAddFiles = useCallback(
(files: File[]) => {
const result = addFiles(files);
if (result.added > 0) {
toast.success(t('batch.toast.added', { count: result.added }));
}
if (result.skipped > 0) {
toast.warning(t('batch.toast.skipped', { count: result.skipped, max: BATCH_MAX_FILES }));
}
},
[addFiles, t],
);
const onDrop = useCallback(
(accepted: File[]) => {
if (accepted.length === 0) return;
handleAddFiles(accepted);
},
[handleAddFiles],
);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
accept: { 'application/json': ['.json'], 'text/plain': ['.txt'] },
multiple: true,
noClick: true,
noKeyboard: true,
});
const handleStart = useCallback(async () => {
const queued = itemOrder
.map((id) => items[id])
.filter((it): it is BatchItem => !!it && it.status !== 'done' && it.status !== 'processing');
if (queued.length === 0) {
toast.info(t('batch.toast.nothing_to_process'));
return;
}
const controller = new AbortController();
setAbortController(controller);
setProcessing(true);
toast.success(t('batch.toast.started', { count: queued.length }));
try {
await processBatch(
queued,
format,
options,
{
onUpdate: (id, patch) => updateItem(id, patch),
},
controller.signal,
);
if (!controller.signal.aborted) {
toast.success(t('batch.toast.finished'));
}
} catch (err) {
toast.error(t('batch.toast.failed', { message: (err as Error).message }));
} finally {
setProcessing(false);
setAbortController(null);
}
}, [format, items, itemOrder, options, setAbortController, setProcessing, t, updateItem]);
const handleCancel = useCallback(() => {
useBatchStore.getState().abortController?.abort();
toast.info(t('batch.toast.cancelled'));
}, [t]);
const handleDownloadZip = useCallback(async () => {
const done = itemOrder.map((id) => items[id]).filter((it): it is BatchItem => !!it);
try {
const { blob, fileCount } = await zipOutputs(done, format);
const ts = new Date().toISOString().slice(0, 10);
const filename = `jsonprism-batch-${ts}.zip`;
if (isTauri()) {
const saved = await nativeSaveBlob(blob, filename);
if (saved) {
toast.success(t('batch.toast.zipped', { count: fileCount }));
}
} else {
downloadBlob(blob, filename);
toast.success(t('batch.toast.zipped', { count: fileCount }));
}
} catch (err) {
toast.error(t('batch.toast.zip_failed', { message: (err as Error).message }));
}
}, [format, items, itemOrder, t]);
const handleOpenFiles = async () => {
if (isTauri()) {
const paths = await nativeOpenFiles({ multiple: true });
if (!paths || paths.length === 0) return;
const files = await Promise.all(paths.map(fileFromNativePath));
handleAddFiles(files);
return;
}
fileInputRef.current?.click();
};
const onFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files ?? []);
if (files.length > 0) handleAddFiles(files);
e.target.value = '';
};
// Cancel processing if the user clears the queue while it's running.
useEffect(() => {
if (totalCount === 0 && processing) {
useBatchStore.getState().abortController?.abort();
}
}, [totalCount, processing]);
const formatLabel = getConverter(format).meta.labelKey;
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetTrigger asChild>
<button
type="button"
className={cn(
'text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md border border-border/60 px-2.5 py-1 text-xs transition',
totalCount > 0 && 'border-primary/40 text-foreground',
)}
>
<FileStack className="h-3.5 w-3.5" />
<span>{t('batch.trigger')}</span>
{totalCount > 0 && (
<span className="bg-primary/15 text-primary rounded px-1 py-px font-mono text-[10px] leading-none">
{totalCount}
</span>
)}
</button>
</SheetTrigger>
<SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-lg">
<SheetHeader>
<SheetTitle>
<span className="text-spectrum italic">{t('batch.title')}</span>{' '}
<span className="text-muted-foreground font-sans text-base font-normal not-italic">
· {totalCount} / {BATCH_MAX_FILES}
</span>
</SheetTitle>
<SheetDescription>
{t('batch.description', { format: t(formatLabel) })}
</SheetDescription>
</SheetHeader>
{/* Drop zone */}
<div className="px-6 pb-3" {...getRootProps()}>
<input {...getInputProps()} />
<input
ref={fileInputRef}
type="file"
accept=".json,.txt,application/json"
multiple
className="hidden"
onChange={onFileInputChange}
/>
<div
className={cn(
'flex flex-col items-center justify-center gap-1.5 rounded-lg border-2 border-dashed py-6 transition',
isDragActive
? 'border-primary/60 bg-primary/5 text-foreground'
: 'border-border bg-card/30 text-muted-foreground',
)}
>
<FolderOpen className="h-5 w-5" />
<p className="text-xs">
{isDragActive ? t('batch.drop_active') : t('batch.drop_idle')}
</p>
<button
type="button"
onClick={handleOpenFiles}
className="text-primary hover:underline text-xs"
>
{t('batch.browse')}
</button>
</div>
</div>
{/* Summary chips */}
{totalCount > 0 && (
<div className="text-muted-foreground flex flex-wrap items-center gap-2 px-6 pb-3 font-mono text-[11px]">
<Chip label={t('batch.stat.queued')} value={queuedCount} />
<Chip label={t('batch.stat.done')} value={doneCount} tone="ok" />
{errorCount > 0 && <Chip label={t('batch.stat.failed')} value={errorCount} tone="err" />}
</div>
)}
{/* Queue list */}
<div className="flex-1 overflow-y-auto px-6 pb-3">
{totalCount === 0 ? (
<p className="text-muted-foreground py-12 text-center text-sm italic">
{t('batch.empty')}
</p>
) : (
<ul className="flex flex-col divide-y divide-border/40">
{itemOrder.map((id) => {
const item = items[id];
if (!item) return null;
return (
<BatchItemRow
key={id}
item={item}
outputExt={getConverter(format).meta.extension}
onRemove={() => removeItem(id)}
disabled={processing}
/>
);
})}
</ul>
)}
</div>
{/* Footer controls */}
<div className="border-border/60 flex items-center justify-between gap-2 border-t px-6 py-3">
<button
type="button"
onClick={() => clear()}
disabled={totalCount === 0 || processing}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md px-2.5 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
>
<Trash2 className="h-3.5 w-3.5" />
{t('batch.clear')}
</button>
<div className="flex items-center gap-2">
{processing ? (
<button
type="button"
onClick={handleCancel}
className="bg-destructive/10 text-destructive hover:bg-destructive/20 inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition"
>
<StopCircle className="h-3.5 w-3.5" />
{t('batch.cancel')}
</button>
) : (
<button
type="button"
onClick={() => {
resetStatuses();
void handleStart();
}}
disabled={totalCount === 0}
className="bg-primary/15 text-primary hover:bg-primary/25 inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
>
<Play className="h-3.5 w-3.5" />
{t('batch.process')}
</button>
)}
<button
type="button"
onClick={() => void handleDownloadZip()}
disabled={doneCount === 0 || processing}
className="bg-foreground/90 text-background hover:bg-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition disabled:cursor-not-allowed disabled:opacity-40"
>
<Download className="h-3.5 w-3.5" />
{t('batch.download_zip')}
</button>
</div>
</div>
</SheetContent>
</Sheet>
);
}
function Chip({ label, value, tone }: { label: string; value: number; tone?: 'ok' | 'err' }) {
return (
<span
className={cn(
'inline-flex items-center gap-1 rounded px-1.5 py-0.5',
tone === 'ok' && 'bg-primary/10 text-primary',
tone === 'err' && 'bg-destructive/10 text-destructive',
!tone && 'bg-muted/40',
)}
>
<span className="opacity-70">{label}:</span>
<span>{value}</span>
</span>
);
}
interface BatchItemRowProps {
item: BatchItem;
outputExt: string;
onRemove: () => void;
disabled: boolean;
}
function BatchItemRow({ item, outputExt, onRemove, disabled }: BatchItemRowProps) {
const { t } = useTranslation();
const Icon = statusIcon(item.status);
const tone = statusTone(item.status);
return (
<li className="flex items-start gap-2 py-2.5">
<Icon className={cn('mt-0.5 h-4 w-4 shrink-0', tone)} />
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<span className="text-foreground truncate font-mono text-xs">{item.filename}</span>
<span className="text-muted-foreground/60 font-mono text-[10px]">→ .{outputExt}</span>
</div>
<div className="text-muted-foreground mt-0.5 flex items-center gap-2 font-mono text-[10px]">
<span>{formatBytes(item.size)}</span>
{item.outputSize !== undefined && (
<>
<span>·</span>
<span>{t('batch.row.out')}: {formatBytes(item.outputSize)}</span>
</>
)}
</div>
{item.error && (
<p className="text-destructive mt-1 break-words font-mono text-[10px]">{item.error}</p>
)}
</div>
<button
type="button"
onClick={onRemove}
disabled={disabled}
aria-label={t('batch.row.remove')}
className="text-muted-foreground hover:bg-muted hover:text-foreground rounded p-1 transition disabled:cursor-not-allowed disabled:opacity-40"
>
<Trash2 className="h-3 w-3" />
</button>
</li>
);
}
function statusIcon(status: BatchItem['status']) {
switch (status) {
case 'queued':
return CircleIcon;
case 'processing':
return ProcessingIcon;
case 'done':
return CheckIcon;
case 'error':
return ErrorIcon;
}
}
function statusTone(status: BatchItem['status']): string {
switch (status) {
case 'done':
return 'text-primary';
case 'error':
return 'text-destructive';
case 'processing':
return 'text-foreground';
case 'queued':
default:
return 'text-muted-foreground/60';
}
}
function CircleIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<circle cx="8" cy="8" r="6" stroke="currentColor" strokeWidth="1.5" />
</svg>
);
}
function ProcessingIcon({ className }: { className?: string }) {
return <Loader2 className={cn(className, 'animate-spin')} />;
}
function CheckIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path d="M3 8.5L6.5 12L13 5" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
);
}
function ErrorIcon({ className }: { className?: string }) {
return (
<svg viewBox="0 0 16 16" fill="none" className={className} aria-hidden>
<path d="M4 4L12 12M12 4L4 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
</svg>
);
}
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
+132
View File
@@ -0,0 +1,132 @@
import { useMemo } from 'react';
import CodeMirror, { type ReactCodeMirrorRef, EditorView } from '@uiw/react-codemirror';
import { json, jsonParseLinter } from '@codemirror/lang-json';
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { lintGutter, linter } from '@codemirror/lint';
import { tags as t } from '@lezer/highlight';
import { useTheme } from '@/lib/theme';
import { cn } from '@/lib/utils';
interface CodeEditorProps {
value: string;
onChange?: (v: string) => void;
readOnly?: boolean;
language?: 'json' | 'plain';
className?: string;
placeholder?: string;
editorRef?: React.RefObject<ReactCodeMirrorRef | null>;
}
/**
* Prism Spectrum highlight style — assigns each lezer highlight tag
* a color from the prism palette via CSS variables.
*/
const prismHighlightStyle = HighlightStyle.define([
{ tag: t.propertyName, color: 'var(--color-prism-violet)' },
{ tag: t.string, color: 'var(--color-prism-cyan)' },
{ tag: t.number, color: 'var(--color-prism-amber)' },
{ tag: [t.bool, t.null, t.keyword], color: 'var(--color-prism-rose)', fontStyle: 'italic' },
{ tag: t.punctuation, color: 'var(--muted-foreground)' },
{ tag: t.bracket, color: 'var(--muted-foreground)' },
{ tag: t.comment, color: 'var(--muted-foreground)', fontStyle: 'italic' },
]);
export function CodeEditor({
value,
onChange,
readOnly = false,
language = 'json',
className,
placeholder,
editorRef,
}: CodeEditorProps) {
const { resolvedTheme } = useTheme();
const extensions = useMemo(() => {
const exts = [];
if (language === 'json') {
exts.push(json());
if (!readOnly) {
exts.push(lintGutter(), linter(jsonParseLinter()));
}
}
exts.push(syntaxHighlighting(prismHighlightStyle));
exts.push(EditorView.lineWrapping);
return exts;
}, [language, readOnly]);
const themeExt = useMemo(() => {
const isDark = resolvedTheme === 'dark';
return EditorView.theme(
{
'&': {
backgroundColor: 'transparent',
color: 'var(--foreground)',
height: '100%',
fontSize: '13px',
},
'.cm-scroller': {
fontFamily: 'var(--font-mono)',
lineHeight: '1.6',
},
'.cm-content': {
padding: '16px 0',
caretColor: 'var(--color-prism-violet)',
},
'.cm-gutters': {
backgroundColor: 'transparent',
border: 'none',
color: 'var(--muted-foreground)',
opacity: '0.5',
},
'.cm-activeLine': {
backgroundColor: isDark
? 'color-mix(in oklch, var(--color-prism-violet) 6%, transparent)'
: 'color-mix(in oklch, var(--color-prism-violet) 4%, transparent)',
},
'.cm-activeLineGutter': {
backgroundColor: 'transparent',
color: 'var(--foreground)',
opacity: '0.9',
},
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': {
backgroundColor:
'color-mix(in oklch, var(--color-prism-violet) 25%, transparent) !important',
},
'.cm-cursor': {
borderLeftColor: 'var(--color-prism-violet)',
borderLeftWidth: '2px',
},
'.cm-placeholder': {
color: 'var(--muted-foreground)',
opacity: '0.5',
},
},
{ dark: isDark },
);
}, [resolvedTheme]);
return (
<div className={cn('h-full overflow-hidden', className)}>
<CodeMirror
ref={editorRef}
value={value}
onChange={onChange}
readOnly={readOnly}
editable={!readOnly}
placeholder={placeholder}
extensions={[...extensions, themeExt]}
basicSetup={{
lineNumbers: true,
highlightActiveLine: !readOnly,
highlightActiveLineGutter: !readOnly,
foldGutter: true,
autocompletion: false,
searchKeymap: true,
}}
height="100%"
theme="none"
/>
</div>
);
}
@@ -0,0 +1,185 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from '@/components/ui/sonner';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { parseJsonInput } from '@/lib/detect';
import { loadOptions, saveOptions, clearOptions } from '@/lib/options-storage';
import { useKeyboardShortcuts } from '@/hooks/useKeyboardShortcuts';
import { useTauriDragDrop } from '@/hooks/useTauriDragDrop';
import { useBatchStore } from '@/stores/batchStore';
import { FormatPicker } from './FormatPicker';
import { InputPanel } from './InputPanel';
import { OutputPanel } from './OutputPanel';
import { SettingsPanel } from './SettingsPanel';
import { ShapeHint } from './ShapeHint';
import { StatusBar } from './StatusBar';
import { BatchPanel } from './BatchPanel';
const STORAGE_FORMAT_KEY = 'jsonprism.selected_format';
export function ConverterWorkspace() {
const { t } = useTranslation();
const [input, setInput] = useState('');
const [format, setFormat] = useState<FormatId>(() => {
const stored = window.localStorage.getItem(STORAGE_FORMAT_KEY);
return (stored as FormatId | null) ?? 'jsonl';
});
const [optionsByFormat, setOptionsByFormat] = useState<Record<string, Record<string, unknown>>>(
() => {
// Lazy-load on demand; start with default options for current format.
const c = getConverter(format);
return { [format]: loadOptions(format, c.defaultOptions) };
},
);
const actionsRef = useRef<{ copy: () => void; download: () => void } | null>(null);
const [batchOpen, setBatchOpen] = useState(false);
const addBatchFiles = useBatchStore((s) => s.addFiles);
const handleMultiFileDrop = useCallback(
(files: File[]) => {
const result = addBatchFiles(files);
if (result.added > 0) {
toast.success(t('batch.toast.added', { count: result.added }));
setBatchOpen(true);
}
if (result.skipped > 0) {
toast.warning(t('batch.toast.skipped', { count: result.skipped, max: 500 }));
}
},
[addBatchFiles, t],
);
// Native OS drag-drop bridge (no-op outside Tauri).
useTauriDragDrop(handleMultiFileDrop);
const switchFormat = useCallback((next: FormatId) => {
setFormat(next);
window.localStorage.setItem(STORAGE_FORMAT_KEY, next);
setOptionsByFormat((prev) => {
if (prev[next]) return prev;
const c = getConverter(next);
return { ...prev, [next]: loadOptions(next, c.defaultOptions) };
});
}, []);
const currentOptions = optionsByFormat[format] ?? getConverter(format).defaultOptions;
const setCurrentOptions = useCallback(
(next: Record<string, unknown>) => {
setOptionsByFormat((prev) => ({ ...prev, [format]: next }));
saveOptions(format, next);
},
[format],
);
const resetCurrentOptions = useCallback(() => {
const c = getConverter(format);
clearOptions(format);
setOptionsByFormat((prev) => ({ ...prev, [format]: { ...c.defaultOptions } }));
toast.success(t('toast.options_reset'));
}, [format, t]);
const { output, inputError, outputError, shape, parseMs } = useMemo(() => {
const start = performance.now();
if (!input.trim()) {
return { output: '', inputError: null, outputError: null, shape: null, parseMs: null };
}
const parsed = parseJsonInput(input);
if (!parsed.ok) {
const msg = parsed.error === 'empty' ? null : parsed.error;
return {
output: '',
inputError: msg,
outputError: null,
shape: null,
parseMs: performance.now() - start,
};
}
const converter = getConverter(format);
if (!converter.meta.ready) {
return {
output: '',
inputError: null,
outputError: t('errors.converter_not_ready_phase', { phase: converter.meta.phase }),
shape: parsed.shape,
parseMs: performance.now() - start,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = converter.convert({ data: parsed.value, rawText: input }, currentOptions as any);
const ms = performance.now() - start;
if (result.ok) {
return {
output: result.output,
inputError: null,
outputError: null,
shape: parsed.shape,
parseMs: ms,
};
}
return {
output: '',
inputError: null,
outputError: result.error,
shape: parsed.shape,
parseMs: ms,
};
}, [input, format, currentOptions, t]);
useKeyboardShortcuts([
{ key: 'k', mod: true, handler: () => setInput('') },
{ key: 's', mod: true, handler: () => actionsRef.current?.download() },
]);
const inputBytes = useMemo(() => new TextEncoder().encode(input).length, [input]);
const outputBytes = useMemo(() => new TextEncoder().encode(output).length, [output]);
return (
<div className="flex h-full flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<FormatPicker value={format} onChange={switchFormat} shape={shape} />
<div className="flex items-center gap-3">
<ShapeHint shape={shape} />
<BatchPanel
format={format}
options={currentOptions}
open={batchOpen}
onOpenChange={setBatchOpen}
/>
<SettingsPanel
format={format}
options={currentOptions}
onChange={setCurrentOptions}
onReset={resetCurrentOptions}
/>
</div>
</div>
<div className="border-border bg-card/40 flex min-h-0 flex-1 flex-col overflow-hidden rounded-lg border">
<div className="grid min-h-0 flex-1 md:grid-cols-2">
<div className="md:border-border/60 min-h-0 border-b md:border-r md:border-b-0">
<InputPanel
value={input}
onChange={setInput}
error={inputError}
onMultiFileDrop={handleMultiFileDrop}
/>
</div>
<div className="min-h-0">
<OutputPanel
format={format}
content={output}
error={outputError}
registerActions={(a) => {
actionsRef.current = a;
}}
/>
</div>
</div>
<StatusBar inputBytes={inputBytes} outputBytes={outputBytes} parseMs={parseMs} />
</div>
</div>
);
}
+60
View File
@@ -0,0 +1,60 @@
import { useTranslation } from 'react-i18next';
import { ALL_FORMATS, getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import type { JsonShape } from '@/lib/detect';
import { isFormatSuggested } from '@/lib/suggestions';
import { cn } from '@/lib/utils';
interface FormatPickerProps {
value: FormatId;
onChange: (id: FormatId) => void;
/** Drives the subtle highlight ring on suggested chips. */
shape?: JsonShape | null;
}
export function FormatPicker({ value, onChange, shape }: FormatPickerProps) {
const { t } = useTranslation();
return (
<div className="flex flex-wrap gap-1.5">
{ALL_FORMATS.map((id) => {
const c = getConverter(id);
const active = value === id;
const suggested = shape ? isFormatSuggested(id, shape) : false;
const dimmed = shape && !suggested && c.meta.ready;
return (
<button
key={id}
type="button"
onClick={() => onChange(id)}
disabled={!c.meta.ready}
className={cn(
'group relative inline-flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs font-medium transition',
active
? 'border-primary/60 bg-primary/10 text-foreground'
: 'border-border bg-card/40 text-muted-foreground hover:text-foreground hover:border-border',
!c.meta.ready && 'cursor-not-allowed opacity-50',
dimmed && !active && 'opacity-50',
suggested && !active && 'ring-1 ring-primary/30 ring-offset-1 ring-offset-background',
)}
title={
c.meta.ready
? suggested
? t('format_status.suggested')
: t('format_status.ready')
: t('format_status.planned', { phase: c.meta.phase })
}
>
<span className="font-mono">{t(c.meta.labelKey)}</span>
{!c.meta.ready && (
<span className="border-border text-muted-foreground rounded border px-1 text-[10px] tracking-wide">
P{c.meta.phase}
</span>
)}
</button>
);
})}
</div>
);
}
+181
View File
@@ -0,0 +1,181 @@
import { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDropzone } from 'react-dropzone';
import { Eraser, FileText, FolderOpen } from 'lucide-react';
import { toast } from '@/components/ui/sonner';
import { SAMPLE_JSON } from '@/lib/sample';
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
import { CodeEditor } from './CodeEditor';
interface InputPanelProps {
value: string;
onChange: (v: string) => void;
error?: string | null;
/** Called when 2+ files are dropped — workspace routes them into batch. */
onMultiFileDrop?: (files: File[]) => void;
}
export function InputPanel({ value, onChange, error, onMultiFileDrop }: InputPanelProps) {
const { t } = useTranslation();
const fileInputRef = useRef<HTMLInputElement>(null);
const [dragActive, setDragActive] = useState(false);
const onDrop = useCallback(
(acceptedFiles: File[]) => {
setDragActive(false);
if (acceptedFiles.length === 0) return;
if (acceptedFiles.length > 1 && onMultiFileDrop) {
onMultiFileDrop(acceptedFiles);
return;
}
const file = acceptedFiles[0]!;
void readFile(file).then(
(text) => {
onChange(text);
toast.success(t('toast.file_loaded', { name: file.name }));
},
(err: Error) => {
toast.error(t('toast.file_failed', { message: err.message }));
},
);
},
[onChange, onMultiFileDrop, t],
);
const { getRootProps, getInputProps, isDragActive } = useDropzone({
onDrop,
onDragEnter: () => setDragActive(true),
onDragLeave: () => setDragActive(false),
accept: { 'application/json': ['.json'], 'text/plain': ['.txt'] },
multiple: true,
noClick: true,
noKeyboard: true,
});
const handleOpenFile = async () => {
if (isTauri()) {
const paths = await nativeOpenFiles({ multiple: false });
if (!paths || paths.length === 0) return;
try {
const file = await fileFromNativePath(paths[0]!);
const text = await file.text();
onChange(text);
toast.success(t('toast.file_loaded', { name: file.name }));
} catch (err) {
toast.error(t('toast.file_failed', { message: (err as Error).message }));
}
return;
}
fileInputRef.current?.click();
};
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
void readFile(file).then(
(text) => {
onChange(text);
toast.success(t('toast.file_loaded', { name: file.name }));
},
(err: Error) => {
toast.error(t('toast.file_failed', { message: err.message }));
},
);
e.target.value = '';
};
const showOverlay = isDragActive || dragActive;
return (
<div className="relative flex h-full flex-col" {...getRootProps()}>
<input {...getInputProps()} />
<input
ref={fileInputRef}
type="file"
accept=".json,.txt,application/json"
className="hidden"
onChange={handleFileChange}
/>
<div className="border-border/60 flex items-center justify-between border-b px-3 py-2">
<div className="flex min-w-0 items-center gap-2">
<span className="text-muted-foreground text-xs font-medium uppercase tracking-wider">
{t('home.input_label')}
</span>
{error && (
<span className="text-destructive max-w-md truncate text-xs" title={error}>
· {error}
</span>
)}
</div>
<div className="flex items-center gap-1">
<ToolbarButton
onClick={handleOpenFile}
label={t('home.open_file')}
icon={<FolderOpen className="h-3.5 w-3.5" />}
/>
<ToolbarButton
onClick={() => onChange(SAMPLE_JSON)}
label={t('home.load_sample')}
icon={<FileText className="h-3.5 w-3.5" />}
/>
<ToolbarButton
onClick={() => onChange('')}
label={t('home.clear')}
icon={<Eraser className="h-3.5 w-3.5" />}
disabled={!value}
/>
</div>
</div>
<div className="relative flex-1">
<CodeEditor
value={value}
onChange={onChange}
language="json"
placeholder={t('home.input_placeholder')}
/>
{showOverlay && (
<div className="bg-background/80 pointer-events-none absolute inset-0 z-10 flex items-center justify-center backdrop-blur-sm">
<div className="border-primary/60 bg-card flex flex-col items-center gap-2 rounded-lg border-2 border-dashed px-8 py-6">
<FolderOpen className="text-primary h-8 w-8" />
<p className="font-display text-spectrum text-lg italic">
{t('home.drop_zone_active')}
</p>
</div>
</div>
)}
</div>
</div>
);
}
async function readFile(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result ?? ''));
reader.onerror = () => reject(new Error(`Cannot read file: ${file.name}`));
reader.readAsText(file);
});
}
interface ToolbarButtonProps {
onClick: () => void;
label: string;
icon: React.ReactNode;
disabled?: boolean;
}
function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
>
{icon}
<span>{label}</span>
</button>
);
}
+112
View File
@@ -0,0 +1,112 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Copy, Download } from 'lucide-react';
import { toast } from '@/components/ui/sonner';
import type { FormatId } from '@/converters/types';
import { getConverter } from '@/converters/registry';
interface OutputPanelProps {
format: FormatId;
content: string;
error?: string | null;
/** Imperative handle so the workspace can trigger download from a keyboard shortcut. */
registerActions?: (actions: { copy: () => void; download: () => void }) => void;
}
export function OutputPanel({ format, content, error, registerActions }: OutputPanelProps) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const converter = getConverter(format);
const handleCopy = async () => {
if (!content) return;
try {
await navigator.clipboard.writeText(content);
setCopied(true);
toast.success(t('toast.copied', { format: t(converter.meta.labelKey) }));
setTimeout(() => setCopied(false), 1500);
} catch {
toast.error(t('toast.copy_failed'));
}
};
const handleDownload = () => {
if (!content) return;
const blob = new Blob([content], { type: converter.meta.mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `output.${converter.meta.extension}`;
a.click();
URL.revokeObjectURL(url);
toast.success(t('toast.downloaded', { filename: `output.${converter.meta.extension}` }));
};
// Register actions every render — cheap, no useEffect needed.
registerActions?.({ copy: handleCopy, download: handleDownload });
const disabled = !content || !!error;
return (
<div className="flex h-full flex-col">
<div className="border-border/60 flex items-center justify-between border-b px-3 py-2">
<div className="flex items-center gap-2">
<span className="text-muted-foreground text-xs font-medium uppercase tracking-wider">
{t('home.output_label')}
</span>
<span className="text-muted-foreground/60 font-mono text-xs">
· .{converter.meta.extension}
</span>
</div>
<div className="flex items-center gap-1">
<ToolbarButton
onClick={handleCopy}
label={copied ? '✓' : t('home.copy')}
icon={copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
disabled={disabled}
/>
<ToolbarButton
onClick={handleDownload}
label={t('home.download')}
icon={<Download className="h-3.5 w-3.5" />}
disabled={disabled}
/>
</div>
</div>
<div className="relative flex-1 overflow-auto">
{error ? (
<div className="text-destructive p-4 font-mono text-sm whitespace-pre-wrap">{error}</div>
) : content ? (
<pre className="font-mono p-4 text-sm leading-relaxed whitespace-pre-wrap break-words">
{content}
</pre>
) : (
<div className="text-muted-foreground/60 p-4 text-sm italic">
{t('home.output_empty')}
</div>
)}
</div>
</div>
);
}
interface ToolbarButtonProps {
onClick: () => void;
label: string;
icon: React.ReactNode;
disabled?: boolean;
}
function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
return (
<button
type="button"
onClick={onClick}
disabled={disabled}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
>
{icon}
<span>{label}</span>
</button>
);
}
+173
View File
@@ -0,0 +1,173 @@
import { useTranslation } from 'react-i18next';
import { RotateCcw, Settings2 } from 'lucide-react';
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
SheetTrigger,
} from '@/components/ui/sheet';
import { Switch } from '@/components/ui/switch';
import { getConverter } from '@/converters/registry';
import type { FormatId, OptionSchemaField } from '@/converters/types';
import { cn } from '@/lib/utils';
interface SettingsPanelProps {
format: FormatId;
options: Record<string, unknown>;
onChange: (next: Record<string, unknown>) => void;
onReset: () => void;
}
export function SettingsPanel({ format, options, onChange, onReset }: SettingsPanelProps) {
const { t } = useTranslation();
const converter = getConverter(format);
const schema = converter.optionSchema as ReadonlyArray<OptionSchemaField<Record<string, unknown>>>;
const formatLabel = t(converter.meta.labelKey);
const hasFields = schema.length > 0;
const setField = (key: string, value: unknown) => {
onChange({ ...options, [key]: value });
};
return (
<Sheet>
<SheetTrigger asChild>
<button
type="button"
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md border border-border/60 px-2.5 py-1 text-xs transition"
aria-label={t('home.options')}
>
<Settings2 className="h-3.5 w-3.5" />
<span>{t('home.options')}</span>
</button>
</SheetTrigger>
<SheetContent className="flex w-full flex-col gap-0 p-0 sm:max-w-md">
<SheetHeader>
<SheetTitle>
<span className="text-spectrum italic">{formatLabel}</span>{' '}
<span className="text-muted-foreground font-sans text-base font-normal not-italic">
· {t('settings.title')}
</span>
</SheetTitle>
<SheetDescription>
{hasFields ? t('settings.description') : t('settings.no_options')}
</SheetDescription>
</SheetHeader>
<div className="flex-1 overflow-y-auto px-6 pb-6">
{hasFields ? (
<div className="flex flex-col gap-5">
{schema.map((field) => (
<FieldRenderer
key={field.key}
field={field}
value={options[field.key]}
onChange={(v) => setField(field.key, v)}
/>
))}
</div>
) : (
<p className="text-muted-foreground py-12 text-center text-sm italic">
{t('settings.no_options_long')}
</p>
)}
</div>
{hasFields && (
<div className="border-border/60 flex items-center justify-end gap-2 border-t px-6 py-3">
<button
type="button"
onClick={onReset}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs transition"
>
<RotateCcw className="h-3.5 w-3.5" />
{t('settings.reset')}
</button>
</div>
)}
</SheetContent>
</Sheet>
);
}
interface FieldRendererProps {
field: OptionSchemaField<Record<string, unknown>>;
value: unknown;
onChange: (v: unknown) => void;
}
function FieldRenderer({ field, value, onChange }: FieldRendererProps) {
const { t } = useTranslation();
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between gap-3">
<label className="text-sm font-medium" htmlFor={`field-${field.key}`}>
{t(field.labelKey)}
</label>
{field.type === 'boolean' && (
<Switch
id={`field-${field.key}`}
checked={Boolean(value)}
onCheckedChange={(v) => onChange(v)}
/>
)}
</div>
{field.type === 'enum' && (
<div className="flex flex-wrap gap-1">
{field.choices.map((choice) => {
const active = String(value) === choice.value;
return (
<button
key={choice.value}
type="button"
onClick={() => onChange(choice.value)}
className={cn(
'rounded-md border px-2.5 py-1 text-xs font-medium transition',
active
? 'border-primary/60 bg-primary/10 text-foreground'
: 'border-border bg-card/40 text-muted-foreground hover:text-foreground',
)}
>
{t(choice.labelKey)}
</button>
);
})}
</div>
)}
{field.type === 'integer' && (
<input
id={`field-${field.key}`}
type="number"
value={Number(value)}
min={field.min}
max={field.max}
onChange={(e) => {
const n = Number(e.target.value);
if (Number.isFinite(n)) onChange(n);
}}
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:outline-none focus:ring-2"
/>
)}
{field.type === 'string' && (
<input
id={`field-${field.key}`}
type="text"
value={String(value ?? '')}
placeholder={field.placeholder}
onChange={(e) => onChange(e.target.value)}
className="border-border bg-background focus:ring-ring rounded-md border px-3 py-1.5 font-mono text-sm focus:outline-none focus:ring-2"
/>
)}
{field.descriptionKey && (
<p className="text-muted-foreground text-xs">{t(field.descriptionKey)}</p>
)}
</div>
);
}
+20
View File
@@ -0,0 +1,20 @@
import { useTranslation } from 'react-i18next';
import { Sparkles } from 'lucide-react';
import type { JsonShape } from '@/lib/detect';
interface ShapeHintProps {
shape: JsonShape | null;
}
export function ShapeHint({ shape }: ShapeHintProps) {
const { t } = useTranslation();
if (!shape || shape === 'unknown') return null;
return (
<div className="text-muted-foreground inline-flex items-center gap-1.5 font-mono text-xs">
<Sparkles className="text-primary h-3 w-3" />
<span>{t('shape.detected')}:</span>
<span className="text-foreground">{t(`shape.${shape}`)}</span>
</div>
);
}
+54
View File
@@ -0,0 +1,54 @@
import { useTranslation } from 'react-i18next';
import { modKey } from '@/hooks/useKeyboardShortcuts';
interface StatusBarProps {
inputBytes: number;
outputBytes: number;
parseMs: number | null;
}
export function StatusBar({ inputBytes, outputBytes, parseMs }: StatusBarProps) {
const { t } = useTranslation();
return (
<div className="text-muted-foreground border-border/60 flex items-center justify-between border-t px-3 py-1.5 font-mono text-[11px]">
<div className="flex gap-3">
<Stat label={t('status.in')} value={formatBytes(inputBytes)} />
<Stat label={t('status.out')} value={formatBytes(outputBytes)} />
{parseMs !== null && <Stat label={t('status.time')} value={`${parseMs.toFixed(1)}ms`} />}
</div>
<div className="hidden gap-3 md:flex">
<Shortcut keys={`${modKey()}+K`} label={t('shortcut.clear')} />
<Shortcut keys={`${modKey()}+S`} label={t('shortcut.download')} />
<Shortcut keys={`${modKey()}+,`} label={t('shortcut.settings')} />
</div>
</div>
);
}
function Stat({ label, value }: { label: string; value: string }) {
return (
<span className="inline-flex items-center gap-1">
<span className="opacity-60">{label}:</span>
<span className="text-foreground/80">{value}</span>
</span>
);
}
function Shortcut({ keys, label }: { keys: string; label: string }) {
return (
<span className="inline-flex items-center gap-1">
<kbd className="border-border bg-muted/40 text-foreground/80 rounded border px-1 py-0 text-[10px] leading-none">
{keys}
</kbd>
<span className="opacity-60">{label}</span>
</span>
);
}
function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B';
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(2)} MB`;
}
+22
View File
@@ -0,0 +1,22 @@
export function Footer() {
return (
<footer className="border-border/60 text-muted-foreground border-t px-6 py-6 text-xs">
<div className="mx-auto flex max-w-screen-2xl flex-col items-center justify-between gap-2 sm:flex-row">
<div>
<span className="font-mono">JSONPrism</span> · v1.0.0 · Apache-2.0
</div>
<div className="flex items-center gap-1.5">
<span>Built by</span>
<a
href="https://github.com/poli0981"
target="_blank"
rel="noreferrer"
className="hover:text-foreground underline-offset-4 hover:underline"
>
Kokone
</a>
</div>
</div>
</footer>
);
}
+88
View File
@@ -0,0 +1,88 @@
import { Link, NavLink } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Github } from 'lucide-react';
import { ThemeToggle } from './ThemeToggle';
import { LanguageSwitcher } from '../common/LanguageSwitcher';
import { cn } from '@/lib/utils';
export function Header() {
const { t } = useTranslation();
return (
<header className="border-border/60 bg-background/80 sticky top-0 z-40 border-b backdrop-blur-md">
<div className="mx-auto flex h-14 max-w-screen-2xl items-center gap-6 px-6">
<Link to="/" className="group flex items-center gap-2.5">
<BrandMark className="h-7 w-7" />
<span className="font-display text-xl leading-none tracking-tight">
JSON<span className="text-spectrum italic">Prism</span>
</span>
</Link>
<nav className="ml-6 hidden gap-1 md:flex">
<NavItem to="/" end>
{t('nav.home')}
</NavItem>
<NavItem to="/about">{t('nav.about')}</NavItem>
</nav>
<div className="ml-auto flex items-center gap-1">
<LanguageSwitcher />
<ThemeToggle />
<a
href="https://github.com/poli0981/jsonprism"
target="_blank"
rel="noreferrer"
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex h-9 w-9 items-center justify-center rounded-md transition"
aria-label={t('nav.github')}
>
<Github className="h-4 w-4" />
</a>
</div>
</div>
</header>
);
}
interface NavItemProps {
to: string;
end?: boolean;
children: React.ReactNode;
}
function NavItem({ to, end, children }: NavItemProps) {
return (
<NavLink
to={to}
end={end}
className={({ isActive }) =>
cn(
'inline-flex h-9 items-center rounded-md px-3 text-sm font-medium transition',
isActive
? 'text-foreground bg-muted/60'
: 'text-muted-foreground hover:text-foreground hover:bg-muted/40',
)
}
>
{children}
</NavLink>
);
}
function BrandMark({ className }: { className?: string }) {
return (
<svg viewBox="0 0 64 64" fill="none" className={className} aria-hidden>
<line x1="2" y1="32" x2="22" y2="32" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
<path
d="M22 12 L46 32 L22 52 Z"
fill="transparent"
stroke="currentColor"
strokeWidth="2.5"
strokeLinejoin="round"
/>
<line x1="46" y1="32" x2="62" y2="20" stroke="var(--color-prism-violet)" strokeWidth="2.5" strokeLinecap="round" />
<line x1="46" y1="32" x2="62" y2="28" stroke="var(--color-prism-cyan)" strokeWidth="2.5" strokeLinecap="round" />
<line x1="46" y1="32" x2="62" y2="36" stroke="var(--color-prism-amber)" strokeWidth="2.5" strokeLinecap="round" />
<line x1="46" y1="32" x2="62" y2="44" stroke="var(--color-prism-rose)" strokeWidth="2.5" strokeLinecap="round" />
</svg>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { Outlet } from 'react-router-dom';
import { Header } from './Header';
import { Footer } from './Footer';
export function Layout() {
return (
<div className="flex min-h-full flex-col">
<Header />
<main className="flex-1">
<Outlet />
</main>
<Footer />
</div>
);
}
+50
View File
@@ -0,0 +1,50 @@
import { useState } from 'react';
import { Monitor, Moon, Sun } from 'lucide-react';
import { useTheme, type Theme } from '@/lib/theme';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const Icon = theme === 'system' ? Monitor : theme === 'dark' ? Moon : Sun;
return (
<div className="relative">
<button
type="button"
onClick={() => setOpen((v) => !v)}
onBlur={() => setTimeout(() => setOpen(false), 100)}
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex h-9 w-9 items-center justify-center rounded-md transition"
aria-label="Theme"
>
<Icon className="h-4 w-4" />
</button>
{open && (
<div className="border-border bg-popover absolute right-0 top-full z-50 mt-1 w-32 rounded-md border p-1 shadow-lg">
{(['light', 'dark', 'system'] as Theme[]).map((t2) => (
<button
key={t2}
type="button"
onClick={() => {
setTheme(t2);
setOpen(false);
}}
className={cn(
'hover:bg-muted flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-sm',
theme === t2 && 'text-primary',
)}
>
{t2 === 'light' && <Sun className="h-3.5 w-3.5" />}
{t2 === 'dark' && <Moon className="h-3.5 w-3.5" />}
{t2 === 'system' && <Monitor className="h-3.5 w-3.5" />}
{t(`theme.${t2}`)}
</button>
))}
</div>
)}
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import * as React from 'react';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const Sheet = DialogPrimitive.Root;
const SheetTrigger = DialogPrimitive.Trigger;
const SheetClose = DialogPrimitive.Close;
const SheetPortal = DialogPrimitive.Portal;
const SheetOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
'fixed inset-0 z-50 bg-black/40 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
));
SheetOverlay.displayName = DialogPrimitive.Overlay.displayName;
const sheetVariants = cva(
'fixed z-50 gap-4 bg-background shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-200 data-[state=open]:duration-300',
{
variants: {
side: {
top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top',
bottom:
'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom',
left: 'inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm',
right:
'inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-md',
},
},
defaultVariants: { side: 'right' },
},
);
interface SheetContentProps
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>,
VariantProps<typeof sheetVariants> {}
const SheetContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
SheetContentProps
>(({ side = 'right', className, children, ...props }, ref) => (
<SheetPortal>
<SheetOverlay />
<DialogPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
{children}
<SheetClose className="ring-offset-background focus:ring-ring data-[state=open]:bg-muted absolute right-4 top-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:pointer-events-none">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</SheetClose>
</DialogPrimitive.Content>
</SheetPortal>
));
SheetContent.displayName = DialogPrimitive.Content.displayName;
const SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn('flex flex-col gap-1 p-6 pb-2 text-left', className)} {...props} />
);
SheetHeader.displayName = 'SheetHeader';
const SheetTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn('font-display text-xl tracking-tight', className)}
{...props}
/>
));
SheetTitle.displayName = DialogPrimitive.Title.displayName;
const SheetDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
));
SheetDescription.displayName = DialogPrimitive.Description.displayName;
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetTitle,
SheetDescription,
};
+28
View File
@@ -0,0 +1,28 @@
import { Toaster as SonnerToaster, type ToasterProps } from 'sonner';
import { useTheme } from '@/lib/theme';
export function Toaster(props: ToasterProps) {
const { resolvedTheme } = useTheme();
return (
<SonnerToaster
theme={resolvedTheme}
position="bottom-right"
richColors
closeButton
toastOptions={{
classNames: {
toast:
'group toast group-[.toaster]:bg-card group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg group-[.toaster]:font-sans',
description: 'group-[.toast]:text-muted-foreground',
actionButton: 'group-[.toast]:bg-primary group-[.toast]:text-primary-foreground',
cancelButton: 'group-[.toast]:bg-muted group-[.toast]:text-muted-foreground',
},
}}
{...props}
/>
);
}
// Re-export toast() for ergonomics
export { toast } from 'sonner';
+26
View File
@@ -0,0 +1,26 @@
import * as React from 'react';
import * as SwitchPrimitives from '@radix-ui/react-switch';
import { cn } from '@/lib/utils';
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
'peer focus-visible:ring-ring focus-visible:ring-offset-background data-[state=checked]:bg-primary data-[state=unchecked]:bg-input inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
className,
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
'bg-background pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0',
)}
/>
</SwitchPrimitives.Root>
));
Switch.displayName = SwitchPrimitives.Root.displayName;
export { Switch };
+71
View File
@@ -0,0 +1,71 @@
import { describe, expect, it } from 'vitest';
import { csvConverter, tsvConverter } from '../csv';
describe('csvConverter', () => {
it('emits a header row and data rows for flat objects', () => {
const data = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
];
const result = csvConverter.convert({ data }, csvConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const lines = result.output.split('\n');
expect(lines[0]).toBe('id,name');
expect(lines[1]).toBe('1,a');
expect(lines[2]).toBe('2,b');
});
it('rejects non-array roots', () => {
const result = csvConverter.convert({ data: { a: 1 } }, csvConverter.defaultOptions);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatch(/array/i);
});
it('rejects rows that are not objects', () => {
const result = csvConverter.convert({ data: [1, 2, 3] }, csvConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('JSON-stringifies nested values by default', () => {
const data = [{ id: 1, tags: ['a', 'b'] }];
const result = csvConverter.convert({ data }, csvConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('["a","b"]');
});
it('honors header=false option', () => {
const data = [{ id: 1, name: 'a' }];
const result = csvConverter.convert(
{ data },
{ ...csvConverter.defaultOptions, header: false },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
// No header line — first line is data
expect(result.output.startsWith('1,a')).toBe(true);
});
it('declares CSV mime type and extension', () => {
expect(csvConverter.meta.mimeType).toBe('text/csv');
expect(csvConverter.meta.extension).toBe('csv');
});
});
describe('tsvConverter', () => {
it('separates fields with tabs', () => {
const data = [{ id: 1, name: 'a' }];
const result = tsvConverter.convert({ data }, tsvConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('id\tname');
expect(result.output).toContain('1\ta');
});
it('declares TSV mime type and extension', () => {
expect(tsvConverter.meta.mimeType).toBe('text/tab-separated-values');
expect(tsvConverter.meta.extension).toBe('tsv');
});
});
+50
View File
@@ -0,0 +1,50 @@
import { describe, expect, it } from 'vitest';
import { jsonlConverter } from '../jsonl';
describe('jsonlConverter', () => {
it('serializes an array of objects, one record per line', () => {
const data = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
];
const result = jsonlConverter.convert({ data }, { pretty: false });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toBe('{"id":1,"name":"a"}\n{"id":2,"name":"b"}\n');
});
it('rejects non-array roots', () => {
const result = jsonlConverter.convert({ data: { a: 1 } }, { pretty: false });
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatch(/array/i);
});
it('handles empty arrays', () => {
const result = jsonlConverter.convert({ data: [] }, { pretty: false });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toBe('\n');
});
it('pretty-prints when option is set', () => {
const data = [{ a: 1 }];
const result = jsonlConverter.convert({ data }, { pretty: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('\n ');
});
it('preserves nested structures', () => {
const data = [{ tags: ['a', 'b'], meta: { v: 1 } }];
const result = jsonlConverter.convert({ data }, { pretty: false });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toBe('{"tags":["a","b"],"meta":{"v":1}}\n');
});
it('declares phase 1 and ready', () => {
expect(jsonlConverter.meta.phase).toBe(1);
expect(jsonlConverter.meta.ready).toBe(true);
});
});
+111
View File
@@ -0,0 +1,111 @@
import { describe, expect, it } from 'vitest';
import { markdownConverter } from '../markdown';
describe('markdownConverter', () => {
it('emits header + alignment + data rows', () => {
const data = [
{ id: 1, name: 'a' },
{ id: 2, name: 'b' },
];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const lines = result.output.trim().split('\n');
expect(lines[0]).toBe('| id | name |');
expect(lines[1]).toBe('| :--- | :--- |');
expect(lines[2]).toBe('| 1 | a |');
expect(lines[3]).toBe('| 2 | b |');
});
it('rejects non-array roots', () => {
const result = markdownConverter.convert({ data: { a: 1 } }, markdownConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('rejects rows that are not objects', () => {
const result = markdownConverter.convert({ data: [1, 2] }, markdownConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('handles empty arrays gracefully', () => {
const result = markdownConverter.convert({ data: [] }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toBe('');
});
it('uses center alignment when configured', () => {
const data = [{ a: 1 }];
const result = markdownConverter.convert(
{ data },
{ ...markdownConverter.defaultOptions, alignment: 'center' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('| :---: |');
});
it('uses right alignment when configured', () => {
const data = [{ a: 1 }];
const result = markdownConverter.convert(
{ data },
{ ...markdownConverter.defaultOptions, alignment: 'right' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('| ---: |');
});
it('escapes pipe characters in cells when enabled', () => {
const data = [{ note: 'a|b|c' }];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('a\\|b\\|c');
});
it('does not escape pipes when disabled', () => {
const data = [{ note: 'a|b' }];
const result = markdownConverter.convert(
{ data },
{ ...markdownConverter.defaultOptions, escapePipes: false },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('a|b');
});
it('converts newlines to <br>', () => {
const data = [{ multi: 'line1\nline2' }];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('line1<br>line2');
});
it('JSON-stringifies nested values', () => {
const data = [{ tags: ['x', 'y'] }];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('["x","y"]');
});
it('emits empty cells for missing keys across rows', () => {
const data = [{ a: 1, b: 2 }, { a: 3 }];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const lines = result.output.trim().split('\n');
expect(lines[0]).toBe('| a | b |');
expect(lines[3]).toBe('| 3 | |');
});
it('preserves key insertion order from the first occurrence', () => {
const data = [{ z: 1, a: 2 }, { a: 3, z: 4 }];
const result = markdownConverter.convert({ data }, markdownConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output.split('\n')[0]).toBe('| z | a |');
});
});
+55
View File
@@ -0,0 +1,55 @@
import { describe, expect, it } from 'vitest';
import { ALL_FORMATS, CONVERTERS, getConverter } from '../registry';
import type { FormatId } from '../types';
describe('converter registry', () => {
it('exposes all 9 format IDs', () => {
expect(ALL_FORMATS).toHaveLength(9);
expect(new Set(ALL_FORMATS)).toEqual(
new Set<FormatId>([
'jsonl',
'csv',
'tsv',
'yaml',
'xml',
'toml',
'resx',
'markdown',
'sql',
]),
);
});
it('CONVERTERS map matches ALL_FORMATS keys', () => {
expect(Object.keys(CONVERTERS).sort()).toEqual([...ALL_FORMATS].sort());
});
it('getConverter returns a converter for every format', () => {
for (const id of ALL_FORMATS) {
const c = getConverter(id);
expect(c.meta.id).toBe(id);
}
});
it('each converter declares defaultOptions and optionSchema', () => {
for (const id of ALL_FORMATS) {
const c = getConverter(id);
expect(c.defaultOptions).toBeDefined();
expect(Array.isArray(c.optionSchema)).toBe(true);
}
});
it('Phase 1 converters are marked ready', () => {
const phase1 = ['jsonl', 'csv', 'tsv', 'yaml'] as const;
for (const id of phase1) {
expect(getConverter(id).meta.ready).toBe(true);
}
});
it('Phase 2/3 converters are marked not ready', () => {
const notReady = ['xml', 'toml', 'markdown', 'sql', 'resx'] as const;
for (const id of notReady) {
expect(getConverter(id).meta.ready).toBe(false);
}
});
});
+194
View File
@@ -0,0 +1,194 @@
import { describe, expect, it } from 'vitest';
import { escapeAttr, escapeText, resxConverter } from '../resx';
describe('escapeText', () => {
it('escapes &, <, > in text content', () => {
expect(escapeText('a & b < c > d')).toBe('a &amp; b &lt; c &gt; d');
});
it('preserves quotes in text', () => {
expect(escapeText(`hello "world"`)).toBe(`hello "world"`);
});
it('handles empty strings', () => {
expect(escapeText('')).toBe('');
});
});
describe('escapeAttr', () => {
it('escapes &, <, >, and quotes', () => {
expect(escapeAttr(`a"b`)).toBe('a&quot;b');
expect(escapeAttr('a<b>c&d')).toBe('a&lt;b&gt;c&amp;d');
});
});
describe('resxConverter', () => {
it('emits the XML declaration and root element', () => {
const result = resxConverter.convert(
{ data: { Hello: 'Hi' } },
resxConverter.defaultOptions,
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output.startsWith('<?xml version="1.0" encoding="utf-8"?>\n<root>')).toBe(true);
expect(result.output.trimEnd().endsWith('</root>')).toBe(true);
});
it('emits the standard schema header by default', () => {
const result = resxConverter.convert(
{ data: { K: 'V' } },
resxConverter.defaultOptions,
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<xsd:schema id="root"');
expect(result.output).toContain('<resheader name="resmimetype">');
expect(result.output).toContain('<value>text/microsoft-resx</value>');
expect(result.output).toContain('<resheader name="version">');
expect(result.output).toContain('<value>2.0</value>');
expect(result.output).toContain('System.Resources.ResXResourceReader');
expect(result.output).toContain('System.Resources.ResXResourceWriter');
});
it('omits schema header when includeSchema=false', () => {
const result = resxConverter.convert(
{ data: { K: 'V' } },
{ ...resxConverter.defaultOptions, includeSchema: false },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).not.toContain('<xsd:schema');
expect(result.output).not.toContain('<resheader');
});
it('emits each entry as a <data> element with xml:space="preserve"', () => {
const data = { Greeting: 'Hello', Farewell: 'Goodbye' };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<data name="Greeting" xml:space="preserve">');
expect(result.output).toContain('<value>Hello</value>');
expect(result.output).toContain('<data name="Farewell" xml:space="preserve">');
expect(result.output).toContain('<value>Goodbye</value>');
});
it('supports the { value, _comment } shape for entries with comments', () => {
const data = {
WelcomeMsg: { value: 'Hi there', _comment: 'Shown on home screen' },
};
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<value>Hi there</value>');
expect(result.output).toContain('<comment>Shown on home screen</comment>');
});
it('honors a custom commentKey', () => {
const data = { Key1: { value: 'V', note: 'N' } };
const result = resxConverter.convert(
{ data },
{ ...resxConverter.defaultOptions, commentKey: 'note' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<comment>N</comment>');
});
it('escapes XML special characters in values', () => {
const data = { Tag: '<script>alert("x")</script> & co.' };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain(
'&lt;script&gt;alert("x")&lt;/script&gt; &amp; co.',
);
});
it('escapes special characters in key names (attribute context)', () => {
const data = { 'Key&Name': 'value' };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<data name="Key&amp;Name"');
});
it('coerces numbers and booleans to strings', () => {
const data = { Count: 42, Enabled: true };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<value>42</value>');
expect(result.output).toContain('<value>true</value>');
});
it('treats null/undefined as empty string', () => {
const data = { Empty: null };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<data name="Empty" xml:space="preserve">');
expect(result.output).toContain('<value></value>');
});
it('rejects array roots with a clear error', () => {
const result = resxConverter.convert({ data: [1, 2, 3] }, resxConverter.defaultOptions);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatch(/flat object/i);
});
it('rejects scalar roots', () => {
const result = resxConverter.convert({ data: 'hello' }, resxConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('rejects nested-object values (without the { value, _comment } shape)', () => {
const data = { K: { foo: { bar: 'baz' } } };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatch(/nested|flat/i);
});
it('sortKeys=true sorts entries alphabetically', () => {
const data = { Zebra: 'z', Apple: 'a', Mango: 'm' };
const result = resxConverter.convert(
{ data },
{ ...resxConverter.defaultOptions, sortKeys: true },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const appleIdx = result.output.indexOf('"Apple"');
const mangoIdx = result.output.indexOf('"Mango"');
const zebraIdx = result.output.indexOf('"Zebra"');
expect(appleIdx).toBeLessThan(mangoIdx);
expect(mangoIdx).toBeLessThan(zebraIdx);
});
it('preserves insertion order when sortKeys=false', () => {
const data = { Zebra: 'z', Apple: 'a' };
const result = resxConverter.convert({ data }, resxConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const zebraIdx = result.output.indexOf('"Zebra"');
const appleIdx = result.output.indexOf('"Apple"');
expect(zebraIdx).toBeLessThan(appleIdx);
});
it('declares phase 3 and ready', () => {
expect(resxConverter.meta.phase).toBe(3);
expect(resxConverter.meta.ready).toBe(true);
});
it('matches Visual Studio resmimetype + version exactly', () => {
const result = resxConverter.convert(
{ data: { K: 'V' } },
resxConverter.defaultOptions,
);
expect(result.ok).toBe(true);
if (!result.ok) return;
// These literal strings must round-trip through Visual Studio's editor without churn.
expect(result.output).toContain('<value>text/microsoft-resx</value>');
expect(result.output).toContain('<value>2.0</value>');
});
});
+211
View File
@@ -0,0 +1,211 @@
import { describe, expect, it } from 'vitest';
import {
formatSqlValue,
inferSqlType,
quoteIdentifier,
sqlConverter,
type SqlDialect,
} from '../sql';
describe('quoteIdentifier', () => {
it('quotes with double-quotes for standard/postgres/sqlite', () => {
expect(quoteIdentifier('col', 'standard')).toBe('"col"');
expect(quoteIdentifier('col', 'postgres')).toBe('"col"');
expect(quoteIdentifier('col', 'sqlite')).toBe('"col"');
});
it('quotes with backticks for mysql', () => {
expect(quoteIdentifier('col', 'mysql')).toBe('`col`');
});
it('quotes with brackets for mssql', () => {
expect(quoteIdentifier('col', 'mssql')).toBe('[col]');
});
it('escapes embedded quotes correctly per dialect', () => {
expect(quoteIdentifier('a"b', 'postgres')).toBe('"a""b"');
expect(quoteIdentifier('a`b', 'mysql')).toBe('`a``b`');
expect(quoteIdentifier('a]b', 'mssql')).toBe('[a]]b]');
});
});
describe('formatSqlValue', () => {
it('renders NULL for null/undefined', () => {
expect(formatSqlValue(null, 'standard')).toBe('NULL');
expect(formatSqlValue(undefined, 'standard')).toBe('NULL');
});
it('renders booleans as TRUE/FALSE for standard/postgres', () => {
expect(formatSqlValue(true, 'standard')).toBe('TRUE');
expect(formatSqlValue(false, 'postgres')).toBe('FALSE');
});
it('renders booleans as 1/0 for mysql/sqlite/mssql', () => {
expect(formatSqlValue(true, 'mysql')).toBe('1');
expect(formatSqlValue(false, 'sqlite')).toBe('0');
expect(formatSqlValue(true, 'mssql')).toBe('1');
});
it('renders integers and floats as-is', () => {
expect(formatSqlValue(42, 'standard')).toBe('42');
expect(formatSqlValue(3.14, 'standard')).toBe('3.14');
});
it('renders non-finite numbers as NULL', () => {
expect(formatSqlValue(NaN, 'standard')).toBe('NULL');
expect(formatSqlValue(Infinity, 'standard')).toBe('NULL');
});
it('escapes single quotes in strings', () => {
expect(formatSqlValue("O'Brien", 'standard')).toBe("'O''Brien'");
});
it('JSON-stringifies objects and arrays', () => {
expect(formatSqlValue({ a: 1 }, 'standard')).toBe(`'{"a":1}'`);
expect(formatSqlValue([1, 2], 'standard')).toBe(`'[1,2]'`);
});
});
describe('inferSqlType', () => {
it('infers BOOLEAN for booleans in postgres', () => {
expect(inferSqlType(true, 'postgres')).toBe('BOOLEAN');
});
it('infers TINYINT(1) for booleans in mysql', () => {
expect(inferSqlType(true, 'mysql')).toBe('TINYINT(1)');
});
it('infers BIT for booleans in mssql', () => {
expect(inferSqlType(true, 'mssql')).toBe('BIT');
});
it('infers INTEGER for integer numbers in all dialects', () => {
const dialects: SqlDialect[] = ['standard', 'postgres', 'mysql', 'sqlite', 'mssql'];
for (const d of dialects) {
expect(inferSqlType(42, d)).toBe('INTEGER');
}
});
it('infers DOUBLE PRECISION for floats in postgres', () => {
expect(inferSqlType(3.14, 'postgres')).toBe('DOUBLE PRECISION');
});
it('infers VARCHAR(255) for strings in mysql/mssql, TEXT elsewhere', () => {
expect(inferSqlType('s', 'mysql')).toBe('VARCHAR(255)');
expect(inferSqlType('s', 'mssql')).toBe('VARCHAR(255)');
expect(inferSqlType('s', 'postgres')).toBe('TEXT');
expect(inferSqlType('s', 'sqlite')).toBe('TEXT');
});
it('infers JSONB for objects in postgres, JSON in mysql, TEXT elsewhere', () => {
expect(inferSqlType({ a: 1 }, 'postgres')).toBe('JSONB');
expect(inferSqlType({ a: 1 }, 'mysql')).toBe('JSON');
expect(inferSqlType({ a: 1 }, 'sqlite')).toBe('TEXT');
});
});
describe('sqlConverter', () => {
const sampleData = [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false },
];
it('emits multi-row INSERT by default', () => {
const result = sqlConverter.convert({ data: sampleData }, sqlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toMatch(/INSERT INTO "records" \("id", "name", "active"\) VALUES/);
expect(result.output).toContain('(1, \'Alice\', TRUE)');
expect(result.output).toContain('(2, \'Bob\', FALSE)');
});
it('emits one INSERT per row when multiRow=false', () => {
const result = sqlConverter.convert(
{ data: sampleData },
{ ...sqlConverter.defaultOptions, multiRow: false },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const inserts = result.output.split('INSERT INTO').length - 1;
expect(inserts).toBe(2);
});
it('chunks multi-row inserts at chunkSize boundary', () => {
const data = Array.from({ length: 5 }, (_, i) => ({ id: i }));
const result = sqlConverter.convert(
{ data },
{ ...sqlConverter.defaultOptions, chunkSize: 2 },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
// 5 rows, chunkSize 2 → 3 INSERT statements
const inserts = result.output.split('INSERT INTO').length - 1;
expect(inserts).toBe(3);
});
it('uses MySQL backtick quoting when dialect=mysql', () => {
const result = sqlConverter.convert(
{ data: sampleData },
{ ...sqlConverter.defaultOptions, dialect: 'mysql' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('`records`');
expect(result.output).toContain('`id`');
});
it('uses MSSQL bracket quoting when dialect=mssql', () => {
const result = sqlConverter.convert(
{ data: sampleData },
{ ...sqlConverter.defaultOptions, dialect: 'mssql' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('[records]');
expect(result.output).toContain('[id]');
});
it('includes CREATE TABLE when includeCreate=true', () => {
const result = sqlConverter.convert(
{ data: sampleData },
{ ...sqlConverter.defaultOptions, includeCreate: true },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('CREATE TABLE "records"');
expect(result.output).toContain('"id" INTEGER');
expect(result.output).toContain('"active" BOOLEAN');
});
it('respects custom table name', () => {
const result = sqlConverter.convert(
{ data: sampleData },
{ ...sqlConverter.defaultOptions, tableName: 'users' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('"users"');
expect(result.output).not.toContain('"records"');
});
it('rejects non-array roots', () => {
const result = sqlConverter.convert({ data: { a: 1 } }, sqlConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('emits comment for empty array', () => {
const result = sqlConverter.convert({ data: [] }, sqlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toMatch(/^--/);
});
it('handles NULL values for missing keys across rows', () => {
const data = [{ a: 1, b: 2 }, { a: 3 }];
const result = sqlConverter.convert({ data }, sqlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
// Second row's missing 'b' should be NULL
expect(result.output).toContain('(3, NULL)');
});
});
+63
View File
@@ -0,0 +1,63 @@
import { describe, expect, it } from 'vitest';
import { parse } from 'smol-toml';
import { tomlConverter } from '../toml';
describe('tomlConverter', () => {
it('serializes a flat object', () => {
const data = { name: 'JSONPrism', version: '0.3.0' };
const result = tomlConverter.convert({ data }, tomlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('name = "JSONPrism"');
expect(result.output).toContain('version = "0.3.0"');
});
it('round-trips through smol-toml parse', () => {
const data = { name: 'test', count: 42, enabled: true, tags: ['a', 'b'] };
const result = tomlConverter.convert({ data }, tomlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const parsed = parse(result.output);
expect(parsed).toEqual(data);
});
it('rejects non-object roots (array)', () => {
const result = tomlConverter.convert({ data: [1, 2] }, tomlConverter.defaultOptions);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatch(/plain object|table/i);
});
it('rejects non-object roots (scalar)', () => {
const result = tomlConverter.convert({ data: 'hello' }, tomlConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('rejects null root', () => {
const result = tomlConverter.convert({ data: null }, tomlConverter.defaultOptions);
expect(result.ok).toBe(false);
});
it('emits nested tables for nested objects', () => {
const data = { db: { host: 'localhost', port: 5432 } };
const result = tomlConverter.convert({ data }, tomlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toMatch(/\[db\]|db\.host/);
});
it('sorts keys when sortKeys=true', () => {
const data = { zebra: 1, apple: 2, mango: 3 };
const result = tomlConverter.convert(
{ data },
{ ...tomlConverter.defaultOptions, sortKeys: true },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
const appleIdx = result.output.indexOf('apple');
const mangoIdx = result.output.indexOf('mango');
const zebraIdx = result.output.indexOf('zebra');
expect(appleIdx).toBeLessThan(mangoIdx);
expect(mangoIdx).toBeLessThan(zebraIdx);
});
});
+89
View File
@@ -0,0 +1,89 @@
import { describe, expect, it } from 'vitest';
import { XMLParser } from 'fast-xml-parser';
import { xmlConverter } from '../xml';
describe('xmlConverter', () => {
it('wraps an object under the root element', () => {
const data = { name: 'JSONPrism', version: 1 };
const result = xmlConverter.convert({ data }, xmlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<root>');
expect(result.output).toContain('<name>JSONPrism</name>');
expect(result.output).toContain('<version>1</version>');
expect(result.output).toContain('</root>');
});
it('wraps an array using itemName', () => {
const data = [1, 2, 3];
const result = xmlConverter.convert({ data }, xmlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<item>1</item>');
expect(result.output).toContain('<item>2</item>');
expect(result.output).toContain('<item>3</item>');
});
it('emits the XML declaration when enabled', () => {
const data = { a: 1 };
const result = xmlConverter.convert({ data }, { ...xmlConverter.defaultOptions, declaration: true });
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(true);
});
it('omits the declaration when disabled', () => {
const data = { a: 1 };
const result = xmlConverter.convert(
{ data },
{ ...xmlConverter.defaultOptions, declaration: false },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output.startsWith('<?xml')).toBe(false);
});
it('respects custom rootName and itemName', () => {
const data = [{ id: 1 }];
const result = xmlConverter.convert(
{ data },
{ ...xmlConverter.defaultOptions, rootName: 'games', itemName: 'game' },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('<games>');
expect(result.output).toContain('<game>');
expect(result.output).toContain('<id>1</id>');
});
it('round-trips simple objects through fast-xml-parser', () => {
const data = { name: 'Alice', age: 30 };
const result = xmlConverter.convert({ data }, xmlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const parser = new XMLParser();
const parsed = parser.parse(result.output) as { root: { name: string; age: number } };
expect(parsed.root.name).toBe('Alice');
expect(parsed.root.age).toBe(30);
});
it('supports attributes via @_ prefix', () => {
const data = { person: { '@_id': '1', name: 'Alice' } };
const result = xmlConverter.convert({ data }, xmlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('id="1"');
expect(result.output).toContain('<name>Alice</name>');
});
it('respects indent=0 for compact output', () => {
const data = { a: 1, b: 2 };
const result = xmlConverter.convert(
{ data },
{ ...xmlConverter.defaultOptions, indent: 0, declaration: false },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).not.toContain('\n '); // no indentation
});
});
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from 'vitest';
import yaml from 'js-yaml';
import { yamlConverter } from '../yaml';
describe('yamlConverter', () => {
it('serializes objects to block-style YAML', () => {
const data = { name: 'JSONPrism', version: 1 };
const result = yamlConverter.convert({ data }, yamlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('name: JSONPrism');
expect(result.output).toContain('version: 1');
});
it('round-trips through js-yaml parse', () => {
const data = { a: 1, b: [1, 2, 3], c: { d: 'x' } };
const result = yamlConverter.convert({ data }, yamlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
const parsed = yaml.load(result.output);
expect(parsed).toEqual(data);
});
it('respects indent setting', () => {
const data = { nested: { deeply: { value: 1 } } };
const result = yamlConverter.convert(
{ data },
{ ...yamlConverter.defaultOptions, indent: 4 },
);
expect(result.ok).toBe(true);
if (!result.ok) return;
// Indent of 4 spaces should appear before "deeply"
expect(result.output).toMatch(/\n {4}deeply:/);
});
it('handles arrays of scalars', () => {
const data = ['a', 'b', 'c'];
const result = yamlConverter.convert({ data }, yamlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('- a');
expect(result.output).toContain('- b');
expect(result.output).toContain('- c');
});
it('serializes null without crashing', () => {
const data = { x: null };
const result = yamlConverter.convert({ data }, yamlConverter.defaultOptions);
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.output).toContain('x: null');
});
});
+111
View File
@@ -0,0 +1,111 @@
import Papa from 'papaparse';
import type { Converter } from './types';
interface CsvOptions {
delimiter: ',' | '\t';
/** Include header row from object keys. */
header: boolean;
/** Newline sequence. */
newline: '\n' | '\r\n';
/** How to serialize nested objects/arrays in cells. */
nestedStrategy: 'json' | 'flatten';
}
function tabularizeForCsv(data: unknown, strategy: 'json' | 'flatten'): Array<Record<string, unknown>> {
if (!Array.isArray(data)) {
throw new Error('CSV/TSV requires the root value to be an array of objects.');
}
return data.map((row, i) => {
if (row === null || typeof row !== 'object' || Array.isArray(row)) {
throw new Error(`Row ${i} is not an object — CSV requires objects.`);
}
const obj = row as Record<string, unknown>;
const out: Record<string, unknown> = {};
for (const [k, v] of Object.entries(obj)) {
if (v !== null && typeof v === 'object') {
out[k] = strategy === 'json' ? JSON.stringify(v) : flatten(v, k, out);
} else {
out[k] = v;
}
}
return out;
});
}
function flatten(value: unknown, prefix: string, out: Record<string, unknown>): unknown {
if (value === null || typeof value !== 'object') {
out[prefix] = value;
return value;
}
if (Array.isArray(value)) {
out[prefix] = JSON.stringify(value); // arrays still get stringified for now
return value;
}
for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
flatten(v, `${prefix}.${k}`, out);
}
return '';
}
function makeCsv(delimiter: ',' | '\t'): Converter<CsvOptions> {
return {
meta: {
id: delimiter === ',' ? 'csv' : 'tsv',
labelKey: delimiter === ',' ? 'formats.csv' : 'formats.tsv',
extension: delimiter === ',' ? 'csv' : 'tsv',
mimeType: delimiter === ',' ? 'text/csv' : 'text/tab-separated-values',
phase: 1,
ready: true,
},
defaultOptions: {
delimiter,
header: true,
newline: '\n',
nestedStrategy: 'json',
},
optionSchema: [
{
type: 'boolean',
key: 'header',
labelKey: 'options.csv.header',
descriptionKey: 'options.csv.header_desc',
},
{
type: 'enum',
key: 'newline',
labelKey: 'options.csv.newline',
choices: [
{ value: '\n', labelKey: 'options.csv.newline_lf' },
{ value: '\r\n', labelKey: 'options.csv.newline_crlf' },
],
},
{
type: 'enum',
key: 'nestedStrategy',
labelKey: 'options.csv.nested_strategy',
descriptionKey: 'options.csv.nested_strategy_desc',
choices: [
{ value: 'json', labelKey: 'options.csv.nested_json' },
{ value: 'flatten', labelKey: 'options.csv.nested_flatten' },
],
},
],
convert({ data }, opts) {
try {
const rows = tabularizeForCsv(data, opts.nestedStrategy);
const output = Papa.unparse(rows, {
delimiter: opts.delimiter,
header: opts.header,
newline: opts.newline,
quotes: false,
});
return { ok: true, output };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
}
export const csvConverter = makeCsv(',');
export const tsvConverter = makeCsv('\t');
+42
View File
@@ -0,0 +1,42 @@
import type { Converter } from './types';
interface JsonlOptions {
/** Pretty-print each line? Usually false (canonical JSONL is one-line-per-record). */
pretty: boolean;
}
export const jsonlConverter: Converter<JsonlOptions> = {
meta: {
id: 'jsonl',
labelKey: 'formats.jsonl',
extension: 'jsonl',
mimeType: 'application/x-ndjson',
phase: 1,
ready: true,
},
defaultOptions: { pretty: false },
optionSchema: [
{
type: 'boolean',
key: 'pretty',
labelKey: 'options.jsonl.pretty',
descriptionKey: 'options.jsonl.pretty_desc',
},
],
convert({ data }, { pretty }) {
if (!Array.isArray(data)) {
return {
ok: false,
error: 'JSONL requires the root value to be an array. Wrap your object in [] first.',
};
}
try {
const lines = data.map((row) =>
pretty ? JSON.stringify(row, null, 2) : JSON.stringify(row),
);
return { ok: true, output: lines.join('\n') + '\n' };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
+115
View File
@@ -0,0 +1,115 @@
import type { Converter } from './types';
type Alignment = 'left' | 'center' | 'right' | 'none';
interface MarkdownOptions {
alignment: Alignment;
escapePipes: boolean;
}
export const markdownConverter: Converter<MarkdownOptions> = {
meta: {
id: 'markdown',
labelKey: 'formats.markdown',
extension: 'md',
mimeType: 'text/markdown',
phase: 2,
ready: true,
},
defaultOptions: {
alignment: 'left',
escapePipes: true,
},
optionSchema: [
{
type: 'enum',
key: 'alignment',
labelKey: 'options.markdown.alignment',
choices: [
{ value: 'left', labelKey: 'options.markdown.align_left' },
{ value: 'center', labelKey: 'options.markdown.align_center' },
{ value: 'right', labelKey: 'options.markdown.align_right' },
{ value: 'none', labelKey: 'options.markdown.align_none' },
],
},
{
type: 'boolean',
key: 'escapePipes',
labelKey: 'options.markdown.escape_pipes',
descriptionKey: 'options.markdown.escape_pipes_desc',
},
],
convert({ data }, opts) {
if (!Array.isArray(data)) {
return {
ok: false,
error: 'Markdown table requires the root value to be an array of objects.',
};
}
if (data.length === 0) {
return { ok: true, output: '' };
}
for (let i = 0; i < data.length; i++) {
const row = data[i];
if (row === null || typeof row !== 'object' || Array.isArray(row)) {
return {
ok: false,
error: `Row ${i} is not an object — Markdown table requires objects.`,
};
}
}
// Collect keys preserving insertion order from first occurrence.
const keys: string[] = [];
const seen = new Set<string>();
for (const row of data) {
for (const k of Object.keys(row as Record<string, unknown>)) {
if (!seen.has(k)) {
seen.add(k);
keys.push(k);
}
}
}
const headerCells = keys.map((k) => formatCell(k, opts.escapePipes));
const header = `| ${headerCells.join(' | ')} |`;
const sep = alignmentSeparator(opts.alignment);
const alignRow = `| ${keys.map(() => sep).join(' | ')} |`;
const dataRows = data.map((row) => {
const obj = row as Record<string, unknown>;
const cells = keys.map((k) => formatCell(obj[k], opts.escapePipes));
return `| ${cells.join(' | ')} |`;
});
return { ok: true, output: [header, alignRow, ...dataRows].join('\n') + '\n' };
},
};
function alignmentSeparator(alignment: Alignment): string {
switch (alignment) {
case 'left':
return ':---';
case 'center':
return ':---:';
case 'right':
return '---:';
case 'none':
return '---';
}
}
function formatCell(value: unknown, escapePipes: boolean): string {
if (value === undefined || value === null) return '';
let str: string;
if (typeof value === 'object') {
str = JSON.stringify(value);
} else {
str = String(value);
}
// GFM convention: line breaks inside cells become <br>.
str = str.replace(/\r?\n/g, '<br>');
if (escapePipes) {
str = str.replace(/\|/g, '\\|');
}
return str;
}
+41
View File
@@ -0,0 +1,41 @@
import type { Converter, FormatId } from './types';
import { jsonlConverter } from './jsonl';
import { csvConverter, tsvConverter } from './csv';
import { yamlConverter } from './yaml';
import { xmlConverter } from './xml';
import { tomlConverter } from './toml';
import { resxConverter } from './resx';
import { markdownConverter } from './markdown';
import { sqlConverter } from './sql';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const CONVERTERS: Record<FormatId, Converter<any>> = {
jsonl: jsonlConverter,
csv: csvConverter,
tsv: tsvConverter,
yaml: yamlConverter,
xml: xmlConverter,
toml: tomlConverter,
resx: resxConverter,
markdown: markdownConverter,
sql: sqlConverter,
};
export const ALL_FORMATS: FormatId[] = [
'jsonl',
'csv',
'tsv',
'yaml',
'xml',
'toml',
'resx',
'markdown',
'sql',
];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function getConverter(id: FormatId): Converter<any> {
const c = CONVERTERS[id];
if (!c) throw new Error(`Unknown converter: ${id}`);
return c;
}
+210
View File
@@ -0,0 +1,210 @@
import type { Converter } from './types';
interface ResxOptions {
/**
* If a value is an object with this key, its sibling `value` is used
* as the resource and this key's value becomes the `<comment>` element.
* Example with default `_comment`:
* `{ "WelcomeMsg": { "value": "Hi", "_comment": "Greeting" } }`
*/
commentKey: string;
/** Emit the standard xsd:schema header. Visual Studio expects it. */
includeSchema: boolean;
/** Sort entries alphabetically — useful for stable diffs across locales. */
sortKeys: boolean;
}
/**
* Standard RESX 2.0 schema header. Bytes are aligned with output produced by
* Visual Studio's .resx editor so round-tripping doesn't churn diffs.
*
* Source: https://learn.microsoft.com/en-us/dotnet/framework/resources/working-with-resx-files-programmatically
*/
const RESX_SCHEMA_HEADER = ` <!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format are to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true" msdata:UseCurrentLocale="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>`;
export const resxConverter: Converter<ResxOptions> = {
meta: {
id: 'resx',
labelKey: 'formats.resx',
extension: 'resx',
mimeType: 'application/xml',
phase: 3,
ready: true,
},
defaultOptions: {
commentKey: '_comment',
includeSchema: true,
sortKeys: false,
},
optionSchema: [
{
type: 'string',
key: 'commentKey',
labelKey: 'options.resx.comment_key',
descriptionKey: 'options.resx.comment_key_desc',
placeholder: '_comment',
},
{
type: 'boolean',
key: 'includeSchema',
labelKey: 'options.resx.include_schema',
descriptionKey: 'options.resx.include_schema_desc',
},
{
type: 'boolean',
key: 'sortKeys',
labelKey: 'options.resx.sort_keys',
descriptionKey: 'options.resx.sort_keys_desc',
},
],
convert({ data }, opts) {
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
return {
ok: false,
error:
'RESX requires a flat object of `{ "Key": "value" }` entries. Wrap arrays in an object first.',
};
}
const entries: Array<{ key: string; value: string; comment?: string }> = [];
for (const [key, raw] of Object.entries(data as Record<string, unknown>)) {
if (typeof raw === 'string' || typeof raw === 'number' || typeof raw === 'boolean') {
entries.push({ key, value: String(raw) });
continue;
}
if (raw === null || raw === undefined) {
entries.push({ key, value: '' });
continue;
}
if (
typeof raw === 'object' &&
!Array.isArray(raw) &&
'value' in raw &&
typeof (raw as { value: unknown }).value !== 'object'
) {
// { "value": "...", "_comment": "..." } shape
const obj = raw as Record<string, unknown>;
const value = String(obj.value ?? '');
const commentRaw = obj[opts.commentKey];
const comment =
typeof commentRaw === 'string' || typeof commentRaw === 'number'
? String(commentRaw)
: undefined;
entries.push({ key, value, ...(comment !== undefined ? { comment } : {}) });
continue;
}
return {
ok: false,
error: `Key "${key}" has a nested value. RESX requires flat string entries. Flatten nested objects or use the { value, _comment } shape.`,
};
}
if (opts.sortKeys) {
entries.sort((a, b) => a.key.localeCompare(b.key));
}
return { ok: true, output: buildResx(entries, opts) };
},
};
function buildResx(
entries: Array<{ key: string; value: string; comment?: string }>,
opts: ResxOptions,
): string {
const parts: string[] = [];
parts.push('<?xml version="1.0" encoding="utf-8"?>');
parts.push('<root>');
if (opts.includeSchema) {
parts.push(RESX_SCHEMA_HEADER);
}
for (const e of entries) {
parts.push(` <data name="${escapeAttr(e.key)}" xml:space="preserve">`);
parts.push(` <value>${escapeText(e.value)}</value>`);
if (e.comment !== undefined) {
parts.push(` <comment>${escapeText(e.comment)}</comment>`);
}
parts.push(' </data>');
}
parts.push('</root>');
return parts.join('\n') + '\n';
}
export function escapeText(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
export function escapeAttr(s: string): string {
return s
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
+241
View File
@@ -0,0 +1,241 @@
import type { Converter } from './types';
export type SqlDialect = 'standard' | 'postgres' | 'mysql' | 'sqlite' | 'mssql';
interface SqlOptions {
tableName: string;
dialect: SqlDialect;
/** Multi-row INSERT (one statement per chunk) vs single-row INSERT per record. */
multiRow: boolean;
/** Chunk size when multiRow is true. */
chunkSize: number;
/** Emit a CREATE TABLE statement inferred from the first row's types. */
includeCreate: boolean;
}
export const sqlConverter: Converter<SqlOptions> = {
meta: {
id: 'sql',
labelKey: 'formats.sql',
extension: 'sql',
mimeType: 'application/sql',
phase: 2,
ready: true,
},
defaultOptions: {
tableName: 'records',
dialect: 'standard',
multiRow: true,
chunkSize: 100,
includeCreate: false,
},
optionSchema: [
{
type: 'string',
key: 'tableName',
labelKey: 'options.sql.table_name',
placeholder: 'records',
},
{
type: 'enum',
key: 'dialect',
labelKey: 'options.sql.dialect',
choices: [
{ value: 'standard', labelKey: 'options.sql.dialect_standard' },
{ value: 'postgres', labelKey: 'options.sql.dialect_postgres' },
{ value: 'mysql', labelKey: 'options.sql.dialect_mysql' },
{ value: 'sqlite', labelKey: 'options.sql.dialect_sqlite' },
{ value: 'mssql', labelKey: 'options.sql.dialect_mssql' },
],
},
{
type: 'boolean',
key: 'multiRow',
labelKey: 'options.sql.multi_row',
descriptionKey: 'options.sql.multi_row_desc',
},
{
type: 'integer',
key: 'chunkSize',
labelKey: 'options.sql.chunk_size',
descriptionKey: 'options.sql.chunk_size_desc',
min: 1,
max: 10000,
},
{
type: 'boolean',
key: 'includeCreate',
labelKey: 'options.sql.include_create',
descriptionKey: 'options.sql.include_create_desc',
},
],
convert({ data }, opts) {
if (!Array.isArray(data)) {
return {
ok: false,
error: 'SQL INSERT requires the root value to be an array of objects.',
};
}
if (data.length === 0) {
return { ok: true, output: '-- No data rows.\n' };
}
for (let i = 0; i < data.length; i++) {
const row = data[i];
if (row === null || typeof row !== 'object' || Array.isArray(row)) {
return {
ok: false,
error: `Row ${i} is not an object — SQL INSERT requires objects.`,
};
}
}
try {
// Collect keys preserving insertion order across all rows.
const keys: string[] = [];
const seen = new Set<string>();
for (const row of data) {
for (const k of Object.keys(row as Record<string, unknown>)) {
if (!seen.has(k)) {
seen.add(k);
keys.push(k);
}
}
}
const quoteId = (name: string) => quoteIdentifier(name, opts.dialect);
const tableId = quoteId(opts.tableName);
const cols = keys.map(quoteId).join(', ');
const parts: string[] = [];
if (opts.includeCreate) {
const first = data[0] as Record<string, unknown>;
const colDefs = keys.map((k) => ` ${quoteId(k)} ${inferSqlType(first[k], opts.dialect)}`);
parts.push(`CREATE TABLE ${tableId} (\n${colDefs.join(',\n')}\n);`);
parts.push('');
}
if (opts.multiRow) {
const chunkSize = Math.max(1, opts.chunkSize | 0);
for (let chunkStart = 0; chunkStart < data.length; chunkStart += chunkSize) {
const chunk = data.slice(chunkStart, chunkStart + chunkSize);
const valueRows = chunk.map((row) => {
const obj = row as Record<string, unknown>;
const values = keys.map((k) => formatSqlValue(obj[k], opts.dialect));
return ` (${values.join(', ')})`;
});
parts.push(`INSERT INTO ${tableId} (${cols}) VALUES\n${valueRows.join(',\n')};`);
}
} else {
for (const row of data) {
const obj = row as Record<string, unknown>;
const values = keys.map((k) => formatSqlValue(obj[k], opts.dialect));
parts.push(`INSERT INTO ${tableId} (${cols}) VALUES (${values.join(', ')});`);
}
}
return { ok: true, output: parts.join('\n') + '\n' };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
// ---------------------------------------------------------------------------
// Dialect-aware helpers (exported for testing)
// ---------------------------------------------------------------------------
export function quoteIdentifier(name: string, dialect: SqlDialect): string {
switch (dialect) {
case 'mysql':
return '`' + name.replace(/`/g, '``') + '`';
case 'mssql':
return '[' + name.replace(/]/g, ']]') + ']';
case 'standard':
case 'postgres':
case 'sqlite':
default:
return '"' + name.replace(/"/g, '""') + '"';
}
}
export function formatSqlValue(value: unknown, dialect: SqlDialect): string {
if (value === null || value === undefined) return 'NULL';
if (typeof value === 'boolean') {
switch (dialect) {
case 'standard':
case 'postgres':
return value ? 'TRUE' : 'FALSE';
case 'mysql':
case 'sqlite':
case 'mssql':
return value ? '1' : '0';
}
}
if (typeof value === 'number') {
if (!Number.isFinite(value)) return 'NULL';
return String(value);
}
if (typeof value === 'bigint') {
return value.toString();
}
if (typeof value === 'string') {
return "'" + escapeSqlString(value) + "'";
}
if (typeof value === 'object') {
return "'" + escapeSqlString(JSON.stringify(value)) + "'";
}
return "'" + escapeSqlString(String(value)) + "'";
}
export function inferSqlType(value: unknown, dialect: SqlDialect): string {
if (value === null || value === undefined) return 'TEXT NULL';
if (typeof value === 'boolean') {
switch (dialect) {
case 'standard':
case 'postgres':
return 'BOOLEAN';
case 'mysql':
return 'TINYINT(1)';
case 'mssql':
return 'BIT';
case 'sqlite':
return 'INTEGER';
}
}
if (typeof value === 'number') {
if (Number.isInteger(value)) return 'INTEGER';
switch (dialect) {
case 'standard':
case 'postgres':
return 'DOUBLE PRECISION';
case 'mysql':
case 'sqlite':
return 'DOUBLE';
case 'mssql':
return 'FLOAT';
}
}
if (typeof value === 'object') {
switch (dialect) {
case 'postgres':
return 'JSONB';
case 'mysql':
return 'JSON';
default:
return 'TEXT';
}
}
// string fallback
switch (dialect) {
case 'mysql':
case 'mssql':
return 'VARCHAR(255)';
default:
return 'TEXT';
}
}
function escapeSqlString(s: string): string {
return s.replace(/'/g, "''");
}
+57
View File
@@ -0,0 +1,57 @@
import { stringify } from 'smol-toml';
import type { Converter } from './types';
interface TomlOptions {
/** Sort keys alphabetically (recursive). Useful for diffs. */
sortKeys: boolean;
}
export const tomlConverter: Converter<TomlOptions> = {
meta: {
id: 'toml',
labelKey: 'formats.toml',
extension: 'toml',
mimeType: 'application/toml',
phase: 2,
ready: true,
},
defaultOptions: {
sortKeys: false,
},
optionSchema: [
{
type: 'boolean',
key: 'sortKeys',
labelKey: 'options.toml.sort_keys',
descriptionKey: 'options.toml.sort_keys_desc',
},
],
convert({ data }, opts) {
if (data === null || typeof data !== 'object' || Array.isArray(data)) {
return {
ok: false,
error: 'TOML requires the root value to be a plain object (table).',
};
}
try {
const processed = opts.sortKeys ? sortKeysRecursive(data) : data;
// smol-toml's stringify signature accepts a TOML-compatible object.
// We cast through unknown because the library types are strict.
const output = stringify(processed as Parameters<typeof stringify>[0]);
return { ok: true, output };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
function sortKeysRecursive(value: unknown): unknown {
if (value === null || typeof value !== 'object') return value;
if (Array.isArray(value)) return value.map(sortKeysRecursive);
const obj = value as Record<string, unknown>;
const sorted: Record<string, unknown> = {};
for (const k of Object.keys(obj).sort()) {
sorted[k] = sortKeysRecursive(obj[k]);
}
return sorted;
}
+82
View File
@@ -0,0 +1,82 @@
/**
* Converter framework.
*
* Every target format implements `Converter<TOptions>`. The framework
* handles parsing JSON, dispatching to the converter, surfacing
* errors uniformly, and auto-generating the settings UI from
* `optionSchema`.
*/
export type FormatId =
| 'jsonl'
| 'csv'
| 'tsv'
| 'yaml'
| 'xml'
| 'toml'
| 'resx'
| 'markdown'
| 'sql';
export type ImplementationPhase = 1 | 2 | 3;
export interface ConverterMeta {
id: FormatId;
labelKey: string;
extension: string;
mimeType: string;
phase: ImplementationPhase;
ready: boolean;
}
export interface ConversionInput {
data: unknown;
rawText?: string;
sourceName?: string;
}
export type ConversionResult =
| { ok: true; output: string }
| { ok: false; error: string };
/**
* Schema describing a single option field, used by the settings UI
* to auto-render the right form widget.
*/
export type OptionSchemaField<TOptions> =
| {
type: 'boolean';
key: keyof TOptions & string;
labelKey: string;
descriptionKey?: string;
}
| {
type: 'enum';
key: keyof TOptions & string;
labelKey: string;
descriptionKey?: string;
choices: ReadonlyArray<{ value: string; labelKey: string }>;
}
| {
type: 'integer';
key: keyof TOptions & string;
labelKey: string;
descriptionKey?: string;
min?: number;
max?: number;
}
| {
type: 'string';
key: keyof TOptions & string;
labelKey: string;
descriptionKey?: string;
placeholder?: string;
};
export interface Converter<TOptions = Record<string, never>> {
meta: ConverterMeta;
defaultOptions: TOptions;
/** Schema for auto-generating the settings UI. Empty for stub converters. */
optionSchema: ReadonlyArray<OptionSchemaField<TOptions>>;
convert(input: ConversionInput, options: TOptions): ConversionResult;
}
+95
View File
@@ -0,0 +1,95 @@
import { XMLBuilder } from 'fast-xml-parser';
import type { Converter } from './types';
interface XmlOptions {
/** Indentation width in spaces (0 = compact, no newlines). */
indent: number;
/** Tag name for the wrapping root element. */
rootName: string;
/** Tag name for array items when the array is at the root or nameless. */
itemName: string;
/** Emit `<?xml version="1.0" encoding="UTF-8"?>` declaration. */
declaration: boolean;
}
/**
* Attribute convention: object keys starting with `@_` are emitted as
* attributes on the parent element (fast-xml-parser default).
* Example:
* `{ person: { "@_id": "1", name: "Alice" } }`
* → `<person id="1"><name>Alice</name></person>`
*/
export const xmlConverter: Converter<XmlOptions> = {
meta: {
id: 'xml',
labelKey: 'formats.xml',
extension: 'xml',
mimeType: 'application/xml',
phase: 2,
ready: true,
},
defaultOptions: {
indent: 2,
rootName: 'root',
itemName: 'item',
declaration: true,
},
optionSchema: [
{
type: 'integer',
key: 'indent',
labelKey: 'options.xml.indent',
min: 0,
max: 8,
},
{
type: 'string',
key: 'rootName',
labelKey: 'options.xml.root_name',
placeholder: 'root',
},
{
type: 'string',
key: 'itemName',
labelKey: 'options.xml.item_name',
descriptionKey: 'options.xml.item_name_desc',
placeholder: 'item',
},
{
type: 'boolean',
key: 'declaration',
labelKey: 'options.xml.declaration',
descriptionKey: 'options.xml.declaration_desc',
},
],
convert({ data }, opts) {
try {
const wrapped = wrapForXml(data, opts.rootName, opts.itemName);
const builder = new XMLBuilder({
format: opts.indent > 0,
indentBy: ' '.repeat(opts.indent),
ignoreAttributes: false,
attributeNamePrefix: '@_',
textNodeName: '#text',
suppressEmptyNode: false,
});
const xml = builder.build(wrapped) as string;
const decl = opts.declaration ? '<?xml version="1.0" encoding="UTF-8"?>\n' : '';
// fast-xml-parser sometimes omits trailing newline; normalize.
const body = xml.endsWith('\n') ? xml : xml + '\n';
return { ok: true, output: decl + body };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
function wrapForXml(data: unknown, rootName: string, itemName: string): Record<string, unknown> {
if (Array.isArray(data)) {
return { [rootName]: { [itemName]: data } };
}
if (data === null || typeof data !== 'object') {
return { [rootName]: data };
}
return { [rootName]: data };
}
+63
View File
@@ -0,0 +1,63 @@
import yaml from 'js-yaml';
import type { Converter } from './types';
interface YamlOptions {
indent: number;
/** Use flow style for collections? Block is the default and more readable. */
flowLevel: number; // -1 = always block, 0 = flow at root, etc.
/** Quote style for strings. */
quoteStyle: 'auto' | 'single' | 'double';
}
export const yamlConverter: Converter<YamlOptions> = {
meta: {
id: 'yaml',
labelKey: 'formats.yaml',
extension: 'yaml',
mimeType: 'application/yaml',
phase: 1,
ready: true,
},
defaultOptions: {
indent: 2,
flowLevel: -1,
quoteStyle: 'auto',
},
optionSchema: [
{
type: 'integer',
key: 'indent',
labelKey: 'options.yaml.indent',
min: 2,
max: 8,
},
{
type: 'enum',
key: 'quoteStyle',
labelKey: 'options.yaml.quote_style',
choices: [
{ value: 'auto', labelKey: 'options.yaml.quote_auto' },
{ value: 'single', labelKey: 'options.yaml.quote_single' },
{ value: 'double', labelKey: 'options.yaml.quote_double' },
],
},
],
convert({ data }, opts) {
try {
const output = yaml.dump(data, {
indent: opts.indent,
flowLevel: opts.flowLevel,
styles: {
// No-op for now; quote style hook reserved for Phase 1 polish.
},
forceQuotes: opts.quoteStyle === 'double',
quotingType: opts.quoteStyle === 'single' ? "'" : '"',
noRefs: true,
sortKeys: false,
});
return { ok: true, output };
} catch (err) {
return { ok: false, error: (err as Error).message };
}
},
};
+49
View File
@@ -0,0 +1,49 @@
import { useEffect } from 'react';
export interface ShortcutDef {
key: string; // lowercase key, e.g. 'k', 's', '/'
mod?: boolean; // require Ctrl (Win/Linux) or Cmd (macOS)
shift?: boolean;
preventDefault?: boolean;
handler: () => void;
}
function isMac(): boolean {
if (typeof navigator === 'undefined') return false;
return /Mac|iPhone|iPad/.test(navigator.platform);
}
export function useKeyboardShortcuts(shortcuts: ShortcutDef[]): void {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
// Skip if user is typing in editable text — except for Mod-prefixed.
const target = e.target as HTMLElement | null;
const inEditable =
!!target &&
(target.tagName === 'INPUT' ||
target.tagName === 'TEXTAREA' ||
target.isContentEditable ||
// CodeMirror's contenteditable element
target.closest('.cm-editor') !== null);
for (const s of shortcuts) {
if (e.key.toLowerCase() !== s.key.toLowerCase()) continue;
const wantMod = s.mod === true;
const modPressed = isMac() ? e.metaKey : e.ctrlKey;
if (wantMod !== modPressed) continue;
if ((s.shift ?? false) !== e.shiftKey) continue;
// If non-mod shortcut and user is in editable, skip.
if (!wantMod && inEditable) continue;
if (s.preventDefault ?? true) e.preventDefault();
s.handler();
return;
}
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [shortcuts]);
}
export function modKey(): 'Cmd' | 'Ctrl' {
return isMac() ? 'Cmd' : 'Ctrl';
}
+58
View File
@@ -0,0 +1,58 @@
import { useCallback, useEffect, useState } from 'react';
/**
* React hook for persistent state in localStorage.
* Survives reload; synced across tabs via `storage` event.
*/
export function useLocalStorage<T>(
key: string,
initialValue: T,
): [T, (value: T | ((prev: T) => T)) => void] {
const read = useCallback((): T => {
if (typeof window === 'undefined') return initialValue;
try {
const raw = window.localStorage.getItem(key);
if (raw === null) return initialValue;
return JSON.parse(raw) as T;
} catch {
return initialValue;
}
}, [key, initialValue]);
const [stored, setStored] = useState<T>(read);
const setValue = useCallback(
(value: T | ((prev: T) => T)) => {
setStored((prev) => {
const next = typeof value === 'function' ? (value as (p: T) => T)(prev) : value;
try {
window.localStorage.setItem(key, JSON.stringify(next));
} catch {
/* quota errors are non-fatal */
}
return next;
});
},
[key],
);
// Cross-tab sync
useEffect(() => {
const handler = (e: StorageEvent) => {
if (e.key !== key) return;
if (e.newValue === null) {
setStored(initialValue);
return;
}
try {
setStored(JSON.parse(e.newValue) as T);
} catch {
/* ignore malformed */
}
};
window.addEventListener('storage', handler);
return () => window.removeEventListener('storage', handler);
}, [key, initialValue]);
return [stored, setValue];
}
+42
View File
@@ -0,0 +1,42 @@
import { useEffect } from 'react';
import { fileFromNativePath, isTauri } from '@/lib/tauri';
/**
* Listen for native OS drag-drop events fired by the Tauri webview.
* When files are dropped from File Explorer / Finder / Nautilus,
* Tauri delivers a list of paths; we read them and hand back File
* objects so the existing web-based batch flow can consume them.
*
* No-op outside Tauri.
*/
export function useTauriDragDrop(onFiles: (files: File[]) => void): void {
useEffect(() => {
if (!isTauri()) return;
let unlisten: (() => void) | null = null;
let cancelled = false;
void (async () => {
const { getCurrentWebviewWindow } = await import('@tauri-apps/api/webviewWindow');
const win = getCurrentWebviewWindow();
// Tauri 2 fires `tauri://drag-drop` with payload `{ paths: string[], position }`.
unlisten = await win.listen<{ paths: string[] }>('tauri://drag-drop', async (event) => {
if (cancelled) return;
const paths = event.payload?.paths ?? [];
if (paths.length === 0) return;
try {
const files = await Promise.all(paths.map(fileFromNativePath));
onFiles(files);
} catch (err) {
// eslint-disable-next-line no-console
console.error('Tauri drag-drop read failed:', err);
}
});
})();
return () => {
cancelled = true;
unlisten?.();
};
}, [onFiles]);
}
+26
View File
@@ -0,0 +1,26 @@
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import { initReactI18next } from 'react-i18next';
import en from './locales/en.json';
import vi from './locales/vi.json';
void i18n
.use(LanguageDetector)
.use(initReactI18next)
.init({
resources: {
en: { translation: en },
vi: { translation: vi },
},
fallbackLng: 'en',
supportedLngs: ['en', 'vi'],
interpolation: { escapeValue: false },
detection: {
order: ['localStorage', 'navigator', 'htmlTag'],
caches: ['localStorage'],
lookupLocalStorage: 'jsonprism.lang',
},
});
export default i18n;
+209
View File
@@ -0,0 +1,209 @@
{
"app": {
"name": "JSONPrism",
"tagline": "Disperse JSON into many formats",
"description": "One JSON input. Eight target formats. Fully in your browser."
},
"nav": {
"home": "Convert",
"about": "About",
"github": "GitHub"
},
"home": {
"input_label": "Input JSON",
"input_placeholder": "Paste your JSON here, drop files, or load a sample…",
"output_label": "Output",
"output_empty": "Output will appear here once you provide valid JSON.",
"drop_zone": "Drop JSON files here",
"drop_zone_active": "Drop to load",
"drop_zone_hint": "Up to 500 files. Everything runs in your browser — nothing leaves your device.",
"load_sample": "Sample",
"open_file": "Open",
"clear": "Clear",
"format_picker_label": "Target format",
"convert": "Convert",
"copy": "Copy",
"download": "Download",
"options": "Options"
},
"formats": {
"jsonl": "JSONL",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
"xml": "XML",
"toml": "TOML",
"resx": "RESX",
"markdown": "Markdown table",
"sql": "SQL INSERT"
},
"format_status": {
"ready": "Ready",
"suggested": "Suggested for the detected shape",
"planned": "Coming in Phase {{phase}}"
},
"options": {
"jsonl": {
"pretty": "Pretty-print each line",
"pretty_desc": "Canonical JSONL is single-line. Enable for human-readable multi-line records."
},
"csv": {
"header": "Include header row",
"header_desc": "Emit the first row as column names derived from object keys.",
"newline": "Newline",
"newline_lf": "LF (\\n)",
"newline_crlf": "CRLF (\\r\\n)",
"nested_strategy": "Nested values",
"nested_strategy_desc": "How to handle nested objects/arrays inside cells.",
"nested_json": "JSON-stringify",
"nested_flatten": "Flatten keys (alpha)"
},
"yaml": {
"indent": "Indent (spaces)",
"quote_style": "Quote style",
"quote_auto": "Auto",
"quote_single": "Single",
"quote_double": "Double"
},
"xml": {
"indent": "Indent (spaces)",
"root_name": "Root element name",
"item_name": "Array item element name",
"item_name_desc": "Used for items when the root is an array. Object keys name their own array items.",
"declaration": "Include XML declaration",
"declaration_desc": "Prepend <?xml version=\"1.0\" encoding=\"UTF-8\"?>."
},
"toml": {
"sort_keys": "Sort keys alphabetically",
"sort_keys_desc": "Recursive — applies at every nesting level. Useful for stable diffs."
},
"markdown": {
"alignment": "Column alignment",
"align_left": "Left",
"align_center": "Center",
"align_right": "Right",
"align_none": "None",
"escape_pipes": "Escape pipes in cells",
"escape_pipes_desc": "Replace | with \\| inside cell values so they don't break the table."
},
"sql": {
"table_name": "Table name",
"dialect": "Dialect",
"dialect_standard": "Standard",
"dialect_postgres": "PostgreSQL",
"dialect_mysql": "MySQL",
"dialect_sqlite": "SQLite",
"dialect_mssql": "MS SQL Server",
"multi_row": "Multi-row INSERT",
"multi_row_desc": "Combine rows into a single INSERT statement per chunk.",
"chunk_size": "Chunk size",
"chunk_size_desc": "Maximum rows per INSERT when multi-row is on.",
"include_create": "Include CREATE TABLE",
"include_create_desc": "Infer column types from the first row and emit a CREATE TABLE statement."
},
"resx": {
"comment_key": "Comment key",
"comment_key_desc": "When an entry is shaped as { value, _comment }, this key supplies the <comment> element.",
"include_schema": "Include xsd:schema header",
"include_schema_desc": "Visual Studio expects this. Disable only if you're generating diffs.",
"sort_keys": "Sort entries alphabetically",
"sort_keys_desc": "Useful for stable diffs across locale files."
}
},
"shape": {
"detected": "Detected shape",
"scalar": "scalar",
"object": "object",
"array": "array",
"flat-object": "flat object",
"array-of-objects": "array of objects",
"unknown": "unknown"
},
"status": {
"in": "in",
"out": "out",
"time": "parse"
},
"shortcut": {
"clear": "Clear",
"download": "Download",
"settings": "Settings"
},
"settings": {
"title": "Options",
"description": "Adjust how this format is generated. Settings persist per format.",
"no_options": "No options for this format yet.",
"no_options_long": "This converter doesn't expose any options yet. Once Phase 2 lands, you'll find dialect, indent, and other knobs here.",
"reset": "Reset to defaults"
},
"toast": {
"copied": "Copied {{format}} to clipboard",
"copy_failed": "Couldn't copy to clipboard",
"downloaded": "Downloaded {{filename}}",
"file_loaded": "Loaded {{name}}",
"file_failed": "Failed to load file: {{message}}",
"options_reset": "Options reset to defaults"
},
"batch": {
"trigger": "Batch",
"title": "Batch queue",
"description": "Process multiple JSON files into {{format}} at once. All processing happens in your browser.",
"drop_idle": "Drop JSON files here",
"drop_active": "Release to add files",
"browse": "or click to browse…",
"empty": "No files queued yet. Drop JSON files above to begin.",
"stat": {
"queued": "queued",
"done": "done",
"failed": "failed"
},
"process": "Process",
"cancel": "Cancel",
"clear": "Clear",
"download_zip": "Download .zip",
"row": {
"out": "out",
"remove": "Remove from queue"
},
"toast": {
"added": "Added {{count}} file to the queue",
"added_other": "Added {{count}} files to the queue",
"skipped": "Skipped {{count}} file (limit: {{max}})",
"skipped_other": "Skipped {{count}} files (limit: {{max}})",
"started": "Processing {{count}} file…",
"started_other": "Processing {{count}} files…",
"finished": "Batch complete",
"cancelled": "Batch cancelled",
"failed": "Batch failed: {{message}}",
"zipped": "Packed {{count}} file into a .zip",
"zipped_other": "Packed {{count}} files into a .zip",
"zip_failed": "Could not build .zip: {{message}}",
"nothing_to_process": "Nothing queued to process."
}
},
"theme": {
"light": "Light",
"dark": "Dark",
"system": "System"
},
"errors": {
"invalid_json": "Invalid JSON: {{message}}",
"empty_input": "Input is empty.",
"converter_not_ready": "This converter is not implemented yet.",
"converter_not_ready_phase": "This converter lands in Phase {{phase}}. See the roadmap for status.",
"batch_limit": "Batch limit reached ({{max}} files). Remove some files first.",
"unknown": "Something went wrong. {{message}}"
},
"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. Everything runs client-side, so your data never leaves your device.",
"p2": "Built with React 19, Vite 6, Tailwind CSS v4, and shadcn/ui. Source on GitHub.",
"version": "Version {{version}}"
},
"common": {
"loading": "Loading…",
"error": "Error",
"retry": "Retry"
}
}
+209
View File
@@ -0,0 +1,209 @@
{
"app": {
"name": "JSONPrism",
"tagline": "Tán sắc JSON ra nhiều định dạng",
"description": "Một JSON đầu vào. Tám định dạng đích. Chạy hoàn toàn trong trình duyệt."
},
"nav": {
"home": "Chuyển đổi",
"about": "Giới thiệu",
"github": "GitHub"
},
"home": {
"input_label": "JSON đầu vào",
"input_placeholder": "Dán JSON vào đây, thả file, hoặc nạp mẫu…",
"output_label": "Kết quả",
"output_empty": "Kết quả sẽ hiện ở đây khi bạn cung cấp JSON hợp lệ.",
"drop_zone": "Thả file JSON vào đây",
"drop_zone_active": "Thả ra để nạp",
"drop_zone_hint": "Tối đa 500 file. Mọi thứ chạy trong trình duyệt — không có dữ liệu nào rời khỏi máy của bạn.",
"load_sample": "Mẫu",
"open_file": "Mở",
"clear": "Xoá",
"format_picker_label": "Định dạng đích",
"convert": "Chuyển đổi",
"copy": "Sao chép",
"download": "Tải về",
"options": "Tuỳ chọn"
},
"formats": {
"jsonl": "JSONL",
"csv": "CSV",
"tsv": "TSV",
"yaml": "YAML",
"xml": "XML",
"toml": "TOML",
"resx": "RESX",
"markdown": "Bảng Markdown",
"sql": "SQL INSERT"
},
"format_status": {
"ready": "Sẵn sàng",
"suggested": "Gợi ý cho shape phát hiện được",
"planned": "Sẽ có ở Phase {{phase}}"
},
"options": {
"jsonl": {
"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."
},
"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.",
"newline": "Newline",
"newline_lf": "LF (\\n)",
"newline_crlf": "CRLF (\\r\\n)",
"nested_strategy": "Giá trị lồng nhau",
"nested_strategy_desc": "Cách xử lý object/array lồng nhau trong ô.",
"nested_json": "JSON-stringify",
"nested_flatten": "Flatten key (alpha)"
},
"yaml": {
"indent": "Indent (số space)",
"quote_style": "Kiểu nháy",
"quote_auto": "Tự động",
"quote_single": "Nháy đơn",
"quote_double": "Nháy kép"
},
"xml": {
"indent": "Indent (số space)",
"root_name": "Tên element gốc",
"item_name": "Tên element cho item của mảng",
"item_name_desc": "Dùng cho item khi root là mảng. Object key đặt tên cho array item của chính nó.",
"declaration": "Bao gồm khai báo XML",
"declaration_desc": "Thêm <?xml version=\"1.0\" encoding=\"UTF-8\"?> ở đầu."
},
"toml": {
"sort_keys": "Sắp xếp key theo bảng chữ cái",
"sort_keys_desc": "Đệ quy — áp dụng ở mọi cấp lồng nhau. Hữu ích cho diff ổn định."
},
"markdown": {
"alignment": "Căn cột",
"align_left": "Trái",
"align_center": "Giữa",
"align_right": "Phải",
"align_none": "Không",
"escape_pipes": "Escape ký tự pipe trong ô",
"escape_pipes_desc": "Thay | bằng \\| trong giá trị ô để không phá bảng."
},
"sql": {
"table_name": "Tên bảng",
"dialect": "Dialect",
"dialect_standard": "Chuẩn",
"dialect_postgres": "PostgreSQL",
"dialect_mysql": "MySQL",
"dialect_sqlite": "SQLite",
"dialect_mssql": "MS SQL Server",
"multi_row": "INSERT đa dòng",
"multi_row_desc": "Gộp nhiều dòng vào một câu lệnh INSERT theo chunk.",
"chunk_size": "Kích thước chunk",
"chunk_size_desc": "Số dòng tối đa cho mỗi INSERT khi bật đa dòng.",
"include_create": "Bao gồm CREATE TABLE",
"include_create_desc": "Suy luận kiểu cột từ dòng đầu và phát sinh câu lệnh CREATE TABLE."
},
"resx": {
"comment_key": "Key của comment",
"comment_key_desc": "Khi entry có shape { value, _comment }, key này sẽ cung cấp element <comment>.",
"include_schema": "Bao gồm header xsd:schema",
"include_schema_desc": "Visual Studio yêu cầu. Chỉ tắt khi đang generate diff.",
"sort_keys": "Sắp xếp entry theo bảng chữ cái",
"sort_keys_desc": "Hữu ích để diff ổn định giữa các file locale."
}
},
"shape": {
"detected": "Shape phát hiện",
"scalar": "scalar",
"object": "object",
"array": "mảng",
"flat-object": "object phẳng",
"array-of-objects": "mảng object",
"unknown": "không rõ"
},
"status": {
"in": "vào",
"out": "ra",
"time": "parse"
},
"shortcut": {
"clear": "Xoá",
"download": "Tải về",
"settings": "Tuỳ chọn"
},
"settings": {
"title": "Tuỳ chọn",
"description": "Tinh chỉnh cách format này được tạo. Lưu riêng cho từng format.",
"no_options": "Format này chưa có tuỳ chọn.",
"no_options_long": "Converter này chưa expose tuỳ chọn nào. Khi Phase 2 ra mắt, bạn sẽ thấy dialect, indent và các knob khác ở đây.",
"reset": "Khôi phục mặc định"
},
"toast": {
"copied": "Đã chép {{format}} vào clipboard",
"copy_failed": "Không thể chép vào clipboard",
"downloaded": "Đã tải {{filename}}",
"file_loaded": "Đã nạp {{name}}",
"file_failed": "Không nạp được file: {{message}}",
"options_reset": "Đã khôi phục tuỳ chọn mặc định"
},
"batch": {
"trigger": "Batch",
"title": "Hàng đợi batch",
"description": "Xử lý nhiều file JSON sang {{format}} cùng lúc. Mọi thứ chạy trong trình duyệt.",
"drop_idle": "Thả file JSON vào đây",
"drop_active": "Thả ra để thêm file",
"browse": "hoặc click để duyệt…",
"empty": "Chưa có file nào trong hàng đợi. Thả file JSON ở trên để bắt đầu.",
"stat": {
"queued": "chờ",
"done": "xong",
"failed": "lỗi"
},
"process": "Xử lý",
"cancel": "Huỷ",
"clear": "Xoá",
"download_zip": "Tải .zip",
"row": {
"out": "ra",
"remove": "Bỏ khỏi hàng đợi"
},
"toast": {
"added": "Đã thêm {{count}} file vào hàng đợi",
"added_other": "Đã thêm {{count}} file vào hàng đợi",
"skipped": "Bỏ qua {{count}} file (giới hạn: {{max}})",
"skipped_other": "Bỏ qua {{count}} file (giới hạn: {{max}})",
"started": "Đang xử lý {{count}} file…",
"started_other": "Đang xử lý {{count}} file…",
"finished": "Batch hoàn thành",
"cancelled": "Đã huỷ batch",
"failed": "Batch thất bại: {{message}}",
"zipped": "Đã đóng {{count}} file vào .zip",
"zipped_other": "Đã đóng {{count}} file vào .zip",
"zip_failed": "Không tạo được .zip: {{message}}",
"nothing_to_process": "Không có gì trong hàng đợi để xử lý."
}
},
"theme": {
"light": "Sáng",
"dark": "Tối",
"system": "Theo hệ thống"
},
"errors": {
"invalid_json": "JSON không hợp lệ: {{message}}",
"empty_input": "Đầu vào trống.",
"converter_not_ready": "Converter này chưa được cài đặt.",
"converter_not_ready_phase": "Converter này sẽ có ở Phase {{phase}}. Xem roadmap để biết trạng thái.",
"batch_limit": "Đã đạt giới hạn batch ({{max}} file). Hãy bỏ bớt file.",
"unknown": "Đã có lỗi xảy ra. {{message}}"
},
"about": {
"title": "Về JSONPrism",
"lead": "Một công cụ tán sắc cho developer.",
"p1": "JSONPrism nhận một JSON đầu vào và tán sắc nó ra nhiều định dạng đích — như ánh sáng trắng đi qua lăng kính. Mọi thứ chạy client-side, nên dữ liệu của bạn không bao giờ rời khỏi máy.",
"p2": "Xây dựng với React 19, Vite 6, Tailwind CSS v4 và shadcn/ui. Mã nguồn trên GitHub.",
"version": "Phiên bản {{version}}"
},
"common": {
"loading": "Đang tải…",
"error": "Lỗi",
"retry": "Thử lại"
}
}
+227
View File
@@ -0,0 +1,227 @@
import { describe, expect, it } from 'vitest';
import { unzipSync, strFromU8 } from 'fflate';
import {
outputFilename,
processBatch,
uniquifyFilenames,
zipOutputs,
} from '../batch-processor';
import type { BatchItem } from '@/stores/batchStore';
function makeItem(id: string, name: string, content: string): BatchItem {
return {
id,
file: new File([content], name, { type: 'application/json' }),
filename: name,
size: content.length,
status: 'queued',
};
}
describe('outputFilename', () => {
it('replaces an existing extension', () => {
expect(outputFilename('data.json', 'csv')).toBe('data.csv');
expect(outputFilename('foo.txt', 'yaml')).toBe('foo.yaml');
});
it('appends extension when source has none', () => {
expect(outputFilename('noext', 'csv')).toBe('noext.csv');
});
it('handles dot-prefixed names without losing them', () => {
expect(outputFilename('.config', 'yaml')).toBe('.config.yaml');
});
});
describe('uniquifyFilenames', () => {
it('preserves unique names', () => {
expect(uniquifyFilenames(['a.csv', 'b.csv'])).toEqual(['a.csv', 'b.csv']);
});
it('appends counter suffix on collisions', () => {
expect(uniquifyFilenames(['a.csv', 'a.csv', 'a.csv'])).toEqual([
'a.csv',
'a_2.csv',
'a_3.csv',
]);
});
it('preserves extension when uniquifying', () => {
expect(uniquifyFilenames(['foo.yaml', 'foo.yaml'])).toEqual(['foo.yaml', 'foo_2.yaml']);
});
});
describe('processBatch', () => {
it('runs every item and reports done status', async () => {
const items = [
makeItem('1', 'a.json', '[{"id":1}]'),
makeItem('2', 'b.json', '[{"id":2}]'),
];
const updates: Record<string, Partial<BatchItem>[]> = {};
await processBatch(
items,
'jsonl',
{ pretty: false },
{
onUpdate: (id, patch) => {
(updates[id] ??= []).push(patch);
},
},
new AbortController().signal,
);
expect(updates['1']?.some((p) => p.status === 'done')).toBe(true);
expect(updates['2']?.some((p) => p.status === 'done')).toBe(true);
const final1 = updates['1']!.at(-1)!;
expect(final1.status).toBe('done');
expect(final1.output).toContain('"id":1');
});
it('reports error for invalid JSON but continues processing', async () => {
const items = [
makeItem('bad', 'broken.json', '{not valid'),
makeItem('good', 'good.json', '[{"a":1}]'),
];
const finalStatuses: Record<string, string> = {};
await processBatch(
items,
'jsonl',
{ pretty: false },
{
onUpdate: (id, patch) => {
if (patch.status) finalStatuses[id] = patch.status;
},
},
new AbortController().signal,
);
expect(finalStatuses['bad']).toBe('error');
expect(finalStatuses['good']).toBe('done');
});
it('reports converter-level errors per item', async () => {
const items = [
// JSONL requires array root; passing an object should fail.
makeItem('obj', 'obj.json', '{"a":1}'),
makeItem('arr', 'arr.json', '[{"a":1}]'),
];
const finalStatuses: Record<string, string> = {};
await processBatch(
items,
'jsonl',
{ pretty: false },
{
onUpdate: (id, patch) => {
if (patch.status) finalStatuses[id] = patch.status;
},
},
new AbortController().signal,
);
expect(finalStatuses['obj']).toBe('error');
expect(finalStatuses['arr']).toBe('done');
});
it('aborts mid-batch when signal is triggered', async () => {
const items = Array.from({ length: 10 }, (_, i) =>
makeItem(`i${i}`, `file${i}.json`, '[{"a":1}]'),
);
const controller = new AbortController();
const seen = new Set<string>();
const promise = processBatch(
items,
'jsonl',
{ pretty: false },
{
onUpdate: (id, patch) => {
if (patch.status === 'processing') seen.add(id);
},
},
controller.signal,
);
// Abort almost immediately.
setTimeout(() => controller.abort(), 0);
await promise;
// Should not have processed all 10.
expect(seen.size).toBeLessThan(items.length);
});
it('marks all items as error if converter is not ready', async () => {
const items = [makeItem('1', 'a.json', '{}')];
const updates: Partial<BatchItem>[] = [];
await processBatch(
items,
'resx',
{},
{ onUpdate: (_id, patch) => updates.push(patch) },
new AbortController().signal,
);
expect(updates.some((u) => u.status === 'error')).toBe(true);
});
});
describe('zipOutputs', () => {
it('zips successful outputs only', async () => {
const items: BatchItem[] = [
{
id: '1',
file: new File(['{}'], 'a.json'),
filename: 'a.json',
size: 2,
status: 'done',
output: '{"id":1}\n',
outputSize: 9,
},
{
id: '2',
file: new File(['{}'], 'b.json'),
filename: 'b.json',
size: 2,
status: 'error',
error: 'bad',
},
{
id: '3',
file: new File(['{}'], 'c.json'),
filename: 'c.json',
size: 2,
status: 'done',
output: '{"id":3}\n',
outputSize: 9,
},
];
const { blob, fileCount } = await zipOutputs(items, 'jsonl');
expect(fileCount).toBe(2);
expect(blob.size).toBeGreaterThan(0);
// Decode and verify both files are present with correct content.
const buffer = await blob.arrayBuffer();
const unzipped = unzipSync(new Uint8Array(buffer));
expect(Object.keys(unzipped).sort()).toEqual(['a.jsonl', 'c.jsonl']);
expect(strFromU8(unzipped['a.jsonl']!)).toBe('{"id":1}\n');
});
it('uniquifies filenames inside the zip on collision', async () => {
const items: BatchItem[] = [
{
id: '1',
file: new File(['{}'], 'data.json'),
filename: 'data.json',
size: 2,
status: 'done',
output: 'a\n',
outputSize: 2,
},
{
id: '2',
file: new File(['{}'], 'data.json'),
filename: 'data.json',
size: 2,
status: 'done',
output: 'b\n',
outputSize: 2,
},
];
const { blob } = await zipOutputs(items, 'jsonl');
const buffer = await blob.arrayBuffer();
const unzipped = unzipSync(new Uint8Array(buffer));
expect(Object.keys(unzipped).sort()).toEqual(['data.jsonl', 'data_2.jsonl']);
});
});
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it } from 'vitest';
import { detectShape, parseJsonInput } from '../detect';
describe('detectShape', () => {
it('recognizes scalars', () => {
expect(detectShape(42)).toBe('scalar');
expect(detectShape('hello')).toBe('scalar');
expect(detectShape(true)).toBe('scalar');
expect(detectShape(null)).toBe('scalar');
});
it('recognizes a flat string-valued object', () => {
expect(detectShape({ a: 'x', b: 'y' })).toBe('flat-object');
});
it('recognizes a non-flat object', () => {
expect(detectShape({ a: 1, b: 'y' })).toBe('object');
expect(detectShape({ a: { nested: true } })).toBe('object');
});
it('recognizes a plain array', () => {
expect(detectShape([1, 2, 3])).toBe('array');
expect(detectShape([1, { a: 1 }])).toBe('array');
});
it('recognizes an array of objects', () => {
expect(detectShape([{ a: 1 }, { a: 2 }])).toBe('array-of-objects');
});
it('does not classify empty array as array-of-objects', () => {
expect(detectShape([])).toBe('array');
});
});
describe('parseJsonInput', () => {
it('parses valid JSON and detects shape', () => {
const result = parseJsonInput('[{"a":1}]');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value).toEqual([{ a: 1 }]);
expect(result.shape).toBe('array-of-objects');
});
it('returns ok=false with sentinel "empty" for whitespace-only input', () => {
const result = parseJsonInput(' \n ');
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBe('empty');
});
it('surfaces parse errors with line/column when possible', () => {
const result = parseJsonInput('{\n "bad": }\n}');
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error.length).toBeGreaterThan(0);
// Line should be detected if position is in the error message
if (result.line !== undefined) {
expect(result.line).toBeGreaterThanOrEqual(1);
}
});
it('handles plain string values', () => {
const result = parseJsonInput('"just a string"');
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.value).toBe('just a string');
expect(result.shape).toBe('scalar');
});
});
+37
View File
@@ -0,0 +1,37 @@
import { afterEach, describe, expect, it } from 'vitest';
import { clearOptions, loadOptions, saveOptions } from '../options-storage';
const KEY = 'jsonprism.options.jsonl';
afterEach(() => {
window.localStorage.clear();
});
describe('options-storage', () => {
it('returns defaults when nothing is stored', () => {
const defaults = { pretty: false };
expect(loadOptions('jsonl', defaults)).toEqual(defaults);
});
it('round-trips through saveOptions / loadOptions', () => {
saveOptions('jsonl', { pretty: true });
expect(loadOptions('jsonl', { pretty: false })).toEqual({ pretty: true });
});
it('merges stored options with new default keys', () => {
window.localStorage.setItem(KEY, JSON.stringify({ pretty: true }));
const defaults = { pretty: false, newOption: 'default' };
expect(loadOptions('jsonl', defaults)).toEqual({ pretty: true, newOption: 'default' });
});
it('falls back to defaults when stored value is malformed', () => {
window.localStorage.setItem(KEY, '{not valid json');
expect(loadOptions('jsonl', { pretty: false })).toEqual({ pretty: false });
});
it('clearOptions removes the stored value', () => {
saveOptions('jsonl', { pretty: true });
clearOptions('jsonl');
expect(window.localStorage.getItem(KEY)).toBeNull();
});
});
+48
View File
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'vitest';
import { isFormatSuggested, suggestedFormats } from '../suggestions';
describe('suggestedFormats', () => {
it('flat-object surfaces RESX first', () => {
const list = suggestedFormats('flat-object');
expect(list[0]).toBe('resx');
expect(list).toContain('yaml');
});
it('array-of-objects covers tabular formats', () => {
const list = suggestedFormats('array-of-objects');
expect(list).toEqual(expect.arrayContaining(['jsonl', 'csv', 'tsv', 'markdown', 'sql']));
});
it('object covers document formats but not tabular', () => {
const list = suggestedFormats('object');
expect(list).toContain('yaml');
expect(list).toContain('toml');
expect(list).not.toContain('csv');
expect(list).not.toContain('sql');
});
it('scalar limits to YAML', () => {
expect(suggestedFormats('scalar')).toEqual(['yaml']);
});
it('null/unknown shape returns empty list', () => {
expect(suggestedFormats(null)).toEqual([]);
expect(suggestedFormats('unknown')).toEqual([]);
});
});
describe('isFormatSuggested', () => {
it('is true for matching shape/format pair', () => {
expect(isFormatSuggested('resx', 'flat-object')).toBe(true);
expect(isFormatSuggested('sql', 'array-of-objects')).toBe(true);
});
it('is false for mismatched pair', () => {
expect(isFormatSuggested('sql', 'flat-object')).toBe(false);
expect(isFormatSuggested('resx', 'array-of-objects')).toBe(false);
});
it('is false when shape is null', () => {
expect(isFormatSuggested('resx', null)).toBe(false);
});
});
+174
View File
@@ -0,0 +1,174 @@
import { zip } from 'fflate';
import { getConverter } from '@/converters/registry';
import type { FormatId } from '@/converters/types';
import { parseJsonInput } from './detect';
import type { BatchItem } from '@/stores/batchStore';
export interface ProcessingCallbacks {
onUpdate(id: string, patch: Partial<BatchItem>): void;
/** Optional progress hook called after each item (for UI yield). */
onProgress?(processed: number, total: number): void;
}
/** Yield control to the browser so the UI stays responsive. */
function yieldToUI(): Promise<void> {
return new Promise((resolve) => {
if (typeof requestIdleCallback === 'function') {
requestIdleCallback(() => resolve(), { timeout: 50 });
} else {
setTimeout(resolve, 0);
}
});
}
async function readFileText(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result ?? ''));
reader.onerror = () => reject(new Error(`Cannot read ${file.name}`));
reader.readAsText(file);
});
}
/**
* Process a batch of queued items through the chosen converter.
*
* - Each item is read, parsed, converted, and reported back via callbacks
* - Errors per item don't stop the rest
* - Yields to the UI after every item
* - Cooperatively cancellable via AbortSignal
*/
export async function processBatch(
items: BatchItem[],
format: FormatId,
options: unknown,
callbacks: ProcessingCallbacks,
signal: AbortSignal,
): Promise<void> {
const converter = getConverter(format);
if (!converter.meta.ready) {
for (const item of items) {
callbacks.onUpdate(item.id, {
status: 'error',
error: `Converter "${format}" is not implemented yet.`,
});
}
return;
}
let processed = 0;
for (const item of items) {
if (signal.aborted) return;
callbacks.onUpdate(item.id, { status: 'processing' });
try {
const text = await readFileText(item.file);
if (signal.aborted) return;
const parsed = parseJsonInput(text);
if (!parsed.ok) {
callbacks.onUpdate(item.id, {
status: 'error',
error: parsed.error === 'empty' ? 'Empty file.' : parsed.error,
});
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = converter.convert(
{ data: parsed.value, rawText: text, sourceName: item.filename },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options as any,
);
if (result.ok) {
const outputSize = new TextEncoder().encode(result.output).length;
callbacks.onUpdate(item.id, {
status: 'done',
output: result.output,
outputSize,
error: undefined,
});
} else {
callbacks.onUpdate(item.id, { status: 'error', error: result.error });
}
}
} catch (err) {
callbacks.onUpdate(item.id, { status: 'error', error: (err as Error).message });
}
processed += 1;
callbacks.onProgress?.(processed, items.length);
await yieldToUI();
}
}
/**
* Strip the .json (or .txt) extension from a source filename and replace it
* with the converter's output extension. Falls back to appending if there
* is no extension to strip.
*/
export function outputFilename(sourceName: string, outputExt: string): string {
const dot = sourceName.lastIndexOf('.');
const base = dot > 0 ? sourceName.slice(0, dot) : sourceName;
return `${base}.${outputExt}`;
}
/** De-duplicate filenames inside the zip by appending `_2`, `_3`, etc. */
export function uniquifyFilenames(names: string[]): string[] {
const seen = new Map<string, number>();
const out: string[] = [];
for (const name of names) {
const count = seen.get(name) ?? 0;
if (count === 0) {
out.push(name);
seen.set(name, 1);
} else {
const dot = name.lastIndexOf('.');
const base = dot > 0 ? name.slice(0, dot) : name;
const ext = dot > 0 ? name.slice(dot) : '';
out.push(`${base}_${count + 1}${ext}`);
seen.set(name, count + 1);
}
}
return out;
}
/** Bundle successful conversion outputs into a ZIP blob. */
export async function zipOutputs(
items: BatchItem[],
format: FormatId,
): Promise<{ blob: Blob; fileCount: number }> {
const converter = getConverter(format);
const done = items.filter((i) => i.status === 'done' && i.output !== undefined);
const rawNames = done.map((i) => outputFilename(i.filename, converter.meta.extension));
const uniqueNames = uniquifyFilenames(rawNames);
const filesForZip: Record<string, Uint8Array> = {};
for (let i = 0; i < done.length; i++) {
const item = done[i]!;
const name = uniqueNames[i]!;
filesForZip[name] = new TextEncoder().encode(item.output!);
}
const zipped = await new Promise<Uint8Array>((resolve, reject) => {
zip(filesForZip, { level: 6 }, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});
return {
blob: new Blob([zipped], { type: 'application/zip' }),
fileCount: done.length,
};
}
/** Trigger a browser download of a Blob. */
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
+81
View File
@@ -0,0 +1,81 @@
/**
* JSON validation + shape detection.
*
* Detection tells the UI which converters are "obvious fits":
* - array-of-objects → CSV/TSV/Markdown/SQL/JSONL
* - flat object (string→string) → RESX
* - any object → YAML/TOML/XML
* - any value → YAML/XML
*/
export type JsonShape =
| 'unknown'
| 'scalar'
| 'object'
| 'array'
| 'flat-object'
| 'array-of-objects';
export interface ParseSuccess {
ok: true;
value: unknown;
shape: JsonShape;
}
export interface ParseFailure {
ok: false;
error: string;
line?: number;
column?: number;
}
export type ParseResult = ParseSuccess | ParseFailure;
export function parseJsonInput(text: string): ParseResult {
const trimmed = text.trim();
if (!trimmed) return { ok: false, error: 'empty' };
try {
const value: unknown = JSON.parse(trimmed);
return { ok: true, value, shape: detectShape(value) };
} catch (err) {
const msg = (err as Error).message;
const pos = parsePosition(msg, trimmed);
if (pos !== null) {
return { ok: false, error: msg, line: pos.line, column: pos.column };
}
return { ok: false, error: msg };
}
}
export function detectShape(value: unknown): JsonShape {
if (value === null) return 'scalar';
if (typeof value !== 'object') return 'scalar';
if (Array.isArray(value)) {
if (value.length > 0 && value.every((v) => v !== null && typeof v === 'object' && !Array.isArray(v))) {
return 'array-of-objects';
}
return 'array';
}
// object
const entries = Object.entries(value as Record<string, unknown>);
if (entries.every(([, v]) => typeof v === 'string')) return 'flat-object';
return 'object';
}
function parsePosition(message: string, text: string): { line: number; column: number } | null {
const match = /position\s+(\d+)/i.exec(message);
if (!match) return null;
const pos = Number.parseInt(match[1]!, 10);
if (!Number.isFinite(pos)) return null;
let line = 1;
let col = 1;
for (let i = 0; i < pos && i < text.length; i++) {
if (text[i] === '\n') {
line++;
col = 1;
} else {
col++;
}
}
return { line, column: col };
}
+32
View File
@@ -0,0 +1,32 @@
import type { FormatId } from '@/converters/types';
const PREFIX = 'jsonprism.options.';
export function loadOptions<T>(format: FormatId, defaults: T): T {
if (typeof window === 'undefined') return defaults;
try {
const raw = window.localStorage.getItem(PREFIX + format);
if (!raw) return defaults;
const parsed = JSON.parse(raw) as Partial<T>;
// Shallow-merge so newly-added option keys default correctly.
return { ...defaults, ...parsed };
} catch {
return defaults;
}
}
export function saveOptions<T>(format: FormatId, options: T): void {
try {
window.localStorage.setItem(PREFIX + format, JSON.stringify(options));
} catch {
/* quota / serialization errors are non-fatal */
}
}
export function clearOptions(format: FormatId): void {
try {
window.localStorage.removeItem(PREFIX + format);
} catch {
/* non-fatal */
}
}
+23
View File
@@ -0,0 +1,23 @@
export const SAMPLE_JSON = `[
{
"id": 1,
"name": "Vampire Survivors",
"genre": "Roguelike",
"free": true,
"tags": ["pixel-art", "indie", "addictive"]
},
{
"id": 2,
"name": "Tunic",
"genre": "Adventure",
"free": false,
"tags": ["isometric", "puzzle"]
},
{
"id": 3,
"name": "Inscryption",
"genre": "Card",
"free": false,
"tags": ["horror", "deck-building"]
}
]`;
+28
View File
@@ -0,0 +1,28 @@
import type { JsonShape } from './detect';
import type { FormatId } from '@/converters/types';
/**
* Map a detected JSON shape to the formats most likely to make sense.
* Used by the format picker to highlight "good fits" and dim others.
*/
export function suggestedFormats(shape: JsonShape | null): FormatId[] {
switch (shape) {
case 'flat-object':
// Flat-object is RESX's native shape — surface it first.
return ['resx', 'yaml', 'toml', 'xml'];
case 'array-of-objects':
return ['jsonl', 'csv', 'tsv', 'markdown', 'sql', 'yaml', 'xml'];
case 'object':
return ['yaml', 'toml', 'xml'];
case 'array':
return ['jsonl', 'yaml', 'xml'];
case 'scalar':
return ['yaml'];
default:
return [];
}
}
export function isFormatSuggested(format: FormatId, shape: JsonShape | null): boolean {
return suggestedFormats(shape).includes(format);
}
+98
View File
@@ -0,0 +1,98 @@
/**
* Tauri runtime helpers.
*
* In a web build these functions are tree-shaken because `isTauri()`
* resolves to a static `false`. In a Tauri build, they bridge to native
* dialogs / file system via the @tauri-apps/* plugins.
*
* Imports are dynamic so the web bundle doesn't pull the Tauri plugins.
*/
interface TauriWindowGlobals {
__TAURI__?: unknown;
__TAURI_INTERNALS__?: unknown;
}
export function isTauri(): boolean {
if (typeof window === 'undefined') return false;
const g = window as unknown as TauriWindowGlobals;
return g.__TAURI__ !== undefined || g.__TAURI_INTERNALS__ !== undefined;
}
/**
* Open a native file picker. Returns selected file paths,
* or null if the user cancelled.
*/
export async function nativeOpenFiles(options?: {
multiple?: boolean;
}): Promise<string[] | null> {
if (!isTauri()) return null;
const { open } = await import('@tauri-apps/plugin-dialog');
const result = await open({
multiple: options?.multiple ?? false,
filters: [
{ name: 'JSON', extensions: ['json'] },
{ name: 'Text', extensions: ['txt'] },
{ name: 'All', extensions: ['*'] },
],
});
if (result === null) return null;
return Array.isArray(result) ? result : [result];
}
/**
* Show a native save dialog for a binary blob (e.g. the batch .zip).
* Returns the path the user picked, or null on cancel.
*/
export async function nativeSaveBlob(blob: Blob, suggestedName: string): Promise<string | null> {
if (!isTauri()) return null;
const { save } = await import('@tauri-apps/plugin-dialog');
const { writeFile } = await import('@tauri-apps/plugin-fs');
const path = await save({
defaultPath: suggestedName,
filters: [
{ name: 'Zip Archive', extensions: ['zip'] },
{ name: 'All Files', extensions: ['*'] },
],
});
if (!path) return null;
const buffer = new Uint8Array(await blob.arrayBuffer());
await writeFile(path, buffer);
return path;
}
/**
* Read a file at the given native path as a UTF-8 string.
*/
export async function nativeReadText(path: string): Promise<string> {
if (!isTauri()) {
throw new Error('nativeReadText is only available inside Tauri.');
}
const { readTextFile } = await import('@tauri-apps/plugin-fs');
return readTextFile(path);
}
/**
* Convert a native file path to a browser-style File so the
* existing batch store and editor flows can consume it unchanged.
*/
export async function fileFromNativePath(path: string): Promise<File> {
const text = await nativeReadText(path);
const name = path.replace(/^.*[\\/]/, ''); // basename
return new File([text], name, { type: 'application/json' });
}
/**
* Diagnostic info from the Rust side (OS, arch, app version).
* Not currently shown in the UI but useful for bug reports.
*/
export async function tauriHostInfo(): Promise<{
os: string;
arch: string;
family: string;
app_version: string;
} | null> {
if (!isTauri()) return null;
const { invoke } = await import('@tauri-apps/api/core');
return invoke('host_info');
}
+76
View File
@@ -0,0 +1,76 @@
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
export type Theme = 'dark' | 'light' | 'system';
interface ThemeContextValue {
theme: Theme;
resolvedTheme: 'dark' | 'light';
setTheme: (t: Theme) => void;
}
const ThemeContext = createContext<ThemeContextValue | null>(null);
const STORAGE_KEY = 'jsonprism.theme';
function getSystemTheme(): 'dark' | 'light' {
if (typeof window === 'undefined') return 'dark';
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function readStored(): Theme {
if (typeof window === 'undefined') return 'system';
const raw = window.localStorage.getItem(STORAGE_KEY);
if (raw === 'dark' || raw === 'light' || raw === 'system') return raw;
return 'system';
}
interface ThemeProviderProps {
children: ReactNode;
defaultTheme?: Theme;
}
export function ThemeProvider({ children, defaultTheme = 'system' }: ThemeProviderProps) {
const [theme, setThemeState] = useState<Theme>(() => readStored() ?? defaultTheme);
const [resolvedTheme, setResolvedTheme] = useState<'dark' | 'light'>(() =>
theme === 'system' ? getSystemTheme() : theme,
);
// Apply class to <html>
useEffect(() => {
const root = document.documentElement;
const next = theme === 'system' ? getSystemTheme() : theme;
root.classList.toggle('dark', next === 'dark');
setResolvedTheme(next);
}, [theme]);
// Listen for system changes when theme === 'system'
useEffect(() => {
if (theme !== 'system') return;
const mq = window.matchMedia('(prefers-color-scheme: dark)');
const handler = () => {
const next = mq.matches ? 'dark' : 'light';
document.documentElement.classList.toggle('dark', next === 'dark');
setResolvedTheme(next);
};
mq.addEventListener('change', handler);
return () => mq.removeEventListener('change', handler);
}, [theme]);
const setTheme = (t: Theme) => {
window.localStorage.setItem(STORAGE_KEY, t);
setThemeState(t);
};
return (
<ThemeContext.Provider value={{ theme, resolvedTheme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// eslint-disable-next-line react-refresh/only-export-components
export function useTheme(): ThemeContextValue {
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error('useTheme must be used inside <ThemeProvider>');
return ctx;
}
+6
View File
@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
+21
View File
@@ -0,0 +1,21 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import './styles/globals.css';
import './i18n';
import { App } from './app/App';
const rootEl = document.getElementById('root');
if (!rootEl) {
throw new Error('Root element #root not found in index.html');
}
const basename = import.meta.env.PROD ? '/jsonprism' : '/';
createRoot(rootEl).render(
<StrictMode>
<BrowserRouter basename={basename}>
<App />
</BrowserRouter>
</StrictMode>,
);
+21
View File
@@ -0,0 +1,21 @@
import { useTranslation } from 'react-i18next';
export function About() {
const { t } = useTranslation();
return (
<div className="mx-auto max-w-2xl px-6 py-16">
<h1 className="font-display text-spectrum mb-4 text-5xl italic tracking-tight">
{t('about.title')}
</h1>
<p className="font-display text-foreground/90 mb-8 text-2xl italic">{t('about.lead')}</p>
<div className="text-muted-foreground space-y-4 text-sm leading-relaxed">
<p>{t('about.p1')}</p>
<p>{t('about.p2')}</p>
</div>
<div className="border-border/60 text-muted-foreground mt-12 border-t pt-6 font-mono text-xs">
{t('about.version', { version: '1.0.0' })}
</div>
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
import { useTranslation } from 'react-i18next';
import { ConverterWorkspace } from '@/components/converter/ConverterWorkspace';
export function Home() {
const { t } = useTranslation();
return (
<div className="mx-auto flex h-[calc(100vh-3.5rem-4rem)] max-w-screen-2xl flex-col gap-6 px-6 py-6">
<header className="flex items-end justify-between gap-6">
<div>
<h1 className="font-display text-4xl leading-none tracking-tight md:text-5xl">
<span className="text-spectrum italic">Disperse</span> JSON.
</h1>
<p className="text-muted-foreground mt-2 max-w-xl text-sm">
{t('app.description')}
</p>
</div>
<div className="text-muted-foreground/60 hidden font-mono text-xs md:block">
{t('home.drop_zone_hint')}
</div>
</header>
<div className="min-h-0 flex-1">
<ConverterWorkspace />
</div>
</div>
);
}
+101
View File
@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { BATCH_MAX_FILES, useBatchStore } from '../batchStore';
function makeFile(name: string, content = '{}'): File {
return new File([content], name, { type: 'application/json' });
}
beforeEach(() => {
useBatchStore.getState().clear();
});
afterEach(() => {
useBatchStore.getState().clear();
});
describe('batchStore', () => {
it('starts empty', () => {
const s = useBatchStore.getState();
expect(s.size()).toBe(0);
expect(s.hasAny()).toBe(false);
expect(s.ready()).toBe(false);
});
it('addFiles adds queued items preserving order', () => {
const result = useBatchStore.getState().addFiles([
makeFile('a.json'),
makeFile('b.json'),
makeFile('c.json'),
]);
expect(result.added).toBe(3);
expect(result.skipped).toBe(0);
const s = useBatchStore.getState();
expect(s.size()).toBe(3);
expect(s.itemOrder.map((id) => s.items[id]!.filename)).toEqual(['a.json', 'b.json', 'c.json']);
expect(s.itemOrder.every((id) => s.items[id]!.status === 'queued')).toBe(true);
});
it('addFiles enforces BATCH_MAX_FILES', () => {
const fitting = Array.from({ length: BATCH_MAX_FILES - 1 }, (_, i) => makeFile(`f${i}.json`));
useBatchStore.getState().addFiles(fitting);
const result = useBatchStore.getState().addFiles([
makeFile('one_more.json'),
makeFile('over_the_limit.json'),
]);
expect(result.added).toBe(1);
expect(result.skipped).toBe(1);
expect(result.reason).toBe('limit');
expect(useBatchStore.getState().size()).toBe(BATCH_MAX_FILES);
});
it('removeItem removes one queue entry by id', () => {
useBatchStore.getState().addFiles([makeFile('a.json'), makeFile('b.json')]);
const firstId = useBatchStore.getState().itemOrder[0]!;
useBatchStore.getState().removeItem(firstId);
expect(useBatchStore.getState().size()).toBe(1);
expect(useBatchStore.getState().items[firstId]).toBeUndefined();
});
it('clear resets everything', () => {
useBatchStore.getState().addFiles([makeFile('a.json')]);
useBatchStore.getState().setProcessing(true);
useBatchStore.getState().clear();
const s = useBatchStore.getState();
expect(s.size()).toBe(0);
expect(s.processing).toBe(false);
});
it('updateItem applies patches', () => {
useBatchStore.getState().addFiles([makeFile('a.json')]);
const id = useBatchStore.getState().itemOrder[0]!;
useBatchStore.getState().updateItem(id, {
status: 'done',
output: 'x',
outputSize: 1,
});
const item = useBatchStore.getState().items[id]!;
expect(item.status).toBe('done');
expect(item.output).toBe('x');
expect(item.outputSize).toBe(1);
});
it('ready() returns true once any item is done', () => {
useBatchStore.getState().addFiles([makeFile('a.json'), makeFile('b.json')]);
const id = useBatchStore.getState().itemOrder[0]!;
useBatchStore.getState().updateItem(id, { status: 'done', output: 'x' });
expect(useBatchStore.getState().ready()).toBe(true);
});
it('resetStatuses sets all items back to queued and clears outputs/errors', () => {
useBatchStore.getState().addFiles([makeFile('a.json'), makeFile('b.json')]);
const [id1, id2] = useBatchStore.getState().itemOrder;
useBatchStore.getState().updateItem(id1!, { status: 'done', output: 'x', outputSize: 1 });
useBatchStore.getState().updateItem(id2!, { status: 'error', error: 'bad' });
useBatchStore.getState().resetStatuses();
const s = useBatchStore.getState();
expect(s.items[id1!]!.status).toBe('queued');
expect(s.items[id1!]!.output).toBeUndefined();
expect(s.items[id2!]!.status).toBe('queued');
expect(s.items[id2!]!.error).toBeUndefined();
});
});
+146
View File
@@ -0,0 +1,146 @@
import { create } from 'zustand';
export type BatchItemStatus = 'queued' | 'processing' | 'done' | 'error';
export interface BatchItem {
id: string;
/** Original file reference; not serializable, kept in memory only. */
file: File;
filename: string;
size: number;
status: BatchItemStatus;
output?: string;
outputSize?: number;
error?: string;
}
/** Hard upper bound on queue size. UI may suggest a smaller default. */
export const BATCH_MAX_FILES = 500;
interface BatchState {
items: Record<string, BatchItem>;
itemOrder: string[];
processing: boolean;
abortController: AbortController | null;
// Queries
size(): number;
ready(): boolean; // any items in 'done' status?
hasAny(): boolean;
// Mutations
addFiles(files: File[]): { added: number; skipped: number; reason?: string };
removeItem(id: string): void;
clear(): void;
setProcessing(p: boolean): void;
setAbortController(c: AbortController | null): void;
updateItem(id: string, patch: Partial<BatchItem>): void;
resetStatuses(): void;
}
let idSeq = 0;
function nextId(): string {
idSeq += 1;
return `b${Date.now().toString(36)}_${idSeq.toString(36)}`;
}
export const useBatchStore = create<BatchState>((set, get) => ({
items: {},
itemOrder: [],
processing: false,
abortController: null,
size: () => get().itemOrder.length,
ready: () => Object.values(get().items).some((i) => i.status === 'done'),
hasAny: () => get().itemOrder.length > 0,
addFiles: (files) => {
let added = 0;
let skipped = 0;
let reason: string | undefined;
set((state) => {
const remaining = BATCH_MAX_FILES - state.itemOrder.length;
if (remaining <= 0) {
skipped = files.length;
reason = 'limit';
return state;
}
const newItems: Record<string, BatchItem> = { ...state.items };
const newOrder = [...state.itemOrder];
for (const file of files) {
if (newOrder.length >= BATCH_MAX_FILES) {
skipped += 1;
reason = 'limit';
continue;
}
const id = nextId();
newItems[id] = {
id,
file,
filename: file.name,
size: file.size,
status: 'queued',
};
newOrder.push(id);
added += 1;
}
return { items: newItems, itemOrder: newOrder };
});
return { added, skipped, reason };
},
removeItem: (id) =>
set((state) => {
if (!state.items[id]) return state;
const { [id]: _removed, ...rest } = state.items;
void _removed;
return {
items: rest,
itemOrder: state.itemOrder.filter((x) => x !== id),
};
}),
clear: () =>
set((state) => {
state.abortController?.abort();
return {
items: {},
itemOrder: [],
processing: false,
abortController: null,
};
}),
setProcessing: (p) => set({ processing: p }),
setAbortController: (c) => set({ abortController: c }),
updateItem: (id, patch) =>
set((state) => {
const current = state.items[id];
if (!current) return state;
return {
items: { ...state.items, [id]: { ...current, ...patch } },
};
}),
resetStatuses: () =>
set((state) => {
const newItems: Record<string, BatchItem> = {};
for (const id of Object.keys(state.items)) {
const item = state.items[id]!;
newItems[id] = {
...item,
status: 'queued',
output: undefined,
outputSize: undefined,
error: undefined,
};
}
return { items: newItems };
}),
}));
+184
View File
@@ -0,0 +1,184 @@
@import 'tailwindcss';
@import 'tw-animate-css';
@custom-variant dark (&:is(.dark *));
/*
JSONPrism — "Prism Spectrum" theme
Editorial-meets-technical: deep midnight backdrop, off-white foreground,
three signature accents (violet / cyan / amber) inspired by light dispersion.
*/
@theme inline {
/* Fonts */
--font-display: 'Instrument Serif', ui-serif, Georgia, serif;
--font-sans: 'Geist', ui-sans-serif, system-ui, sans-serif;
--font-mono: 'JetBrains Mono', ui-monospace, 'SF Mono', Menlo, monospace;
/* Core shadcn tokens — map to CSS vars below */
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
/* Prism signature spectrum */
--color-prism-violet: oklch(0.74 0.18 290);
--color-prism-cyan: oklch(0.82 0.13 200);
--color-prism-amber: oklch(0.82 0.16 80);
--color-prism-rose: oklch(0.74 0.18 5);
--radius-sm: 0.25rem;
--radius-md: 0.5rem;
--radius-lg: 0.75rem;
--radius-xl: 1rem;
}
/* ---- Light theme ---- */
:root {
--background: oklch(0.99 0.005 270);
--foreground: oklch(0.18 0.02 270);
--card: oklch(1 0 0);
--card-foreground: oklch(0.18 0.02 270);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.18 0.02 270);
--primary: oklch(0.55 0.18 290); /* violet */
--primary-foreground: oklch(0.99 0 0);
--secondary: oklch(0.95 0.01 270);
--secondary-foreground: oklch(0.22 0.02 270);
--muted: oklch(0.96 0.005 270);
--muted-foreground: oklch(0.48 0.02 270);
--accent: oklch(0.94 0.03 200); /* cyan tint */
--accent-foreground: oklch(0.22 0.02 270);
--destructive: oklch(0.62 0.22 25);
--destructive-foreground: oklch(0.99 0 0);
--border: oklch(0.9 0.01 270);
--input: oklch(0.9 0.01 270);
--ring: oklch(0.55 0.18 290);
}
/* ---- Dark theme (default) ---- */
.dark {
--background: oklch(0.13 0.015 270);
--foreground: oklch(0.96 0.005 270);
--card: oklch(0.16 0.018 270);
--card-foreground: oklch(0.96 0.005 270);
--popover: oklch(0.16 0.018 270);
--popover-foreground: oklch(0.96 0.005 270);
--primary: oklch(0.78 0.16 290); /* brighter violet on dark */
--primary-foreground: oklch(0.13 0.015 270);
--secondary: oklch(0.22 0.02 270);
--secondary-foreground: oklch(0.96 0.005 270);
--muted: oklch(0.2 0.018 270);
--muted-foreground: oklch(0.7 0.015 270);
--accent: oklch(0.24 0.05 210);
--accent-foreground: oklch(0.96 0.005 270);
--destructive: oklch(0.65 0.22 25);
--destructive-foreground: oklch(0.96 0.005 270);
--border: oklch(0.26 0.02 270);
--input: oklch(0.22 0.02 270);
--ring: oklch(0.78 0.16 290);
}
@layer base {
* {
@apply border-border;
}
html,
body,
#root {
@apply h-full;
}
body {
@apply bg-background text-foreground font-sans antialiased;
font-feature-settings: 'cv11', 'ss01', 'ss02';
}
::selection {
background: var(--color-prism-violet);
color: var(--background);
}
/* Atmospheric backdrop — barely-there mesh gradient + grain */
body::before {
content: '';
position: fixed;
inset: 0;
pointer-events: none;
z-index: -1;
background:
radial-gradient(ellipse 80% 50% at 20% 0%, color-mix(in oklch, var(--color-prism-violet) 8%, transparent), transparent 60%),
radial-gradient(ellipse 60% 50% at 100% 100%, color-mix(in oklch, var(--color-prism-cyan) 6%, transparent), transparent 60%);
}
h1,
h2,
h3 {
@apply font-display tracking-tight;
font-feature-settings: 'liga', 'dlig';
}
code,
pre,
kbd {
@apply font-mono;
}
}
@layer utilities {
.text-spectrum {
background: linear-gradient(
90deg,
var(--color-prism-violet) 0%,
var(--color-prism-cyan) 40%,
var(--color-prism-amber) 70%,
var(--color-prism-rose) 100%
);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
.border-spectrum {
border-image: linear-gradient(
90deg,
var(--color-prism-violet),
var(--color-prism-cyan),
var(--color-prism-amber),
var(--color-prism-rose)
)
1;
}
}
+7
View File
@@ -0,0 +1,7 @@
import '@testing-library/jest-dom/vitest';
import { afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
afterEach(() => {
cleanup();
});
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2023", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Strict typing */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
"exactOptionalPropertyTypes": true,
"noImplicitOverride": true,
/* Path aliases */
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["src"]
}
+13
View File
@@ -0,0 +1,13 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json"},
{ "path": "./tsconfig.node.json"}
],
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": [
"vite.config.ts"
]
}
+73
View File
@@ -0,0 +1,73 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import path from 'node:path';
// Tauri exposes env vars during dev/build; presence indicates a Tauri context.
const isTauriContext = !!process.env.TAURI_ENV_PLATFORM;
const tauriHost = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(({ mode }) => ({
// Web prod build deploys to /jsonprism/. Tauri bundles serve from '/'.
base: isTauriContext ? '/' : mode === 'production' ? '/jsonprism/' : '/',
plugins: [react(), tailwindcss()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
},
// Tauri docs recommend not clearing the screen so Cargo/Tauri logs survive.
clearScreen: !isTauriContext,
build: {
target: 'es2022',
sourcemap: !isTauriContext,
// Tauri uses Chromium/WebKit only — drop legacy fallbacks for smaller bundles.
minify: isTauriContext ? 'esbuild' : 'esbuild',
rollupOptions: {
output: {
manualChunks: {
codemirror: [
'@codemirror/state',
'@codemirror/view',
'@codemirror/lang-json',
'@uiw/react-codemirror',
],
parsers: ['js-yaml', 'smol-toml', 'fast-xml-parser', 'papaparse'],
fflate: ['fflate'],
},
},
},
},
server: {
port: 5173,
strictPort: isTauriContext,
host: tauriHost ?? false,
hmr: tauriHost
? { protocol: 'ws', host: tauriHost, port: 1421 }
: undefined,
watch: {
ignored: ['**/src-tauri/**'],
},
},
// Don't accidentally bundle Tauri-only modules into the web build.
// The runtime check in src/lib/tauri.ts handles this at call time,
// but we also externalize so missing modules don't fail the web build.
optimizeDeps: {
exclude: isTauriContext
? []
: [
'@tauri-apps/api',
'@tauri-apps/plugin-dialog',
'@tauri-apps/plugin-fs',
'@tauri-apps/plugin-os',
'@tauri-apps/plugin-shell',
],
},
}));
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more