3 Commits
Author SHA1 Message Date
poli0981andClaude Opus 4.7 6197334326 chore(release): v1.5.0 — component refactor, knip, scroll-to-top (#58)
- Refactor: decompose BatchPanel (515→289), ConverterWorkspace (314→206),
  and InputPanel (278→216) into pure utilities, leaf components, and hooks.
  Behavior-preserving; all 193 unit tests still pass.
- Tooling: integrate knip for dead-code analysis (knip.json + npm script +
  CI step). Remove orphaned useLocalStorage.ts; declare the previously
  phantom `globals` devDependency.
- Feature: scroll-to-top button on the About page (prefers-reduced-motion
  aware, i18n across all four locales).
- Docs: bump to 1.5.0; update CHANGELOG, THIRD-PARTY, ROADMAP (Phase 4 + 5),
  CONTRIBUTING.

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

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

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

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

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

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

No files matched your search

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