Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b1d461a18e | ||
|
|
4370e36628 | ||
|
|
839bffd000 | ||
|
|
27e704fe4f | ||
|
|
db11ce0f6e | ||
|
|
8bbecd14bd | ||
|
|
5249f92c10 | ||
|
|
40c8c81028 | ||
|
|
2c2f8ca7ec | ||
|
|
3657e21f11 | ||
|
|
3d424f7c0b | ||
|
|
29eace4302 | ||
|
|
4c25ea1c07 | ||
|
|
e6ab02cdef | ||
|
|
b89d99807d | ||
|
|
6197334326 | ||
|
|
30f10cfc36 | ||
|
|
a6caa88d9c |
No files matched your search
@@ -42,6 +42,9 @@ jobs:
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Knip
|
||||
run: npm run knip
|
||||
|
||||
- name: Typecheck
|
||||
run: npm run typecheck
|
||||
|
||||
|
||||
@@ -10,8 +10,44 @@ permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
# Create the draft release ONCE, up front, so every platform in the matrix
|
||||
# below uploads into the same release. Previously each matrix job ran
|
||||
# tauri-action's "find or create release" concurrently; with no release yet,
|
||||
# they raced to create it and produced duplicate drafts that split the assets
|
||||
# (Linux bundles in one draft, macOS/Windows in another). A single
|
||||
# pre-created release referenced by `releaseId` removes the race.
|
||||
create-release:
|
||||
name: Create draft release
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
release_id: ${{ steps.create-release.outputs.result }}
|
||||
steps:
|
||||
- name: Create draft release
|
||||
id: create-release
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
const tag = context.ref.replace('refs/tags/', '').replace('refs/heads/', '');
|
||||
const { data } = await github.rest.repos.createRelease({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
tag_name: tag,
|
||||
name: `JSONPrism ${tag}`,
|
||||
body: [
|
||||
'Native desktop builds for Windows, macOS, and Linux, plus an Android APK (sideload, Android 12+).',
|
||||
'',
|
||||
'Android: download the `.apk`, then enable "install unknown apps" for your browser/file manager to sideload.',
|
||||
'',
|
||||
'See the [CHANGELOG](https://github.com/poli0981/jsonPrism/blob/main/CHANGELOG.md) for details.',
|
||||
].join('\n'),
|
||||
draft: true,
|
||||
prerelease: false,
|
||||
});
|
||||
return data.id;
|
||||
|
||||
build:
|
||||
name: Build · ${{ matrix.platform.name }}
|
||||
needs: create-release
|
||||
runs-on: ${{ matrix.platform.runner }}
|
||||
timeout-minutes: 40
|
||||
|
||||
@@ -74,17 +110,112 @@ jobs:
|
||||
run: npm run tauri:icon
|
||||
shell: pwsh
|
||||
|
||||
- name: Build, sign, and create release
|
||||
- name: Build, sign, and upload to 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
|
||||
# Upload into the single draft created by the create-release job above
|
||||
# instead of finding/creating one per matrix job (which caused
|
||||
# duplicate drafts + split assets). The maintainer un-drafts manually.
|
||||
releaseId: ${{ needs.create-release.outputs.release_id }}
|
||||
args: ${{ matrix.platform.args }}
|
||||
|
||||
# Android is built separately: tauri-action does not build mobile targets, so
|
||||
# this job drives the Tauri CLI directly (Java + Android SDK/NDK + Rust android
|
||||
# targets), signs with the release keystore from secrets, and uploads the
|
||||
# universal APK into the same draft release as the desktop bundles.
|
||||
#
|
||||
# Requires these repository secrets (see docs/TAURI-NOTES.md):
|
||||
# ANDROID_KEYSTORE_BASE64 base64 of upload-keystore.jks
|
||||
# ANDROID_KEYSTORE_PASSWORD the keystore (store) password
|
||||
# ANDROID_KEY_PASSWORD the key password (optional; defaults to store password)
|
||||
# ANDROID_KEY_ALIAS the key alias (optional; defaults to "upload")
|
||||
android:
|
||||
name: Build · Android (APK)
|
||||
needs: create-release
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Setup Java 17
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '17'
|
||||
|
||||
- name: Setup Android SDK
|
||||
uses: android-actions/setup-android@v3
|
||||
|
||||
- name: Install SDK platform + NDK
|
||||
run: |
|
||||
sdkmanager "platforms;android-36" "ndk;27.2.12479018"
|
||||
echo "NDK_HOME=$ANDROID_HOME/ndk/27.2.12479018" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Setup Rust (stable) + Android targets
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-linux-android,armv7-linux-androideabi,i686-linux-android,x86_64-linux-android
|
||||
|
||||
- name: Cache Cargo build artifacts
|
||||
uses: swatinem/rust-cache@v2
|
||||
with:
|
||||
workspaces: './src-tauri -> target'
|
||||
key: android
|
||||
|
||||
- name: Setup Node 22
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22.x
|
||||
cache: npm
|
||||
|
||||
- name: Install npm dependencies
|
||||
run: npm ci --no-audit --no-fund
|
||||
|
||||
- name: Generate icons
|
||||
run: npm run tauri:icon
|
||||
|
||||
- name: Decode release keystore
|
||||
env:
|
||||
ANDROID_KEYSTORE_BASE64: ${{ secrets.ANDROID_KEYSTORE_BASE64 }}
|
||||
ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
ANDROID_KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
ANDROID_KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
run: |
|
||||
if [ -z "$ANDROID_KEYSTORE_BASE64" ]; then
|
||||
echo "::error::ANDROID_KEYSTORE_BASE64 secret is not set — cannot sign the release APK."
|
||||
exit 1
|
||||
fi
|
||||
KEYSTORE_PATH="$RUNNER_TEMP/upload-keystore.jks"
|
||||
echo "$ANDROID_KEYSTORE_BASE64" | base64 -d > "$KEYSTORE_PATH"
|
||||
{
|
||||
echo "storePassword=$ANDROID_KEYSTORE_PASSWORD"
|
||||
echo "keyPassword=${ANDROID_KEY_PASSWORD:-$ANDROID_KEYSTORE_PASSWORD}"
|
||||
echo "keyAlias=${ANDROID_KEY_ALIAS:-upload}"
|
||||
echo "storeFile=$KEYSTORE_PATH"
|
||||
} > src-tauri/gen/android/keystore.properties
|
||||
|
||||
- name: Build signed universal APK
|
||||
run: npm run tauri -- android build --apk
|
||||
|
||||
- name: Upload APK to release
|
||||
uses: actions/github-script@v9
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
const tag = context.ref.replace('refs/tags/', '').replace('refs/heads/', '');
|
||||
const dir = 'src-tauri/gen/android/app/build/outputs/apk/universal/release';
|
||||
const apks = fs.readdirSync(dir).filter((f) => f.endsWith('.apk'));
|
||||
if (apks.length === 0) throw new Error(`No APK found in ${dir}`);
|
||||
const src = `${dir}/${apks[0]}`;
|
||||
const name = `JSONPrism-${tag}-android-universal.apk`;
|
||||
await github.rest.repos.uploadReleaseAsset({
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
release_id: ${{ needs.create-release.outputs.release_id }},
|
||||
name,
|
||||
data: fs.readFileSync(src),
|
||||
});
|
||||
core.info(`Uploaded ${name} from ${src}`);
|
||||
+7
-2
@@ -32,14 +32,19 @@ dist-ssr
|
||||
|
||||
# Tauri (Phase 2C)
|
||||
src-tauri/target
|
||||
src-tauri/Cargo.lock
|
||||
src-tauri/gen
|
||||
# gen/android is committed (source). Build outputs inside it are ignored by its own
|
||||
# nested .gitignore files. Only the generated JSON schemas are ignored here.
|
||||
src-tauri/gen/schemas
|
||||
src-tauri/icons/*.png
|
||||
src-tauri/icons/*.ico
|
||||
src-tauri/icons/*.icns
|
||||
src-tauri/icons/android/
|
||||
src-tauri/icons/ios/
|
||||
|
||||
# Android signing keystore — never commit the keystore binary.
|
||||
*.jks
|
||||
*.keystore
|
||||
|
||||
# Test artifacts
|
||||
coverage
|
||||
.nyc_output
|
||||
|
||||
+97
-1
@@ -6,7 +6,103 @@ 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.7.1] — 2026-06-16
|
||||
|
||||
### Fixed
|
||||
|
||||
- **First-launch legal gate now appears on the Android app.** The consent gate (added in 1.6.0) was skipped on *every* Tauri build — correct for desktop, where the installer's license page already gates acceptance, but the Android sideload APK has no installer step, so Android users never saw or accepted the License / Terms / Privacy / Disclaimer. A new build-time `__IS_ANDROID_BUILD__` define (`TAURI_ENV_PLATFORM === 'android'`, mirrored as `false` in `vitest.config.ts` so tests still run) makes the gate skip **only** on desktop (`__IS_TAURI_BUILD__ && !__IS_ANDROID_BUILD__`); Android and web both show it. Acceptance persists in the WebView's `localStorage` like the web build, so it asks once. The gate's links also gained an `openExternal()` helper (`src/lib/tauri.ts`) that routes through `@tauri-apps/plugin-shell` inside Tauri — the Android WebView swallows plain `target="_blank"`, so the legal links were previously unreachable there. The intro copy now reads "runs entirely on your device" (was "in your browser", inaccurate on the native app).
|
||||
- **File-load toast no longer shows opaque Android document ids.** Android's Storage Access Framework often returns a `content://` URI whose document id carries no real filename (e.g. `msf:1000000123`), so the native-open success toast read "Loaded 1000000123". It now falls back to a count-based "N file(s) loaded" message (new `toast.files_loaded` keys, EN + VI) when the picked name has no usable extension, and keeps the clean "Loaded <name>" when a real filename is available. Desktop and web are unchanged. `bundle.android.versionCode` bumps to 10701 (`1.7.1` → `MAJOR*10000 + MINOR*100 + PATCH`).
|
||||
|
||||
## [1.7.0] — 2026-06-16
|
||||
|
||||
### Added
|
||||
|
||||
- **Android app (sideload APK).** JSONPrism now ships as an Android app built with Tauri 2 — download a signed **universal `.apk`** from Releases and sideload it. **Requires Android 12 (API 31) or newer**; the OS refuses to install on older versions (`bundle.android.minSdkVersion = 31`, verified: `INSTALL_FAILED_OLDER_SDK` on API 24). The same React UI runs in the Android System WebView, with the native Storage Access Framework file picker wired into the existing open/batch flows via `plugin-dialog` + `plugin-fs` (no behavior change to the converters). The generated Gradle project lives in `src-tauri/gen/android/` (committed — source only; build outputs + signing material gitignored); release signing reads a gitignored `keystore.properties` with a graceful unsigned fallback. New `npm run tauri:android:{init,dev,build}` scripts, and an `android` job in `.github/workflows/release.yml` builds + signs the APK and attaches it to the same draft release as the desktop bundles. `bundle.android.versionCode` is derived from the version as `MAJOR*10000 + MINOR*100 + PATCH` (1.7.0 → 10700). **Note:** the layout needs a WebView of **Chromium ≥ 111** (an existing Tailwind v4 requirement) — current Android 12+ devices satisfy this via the Play-updated System WebView; see `docs/TAURI-NOTES.md`.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Self-hosted fonts (offline-ready).** Geist, Instrument Serif, and JetBrains Mono are now bundled via `@fontsource` (imported in `src/main.tsx`) instead of fetched from Google Fonts. The `<link>` tags are gone and the CSP no longer allows `fonts.googleapis.com` / `fonts.gstatic.com`, so the app renders with the correct fonts **fully offline** — required for the sideloaded Android build and a privacy win for the web build. CJK still falls back to system fonts as before.
|
||||
- **Robust native file open on Android.** `fileFromNativePath()` recovers a usable filename from Android `content://` URIs via a new `basenameFromPath()` helper, and the native-open path filters extensions leniently so opaque MediaStore document URIs — which carry no filename — that the user explicitly picked through the native dialog are no longer wrongly rejected. Desktop and web drag-drop behavior is unchanged.
|
||||
|
||||
### Tests
|
||||
|
||||
- **+6 unit tests (215 total).** New coverage for `basenameFromPath` (desktop paths, `content://` `raw:` + `msf:` URIs, malformed escapes) and the lenient `filterByExtension` mode. Format / typecheck / lint / `knip` / tests all green. The signed APK was validated on emulators: installs on Android 12+, blocked on API < 31, launches, renders (CodeMirror + self-hosted fonts), runs converters, reads files via the SAF picker, fully offline.
|
||||
|
||||
## [1.6.1] — 2026-06-14
|
||||
|
||||
### Changed
|
||||
|
||||
- **Split the CodeMirror core chunk to clear the 500 kB build warning.** The `cm-core` chunk was ~614 kB raw (210 kB gzip) and tripped Vite's `chunkSizeWarningLimit` on every build, even though it is already lazy-loaded behind the editor. Vite 8 / Rolldown deprecates the `manualChunks` function form (its optimizer silently merged sub-chunks back together), so `vite.config.ts` now uses `advancedChunks.groups` with explicit `priority`-ordered, honored boundaries. The CodeMirror core splits into `cm-view` (~245 kB, the `@codemirror/view` DOM engine) + `cm-core` (~362 kB, state/language/lezer/`@uiw` wrapper); `cm-langs` is unchanged (~60 kB). No chunk now exceeds 500 kB. Total bytes and gzip size are unchanged — the editor still loads all three pieces together behind its existing `React.lazy` boundary, so this is purely finer file granularity (better cache reuse across deploys). No converter or UI behavior changed; verified in a production preview build (editor renders, highlights, and converts; all `cm-*` chunks 200 OK, no console errors).
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Stop shipping source maps on the public web build.** `vite.config.ts` now emits source maps only for local non-production web builds (`sourcemap: !isTauriContext && mode !== 'production'`) — never for the GitHub Pages deploy or Tauri bundles. The entire `dist/` is uploaded to Pages, so earlier production builds exposed the full original source via `.map` files even though nothing consumes them (`PRIVACY.md`: no remote error reporting). Smaller deploy, no source exposure.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- **27 npm minor/patch updates** (the grouped `npm-minor-patch` Dependabot bump).
|
||||
|
||||
## [1.6.0] — 2026-06-14
|
||||
|
||||
### Added
|
||||
|
||||
- **Custom error pages.** A reusable presentational `ErrorState` component (`src/components/common/ErrorState.tsx`) backs a 404 catch-all route (`src/pages/errors/NotFound.tsx`) and a generic `/error/:code` route (`src/pages/errors/ErrorRoute.tsx`) with dedicated copy for 403 / 404 / 419 / 500 and a fallback for anything else. JSONPrism is a static client-side SPA and never emits these from a server itself — the route exists so any code (a future backend, a Tauri IPC failure) can render a polished, consistent page. New `error_page.*` i18n group in EN + VI.
|
||||
- **First-launch legal consent gate (web only).** A non-dismissible modal (`src/components/common/ConsentGate.tsx`, built on a new `src/components/ui/dialog.tsx` Radix wrapper) blocks the app on first launch / incognito until the user ticks agreement to the License, Terms (EULA), Privacy Policy, and Disclaimer (linked to GitHub). Acceptance persists to `localStorage` (`jsonprism.consent` — flag + version + timestamp) via `src/lib/consent-storage.ts` and a Zustand store (`src/stores/consentStore.ts`); bump `CONSENT_VERSION` to re-prompt when terms change. Skipped in desktop builds (gated by the installer instead) with zero runtime branching, via the build-time `__IS_TAURI_BUILD__` flag. New `consent.*` i18n group in EN + VI; `PRIVACY.md` documents the new key.
|
||||
- **Windows installer license-acceptance page.** `bundle.licenseFile` in `tauri.conf.json` now points at `src-tauri/license.rtf` (a short EULA referencing Apache-2.0 + TERMS / PRIVACY / DISCLAIMER). Both the NSIS `.exe` and the WiX `.msi` show an accept-to-continue license page — RTF satisfies both, so `targets: "all"` is preserved.
|
||||
- **Offline indicator.** `useOnlineStatus` hook + a non-blocking `OfflineBanner` strip between the header and content. Informational only — JSONPrism keeps working offline.
|
||||
- **GitHub Pages deep-link support.** `public/404.html` (spa-github-pages redirect, `pathSegmentsToKeep = 1` for the `/jsonPrism/` base) plus a tiny decoder in `index.html` make refreshing a deep link (e.g. `/jsonPrism/about`) resolve to the right route instead of GitHub's 404. No-op under Tauri.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Lazy-loading + finer code-splitting (web).** Routes (`Home`, `About`, error pages) and the CodeMirror editor are now `React.lazy` + `Suspense` (the editor degrades to a real `<textarea>` while its chunk loads, so input stays usable). A `ChunkErrorBoundary` catches a failed dynamic import (e.g. stale deploy) and offers reload without crashing the page; non-chunk errors rethrow to the existing crash `ErrorBoundary`, which now shares the `ErrorState` visual. `manualChunks` in `vite.config.ts` was refined to split `react` / `router` / `i18n` / `cm-core` / `cm-langs` / one chunk per parser / `ui` — the heavy CodeMirror core is no longer in the initial paint graph.
|
||||
- **Removed a hidden `bson` leak.** `decodeBytes` / `encodeBytes` moved from `src/converters/bson.ts` to a parser-free `src/lib/bytes.ts`; `OutputPanel` and the CBOR / MessagePack converters import from there, so the `bson` library no longer enters the initial bundle graph just because the output panel renders.
|
||||
|
||||
### Tests
|
||||
|
||||
- **+16 unit tests (209 total).** New coverage for `consent-storage`, `consentStore`, `bytes` codec, `isChunkLoadError`, the `ErrorState` component, and the `useOnlineStatus` hook. Typecheck, lint, `knip`, `prettier --check`, and `npm audit` (0 vulnerabilities) all green; consent gate / 404 / `/error/:code` verified in a running dev build.
|
||||
|
||||
## [1.5.0] — 2026-05-21
|
||||
|
||||
### Added
|
||||
|
||||
- **Scroll-to-top button on the About page.** A floating up-arrow button (`src/components/common/ScrollToTop.tsx`) fades in at the bottom-right once the About page is scrolled past ~320px, and smoothly returns to the top on click. The About page hides its scrollbar (`.scrollbar-hide`), so there was previously no quick way back up. Respects `prefers-reduced-motion` (jumps instead of animating) and stays out of the keyboard tab order / accessibility tree while hidden. New i18n key `common.scroll_to_top` across all four locales (en/vi/ja/zh-CN). The button is About-only by design — the converter workspace uses a fixed `h-dvh` layout that never page-scrolls.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Internal refactor — three oversized components decomposed (behavior-preserving).** `BatchPanel.tsx` (515 lines), `ConverterWorkspace.tsx` (314), and `InputPanel.tsx` (278) were split into focused, reusable units: pure utilities (`lib/format-bytes.ts`, `lib/editor-language.ts`, `lib/read-file.ts`), leaf components (`common/ToolbarButton.tsx` — de-duplicated from InputPanel + OutputPanel — plus `converter/BatchItemRow.tsx` and `converter/BatchSummaryChips.tsx`), and hooks (`useFileAccept`, `useBatchActions`, `useConversionResult`, `useOutputBadge`, `useBatchFileRouter`). No converter or UI behavior changed; all 193 unit tests still pass.
|
||||
|
||||
### Tooling
|
||||
|
||||
- **`knip` integrated for dead-code analysis.** New `knip.json` config, an `npm run knip` script, and a `Knip` step in CI (`.github/workflows/ci.yml`) — unused files and dependencies are now caught on every push. The initial sweep deleted the orphaned `src/hooks/useLocalStorage.ts` (superseded by `lib/options-storage.ts`), dropped the unused `i18n` default export and the unused `BatchPanel` prop `onAddExternalFiles`, and un-exported the internally-used `nativeReadText`. knip's export-level `types` check is disabled — the converter-contract types in `converters/types.ts` are intentional public vocabulary, not dead code.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`globals` was a phantom (undeclared) devDependency.** `eslint.config.js` imports `globals`, but it was never listed in `package.json` — linting only worked because ESLint pulls `globals` in transitively. Now declared explicitly so a stricter or deduped install can't break `npm run lint`. Surfaced by the new `knip` check.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Added `knip` `^6.14.1` (ISC, dead-code analyzer, devDep) and `globals` `^14.0.0` (MIT, explicit devDep — previously resolved transitively). `THIRD-PARTY.md` updated.
|
||||
|
||||
### Tests
|
||||
|
||||
- No new tests this round — the refactor is behavior-preserving and the scroll button is editor/CSS/i18n surface best verified manually. The **193** existing unit tests still pass; typecheck, lint, `knip`, and `prettier --check` are all green.
|
||||
|
||||
## [1.4.3] — 2026-05-14
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Toast close button (`×`) did nothing on click/tap** on both desktop and mobile. `sonner@1.7.4`'s toast root attached `r.target.setPointerCapture(r.pointerId)` unconditionally on `pointerdown`, and combined with React 19's new container-root event delegation, the pointer-capture quirk swallowed the synthetic click event on the close button — so the bundled `dismiss()` handler never ran. The bug fired on both mouse and touch because the PointerEvent API is unified. Upgraded `sonner` `^1.7.0` → `^2.0.7`, which rewrote pointer/swipe handling and ships first-class React 19 support. `<Toaster>` props (`position`, `theme`, `richColors`, `closeButton`, `toastOptions.classNames`) and the `toast.success/warning/error/info` call sites are API-compatible — no code changes needed beyond the version bump.
|
||||
|
||||
### Added
|
||||
|
||||
- **`docs/tested-viewports.md`** — the maintainer's manual device test matrix (BlackBerry Z30 / Galaxy S9+ / Pixel 3/4/7 / iPhone SE/12/14 Pro/XR/Pro Max / iPad / BlackBerry PlayBook). Documents Nokia Lumia 520 (320×533) as a known limitation below the recommended `360×640` minimum. README EN + VI link to it.
|
||||
- **Touch hit-area expansion on the toast close button.** A `::after` pseudo gives an effective ~36–40px tap target (visible size stays at sonner's 20px default), plus `touch-action: manipulation` to drop the 300ms tap delay on touch devices. Defensive — sonner v2 already fixes the underlying click — but a free mobile UX win.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Bumped `sonner` `^1.7.0` → `^2.0.7` (MIT). THIRD-PARTY.md updated.
|
||||
|
||||
## [1.4.2] — 2026-05-14
|
||||
|
||||
|
||||
+2
-1
@@ -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).
|
||||
|
||||
|
||||
@@ -31,6 +31,7 @@ These keys are written by JSONPrism:
|
||||
| `jsonprism.selected_format` | The target format chip you last selected |
|
||||
| `jsonprism.direction` | Conversion direction (`forward` / `reverse`) |
|
||||
| `jsonprism.options.<format>` | Per-format options (e.g. CSV header on/off) |
|
||||
| `jsonprism.consent` | That you accepted the License / Terms / Privacy / Disclaimer (acceptance flag + version + timestamp). Web only — the desktop app gates this in its installer. |
|
||||
|
||||
That is the entire on-disk footprint. Clearing your browser's site data
|
||||
removes everything. Nothing leaves your device.
|
||||
|
||||
@@ -38,11 +38,12 @@ JSONPrism is a refracting tool for developers. It takes a single JSON input and
|
||||
## Features
|
||||
|
||||
- **Client-side only** — no server, no telemetry, no upload. Your JSON stays in your browser.
|
||||
- **Fast first paint** — routes and the CodeMirror editor are lazy-loaded, and vendor/parser code is split into small per-feature chunks, so the browser only downloads what you actually use.
|
||||
- **Batch processing** — up to 500 files at once (Phase 2).
|
||||
- **Smart shape detection** — recognizes flat objects, arrays of objects, scalars; suggests the best target format.
|
||||
- **Per-format options** — pretty-print, indentation, dialect (for SQL), alignment (for Markdown), and more.
|
||||
- **Dark + light themes** — Prism Spectrum palette with violet / cyan / amber / rose accents.
|
||||
- **Responsive — designed for viewports ≥ 360 × 640.** Smaller screens still work but may feel cramped; on mobile, Input and Output use a Tabs UI to give each panel full height.
|
||||
- **Responsive — designed for viewports ≥ 360 × 640.** Smaller screens still work but may feel cramped; on mobile, Input and Output use a Tabs UI to give each panel full height. See [`docs/tested-viewports.md`](docs/tested-viewports.md) for the full device test matrix.
|
||||
- **EN + VI** — bilingual interface out of the box. More languages welcome.
|
||||
- **Tauri desktop build** — drag-and-drop file workflow, offline-first (Phase 2 milestone).
|
||||
|
||||
@@ -104,6 +105,54 @@ Output:
|
||||
|
||||
**Automated releases**: pushing a `v*` tag triggers `.github/workflows/release.yml`, which builds for all platforms in parallel and creates a draft GitHub release.
|
||||
|
||||
## Android app (Tauri 2)
|
||||
|
||||
JSONPrism also ships as an Android app you sideload from a `.apk`. Same React UI; native file picker via the dialog plugin. **Requires Android 12 (API 31) or newer** — the OS refuses to install it on older versions.
|
||||
|
||||
### System requirements
|
||||
|
||||
| Requirement | Detail |
|
||||
| --- | --- |
|
||||
| **Android version** | **12 (API 31)** or newer — older versions are blocked at install time (`INSTALL_FAILED_OLDER_SDK`) |
|
||||
| **System WebView** | **Chromium 111+** (Android System WebView / Chrome). Kept current by the Play Store on most devices; a much older WebView renders the layout incorrectly — update "Android System WebView" and Chrome from the Play Store if the UI looks broken. |
|
||||
| **CPU / ABI** | arm64-v8a, armeabi-v7a, x86, or x86_64 — the single universal APK runs on all of them (modern phones are arm64-v8a) |
|
||||
| **RAM** | 2 GB minimum; 4 GB recommended for large or batch (up to 500 files) conversions |
|
||||
| **Storage** | ~27 MB to download; ~100 MB free recommended (install + temporary working files) |
|
||||
| **Network** | None — the app runs fully offline and sends nothing off the device |
|
||||
|
||||
### Install (users)
|
||||
|
||||
1. Download `JSONPrism-<version>-android-universal.apk` from the [Releases](https://github.com/poli0981/jsonPrism/releases) page.
|
||||
2. Open it; Android will ask you to allow "install unknown apps" for your browser/file manager — enable it, then install.
|
||||
3. Needs Android 12+. The app runs fully offline.
|
||||
|
||||
### Build (developers)
|
||||
|
||||
**Additional requirements** (on top of the desktop Rust toolchain):
|
||||
|
||||
- **Android Studio** with SDK Platform **31+**, Build-Tools, Platform-Tools, Command-line Tools, and an **NDK**
|
||||
- **JDK** — the JBR bundled with Android Studio is fine
|
||||
- Environment variables: `JAVA_HOME`, `ANDROID_HOME`, `NDK_HOME` (see [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md))
|
||||
- Rust Android targets: `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android`
|
||||
|
||||
The Android Gradle project lives in `src-tauri/gen/android/` and is committed. You do **not** need to run `tauri android init` for a normal build.
|
||||
|
||||
**Run on a device/emulator** (Android 12+):
|
||||
|
||||
```bash
|
||||
npm run tauri:android:dev
|
||||
```
|
||||
|
||||
**Build a universal release APK**:
|
||||
|
||||
```bash
|
||||
npm run tauri:android:build
|
||||
```
|
||||
|
||||
Output: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`. Release signing is read from `src-tauri/gen/android/keystore.properties` (gitignored); without it the APK builds unsigned. See [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) for keystore setup and the CI signing secrets.
|
||||
|
||||
**Automated releases**: the same `v*` tag also runs the `android` job in `release.yml`, which signs the APK with the keystore from repository secrets and attaches it to the draft release.
|
||||
|
||||
### Scripts
|
||||
|
||||
| Script | What it does |
|
||||
|
||||
+50
-1
@@ -38,11 +38,12 @@ JSONPrism là công cụ "tán sắc" cho developer. Nhận một JSON đầu v
|
||||
## Tính năng
|
||||
|
||||
- **Chạy hoàn toàn client-side** — không server, không telemetry, không upload. JSON của bạn ở lại trong trình duyệt.
|
||||
- **Khởi động nhanh** — route và editor CodeMirror được lazy-load, mã vendor/parser tách thành nhiều chunk nhỏ theo tính năng, nên trình duyệt chỉ tải đúng phần bạn dùng.
|
||||
- **Xử lý batch** — tới 500 file cùng lúc (Phase 2).
|
||||
- **Phát hiện shape thông minh** — nhận diện flat object, mảng object, scalar; gợi ý format đích phù hợp.
|
||||
- **Tuỳ chọn theo từng format** — pretty-print, indentation, dialect (SQL), alignment (Markdown), v.v.
|
||||
- **Theme sáng/tối** — bảng màu Prism Spectrum với violet / cyan / amber / rose.
|
||||
- **Responsive — tối ưu cho viewport ≥ 360 × 640.** Màn hình nhỏ hơn vẫn dùng được nhưng có thể chật; trên mobile, Input và Output dùng Tabs UI để mỗi panel có toàn bộ chiều cao.
|
||||
- **Responsive — tối ưu cho viewport ≥ 360 × 640.** Màn hình nhỏ hơn vẫn dùng được nhưng có thể chật; trên mobile, Input và Output dùng Tabs UI để mỗi panel có toàn bộ chiều cao. Xem [`docs/tested-viewports.md`](docs/tested-viewports.md) cho ma trận thiết bị đã kiểm thử.
|
||||
- **Đa ngôn ngữ EN + VI** — sẵn sàng từ ngày đầu. Hoan nghênh thêm ngôn ngữ khác.
|
||||
- **Bản desktop Tauri** — drag-and-drop file, hoạt động offline (mốc Phase 2).
|
||||
|
||||
@@ -104,6 +105,54 @@ Output:
|
||||
|
||||
**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.
|
||||
|
||||
## Bản Android (Tauri 2)
|
||||
|
||||
JSONPrism còn có bản Android để bạn sideload từ file `.apk`. Cùng React UI; chọn file qua dialog native. **Yêu cầu Android 12 (API 31) trở lên** — máy cũ hơn sẽ bị hệ điều hành chặn cài.
|
||||
|
||||
### Yêu cầu hệ thống
|
||||
|
||||
| Yêu cầu | Chi tiết |
|
||||
| --- | --- |
|
||||
| **Phiên bản Android** | **12 (API 31)** trở lên — máy cũ hơn bị chặn ngay khi cài (`INSTALL_FAILED_OLDER_SDK`) |
|
||||
| **System WebView** | **Chromium 111+** (Android System WebView / Chrome). Đa số máy được Play Store cập nhật sẵn; WebView quá cũ sẽ render giao diện sai — nếu UI bị vỡ, hãy cập nhật "Android System WebView" và Chrome trong Play Store. |
|
||||
| **CPU / ABI** | arm64-v8a, armeabi-v7a, x86 hoặc x86_64 — một file APK universal chạy được trên tất cả (máy hiện đại là arm64-v8a) |
|
||||
| **RAM** | Tối thiểu 2 GB; khuyến nghị 4 GB cho file lớn hoặc xử lý hàng loạt (tối đa 500 file) |
|
||||
| **Dung lượng** | ~27 MB để tải; nên có ~100 MB trống (cài đặt + file tạm khi làm việc) |
|
||||
| **Mạng** | Không cần — app chạy hoàn toàn offline, không gửi gì ra ngoài |
|
||||
|
||||
### Cài đặt (người dùng)
|
||||
|
||||
1. Tải `JSONPrism-<version>-android-universal.apk` từ trang [Releases](https://github.com/poli0981/jsonPrism/releases).
|
||||
2. Mở file; Android sẽ hỏi cho phép "cài app không rõ nguồn" cho trình duyệt/trình quản lý file — bật lên rồi cài.
|
||||
3. Cần Android 12+. App chạy hoàn toàn offline.
|
||||
|
||||
### Build (lập trình viên)
|
||||
|
||||
**Yêu cầu thêm** (ngoài Rust toolchain của bản desktop):
|
||||
|
||||
- **Android Studio** với SDK Platform **31+**, Build-Tools, Platform-Tools, Command-line Tools và một bản **NDK**
|
||||
- **JDK** — dùng JBR đi kèm Android Studio là được
|
||||
- Biến môi trường: `JAVA_HOME`, `ANDROID_HOME`, `NDK_HOME` (xem [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md))
|
||||
- Rust Android targets: `rustup target add aarch64-linux-android armv7-linux-androideabi i686-linux-android x86_64-linux-android`
|
||||
|
||||
Project Gradle nằm ở `src-tauri/gen/android/` và đã được commit. Bạn **không** cần chạy `tauri android init` cho build thường.
|
||||
|
||||
**Chạy trên thiết bị/emulator** (Android 12+):
|
||||
|
||||
```bash
|
||||
npm run tauri:android:dev
|
||||
```
|
||||
|
||||
**Build APK release universal**:
|
||||
|
||||
```bash
|
||||
npm run tauri:android:build
|
||||
```
|
||||
|
||||
Output: `src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`. Thông tin ký lấy từ `src-tauri/gen/android/keystore.properties` (gitignored); thiếu file này thì APK build ra chưa ký. Xem [`docs/TAURI-NOTES.md`](docs/TAURI-NOTES.md) để biết cách tạo keystore và các secret ký trong CI.
|
||||
|
||||
**Release tự động**: cùng tag `v*` cũng chạy job `android` trong `release.yml`, ký APK bằng keystore từ repository secrets và đính vào draft release.
|
||||
|
||||
### Các script
|
||||
|
||||
| Script | Chức năng |
|
||||
|
||||
+5
-3
@@ -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
|
||||
@@ -84,8 +84,8 @@ installed as a runtime dependency.
|
||||
| `@tauri-apps/api` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-dialog` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-fs` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-opener` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-os` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/plugin-shell` | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
| `@tauri-apps/cli` (devDep) | ^2.0.0 | Apache-2.0 OR MIT | [tauri.app](https://tauri.app/) |
|
||||
|
||||
### Rust crates (`src-tauri/Cargo.toml`)
|
||||
@@ -96,8 +96,8 @@ installed as a runtime dependency.
|
||||
| `tauri-build` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-build](https://crates.io/crates/tauri-build) |
|
||||
| `tauri-plugin-dialog` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-dialog](https://crates.io/crates/tauri-plugin-dialog) |
|
||||
| `tauri-plugin-fs` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-fs](https://crates.io/crates/tauri-plugin-fs) |
|
||||
| `tauri-plugin-opener` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-opener](https://crates.io/crates/tauri-plugin-opener) |
|
||||
| `tauri-plugin-os` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-os](https://crates.io/crates/tauri-plugin-os) |
|
||||
| `tauri-plugin-shell` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-shell](https://crates.io/crates/tauri-plugin-shell) |
|
||||
| `tauri-plugin-single-instance` | 2 | Apache-2.0 OR MIT | [crates.io/crates/tauri-plugin-single-instance](https://crates.io/crates/tauri-plugin-single-instance) |
|
||||
| `serde` | 1 | Apache-2.0 OR MIT | [serde.rs](https://serde.rs/) |
|
||||
| `serde_json` | 1 | Apache-2.0 OR MIT | [github.com/serde-rs/json](https://github.com/serde-rs/json) |
|
||||
@@ -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
|
||||
|
||||
|
||||
+70
-2
@@ -219,7 +219,75 @@ Goal: ship the .NET RESX converter and integrate with existing AutoClickForge /
|
||||
|
||||
---
|
||||
|
||||
## Beyond Phase 3 — Ideas (no commitment)
|
||||
## Phase 4 — Binary formats & reverse conversion ✅
|
||||
|
||||
**Status**: complete (shipped in v1.1.0)
|
||||
|
||||
Post-1.0 expansion: three binary target formats and bidirectional conversion.
|
||||
|
||||
- [x] **BSON / CBOR / MessagePack** converters — output rendered as base64 (default) or hex; downloads decode back to raw bytes. New `ConverterMeta.binary` flag.
|
||||
- [x] **Reverse conversion** — optional `Converter<T>.reverse()` interface method; JSONL, CSV/TSV, YAML, TOML, RESX → JSON. New `DirectionToggle` component, direction persisted to localStorage.
|
||||
- [x] Reverse batch processing — drop non-JSON files, get a `.zip` of `.json` outputs back.
|
||||
|
||||
**12/12 formats production-ready.**
|
||||
|
||||
---
|
||||
|
||||
## Phase 5 — Maintenance & refactor ✅
|
||||
|
||||
**Status**: complete (shipped in v1.5.0)
|
||||
|
||||
Codebase hygiene plus a small UX addition — no converter behavior changed.
|
||||
|
||||
- [x] Decomposed three oversized components (`BatchPanel`, `ConverterWorkspace`, `InputPanel`) into focused pure utilities, leaf components, and hooks — behavior-preserving, all 193 tests still green.
|
||||
- [x] Integrated `knip` for dead-code analysis: `knip.json` config, `npm run knip` script, and a CI step. Initial sweep removed orphaned code and a phantom dependency.
|
||||
- [x] Scroll-to-top button on the long, scrollbar-hidden About page (respects `prefers-reduced-motion`).
|
||||
|
||||
---
|
||||
|
||||
## Phase 6 — Legal gates, error pages & load performance ✅
|
||||
|
||||
**Status**: complete (shipped in v1.6.0)
|
||||
|
||||
Compliance + reliability + first-paint performance. No converter behavior changed.
|
||||
|
||||
- [x] Custom error pages: reusable `ErrorState`, 404 catch-all, generic `/error/:code` (403/419/5xx variants), offline banner, and a chunk-load error boundary folded into the existing crash boundary's look.
|
||||
- [x] GitHub Pages SPA deep-link fix (`public/404.html` + `index.html` decoder for the `/jsonPrism/` base).
|
||||
- [x] First-launch legal consent gate (web only) — accept License/Terms/Privacy/Disclaimer, persisted to `localStorage` with a version for re-prompting; skipped on desktop.
|
||||
- [x] Windows installer license-acceptance page via Tauri `bundle.licenseFile` (`src-tauri/license.rtf`), covering both NSIS `.exe` and WiX `.msi`.
|
||||
- [x] Lazy-load routes + the CodeMirror editor; refined `manualChunks` (react/router/i18n/cm-core/cm-langs/per-parser/ui); removed the `bson` initial-graph leak via `lib/bytes.ts`. +16 tests (209 total).
|
||||
|
||||
---
|
||||
|
||||
## Phase 7 — Android (sideload APK) 🔜
|
||||
|
||||
**Status**: in progress
|
||||
|
||||
Goal: ship JSONPrism as an Android app users sideload from a `.apk`. Same React UI, no behavior change to the converters. **Minimum Android 12 (API 31)** — older devices are blocked by the OS.
|
||||
|
||||
### Tasks
|
||||
|
||||
- [x] `bundle.android` in `tauri.conf.json`: `minSdkVersion: 31`, deterministic `versionCode` (`MAJOR*10000+MINOR*100+PATCH`)
|
||||
- [x] `tauri android init` → Android Gradle project at `src-tauri/gen/android/`, **committed** (source only; build outputs + secrets gitignored via nested + root `.gitignore`)
|
||||
- [x] Verified `minSdk = 31` propagated to `app/build.gradle.kts`; Rust compiles for all 4 ABIs (validated against NDK r27/r30)
|
||||
- [x] Release signing wired in `app/build.gradle.kts` from a gitignored `keystore.properties` (graceful unsigned fallback when absent)
|
||||
- [x] Self-hosted fonts via `@fontsource` (Geist / Instrument Serif / JetBrains Mono) — removed Google Fonts `<link>`, tightened CSP, app renders correctly **offline**
|
||||
- [x] Local scripts: `tauri:android:init` / `tauri:android:dev` / `tauri:android:build` (universal APK; chains `tauri:icon`)
|
||||
- [x] CI: `android` job in `release.yml` builds + signs (keystore from secrets) + uploads the universal APK to the same draft release
|
||||
- [x] Docs: README / README.vi "Android" sections + maintainer notes in `docs/TAURI-NOTES.md`
|
||||
- [x] Emulator-validated: signed APK installs on Android 12+, **blocked on API < 31** (`INSTALL_FAILED_OLDER_SDK`), launches, renders (CodeMirror + self-hosted fonts), runs converters, fully offline
|
||||
- [x] Native file open works — `plugin-dialog` fires the SAF picker, `plugin-fs` reads the `content://` URI; `basenameFromPath()` recovers a clean filename (unit-tested)
|
||||
- [x] Found: layout needs WebView **Chromium ≥ 111** (Tailwind v4); fine on updated Android 12+ devices, broken on the API 31 emulator's stock Chromium 91 — see `docs/TAURI-NOTES.md`
|
||||
- [ ] Add CI signing secrets (`ANDROID_KEYSTORE_BASE64`, `ANDROID_KEYSTORE_PASSWORD`, …) — maintainer action
|
||||
- [ ] Remaining manual checks: save `.zip` via SAF, all 12 converters end-to-end, theme + 4 locales, upgrade-in-place on a real device
|
||||
|
||||
### Deliverable
|
||||
|
||||
A signed universal `.apk` attached to each GitHub release, installable on Android 12+. Same converter feature set as web/desktop, fully offline.
|
||||
|
||||
---
|
||||
|
||||
## 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 +296,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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+157
-4
@@ -15,8 +15,8 @@ process from outliving the main webview:
|
||||
any spawned shell children (none today, but the hook is in place) are
|
||||
signaled before the process exits.
|
||||
|
||||
If you ever add long-running spawned commands (e.g. via `tauri_plugin_shell`),
|
||||
remember to track their handles and kill them in the same hook.
|
||||
If you ever add long-running spawned commands (e.g. via a shell/command
|
||||
plugin), remember to track their handles and kill them in the same hook.
|
||||
|
||||
## WebView2 GDI leak (Windows, upstream)
|
||||
|
||||
@@ -45,8 +45,9 @@ See `src-tauri/capabilities/default.json`. Scope is intentionally narrow:
|
||||
- Filesystem reads/writes only inside `$HOME`, `$DOCUMENT`, `$DOWNLOAD`,
|
||||
`$DESKTOP`.
|
||||
- Dialog plugin for open/save.
|
||||
- Shell plugin restricted to `shell:allow-open` (URL opening only — no
|
||||
arbitrary command spawn).
|
||||
- Opener plugin (`opener:default`) for handing external URLs to the system
|
||||
browser — `shell:open` has no native Android URL handler, so the opener
|
||||
plugin's `openUrl` is used instead.
|
||||
|
||||
Widening the scope requires both a capability edit and a CSP review in
|
||||
`tauri.conf.json`.
|
||||
@@ -61,3 +62,155 @@ Widening the scope requires both a capability edit and a CSP review in
|
||||
The release matrix in `.github/workflows/release.yml` builds all four
|
||||
combinations (Linux, macOS Intel, macOS Apple Silicon, Windows) on a `v*`
|
||||
tag push.
|
||||
|
||||
## Android (sideload APK)
|
||||
|
||||
JSONPrism ships an Android APK that users sideload. **Minimum Android 12
|
||||
(API 31)** — set via `bundle.android.minSdkVersion` in `tauri.conf.json`; the
|
||||
OS installer refuses older devices. The build target is a **universal APK**
|
||||
(all ABIs in one file) so users only ever download one `.apk`.
|
||||
|
||||
### Toolchain (local, Windows)
|
||||
|
||||
Environment variables Tauri's CLI reads:
|
||||
|
||||
- `JAVA_HOME` → Android Studio's JBR, e.g. `C:\Jetbrains\Android Studio\jbr`
|
||||
- `ANDROID_HOME` → `C:\Users\<you>\AppData\Local\Android\Sdk`
|
||||
- `NDK_HOME` → `…\Android\Sdk\ndk\<version>`
|
||||
|
||||
Rust targets: `rustup target add aarch64-linux-android armv7-linux-androideabi
|
||||
i686-linux-android x86_64-linux-android`. Verify with `npm run tauri info`.
|
||||
|
||||
> **NDK selection.** The CLI auto-picks the **highest** NDK under
|
||||
> `$ANDROID_HOME/ndk`, regardless of `NDK_HOME`. If you keep multiple NDKs and
|
||||
> want a specific one, leave only that version installed. Builds are validated
|
||||
> against NDK r27+; CI pins `ndk;27.2.12479018`.
|
||||
|
||||
### The `gen/android` project
|
||||
|
||||
`src-tauri/gen/android/` (the Gradle project from `tauri android init`) is
|
||||
**committed** — source only. Its nested `.gitignore` files exclude build
|
||||
outputs (`build/`, `.gradle/`, `.cxx/`, `*.so`, `local.properties`,
|
||||
`keystore.properties`). Committing it keeps the signing edits in
|
||||
`app/build.gradle.kts` and `minSdkVersion` stable, and makes CI reproducible.
|
||||
|
||||
You normally do **not** run `tauri android init` again. Only re-run it after a
|
||||
major `@tauri-apps/cli` bump, and re-apply the signing block + verify
|
||||
`minSdk = 31` in `app/build.gradle.kts` afterward (the init overwrites it).
|
||||
|
||||
Launcher icons (`res/mipmap-*/ic_launcher*.png`) are generated by
|
||||
`npm run tauri:icon` and gitignored, like the desktop icons — both the local
|
||||
`tauri:android:build` script and CI regenerate them before building.
|
||||
|
||||
### versionCode
|
||||
|
||||
`bundle.android.versionCode` in `tauri.conf.json` must increase monotonically
|
||||
(needed for in-place upgrades). Derive it deterministically from semver:
|
||||
|
||||
```
|
||||
versionCode = MAJOR*10000 + MINOR*100 + PATCH
|
||||
```
|
||||
|
||||
e.g. `1.6.1 → 10601`, `1.7.0 → 10700`. Bump it together with `version` in
|
||||
`package.json` / `Cargo.toml` / `tauri.conf.json` at release time.
|
||||
|
||||
### Signing
|
||||
|
||||
Release signing is read from `src-tauri/gen/android/keystore.properties`
|
||||
(gitignored), which points at a keystore `.jks` (also gitignored, kept outside
|
||||
the repo). If the file is absent the release variant builds **unsigned** — fine
|
||||
for contributors, but a release APK must be signed so it installs and so future
|
||||
versions can upgrade in place.
|
||||
|
||||
Generate a keystore once:
|
||||
|
||||
```powershell
|
||||
& "$env:JAVA_HOME\bin\keytool.exe" -genkeypair -v `
|
||||
-keystore "$env:USERPROFILE\jsonprism-upload-keystore.jks" -storetype JKS `
|
||||
-keyalg RSA -keysize 2048 -validity 10000 -alias upload
|
||||
```
|
||||
|
||||
Then create `src-tauri/gen/android/keystore.properties`:
|
||||
|
||||
```
|
||||
storePassword=…
|
||||
keyPassword=…
|
||||
keyAlias=upload
|
||||
storeFile=C:/Users/<you>/jsonprism-upload-keystore.jks
|
||||
```
|
||||
|
||||
> Use forward slashes in `storeFile` — `.properties` treats `\` as an escape.
|
||||
> **Back up the `.jks` and its passwords** (password manager). Losing the key
|
||||
> means users can no longer upgrade in place — they'd have to uninstall first.
|
||||
|
||||
### CI signing secrets
|
||||
|
||||
The `android` job in `release.yml` needs these repository secrets:
|
||||
|
||||
| Secret | Value |
|
||||
| --- | --- |
|
||||
| `ANDROID_KEYSTORE_BASE64` | base64 of the `.jks` (required) |
|
||||
| `ANDROID_KEYSTORE_PASSWORD` | the store password (required) |
|
||||
| `ANDROID_KEY_PASSWORD` | the key password (optional; defaults to store password) |
|
||||
| `ANDROID_KEY_ALIAS` | the alias (optional; defaults to `upload`) |
|
||||
|
||||
Produce the base64 (PowerShell):
|
||||
|
||||
```powershell
|
||||
[Convert]::ToBase64String([IO.File]::ReadAllBytes("$env:USERPROFILE\jsonprism-upload-keystore.jks")) | Set-Clipboard
|
||||
```
|
||||
|
||||
CI decodes it to a temp path, writes `keystore.properties`, builds with
|
||||
`tauri android build --apk`, and uploads the universal APK to the same draft
|
||||
release as the desktop bundles. If `ANDROID_KEYSTORE_BASE64` is unset the job
|
||||
fails fast rather than shipping an unsigned APK.
|
||||
|
||||
### Output
|
||||
|
||||
`src-tauri/gen/android/app/build/outputs/apk/universal/release/app-universal-release.apk`
|
||||
|
||||
### Offline fonts
|
||||
|
||||
Fonts (Geist / Instrument Serif / JetBrains Mono) are self-hosted via
|
||||
`@fontsource` (imported in `src/main.tsx`), not loaded from Google Fonts, so the
|
||||
app renders correctly offline. The CSP in `tauri.conf.json` no longer allows the
|
||||
Google Fonts hosts — keep it that way unless fonts move back to a CDN.
|
||||
|
||||
### WebView version requirement (important)
|
||||
|
||||
The Android app renders inside the device's **Android System WebView**, which is
|
||||
Chromium. Tailwind v4 (our CSS) requires **Chromium ≥ 111** (`@layer`, `oklch()`,
|
||||
`@property`). On an older WebView the layout breaks badly (giant icons, unhidden
|
||||
elements, no responsive layout) even though the app installs and runs.
|
||||
|
||||
- Real Android 12+ devices keep WebView updated via Play Store → modern Chromium
|
||||
→ renders correctly. This is the normal case.
|
||||
- The bundled WebView in the **API 31 emulator system image is Chromium 91** and
|
||||
shows the broken layout. Use a newer emulator image (e.g. `android-34`+, which
|
||||
ships Chromium ≥ 120) or update the emulator's WebView via Play to test
|
||||
rendering. The `android-31` install/`minSdk` gate can still be tested on the
|
||||
stock API 31 image.
|
||||
|
||||
This is inherent to the Tailwind v4 stack (the web app has the same requirement);
|
||||
it is not Android-specific code. No action needed unless you must support devices
|
||||
with a very outdated WebView.
|
||||
|
||||
### Native file I/O on Android
|
||||
|
||||
`plugin-dialog` `open()` returns a percent-encoded `content://` URI on Android
|
||||
(not a filesystem path). `plugin-fs` `readTextFile()` reads it fine — validated on
|
||||
an emulator for both URI flavours. `fileFromNativePath()` (`src/lib/tauri.ts`)
|
||||
runs the URI through `basenameFromPath()` to recover a filename for the editor,
|
||||
the extension filter, and toasts. `stat()` on a content URI is unreliable, so
|
||||
`lastModified` falls back to a deterministic path hash — dedup still works.
|
||||
|
||||
Two URI flavours show up:
|
||||
- **`raw:` URIs** (most local/Downloads files) embed the real path →
|
||||
`basenameFromPath()` recovers `data.json`.
|
||||
- **`msf:` URIs** (MediaStore-indexed files) are opaque document ids with no
|
||||
filename → they collapse to a numeric id (e.g. `18`) and **carry no
|
||||
extension**. The native open path therefore filters leniently
|
||||
(`filterByExtension(..., true)` / the `extOf(name) && !allowed` guard in
|
||||
`InputPanel`) so a file the user explicitly picked is never wrongly rejected.
|
||||
The real display name would need a content-resolver `DISPLAY_NAME` query via a
|
||||
custom Rust command — not worth it; the file content loads correctly either way.
|
||||
@@ -25,8 +25,12 @@ Dùng để kiểm tra bản web (chủ yếu là deploy lên GitHub Pages) trê
|
||||
- iPhone 14 Pro — iOS 26.x — Chrome, Brave
|
||||
- iPhone 13 Pro Max — iOS 26.x — Chrome, Brave
|
||||
|
||||
Test Android là cơ hội (không có thiết bị chuyên dụng); bản web vẫn nên
|
||||
chạy được với các phiên bản WebView phổ thông.
|
||||
Android: app được build và smoke-test trên emulator (API 31 cho cổng chặn
|
||||
cài / min-SDK, API 36 với WebView Chromium 134 cho phần render) — chưa có
|
||||
thiết bị thật chuyên dụng. **Yêu cầu hệ thống cho người dùng cuối** (Android
|
||||
12+, WebView Chromium 111+, RAM, dung lượng) nằm ở mục "Yêu cầu hệ thống"
|
||||
trong README; chi tiết build / ký nằm ở
|
||||
[docs/TAURI-NOTES.md](../../TAURI-NOTES.md).
|
||||
|
||||
## Tài liệu liên quan
|
||||
|
||||
|
||||
+6
-2
@@ -26,8 +26,12 @@ form factors:
|
||||
- iPhone 14 Pro — iOS 26.x — Chrome, Brave
|
||||
- iPhone 13 Pro Max — iOS 26.x — Chrome, Brave
|
||||
|
||||
Android testing is opportunistic (no dedicated device); the web build
|
||||
should still work given mainstream WebView versions.
|
||||
Android: the app is built and smoke-tested on emulators (API 31 for the
|
||||
install / min-SDK gate, API 36 with a Chromium 134 WebView for rendering) —
|
||||
no dedicated physical device yet. **End-user system requirements** (Android
|
||||
12+, WebView Chromium 111+, RAM, storage) live in the README "System
|
||||
requirements" section; build / signing details are in
|
||||
[docs/TAURI-NOTES.md](TAURI-NOTES.md).
|
||||
|
||||
## Related docs
|
||||
|
||||
|
||||
@@ -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.
|
||||
+26
-7
@@ -7,6 +7,27 @@
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<meta name="theme-color" content="#0a0b14" />
|
||||
|
||||
<!--
|
||||
Restores a deep-link path that public/404.html encoded into the query
|
||||
string on GitHub Pages (see that file). Must run before the SPA router
|
||||
reads the URL. No-op everywhere else (including Tauri) since `?/` is only
|
||||
ever present right after the 404 redirect.
|
||||
-->
|
||||
<script type="text/javascript">
|
||||
(function (l) {
|
||||
if (l.search[1] === '/') {
|
||||
var decoded = l.search
|
||||
.slice(1)
|
||||
.split('&')
|
||||
.map(function (s) {
|
||||
return s.replace(/~and~/g, '&');
|
||||
})
|
||||
.join('?');
|
||||
window.history.replaceState(null, null, l.pathname.slice(0, -1) + decoded + l.hash);
|
||||
}
|
||||
})(window.location);
|
||||
</script>
|
||||
|
||||
<meta name="description" content="JSONPrism — disperse JSON into many formats. Convert to JSONL, CSV, YAML, XML, TOML, RESX, Markdown, SQL. Fully client-side, batch up to 500 files." />
|
||||
<meta name="keywords" content="JSON, converter, JSONL, YAML, CSV, XML, TOML, RESX, Markdown, SQL, batch, offline" />
|
||||
|
||||
@@ -15,13 +36,11 @@
|
||||
<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"
|
||||
/>
|
||||
<!--
|
||||
Fonts: Instrument Serif (display) + Geist (body) + JetBrains Mono (code).
|
||||
Self-hosted via @fontsource and imported in src/main.tsx so the app works
|
||||
fully offline (desktop + Android sideload) with no third-party requests.
|
||||
-->
|
||||
|
||||
<title>JSONPrism · Disperse JSON</title>
|
||||
</head>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"project": ["src/**/*.{ts,tsx}"],
|
||||
"ignore": ["src/components/ui/**"],
|
||||
"ignoreDependencies": [
|
||||
"@radix-ui/react-slot",
|
||||
"tailwindcss",
|
||||
"tw-animate-css",
|
||||
"@tauri-apps/plugin-opener",
|
||||
"@tauri-apps/plugin-os",
|
||||
"@testing-library/user-event"
|
||||
],
|
||||
"rules": {
|
||||
"types": "off"
|
||||
}
|
||||
}
|
||||
Generated
+1490
-693
File diff suppressed because it is too large.
Load diff
+36
-27
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "jsonprism",
|
||||
"private": true,
|
||||
"version": "1.4.2",
|
||||
"version": "1.7.2",
|
||||
"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",
|
||||
@@ -30,7 +31,10 @@
|
||||
"tauri": "tauri",
|
||||
"tauri:dev": "tauri dev",
|
||||
"tauri:build": "tauri build",
|
||||
"tauri:icon": "tauri icon src-tauri/icons/icon.svg"
|
||||
"tauri:icon": "tauri icon src-tauri/icons/icon.svg",
|
||||
"tauri:android:init": "tauri android init",
|
||||
"tauri:android:dev": "npm run tauri:icon && tauri android dev",
|
||||
"tauri:android:build": "npm run tauri:icon && tauri android build --apk"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-json": "^6.0.0",
|
||||
@@ -39,68 +43,73 @@
|
||||
"@codemirror/lang-xml": "^6.1.0",
|
||||
"@codemirror/lang-yaml": "^6.1.3",
|
||||
"@codemirror/language": "^6.10.0",
|
||||
"@codemirror/legacy-modes": "^6.5.2",
|
||||
"@codemirror/lint": "^6.8.0",
|
||||
"@codemirror/legacy-modes": "^6.5.3",
|
||||
"@codemirror/lint": "^6.9.7",
|
||||
"@codemirror/state": "^6.4.0",
|
||||
"@codemirror/view": "^6.34.0",
|
||||
"@codemirror/view": "^6.43.1",
|
||||
"@fontsource-variable/geist": "^5.2.9",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.2.8",
|
||||
"@fontsource/instrument-serif": "^5.2.8",
|
||||
"@lezer/highlight": "^1.2.0",
|
||||
"@msgpack/msgpack": "^3.1.3",
|
||||
"@radix-ui/react-dialog": "^1.1.0",
|
||||
"@radix-ui/react-dialog": "^1.1.16",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-switch": "^1.1.0",
|
||||
"@radix-ui/react-tabs": "^1.1.13",
|
||||
"@radix-ui/react-switch": "^1.3.0",
|
||||
"@radix-ui/react-tabs": "^1.1.14",
|
||||
"@tauri-apps/api": "^2.0.0",
|
||||
"@tauri-apps/plugin-dialog": "^2.0.0",
|
||||
"@tauri-apps/plugin-fs": "^2.0.0",
|
||||
"@tauri-apps/plugin-opener": "^2.0.0",
|
||||
"@tauri-apps/plugin-os": "^2.0.0",
|
||||
"@tauri-apps/plugin-shell": "^2.0.0",
|
||||
"@uiw/react-codemirror": "^4.23.0",
|
||||
"@uiw/react-codemirror": "^4.25.10",
|
||||
"bson": "^7.2.0",
|
||||
"cbor-x": "^1.6.4",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.0",
|
||||
"fast-xml-parser": "^5.8.0",
|
||||
"fflate": "^0.8.2",
|
||||
"fflate": "^0.8.3",
|
||||
"i18next": "^23.0.0",
|
||||
"i18next-browser-languagedetector": "^8.0.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"js-yaml": "^4.2.0",
|
||||
"lucide-react": "^0.460.0",
|
||||
"papaparse": "^5.4.0",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-dropzone": "^14.3.0",
|
||||
"react-i18next": "^15.0.0",
|
||||
"react-router-dom": "^7.0.0",
|
||||
"react-router-dom": "^7.17.0",
|
||||
"smol-toml": "^1.3.0",
|
||||
"sonner": "^1.7.0",
|
||||
"sonner": "^2.0.7",
|
||||
"tailwind-merge": "^2.5.0",
|
||||
"zustand": "^5.0.0"
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.15.0",
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tauri-apps/cli": "^2.0.0",
|
||||
"@tailwindcss/vite": "^4.3.1",
|
||||
"@tauri-apps/cli": "^2.11.2",
|
||||
"@testing-library/jest-dom": "^6.6.0",
|
||||
"@testing-library/react": "^16.1.0",
|
||||
"@testing-library/user-event": "^14.5.0",
|
||||
"@types/js-yaml": "^4.0.0",
|
||||
"@types/node": "^22.0.0",
|
||||
"@types/papaparse": "^5.3.0",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^6.0.0",
|
||||
"@vitest/coverage-v8": "^4.1.6",
|
||||
"@vitejs/plugin-react": "^6.0.2",
|
||||
"@vitest/coverage-v8": "^4.1.8",
|
||||
"eslint": "^9.15.0",
|
||||
"eslint-plugin-react-hooks": "^5.0.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.0",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^14.0.0",
|
||||
"jsdom": "^29.0.0",
|
||||
"prettier": "^3.4.0",
|
||||
"prettier-plugin-tailwindcss": "^0.6.0",
|
||||
"knip": "^6.16.1",
|
||||
"prettier": "^3.8.4",
|
||||
"prettier-plugin-tailwindcss": "^0.8.0",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"tw-animate-css": "^1.2.0",
|
||||
"typescript": "^5.7.0",
|
||||
"typescript-eslint": "^8.15.0",
|
||||
"vite": "^8.0.0",
|
||||
"typescript-eslint": "^8.61.0",
|
||||
"vite": "^8.0.16",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>JSONPrism</title>
|
||||
<!--
|
||||
GitHub Pages serves this file for any unknown path. Because JSONPrism is a
|
||||
BrowserRouter SPA, a deep-link refresh (e.g. /jsonPrism/about) would 404
|
||||
here. This script encodes the requested path into a query string and
|
||||
redirects to the app's index, where a small decoder in index.html restores
|
||||
the real route. Technique: https://github.com/rafgraph/spa-github-pages
|
||||
|
||||
pathSegmentsToKeep = 1 preserves the project-page base segment (/jsonPrism/).
|
||||
-->
|
||||
<script type="text/javascript">
|
||||
var pathSegmentsToKeep = 1;
|
||||
var l = window.location;
|
||||
l.replace(
|
||||
l.protocol +
|
||||
'//' +
|
||||
l.hostname +
|
||||
(l.port ? ':' + l.port : '') +
|
||||
l.pathname
|
||||
.split('/')
|
||||
.slice(0, 1 + pathSegmentsToKeep)
|
||||
.join('/') +
|
||||
'/?/' +
|
||||
l.pathname
|
||||
.slice(1)
|
||||
.split('/')
|
||||
.slice(pathSegmentsToKeep)
|
||||
.join('/')
|
||||
.replace(/&/g, '~and~') +
|
||||
(l.search ? '&' + l.search.slice(1).replace(/&/g, '~and~') : '') +
|
||||
l.hash,
|
||||
);
|
||||
</script>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
+11
-1
@@ -1,13 +1,23 @@
|
||||
/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/64x64.png
|
||||
icons/128x128.png
|
||||
icons/128x128@2x.png
|
||||
icons/icon.png
|
||||
icons/icon.icns
|
||||
icons/icon.ico
|
||||
icons/Square*.png
|
||||
icons/StoreLogo.png
|
||||
icons/ios/
|
||||
|
||||
# Android launcher icons are also generated by `npm run tauri:icon` (run before each Android build).
|
||||
gen/android/app/src/main/res/mipmap-*/ic_launcher*.png
|
||||
|
||||
# Android signing — never commit the keystore binary.
|
||||
# (keystore.properties / key.properties are already ignored by gen/android/.gitignore)
|
||||
*.jks
|
||||
*.keystore
|
||||
Generated
+5310
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "jsonprism"
|
||||
version = "1.4.2"
|
||||
version = "1.7.2"
|
||||
description = "Disperse JSON into many formats."
|
||||
authors = ["poli0981 <https://github.com/poli0981>"]
|
||||
license = "Apache-2.0"
|
||||
@@ -20,8 +20,8 @@ tauri-build = { version = "2", features = [] }
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-dialog = "2"
|
||||
tauri-plugin-fs = "2"
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-os = "2"
|
||||
tauri-plugin-shell = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"core:webview:default",
|
||||
"core:window:default",
|
||||
"core:window:allow-set-title",
|
||||
"shell:allow-open",
|
||||
"opener:default",
|
||||
"os:default",
|
||||
"dialog:default",
|
||||
"dialog:allow-open",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# EditorConfig is awesome: https://EditorConfig.org
|
||||
|
||||
# top-most EditorConfig file
|
||||
root = true
|
||||
|
||||
[*]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = false
|
||||
insert_final_newline = false
|
||||
@@ -0,0 +1,20 @@
|
||||
*.iml
|
||||
.gradle
|
||||
/local.properties
|
||||
/.idea/caches
|
||||
/.idea/libraries
|
||||
/.idea/modules.xml
|
||||
/.idea/workspace.xml
|
||||
/.idea/navEditor.xml
|
||||
/.idea/assetWizardSettings.xml
|
||||
.DS_Store
|
||||
build
|
||||
/captures
|
||||
.externalNativeBuild
|
||||
.cxx
|
||||
local.properties
|
||||
key.properties
|
||||
keystore.properties
|
||||
|
||||
/.tauri
|
||||
/tauri.settings.gradle
|
||||
@@ -0,0 +1,6 @@
|
||||
/src/main/**/generated
|
||||
/src/main/jniLibs/**/*.so
|
||||
/src/main/assets/tauri.conf.json
|
||||
/tauri.build.gradle.kts
|
||||
/proguard-tauri.pro
|
||||
/tauri.properties
|
||||
@@ -0,0 +1,97 @@
|
||||
import java.io.FileInputStream
|
||||
import java.util.Properties
|
||||
|
||||
plugins {
|
||||
id("com.android.application")
|
||||
id("org.jetbrains.kotlin.android")
|
||||
id("rust")
|
||||
}
|
||||
|
||||
val tauriProperties = Properties().apply {
|
||||
val propFile = file("tauri.properties")
|
||||
if (propFile.exists()) {
|
||||
propFile.inputStream().use { load(it) }
|
||||
}
|
||||
}
|
||||
|
||||
// Release signing — loaded from `keystore.properties` at the gen/android root.
|
||||
// That file (and the .jks it points to) is gitignored; it lives only on the
|
||||
// maintainer's machine and is decoded from GitHub Secrets in CI. When it's
|
||||
// absent (e.g. a contributor build) the release variant simply stays unsigned.
|
||||
val keystorePropertiesFile = rootProject.file("keystore.properties")
|
||||
val hasReleaseKeystore = keystorePropertiesFile.exists()
|
||||
val keystoreProperties = Properties().apply {
|
||||
if (hasReleaseKeystore) {
|
||||
FileInputStream(keystorePropertiesFile).use { load(it) }
|
||||
}
|
||||
}
|
||||
|
||||
android {
|
||||
compileSdk = 36
|
||||
namespace = "com.poli0981.jsonprism"
|
||||
defaultConfig {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "false"
|
||||
applicationId = "com.poli0981.jsonprism"
|
||||
minSdk = 31
|
||||
targetSdk = 36
|
||||
versionCode = tauriProperties.getProperty("tauri.android.versionCode", "1").toInt()
|
||||
versionName = tauriProperties.getProperty("tauri.android.versionName", "1.0")
|
||||
}
|
||||
signingConfigs {
|
||||
if (hasReleaseKeystore) {
|
||||
create("release") {
|
||||
keyAlias = keystoreProperties.getProperty("keyAlias")
|
||||
keyPassword = keystoreProperties.getProperty("keyPassword")
|
||||
storeFile = file(keystoreProperties.getProperty("storeFile"))
|
||||
storePassword = keystoreProperties.getProperty("storePassword")
|
||||
}
|
||||
}
|
||||
}
|
||||
buildTypes {
|
||||
getByName("debug") {
|
||||
manifestPlaceholders["usesCleartextTraffic"] = "true"
|
||||
isDebuggable = true
|
||||
isJniDebuggable = true
|
||||
isMinifyEnabled = false
|
||||
packaging { jniLibs.keepDebugSymbols.add("*/arm64-v8a/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/armeabi-v7a/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/x86/*.so")
|
||||
jniLibs.keepDebugSymbols.add("*/x86_64/*.so")
|
||||
}
|
||||
}
|
||||
getByName("release") {
|
||||
isMinifyEnabled = true
|
||||
proguardFiles(
|
||||
*fileTree(".") { include("**/*.pro") }
|
||||
.plus(getDefaultProguardFile("proguard-android-optimize.txt"))
|
||||
.toList().toTypedArray()
|
||||
)
|
||||
if (hasReleaseKeystore) {
|
||||
signingConfig = signingConfigs.getByName("release")
|
||||
}
|
||||
}
|
||||
}
|
||||
kotlinOptions {
|
||||
jvmTarget = "1.8"
|
||||
}
|
||||
buildFeatures {
|
||||
buildConfig = true
|
||||
}
|
||||
}
|
||||
|
||||
rust {
|
||||
rootDirRel = "../../../"
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation("androidx.webkit:webkit:1.14.0")
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation("androidx.activity:activity-ktx:1.10.1")
|
||||
implementation("com.google.android.material:material:1.12.0")
|
||||
implementation("androidx.lifecycle:lifecycle-process:2.10.0")
|
||||
testImplementation("junit:junit:4.13.2")
|
||||
androidTestImplementation("androidx.test.ext:junit:1.1.4")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.0")
|
||||
}
|
||||
|
||||
apply(from = "tauri.build.gradle.kts")
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
# Add project specific ProGuard rules here.
|
||||
# You can control the set of applied configuration files using the
|
||||
# proguardFiles setting in build.gradle.
|
||||
#
|
||||
# For more details, see
|
||||
# http://developer.android.com/guide/developing/tools/proguard.html
|
||||
|
||||
# If your project uses WebView with JS, uncomment the following
|
||||
# and specify the fully qualified class name to the JavaScript interface
|
||||
# class:
|
||||
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
|
||||
# public *;
|
||||
#}
|
||||
|
||||
# Uncomment this to preserve the line number information for
|
||||
# debugging stack traces.
|
||||
#-keepattributes SourceFile,LineNumberTable
|
||||
|
||||
# If you keep the line number information, uncomment this to
|
||||
# hide the original source file name.
|
||||
#-renamesourcefileattribute SourceFile
|
||||
@@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
|
||||
<!-- AndroidTV support -->
|
||||
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||
|
||||
<application
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:label="@string/app_name"
|
||||
android:theme="@style/Theme.jsonprism"
|
||||
android:usesCleartextTraffic="${usesCleartextTraffic}">
|
||||
<activity
|
||||
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode"
|
||||
android:launchMode="singleTask"
|
||||
android:label="@string/main_activity_title"
|
||||
android:name=".MainActivity"
|
||||
android:exported="true">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
<!-- AndroidTV support -->
|
||||
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<provider
|
||||
android:name="androidx.core.content.FileProvider"
|
||||
android:authorities="${applicationId}.fileprovider"
|
||||
android:exported="false"
|
||||
android:grantUriPermissions="true">
|
||||
<meta-data
|
||||
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||
android:resource="@xml/file_paths" />
|
||||
</provider>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.poli0981.jsonprism
|
||||
|
||||
import android.os.Bundle
|
||||
import androidx.activity.enableEdgeToEdge
|
||||
|
||||
class MainActivity : TauriActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
enableEdgeToEdge()
|
||||
super.onCreate(savedInstanceState)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:aapt="http://schemas.android.com/aapt"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
|
||||
<aapt:attr name="android:fillColor">
|
||||
<gradient
|
||||
android:endX="85.84757"
|
||||
android:endY="92.4963"
|
||||
android:startX="42.9492"
|
||||
android:startY="49.59793"
|
||||
android:type="linear">
|
||||
<item
|
||||
android:color="#44000000"
|
||||
android:offset="0.0" />
|
||||
<item
|
||||
android:color="#00000000"
|
||||
android:offset="1.0" />
|
||||
</gradient>
|
||||
</aapt:attr>
|
||||
</path>
|
||||
<path
|
||||
android:fillColor="#FFFFFF"
|
||||
android:fillType="nonZero"
|
||||
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
|
||||
android:strokeWidth="1"
|
||||
android:strokeColor="#00000000" />
|
||||
</vector>
|
||||
@@ -0,0 +1,170 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<vector xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:width="108dp"
|
||||
android:height="108dp"
|
||||
android:viewportWidth="108"
|
||||
android:viewportHeight="108">
|
||||
<path
|
||||
android:fillColor="#3DDC84"
|
||||
android:pathData="M0,0h108v108h-108z" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M9,0L9,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,0L19,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,0L29,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,0L39,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,0L49,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,0L59,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,0L69,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,0L79,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M89,0L89,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M99,0L99,108"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,9L108,9"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,19L108,19"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,29L108,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,39L108,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,49L108,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,59L108,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,69L108,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,79L108,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,89L108,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M0,99L108,99"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,29L89,29"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,39L89,39"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,49L89,49"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,59L89,59"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,69L89,69"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M19,79L89,79"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M29,19L29,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M39,19L39,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M49,19L49,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M59,19L59,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M69,19L69,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
<path
|
||||
android:fillColor="#00000000"
|
||||
android:pathData="M79,19L79,89"
|
||||
android:strokeWidth="0.8"
|
||||
android:strokeColor="#33FFFFFF" />
|
||||
</vector>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:app="http://schemas.android.com/apk/res-auto"
|
||||
xmlns:tools="http://schemas.android.com/tools"
|
||||
android:layout_width="match_parent"
|
||||
android:layout_height="match_parent"
|
||||
tools:context=".MainActivity">
|
||||
|
||||
<TextView
|
||||
android:layout_width="wrap_content"
|
||||
android:layout_height="wrap_content"
|
||||
android:text="Hello World!"
|
||||
app:layout_constraintBottom_toBottomOf="parent"
|
||||
app:layout_constraintLeft_toLeftOf="parent"
|
||||
app:layout_constraintRight_toRightOf="parent"
|
||||
app:layout_constraintTop_toTopOf="parent" />
|
||||
|
||||
</androidx.constraintlayout.widget.ConstraintLayout>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<foreground android:drawable="@mipmap/ic_launcher_foreground"/>
|
||||
<background android:drawable="@color/ic_launcher_background"/>
|
||||
</adaptive-icon>
|
||||
@@ -0,0 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.jsonprism" parent="Theme.MaterialComponents.DayNight.NoActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="purple_200">#FFBB86FC</color>
|
||||
<color name="purple_500">#FF6200EE</color>
|
||||
<color name="purple_700">#FF3700B3</color>
|
||||
<color name="teal_200">#FF03DAC5</color>
|
||||
<color name="teal_700">#FF018786</color>
|
||||
<color name="black">#FF000000</color>
|
||||
<color name="white">#FFFFFFFF</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<resources>
|
||||
<color name="ic_launcher_background">#fff</color>
|
||||
</resources>
|
||||
@@ -0,0 +1,4 @@
|
||||
<resources>
|
||||
<string name="app_name">JSONPrism</string>
|
||||
<string name="main_activity_title">JSONPrism</string>
|
||||
</resources>
|
||||
@@ -0,0 +1,6 @@
|
||||
<resources xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- Base application theme. -->
|
||||
<style name="Theme.jsonprism" parent="Theme.MaterialComponents.DayNight.NoActionBar">
|
||||
<!-- Customize your theme here. -->
|
||||
</style>
|
||||
</resources>
|
||||
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<paths xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<external-path name="my_images" path="." />
|
||||
<cache-path name="my_cache_images" path="." />
|
||||
</paths>
|
||||
@@ -0,0 +1,22 @@
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("com.android.tools.build:gradle:8.11.0")
|
||||
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.9.25")
|
||||
}
|
||||
}
|
||||
|
||||
allprojects {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
}
|
||||
|
||||
tasks.register("clean").configure {
|
||||
delete("build")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
plugins {
|
||||
`kotlin-dsl`
|
||||
}
|
||||
|
||||
gradlePlugin {
|
||||
plugins {
|
||||
create("pluginsForCoolKids") {
|
||||
id = "rust"
|
||||
implementationClass = "RustPlugin"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compileOnly(gradleApi())
|
||||
implementation("com.android.tools.build:gradle:8.11.0")
|
||||
}
|
||||
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import java.io.File
|
||||
import org.apache.tools.ant.taskdefs.condition.Os
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.GradleException
|
||||
import org.gradle.api.logging.LogLevel
|
||||
import org.gradle.api.tasks.Input
|
||||
import org.gradle.api.tasks.TaskAction
|
||||
|
||||
open class BuildTask : DefaultTask() {
|
||||
@Input
|
||||
var rootDirRel: String? = null
|
||||
@Input
|
||||
var target: String? = null
|
||||
@Input
|
||||
var release: Boolean? = null
|
||||
|
||||
@TaskAction
|
||||
fun assemble() {
|
||||
val executable = """npm""";
|
||||
try {
|
||||
runTauriCli(executable)
|
||||
} catch (e: Exception) {
|
||||
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
|
||||
// Try different Windows-specific extensions
|
||||
val fallbacks = listOf(
|
||||
"$executable.exe",
|
||||
"$executable.cmd",
|
||||
"$executable.bat",
|
||||
)
|
||||
|
||||
var lastException: Exception = e
|
||||
for (fallback in fallbacks) {
|
||||
try {
|
||||
runTauriCli(fallback)
|
||||
return
|
||||
} catch (fallbackException: Exception) {
|
||||
lastException = fallbackException
|
||||
}
|
||||
}
|
||||
throw lastException
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun runTauriCli(executable: String) {
|
||||
val rootDirRel = rootDirRel ?: throw GradleException("rootDirRel cannot be null")
|
||||
val target = target ?: throw GradleException("target cannot be null")
|
||||
val release = release ?: throw GradleException("release cannot be null")
|
||||
val args = listOf("run", "--", "tauri", "android", "android-studio-script");
|
||||
|
||||
project.exec {
|
||||
workingDir(File(project.projectDir, rootDirRel))
|
||||
executable(executable)
|
||||
args(args)
|
||||
if (project.logger.isEnabled(LogLevel.DEBUG)) {
|
||||
args("-vv")
|
||||
} else if (project.logger.isEnabled(LogLevel.INFO)) {
|
||||
args("-v")
|
||||
}
|
||||
if (release) {
|
||||
args("--release")
|
||||
}
|
||||
args(listOf("--target", target))
|
||||
}.assertNormalExitValue()
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
import com.android.build.api.dsl.ApplicationExtension
|
||||
import org.gradle.api.DefaultTask
|
||||
import org.gradle.api.Plugin
|
||||
import org.gradle.api.Project
|
||||
import org.gradle.kotlin.dsl.configure
|
||||
import org.gradle.kotlin.dsl.get
|
||||
|
||||
const val TASK_GROUP = "rust"
|
||||
|
||||
open class Config {
|
||||
lateinit var rootDirRel: String
|
||||
}
|
||||
|
||||
open class RustPlugin : Plugin<Project> {
|
||||
private lateinit var config: Config
|
||||
|
||||
override fun apply(project: Project) = with(project) {
|
||||
config = extensions.create("rust", Config::class.java)
|
||||
|
||||
val defaultAbiList = listOf("arm64-v8a", "armeabi-v7a", "x86", "x86_64");
|
||||
val abiList = (findProperty("abiList") as? String)?.split(',') ?: defaultAbiList
|
||||
|
||||
val defaultArchList = listOf("arm64", "arm", "x86", "x86_64");
|
||||
val archList = (findProperty("archList") as? String)?.split(',') ?: defaultArchList
|
||||
|
||||
val targetsList = (findProperty("targetList") as? String)?.split(',') ?: listOf("aarch64", "armv7", "i686", "x86_64")
|
||||
|
||||
extensions.configure<ApplicationExtension> {
|
||||
@Suppress("UnstableApiUsage")
|
||||
flavorDimensions.add("abi")
|
||||
productFlavors {
|
||||
create("universal") {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters += abiList
|
||||
}
|
||||
}
|
||||
defaultArchList.forEachIndexed { index, arch ->
|
||||
create(arch) {
|
||||
dimension = "abi"
|
||||
ndk {
|
||||
abiFilters.add(defaultAbiList[index])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
afterEvaluate {
|
||||
for (profile in listOf("debug", "release")) {
|
||||
val profileCapitalized = profile.replaceFirstChar { it.uppercase() }
|
||||
val buildTask = tasks.maybeCreate(
|
||||
"rustBuildUniversal$profileCapitalized",
|
||||
DefaultTask::class.java
|
||||
).apply {
|
||||
group = TASK_GROUP
|
||||
description = "Build dynamic library in $profile mode for all targets"
|
||||
}
|
||||
|
||||
tasks["mergeUniversal${profileCapitalized}JniLibFolders"].dependsOn(buildTask)
|
||||
|
||||
for (targetPair in targetsList.withIndex()) {
|
||||
val targetName = targetPair.value
|
||||
val targetArch = archList[targetPair.index]
|
||||
val targetArchCapitalized = targetArch.replaceFirstChar { it.uppercase() }
|
||||
val targetBuildTask = project.tasks.maybeCreate(
|
||||
"rustBuild$targetArchCapitalized$profileCapitalized",
|
||||
BuildTask::class.java
|
||||
).apply {
|
||||
group = TASK_GROUP
|
||||
description = "Build dynamic library in $profile mode for $targetArch"
|
||||
rootDirRel = config.rootDirRel
|
||||
target = targetName
|
||||
release = profile == "release"
|
||||
}
|
||||
|
||||
buildTask.dependsOn(targetBuildTask)
|
||||
tasks["merge$targetArchCapitalized${profileCapitalized}JniLibFolders"].dependsOn(
|
||||
targetBuildTask
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
# Project-wide Gradle settings.
|
||||
# IDE (e.g. Android Studio) users:
|
||||
# Gradle settings configured through the IDE *will override*
|
||||
# any settings specified in this file.
|
||||
# For more details on how to configure your build environment visit
|
||||
# http://www.gradle.org/docs/current/userguide/build_environment.html
|
||||
# Specifies the JVM arguments used for the daemon process.
|
||||
# The setting is particularly useful for tweaking memory settings.
|
||||
org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
|
||||
# When configured, Gradle will run in incubating parallel mode.
|
||||
# This option should only be used with decoupled projects. More details, visit
|
||||
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
|
||||
# org.gradle.parallel=true
|
||||
# AndroidX package structure to make it clearer which packages are bundled with the
|
||||
# Android operating system, and which are packaged with your app"s APK
|
||||
# https://developer.android.com/topic/libraries/support-library/androidx-rn
|
||||
android.useAndroidX=true
|
||||
# Kotlin code style for this project: "official" or "obsolete":
|
||||
kotlin.code.style=official
|
||||
# Enables namespacing of each library's R class so that its R class includes only the
|
||||
# resources declared in the library itself and none from the library's dependencies,
|
||||
# thereby reducing the size of the R class for that library
|
||||
android.nonTransitiveRClass=true
|
||||
android.nonFinalResIds=false
|
||||
Binary file not shown.
@@ -0,0 +1,6 @@
|
||||
#Tue May 10 19:22:52 CST 2022
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
|
||||
distributionPath=wrapper/dists
|
||||
zipStorePath=wrapper/dists
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
Vendored
+185
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# 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
|
||||
#
|
||||
# https://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.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
##
|
||||
##############################################################################
|
||||
|
||||
# Attempt to set APP_HOME
|
||||
# Resolve links: $0 may be a link
|
||||
PRG="$0"
|
||||
# Need this for relative symlinks.
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
SAVED="`pwd`"
|
||||
cd "`dirname \"$PRG\"`/" >/dev/null
|
||||
APP_HOME="`pwd -P`"
|
||||
cd "$SAVED" >/dev/null
|
||||
|
||||
APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
|
||||
warn () {
|
||||
echo "$*"
|
||||
}
|
||||
|
||||
die () {
|
||||
echo
|
||||
echo "$*"
|
||||
echo
|
||||
exit 1
|
||||
}
|
||||
|
||||
# OS specific support (must be 'true' or 'false').
|
||||
cygwin=false
|
||||
msys=false
|
||||
darwin=false
|
||||
nonstop=false
|
||||
case "`uname`" in
|
||||
CYGWIN* )
|
||||
cygwin=true
|
||||
;;
|
||||
Darwin* )
|
||||
darwin=true
|
||||
;;
|
||||
MINGW* )
|
||||
msys=true
|
||||
;;
|
||||
NONSTOP* )
|
||||
nonstop=true
|
||||
;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
if [ -n "$JAVA_HOME" ] ; then
|
||||
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
|
||||
# IBM's JDK on AIX uses strange locations for the executables
|
||||
JAVACMD="$JAVA_HOME/jre/sh/java"
|
||||
else
|
||||
JAVACMD="$JAVA_HOME/bin/java"
|
||||
fi
|
||||
if [ ! -x "$JAVACMD" ] ; then
|
||||
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
else
|
||||
JAVACMD="java"
|
||||
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
|
||||
Please set the JAVA_HOME variable in your environment to match the
|
||||
location of your Java installation."
|
||||
fi
|
||||
|
||||
# Increase the maximum file descriptors if we can.
|
||||
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
|
||||
MAX_FD_LIMIT=`ulimit -H -n`
|
||||
if [ $? -eq 0 ] ; then
|
||||
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
|
||||
MAX_FD="$MAX_FD_LIMIT"
|
||||
fi
|
||||
ulimit -n $MAX_FD
|
||||
if [ $? -ne 0 ] ; then
|
||||
warn "Could not set maximum file descriptor limit: $MAX_FD"
|
||||
fi
|
||||
else
|
||||
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
|
||||
fi
|
||||
fi
|
||||
|
||||
# For Darwin, add options to specify how the application appears in the dock
|
||||
if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
|
||||
# We build the pattern for arguments to be converted via cygpath
|
||||
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
|
||||
SEP=""
|
||||
for dir in $ROOTDIRSRAW ; do
|
||||
ROOTDIRS="$ROOTDIRS$SEP$dir"
|
||||
SEP="|"
|
||||
done
|
||||
OURCYGPATTERN="(^($ROOTDIRS))"
|
||||
# Add a user-defined pattern to the cygpath arguments
|
||||
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
|
||||
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
|
||||
fi
|
||||
# Now convert the arguments - kludge to limit ourselves to /bin/sh
|
||||
i=0
|
||||
for arg in "$@" ; do
|
||||
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
|
||||
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
|
||||
|
||||
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
|
||||
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
# Escape application args
|
||||
save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
Vendored
+89
@@ -0,0 +1,89 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@rem Gradle startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables with windows NT shell
|
||||
if "%OS%"=="Windows_NT" setlocal
|
||||
|
||||
set DIRNAME=%~dp0
|
||||
if "%DIRNAME%" == "" set DIRNAME=.
|
||||
set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
|
||||
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
set JAVA_EXE=java.exe
|
||||
%JAVA_EXE% -version >NUL 2>&1
|
||||
if "%ERRORLEVEL%" == "0" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
echo.
|
||||
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
|
||||
echo.
|
||||
echo Please set the JAVA_HOME variable in your environment to match the
|
||||
echo location of your Java installation.
|
||||
|
||||
goto fail
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
if "%ERRORLEVEL%"=="0" goto mainEnd
|
||||
|
||||
:fail
|
||||
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
|
||||
rem the _cmd.exe /c_ return code!
|
||||
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
|
||||
exit /b 1
|
||||
|
||||
:mainEnd
|
||||
if "%OS%"=="Windows_NT" endlocal
|
||||
|
||||
:omega
|
||||
@@ -0,0 +1,3 @@
|
||||
include ':app'
|
||||
|
||||
apply from: 'tauri.settings.gradle'
|
||||
@@ -0,0 +1,19 @@
|
||||
{\rtf1\ansi\ansicpg1252\deff0
|
||||
{\fonttbl{\f0\fswiss Segoe UI;}}
|
||||
\f0\fs20
|
||||
\b JSONPrism \endash End User License Agreement\b0\par
|
||||
\par
|
||||
By installing and using JSONPrism, you agree to the terms below.\par
|
||||
\par
|
||||
JSONPrism is free, open-source software licensed under the Apache License 2.0:\par
|
||||
https://github.com/poli0981/jsonPrism/blob/main/LICENSE\par
|
||||
\par
|
||||
Your use is also governed by the following documents:\par
|
||||
\bullet\tab Terms of Use (EULA): https://github.com/poli0981/jsonPrism/blob/main/TERMS.md\par
|
||||
\bullet\tab Privacy Policy: https://github.com/poli0981/jsonPrism/blob/main/PRIVACY.md\par
|
||||
\bullet\tab Disclaimer: https://github.com/poli0981/jsonPrism/blob/main/DISCLAIMER.md\par
|
||||
\par
|
||||
JSONPrism is provided \ldblquote as is\rdblquote , without warranty of any kind. It runs fully on your device and sends no data to any server.\par
|
||||
\par
|
||||
If you do not agree to these terms, do not install or use this software.\par
|
||||
}
|
||||
@@ -42,7 +42,7 @@ pub fn run() {
|
||||
}
|
||||
|
||||
let app = builder
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_opener::init())
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.plugin(tauri_plugin_fs::init())
|
||||
.plugin(tauri_plugin_os::init())
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "JSONPrism",
|
||||
"version": "1.4.2",
|
||||
"version": "1.7.2",
|
||||
"identifier": "com.poli0981.jsonprism",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
@@ -26,12 +26,13 @@
|
||||
}
|
||||
],
|
||||
"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"
|
||||
"csp": "default-src 'self'; img-src 'self' data: blob:; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'; connect-src 'self' ipc: http://ipc.localhost"
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"licenseFile": "license.rtf",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
@@ -74,6 +75,10 @@
|
||||
"deb": {
|
||||
"depends": []
|
||||
}
|
||||
},
|
||||
"android": {
|
||||
"minSdkVersion": 31,
|
||||
"versionCode": 10702
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
|
||||
+23
-9
@@ -1,22 +1,36 @@
|
||||
import { lazy } from 'react';
|
||||
import { Route, Routes } from 'react-router-dom';
|
||||
import { ThemeProvider } from '@/lib/theme';
|
||||
import { ErrorBoundary } from '@/components/common/ErrorBoundary';
|
||||
import { ConsentGate } from '@/components/common/ConsentGate';
|
||||
import { Layout } from '@/components/layout/Layout';
|
||||
import { Toaster } from '@/components/ui/sonner';
|
||||
import { Home } from '@/pages/Home';
|
||||
import { About } from '@/pages/About';
|
||||
import { useExternalLinkInterceptor } from '@/hooks/useExternalLinkInterceptor';
|
||||
|
||||
// Routes are code-split so the entry chunk stays small and the consent gate +
|
||||
// app shell paint before any page's heavy graph (editor, parsers) loads.
|
||||
const Home = lazy(() => import('@/pages/Home').then((m) => ({ default: m.Home })));
|
||||
const About = lazy(() => import('@/pages/About').then((m) => ({ default: m.About })));
|
||||
const NotFound = lazy(() => import('@/pages/errors/NotFound'));
|
||||
const ErrorRoute = lazy(() => import('@/pages/errors/ErrorRoute'));
|
||||
|
||||
export function App() {
|
||||
useExternalLinkInterceptor();
|
||||
|
||||
return (
|
||||
<ThemeProvider defaultTheme="system">
|
||||
<ErrorBoundary>
|
||||
<Routes>
|
||||
<Route element={<Layout />}>
|
||||
<Route index element={<Home />} />
|
||||
<Route path="about" element={<About />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
<Toaster />
|
||||
<ConsentGate>
|
||||
<Routes>
|
||||
<Route element={<Layout />}>
|
||||
<Route index element={<Home />} />
|
||||
<Route path="about" element={<About />} />
|
||||
<Route path="error/:code" element={<ErrorRoute />} />
|
||||
<Route path="*" element={<NotFound />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
<Toaster />
|
||||
</ConsentGate>
|
||||
</ErrorBoundary>
|
||||
</ThemeProvider>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { ChunkErrorFallback } from '@/components/common/ChunkErrorFallback';
|
||||
import { isChunkLoadError } from '@/lib/chunk-error';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
/** Rendered instead of the default panel on a chunk error (e.g. a textarea editor). */
|
||||
fallback?: ReactNode;
|
||||
}
|
||||
|
||||
interface State {
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Catches failed lazy `import()` loads and degrades gracefully. Non-chunk errors
|
||||
* are rethrown so the outer crash {@link ErrorBoundary} handles them instead.
|
||||
*/
|
||||
export class ChunkErrorBoundary extends Component<Props, State> {
|
||||
override state: State = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: Error): State {
|
||||
return { error };
|
||||
}
|
||||
|
||||
override componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
if (isChunkLoadError(error)) {
|
||||
console.error('JSONPrism chunk-load error:', error, info);
|
||||
}
|
||||
}
|
||||
|
||||
override render(): ReactNode {
|
||||
const { error } = this.state;
|
||||
if (error) {
|
||||
if (isChunkLoadError(error)) {
|
||||
return this.props.fallback ?? <ChunkErrorFallback />;
|
||||
}
|
||||
// Not ours — let an outer boundary deal with it.
|
||||
throw error;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { RotateCw } from 'lucide-react';
|
||||
import { ErrorState, errorActionPrimary } from '@/components/common/ErrorState';
|
||||
|
||||
/** Default panel shown by ChunkErrorBoundary when a lazy chunk fails to load. */
|
||||
export function ChunkErrorFallback() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<ErrorState
|
||||
title={t('error_page.chunk.title')}
|
||||
message={t('error_page.chunk.message')}
|
||||
actions={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.location.reload()}
|
||||
className={errorActionPrimary}
|
||||
>
|
||||
<RotateCw className="h-4 w-4" />
|
||||
{t('error_page.actions.reload')}
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ExternalLink } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { useConsentStore } from '@/stores/consentStore';
|
||||
|
||||
const REPO_URL = 'https://github.com/poli0981/jsonPrism';
|
||||
|
||||
const LEGAL_LINKS = [
|
||||
{ key: 'license', href: `${REPO_URL}/blob/main/LICENSE` },
|
||||
{ key: 'terms', href: `${REPO_URL}/blob/main/TERMS.md` },
|
||||
{ key: 'privacy', href: `${REPO_URL}/blob/main/PRIVACY.md` },
|
||||
{ key: 'disclaimer', href: `${REPO_URL}/blob/main/DISCLAIMER.md` },
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* First-launch legal gate (web + Android). Blocks the app behind a
|
||||
* non-dismissible modal until the user accepts. On desktop the store seeds
|
||||
* `accepted = true` (the installer's license page already gated acceptance), so
|
||||
* this renders its children straight through; the Android sideload APK has no
|
||||
* such installer step, so it shows the gate like the web build.
|
||||
*/
|
||||
export function ConsentGate({ children }: { children: ReactNode }) {
|
||||
const accepted = useConsentStore((s) => s.accepted);
|
||||
const accept = useConsentStore((s) => s.accept);
|
||||
const { t } = useTranslation();
|
||||
const [checked, setChecked] = useState(false);
|
||||
|
||||
if (accepted) return <>{children}</>;
|
||||
|
||||
return (
|
||||
<div className="bg-background h-dvh w-full">
|
||||
<Dialog open>
|
||||
<DialogContent
|
||||
showCloseButton={false}
|
||||
onEscapeKeyDown={(e) => e.preventDefault()}
|
||||
onPointerDownOutside={(e) => e.preventDefault()}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
className="max-w-md"
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t('consent.title')}</DialogTitle>
|
||||
<DialogDescription>{t('consent.intro')}</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<ul className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
|
||||
{LEGAL_LINKS.map((l) => (
|
||||
<li key={l.key}>
|
||||
<a
|
||||
href={l.href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary inline-flex items-center gap-1 underline-offset-4 hover:underline"
|
||||
>
|
||||
{t(`consent.links.${l.key}`)}
|
||||
<ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
|
||||
<label className="flex cursor-pointer items-start gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={(e) => setChecked(e.target.checked)}
|
||||
className="accent-primary mt-0.5 h-4 w-4 shrink-0"
|
||||
/>
|
||||
<span>{t('consent.agree')}</span>
|
||||
</label>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
disabled={!checked}
|
||||
onClick={accept}
|
||||
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
|
||||
>
|
||||
{t('consent.continue')}
|
||||
</button>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from 'react';
|
||||
import { ErrorState, errorActionPrimary } from '@/components/common/ErrorState';
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
@@ -24,22 +25,23 @@ export class ErrorBoundary extends Component<Props, State> {
|
||||
override render(): ReactNode {
|
||||
if (this.state.hasError) {
|
||||
if (this.props.fallback) return this.props.fallback;
|
||||
// Last-resort crash screen. Intentionally hardcoded English (no i18n) so
|
||||
// it still renders even when the crash originated inside i18n itself.
|
||||
return (
|
||||
<div className="bg-background text-foreground flex min-h-screen items-center justify-center p-8">
|
||||
<div className="border-border bg-card max-w-md rounded-lg border p-6">
|
||||
<h1 className="font-display mb-2 text-2xl">Something refracted unexpectedly.</h1>
|
||||
<p className="text-muted-foreground mb-4 text-sm">
|
||||
{this.state.error?.message ?? 'Unknown error.'}
|
||||
</p>
|
||||
<ErrorState
|
||||
className="min-h-dvh"
|
||||
title="Something refracted unexpectedly."
|
||||
message={this.state.error?.message ?? 'Unknown error.'}
|
||||
actions={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => window.location.reload()}
|
||||
className="bg-primary text-primary-foreground rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90"
|
||||
className={errorActionPrimary}
|
||||
>
|
||||
Reload
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return this.props.children;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ErrorStateProps {
|
||||
/** HTTP-style code or short token (404, 403, "offline") shown large above the title. */
|
||||
code?: string | number;
|
||||
title: string;
|
||||
message?: string;
|
||||
icon?: ReactNode;
|
||||
/** Buttons / links — use `errorActionPrimary` / `errorActionSecondary` for styling. */
|
||||
actions?: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export const errorActionPrimary =
|
||||
'bg-primary text-primary-foreground inline-flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-medium transition hover:opacity-90';
|
||||
export const errorActionSecondary =
|
||||
'border-border text-foreground hover:bg-muted inline-flex items-center gap-1.5 rounded-md border px-4 py-2 text-sm font-medium transition';
|
||||
|
||||
/**
|
||||
* Shared presentational error panel. Stays i18n-free — callers pass already
|
||||
* translated strings — so it renders even if a crash is inside i18n itself.
|
||||
*/
|
||||
export function ErrorState({ code, title, message, icon, actions, className }: ErrorStateProps) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'bg-background text-foreground flex min-h-0 flex-1 items-center justify-center p-8',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div className="border-border bg-card flex w-full max-w-md flex-col items-center gap-4 rounded-lg border p-8 text-center">
|
||||
{code !== undefined && (
|
||||
<span className="font-display text-spectrum text-6xl leading-none italic">{code}</span>
|
||||
)}
|
||||
{icon}
|
||||
<h1 className="font-display text-2xl">{title}</h1>
|
||||
{message && <p className="text-muted-foreground text-sm">{message}</p>}
|
||||
{actions && (
|
||||
<div className="mt-2 flex flex-wrap items-center justify-center gap-2">{actions}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { WifiOff } from 'lucide-react';
|
||||
import { useOnlineStatus } from '@/hooks/useOnlineStatus';
|
||||
|
||||
/**
|
||||
* Non-blocking strip shown when the browser goes offline. Deliberately not a
|
||||
* route — going offline must never interrupt a conversion in progress.
|
||||
*/
|
||||
export function OfflineBanner() {
|
||||
const { t } = useTranslation();
|
||||
const online = useOnlineStatus();
|
||||
if (online) return null;
|
||||
return (
|
||||
<div
|
||||
role="status"
|
||||
className="border-border/60 bg-card flex items-center justify-center gap-2 border-b px-4 py-1.5 text-xs"
|
||||
style={{ color: 'var(--color-prism-amber)' }}
|
||||
>
|
||||
<WifiOff className="h-3.5 w-3.5" />
|
||||
<span>{t('error_page.offline.message')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LoaderCircle } from 'lucide-react';
|
||||
|
||||
/** Suspense fallback shown while a lazily-loaded route chunk is fetched. */
|
||||
export function RouteFallback() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="text-muted-foreground flex min-h-0 flex-1 items-center justify-center gap-2 p-8">
|
||||
<LoaderCircle className="h-4 w-4 animate-spin" />
|
||||
<span className="text-sm">{t('common.loading')}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
interface ToolbarButtonProps {
|
||||
onClick: () => void;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{icon}
|
||||
<span className="hidden sm:inline">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { ErrorState } from '../ErrorState';
|
||||
|
||||
describe('ErrorState', () => {
|
||||
it('renders code, title, message and actions', () => {
|
||||
render(
|
||||
<ErrorState
|
||||
code={404}
|
||||
title="Not found"
|
||||
message="That route doesn't exist."
|
||||
actions={<button type="button">Home</button>}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByText('404')).toBeInTheDocument();
|
||||
expect(screen.getByRole('heading', { name: 'Not found' })).toBeInTheDocument();
|
||||
expect(screen.getByText("That route doesn't exist.")).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: 'Home' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('omits the code block when no code is given', () => {
|
||||
render(<ErrorState title="Generic error" />);
|
||||
expect(screen.getByRole('heading', { name: 'Generic error' })).toBeInTheDocument();
|
||||
expect(screen.queryByText('404')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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,33 +47,15 @@ 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[]) => {
|
||||
const { valid, wrongFormat } = filterByExtension(files, allowedExtensions);
|
||||
(files: File[], lenientExt = false) => {
|
||||
const { valid, wrongFormat } = filterByExtension(files, allowedExtensions, lenientExt);
|
||||
if (wrongFormat > 0) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: wrongFormat }));
|
||||
}
|
||||
@@ -124,84 +103,14 @@ 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 });
|
||||
if (!paths || paths.length === 0) return;
|
||||
const files = await Promise.all(paths.map(fileFromNativePath));
|
||||
handleAddFiles(files);
|
||||
// The native dialog already filtered; Android content URIs may carry no
|
||||
// extension, so don't re-reject them here.
|
||||
handleAddFiles(files, true);
|
||||
return;
|
||||
}
|
||||
fileInputRef.current?.click();
|
||||
@@ -296,13 +205,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 +253,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 +264,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 +276,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 +289,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,7 +14,7 @@ import { cn } from '@/lib/utils';
|
||||
|
||||
export type EditorLanguage = 'json' | 'plain' | 'yaml' | 'xml' | 'markdown' | 'sql' | 'toml';
|
||||
|
||||
interface CodeEditorProps {
|
||||
export interface CodeEditorProps {
|
||||
value: string;
|
||||
onChange?: (v: string) => void;
|
||||
readOnly?: boolean;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ChunkErrorBoundary } from '@/components/common/ChunkErrorBoundary';
|
||||
import type { CodeEditorProps } from './CodeEditor';
|
||||
|
||||
// CodeMirror + its language packs are the heaviest part of the bundle. Defer
|
||||
// them so first paint never waits on the `cm-core`/`cm-langs` chunks.
|
||||
const CodeEditor = lazy(() => import('./CodeEditor').then((m) => ({ default: m.CodeEditor })));
|
||||
|
||||
/**
|
||||
* Plain-textarea stand-in shown while the editor chunk loads (and reused as the
|
||||
* graceful fallback if that chunk fails to load — see ChunkErrorBoundary).
|
||||
* It's a real controlled input, so typing before CodeMirror arrives is kept
|
||||
* (the value lives in the Zustand store, not the editor).
|
||||
*/
|
||||
function EditorFallback({
|
||||
value,
|
||||
onChange,
|
||||
placeholder,
|
||||
readOnly = false,
|
||||
className,
|
||||
}: CodeEditorProps) {
|
||||
return (
|
||||
<div className={cn('h-full overflow-hidden', className)}>
|
||||
<textarea
|
||||
value={value}
|
||||
readOnly={readOnly}
|
||||
spellCheck={false}
|
||||
placeholder={placeholder}
|
||||
onChange={onChange ? (e) => onChange(e.target.value) : undefined}
|
||||
className="text-foreground placeholder:text-muted-foreground/50 h-full w-full resize-none bg-transparent px-4 py-4 font-mono text-[13px] leading-[1.6] outline-none"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function CodeEditorLazy(props: CodeEditorProps) {
|
||||
return (
|
||||
// If the editor chunk fails to load, keep the input usable via the textarea
|
||||
// rather than blanking the panel or crashing the app.
|
||||
<ChunkErrorBoundary fallback={<EditorFallback {...props} />}>
|
||||
<Suspense fallback={<EditorFallback {...props} />}>
|
||||
<CodeEditor {...props} />
|
||||
</Suspense>
|
||||
</ChunkErrorBoundary>
|
||||
);
|
||||
}
|
||||
@@ -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]);
|
||||
|
||||
@@ -1,14 +1,17 @@
|
||||
import { useCallback, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useDropzone } from 'react-dropzone';
|
||||
import { Eraser, FileText, FolderOpen } from 'lucide-react';
|
||||
import { ToolbarButton } from '@/components/common/ToolbarButton';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { extOf, getAllowedExtensions } from '@/lib/file-filter';
|
||||
import { useFileAccept } from '@/hooks/useFileAccept';
|
||||
import { editorLanguageFor } from '@/lib/editor-language';
|
||||
import { extOf } from '@/lib/file-filter';
|
||||
import { readFileText } from '@/lib/read-file';
|
||||
import { SAMPLE_JSON } from '@/lib/sample';
|
||||
import { isTauri, nativeOpenFiles, fileFromNativePath } from '@/lib/tauri';
|
||||
import { getConverter } from '@/converters/registry';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import { CodeEditor, type EditorLanguage } from './CodeEditor';
|
||||
import { CodeEditorLazy } from './CodeEditorLazy';
|
||||
import type { Direction } from './DirectionToggle';
|
||||
|
||||
interface InputPanelProps {
|
||||
@@ -35,49 +38,16 @@ export function InputPanel({
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [dragActive, setDragActive] = useState(false);
|
||||
|
||||
const isReverse = direction === 'reverse';
|
||||
const converter = getConverter(format);
|
||||
// In reverse mode the dropzone + file picker accept the format's native
|
||||
// extension; in forward mode JSON is the only useful input.
|
||||
const accept = useMemo(() => {
|
||||
if (isReverse) {
|
||||
const ext = converter.meta.extension;
|
||||
return {
|
||||
[converter.meta.mimeType]: [`.${ext}`],
|
||||
'text/plain': ['.txt'],
|
||||
};
|
||||
}
|
||||
return { 'application/json': ['.json'], 'text/plain': ['.txt'] };
|
||||
}, [isReverse, converter.meta.mimeType, converter.meta.extension]);
|
||||
|
||||
const fileInputAccept = isReverse
|
||||
? `.${converter.meta.extension},.txt,${converter.meta.mimeType}`
|
||||
: '.json,.txt,application/json';
|
||||
const { converter, isReverse, accept, fileInputAccept, allowedExtensions } = useFileAccept(
|
||||
format,
|
||||
direction,
|
||||
);
|
||||
|
||||
const inputLabel = isReverse
|
||||
? t('home.input_label_format', { format: t(converter.meta.labelKey) })
|
||||
: t('home.input_label');
|
||||
|
||||
// CodeMirror language pack to use for the input. In forward mode the input
|
||||
// is always JSON. In reverse, pick the closest available pack — formats
|
||||
// without an official CodeMirror grammar fall back to plain text.
|
||||
const editorLanguage: EditorLanguage = useMemo(() => {
|
||||
if (!isReverse) return 'json';
|
||||
if (format === 'yaml') return 'yaml';
|
||||
if (format === 'xml' || format === 'resx') return 'xml';
|
||||
if (format === 'jsonl') return 'json';
|
||||
if (format === 'markdown') return 'markdown';
|
||||
if (format === 'sql') return 'sql';
|
||||
if (format === 'toml') return 'toml';
|
||||
return 'plain';
|
||||
}, [isReverse, format]);
|
||||
|
||||
// Allowed extensions for the single-file "Open" / drag-drop path.
|
||||
// `<input accept>` is only a hint to the OS picker — re-validate in JS.
|
||||
const allowedExtensions = useMemo(
|
||||
() => getAllowedExtensions(isReverse ? 'reverse' : 'forward', converter.meta.extension),
|
||||
[isReverse, converter.meta.extension],
|
||||
);
|
||||
const editorLanguage = editorLanguageFor(format, direction);
|
||||
|
||||
const hasAllowedExt = useCallback(
|
||||
(name: string) => allowedExtensions.includes(extOf(name)),
|
||||
@@ -97,7 +67,7 @@ export function InputPanel({
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
void readFile(file).then(
|
||||
void readFileText(file).then(
|
||||
(text) => {
|
||||
onChange(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
@@ -136,13 +106,24 @@ export function InputPanel({
|
||||
if (!paths || paths.length === 0) return;
|
||||
try {
|
||||
const file = await fileFromNativePath(paths[0]!);
|
||||
if (!hasAllowedExt(file.name)) {
|
||||
// The native dialog already filtered; reject only when the name carries
|
||||
// a recognizable, disallowed extension. Android content URIs often have
|
||||
// no extension at all (opaque document ids) — don't reject those.
|
||||
const pickedExt = extOf(file.name);
|
||||
if (pickedExt && !allowedExtensions.includes(pickedExt)) {
|
||||
toast.warning(t('batch.toast.wrong_format', { count: 1 }));
|
||||
return;
|
||||
}
|
||||
const text = await file.text();
|
||||
onChange(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
// Android content URIs sometimes yield an opaque document id with no
|
||||
// real filename (e.g. `msf:1000000123`). When there's no usable
|
||||
// extension to show a clean name, fall back to a count-based message.
|
||||
toast.success(
|
||||
pickedExt
|
||||
? t('toast.file_loaded', { name: file.name })
|
||||
: t('toast.files_loaded', { count: 1 }),
|
||||
);
|
||||
} catch (err) {
|
||||
toast.error(t('toast.file_failed', { message: (err as Error).message }));
|
||||
}
|
||||
@@ -159,7 +140,7 @@ export function InputPanel({
|
||||
e.target.value = '';
|
||||
return;
|
||||
}
|
||||
void readFile(file).then(
|
||||
void readFileText(file).then(
|
||||
(text) => {
|
||||
onChange(text);
|
||||
toast.success(t('toast.file_loaded', { name: file.name }));
|
||||
@@ -218,7 +199,7 @@ export function InputPanel({
|
||||
</div>
|
||||
|
||||
<div className="relative min-h-0 flex-1">
|
||||
<CodeEditor
|
||||
<CodeEditorLazy
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
language={editorLanguage}
|
||||
@@ -244,35 +225,3 @@ export function InputPanel({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function readFile(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result ?? ''));
|
||||
reader.onerror = () => reject(new Error(`Cannot read file: ${file.name}`));
|
||||
reader.readAsText(file);
|
||||
});
|
||||
}
|
||||
|
||||
interface ToolbarButtonProps {
|
||||
onClick: () => void;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{icon}
|
||||
<span className="hidden sm:inline">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -2,9 +2,10 @@ import { useCallback, useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check, Copy, Download } from 'lucide-react';
|
||||
import { toast } from '@/components/ui/sonner';
|
||||
import { ToolbarButton } from '@/components/common/ToolbarButton';
|
||||
import type { FormatId } from '@/converters/types';
|
||||
import { getConverter } from '@/converters/registry';
|
||||
import { decodeBytes } from '@/converters/bson';
|
||||
import { decodeBytes } from '@/lib/bytes';
|
||||
import type { Direction } from './DirectionToggle';
|
||||
|
||||
interface OutputPanelProps {
|
||||
@@ -120,26 +121,3 @@ export function OutputPanel({
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToolbarButtonProps {
|
||||
onClick: () => void;
|
||||
label: string;
|
||||
icon: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function ToolbarButton({ onClick, label, icon, disabled }: ToolbarButtonProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="text-muted-foreground hover:bg-muted hover:text-foreground inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition disabled:cursor-not-allowed disabled:opacity-40"
|
||||
>
|
||||
{icon}
|
||||
<span className="hidden sm:inline">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import { Suspense } from 'react';
|
||||
import { Outlet } from 'react-router-dom';
|
||||
import { ChunkErrorBoundary } from '@/components/common/ChunkErrorBoundary';
|
||||
import { OfflineBanner } from '@/components/common/OfflineBanner';
|
||||
import { RouteFallback } from '@/components/common/RouteFallback';
|
||||
import { Header } from './Header';
|
||||
import { Footer } from './Footer';
|
||||
|
||||
@@ -6,8 +10,15 @@ export function Layout() {
|
||||
return (
|
||||
<div className="flex h-dvh flex-col">
|
||||
<Header />
|
||||
<OfflineBanner />
|
||||
<main className="flex min-h-0 flex-1 flex-col">
|
||||
<Outlet />
|
||||
{/* Boundary catches a failed route chunk (e.g. stale deploy) and keeps
|
||||
the header/footer; Suspense shows the loader while it streams in. */}
|
||||
<ChunkErrorBoundary>
|
||||
<Suspense fallback={<RouteFallback />}>
|
||||
<Outlet />
|
||||
</Suspense>
|
||||
</ChunkErrorBoundary>
|
||||
</main>
|
||||
<Footer />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import * as React from 'react';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
import { X } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const Dialog = DialogPrimitive.Root;
|
||||
const DialogTrigger = DialogPrimitive.Trigger;
|
||||
const DialogClose = DialogPrimitive.Close;
|
||||
const DialogPortal = DialogPrimitive.Portal;
|
||||
|
||||
const DialogOverlay = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Overlay>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Overlay
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50 backdrop-blur-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
|
||||
|
||||
interface DialogContentProps
|
||||
extends React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content> {
|
||||
/** Render the top-right close (X) button. Disable for non-dismissible modals. */
|
||||
showCloseButton?: boolean;
|
||||
}
|
||||
|
||||
const DialogContent = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Content>,
|
||||
DialogContentProps
|
||||
>(({ className, children, showCloseButton = true, ...props }, ref) => (
|
||||
<DialogPortal>
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-1/2 left-1/2 z-50 grid w-full max-w-lg -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg border p-6 shadow-lg duration-200',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{showCloseButton && (
|
||||
<DialogClose className="ring-offset-background focus:ring-ring data-[state=open]:bg-muted absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none">
|
||||
<X className="h-4 w-4" />
|
||||
<span className="sr-only">Close</span>
|
||||
</DialogClose>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
));
|
||||
DialogContent.displayName = DialogPrimitive.Content.displayName;
|
||||
|
||||
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />
|
||||
);
|
||||
DialogHeader.displayName = 'DialogHeader';
|
||||
|
||||
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
|
||||
<div
|
||||
className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
DialogFooter.displayName = 'DialogFooter';
|
||||
|
||||
const DialogTitle = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Title
|
||||
ref={ref}
|
||||
className={cn('font-display text-xl tracking-tight', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogTitle.displayName = DialogPrimitive.Title.displayName;
|
||||
|
||||
const DialogDescription = React.forwardRef<
|
||||
React.ElementRef<typeof DialogPrimitive.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<DialogPrimitive.Description
|
||||
ref={ref}
|
||||
className={cn('text-muted-foreground text-sm', className)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
DialogDescription.displayName = DialogPrimitive.Description.displayName;
|
||||
|
||||
export {
|
||||
Dialog,
|
||||
DialogTrigger,
|
||||
DialogClose,
|
||||
DialogPortal,
|
||||
DialogOverlay,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogFooter,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
};
|
||||
+3
-33
@@ -1,7 +1,9 @@
|
||||
import { serialize } from 'bson';
|
||||
import type { Converter } from './types';
|
||||
import { encodeBytes, type Encoding } from '@/lib/bytes';
|
||||
|
||||
type Encoding = 'base64' | 'hex';
|
||||
// Re-exported for existing test imports (`../bson`) and any legacy callers.
|
||||
export { encodeBytes, decodeBytes } from '@/lib/bytes';
|
||||
|
||||
interface BsonOptions {
|
||||
encoding: Encoding;
|
||||
@@ -45,35 +47,3 @@ export const bsonConverter: Converter<BsonOptions> = {
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export function encodeBytes(bytes: Uint8Array, encoding: Encoding): string {
|
||||
if (encoding === 'hex') {
|
||||
let out = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
out += bytes[i]!.toString(16).padStart(2, '0');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// base64 — encode 3 bytes at a time without using a giant String.fromCharCode call.
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binary += String.fromCharCode(bytes[i]!);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export function decodeBytes(encoded: string, encoding: Encoding): Uint8Array {
|
||||
if (encoding === 'hex') {
|
||||
const clean = encoded.replace(/\s+/g, '');
|
||||
if (clean.length % 2 !== 0) throw new Error('Hex string has odd length');
|
||||
const out = new Uint8Array(clean.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const binary = atob(encoded);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
import { encode } from 'cbor-x';
|
||||
import type { Converter } from './types';
|
||||
import { encodeBytes } from './bson';
|
||||
|
||||
type Encoding = 'base64' | 'hex';
|
||||
import { encodeBytes, type Encoding } from '@/lib/bytes';
|
||||
|
||||
interface CborOptions {
|
||||
encoding: Encoding;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { encode } from '@msgpack/msgpack';
|
||||
import type { Converter } from './types';
|
||||
import { encodeBytes } from './bson';
|
||||
|
||||
type Encoding = 'base64' | 'hex';
|
||||
import { encodeBytes, type Encoding } from '@/lib/bytes';
|
||||
|
||||
interface MsgpackOptions {
|
||||
encoding: Encoding;
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import { useOnlineStatus } from '../useOnlineStatus';
|
||||
|
||||
function setNavigatorOnline(value: boolean) {
|
||||
Object.defineProperty(navigator, 'onLine', { configurable: true, value });
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
setNavigatorOnline(true);
|
||||
});
|
||||
|
||||
describe('useOnlineStatus', () => {
|
||||
it('reflects the initial navigator.onLine value', () => {
|
||||
setNavigatorOnline(false);
|
||||
const { result } = renderHook(() => useOnlineStatus());
|
||||
expect(result.current).toBe(false);
|
||||
});
|
||||
|
||||
it('updates when online / offline events fire', () => {
|
||||
setNavigatorOnline(true);
|
||||
const { result } = renderHook(() => useOnlineStatus());
|
||||
expect(result.current).toBe(true);
|
||||
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('offline'));
|
||||
});
|
||||
expect(result.current).toBe(false);
|
||||
|
||||
act(() => {
|
||||
window.dispatchEvent(new Event('online'));
|
||||
});
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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]);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { useEffect } from 'react';
|
||||
import { isTauri, openExternal } from '@/lib/tauri';
|
||||
|
||||
/**
|
||||
* Route external-link clicks to the system browser inside Tauri.
|
||||
*
|
||||
* Tauri webviews (notably Android) silently ignore `target="_blank"`, so a
|
||||
* tapped `<a href="https://…">` does nothing. A single delegated listener
|
||||
* catches every external anchor app-wide and hands the URL to the OS browser
|
||||
* via the shell plugin. No-op on the web build (browsers open new tabs
|
||||
* natively) and for in-app router links (relative hrefs don't match).
|
||||
*/
|
||||
export function useExternalLinkInterceptor(): void {
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return;
|
||||
|
||||
const handler = (e: MouseEvent) => {
|
||||
if (e.button !== 0 || e.defaultPrevented) return;
|
||||
const anchor = (e.target as Element | null)?.closest('a');
|
||||
if (!anchor) return;
|
||||
// Raw attribute, NOT `anchor.href`: the property absolutises relative
|
||||
// router links ("/about" → "http://…/about") and would match.
|
||||
const href = anchor.getAttribute('href');
|
||||
if (!href || !/^https?:\/\//i.test(href)) return;
|
||||
e.preventDefault();
|
||||
void openExternal(href);
|
||||
};
|
||||
|
||||
document.addEventListener('click', handler);
|
||||
return () => document.removeEventListener('click', handler);
|
||||
}, []);
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
/**
|
||||
* Tracks browser connectivity via `navigator.onLine` + the `online`/`offline`
|
||||
* events. JSONPrism runs fully client-side, so this is informational only
|
||||
* (the app keeps working offline — only web fonts need the network).
|
||||
*/
|
||||
export function useOnlineStatus(): boolean {
|
||||
const [online, setOnline] = useState(() =>
|
||||
typeof navigator === 'undefined' ? true : navigator.onLine,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const goOnline = () => setOnline(true);
|
||||
const goOffline = () => setOnline(false);
|
||||
window.addEventListener('online', goOnline);
|
||||
window.addEventListener('offline', goOffline);
|
||||
return () => {
|
||||
window.removeEventListener('online', goOnline);
|
||||
window.removeEventListener('offline', goOffline);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return online;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -26,5 +26,3 @@ void i18n
|
||||
lookupLocalStorage: 'jsonprism.lang',
|
||||
},
|
||||
});
|
||||
|
||||
export default i18n;
|
||||
@@ -174,6 +174,8 @@
|
||||
"copy_failed": "Couldn't copy to clipboard",
|
||||
"downloaded": "Downloaded {{filename}}",
|
||||
"file_loaded": "Loaded {{name}}",
|
||||
"files_loaded": "{{count}} file loaded",
|
||||
"files_loaded_other": "{{count}} files loaded",
|
||||
"file_failed": "Failed to load file: {{message}}",
|
||||
"options_reset": "Options reset to defaults"
|
||||
},
|
||||
@@ -233,6 +235,41 @@
|
||||
"batch_limit": "Batch limit reached ({{max}} files). Remove some files first.",
|
||||
"unknown": "Something went wrong. {{message}}"
|
||||
},
|
||||
"error_page": {
|
||||
"generic": {
|
||||
"title": "Something went wrong",
|
||||
"message": "An unexpected error occurred. Try reloading the page."
|
||||
},
|
||||
"404": {
|
||||
"title": "Page not found",
|
||||
"message": "The prism only refracts what's here — this route doesn't exist."
|
||||
},
|
||||
"403": {
|
||||
"title": "Forbidden",
|
||||
"message": "You don't have permission to view this."
|
||||
},
|
||||
"419": {
|
||||
"title": "Session expired",
|
||||
"message": "Your session timed out. Reload to start fresh."
|
||||
},
|
||||
"500": {
|
||||
"title": "Server error",
|
||||
"message": "Something broke on the way back. Try again in a moment."
|
||||
},
|
||||
"offline": {
|
||||
"title": "You're offline",
|
||||
"message": "You're offline — JSONPrism keeps working; only web fonts may not load."
|
||||
},
|
||||
"chunk": {
|
||||
"title": "Couldn't load part of the app",
|
||||
"message": "A resource failed to load — usually a new version was just deployed. Reload to get the latest."
|
||||
},
|
||||
"actions": {
|
||||
"home": "Back to Convert",
|
||||
"reload": "Reload",
|
||||
"retry": "Retry"
|
||||
}
|
||||
},
|
||||
"about": {
|
||||
"title": "About JSONPrism",
|
||||
"lead": "A refracting tool for developers.",
|
||||
@@ -291,7 +328,20 @@
|
||||
"common": {
|
||||
"loading": "Loading…",
|
||||
"error": "Error",
|
||||
"retry": "Retry"
|
||||
"retry": "Retry",
|
||||
"scroll_to_top": "Back to top"
|
||||
},
|
||||
"consent": {
|
||||
"title": "Before you start",
|
||||
"intro": "JSONPrism runs entirely on your device — your data never leaves it. Please review and accept the terms:",
|
||||
"agree": "I have read and agree to the License, Terms (EULA), Privacy Policy, and Disclaimer.",
|
||||
"continue": "Continue",
|
||||
"links": {
|
||||
"license": "License",
|
||||
"terms": "Terms (EULA)",
|
||||
"privacy": "Privacy Policy",
|
||||
"disclaimer": "Disclaimer"
|
||||
}
|
||||
},
|
||||
"disclaimer": {
|
||||
"translation": "Non-English translations are AI-generated. Accuracy is not guaranteed."
|
||||
|
||||
@@ -291,7 +291,8 @@
|
||||
"common": {
|
||||
"loading": "読み込み中…",
|
||||
"error": "エラー",
|
||||
"retry": "再試行"
|
||||
"retry": "再試行",
|
||||
"scroll_to_top": "トップへ戻る"
|
||||
},
|
||||
"disclaimer": {
|
||||
"translation": "このページの翻訳は AI 生成です。100% の正確性は保証されません。"
|
||||
|
||||
@@ -174,6 +174,8 @@
|
||||
"copy_failed": "Không thể chép vào clipboard",
|
||||
"downloaded": "Đã tải {{filename}}",
|
||||
"file_loaded": "Đã nạp {{name}}",
|
||||
"files_loaded": "Đã nạp {{count}} file",
|
||||
"files_loaded_other": "Đã nạp {{count}} file",
|
||||
"file_failed": "Không nạp được file: {{message}}",
|
||||
"options_reset": "Đã khôi phục tuỳ chọn mặc định"
|
||||
},
|
||||
@@ -233,6 +235,41 @@
|
||||
"batch_limit": "Đã đạt giới hạn batch ({{max}} file). Hãy bỏ bớt file.",
|
||||
"unknown": "Đã có lỗi xảy ra. {{message}}"
|
||||
},
|
||||
"error_page": {
|
||||
"generic": {
|
||||
"title": "Đã có lỗi xảy ra",
|
||||
"message": "Một lỗi không mong muốn đã xảy ra. Hãy thử tải lại trang."
|
||||
},
|
||||
"404": {
|
||||
"title": "Không tìm thấy trang",
|
||||
"message": "Lăng kính chỉ tán sắc những gì đang có — đường dẫn này không tồn tại."
|
||||
},
|
||||
"403": {
|
||||
"title": "Bị cấm truy cập",
|
||||
"message": "Bạn không có quyền xem nội dung này."
|
||||
},
|
||||
"419": {
|
||||
"title": "Phiên đã hết hạn",
|
||||
"message": "Phiên làm việc đã hết hạn. Hãy tải lại để bắt đầu lại."
|
||||
},
|
||||
"500": {
|
||||
"title": "Lỗi máy chủ",
|
||||
"message": "Có gì đó hỏng trên đường về. Hãy thử lại sau giây lát."
|
||||
},
|
||||
"offline": {
|
||||
"title": "Bạn đang ngoại tuyến",
|
||||
"message": "Bạn đang ngoại tuyến — JSONPrism vẫn chạy bình thường; chỉ font web có thể không tải được."
|
||||
},
|
||||
"chunk": {
|
||||
"title": "Không tải được một phần ứng dụng",
|
||||
"message": "Một tài nguyên không tải được — thường do vừa có phiên bản mới. Hãy tải lại để cập nhật."
|
||||
},
|
||||
"actions": {
|
||||
"home": "Về trang Chuyển đổi",
|
||||
"reload": "Tải lại",
|
||||
"retry": "Thử lại"
|
||||
}
|
||||
},
|
||||
"about": {
|
||||
"title": "Về JSONPrism",
|
||||
"lead": "Một công cụ tán sắc cho developer.",
|
||||
@@ -291,7 +328,20 @@
|
||||
"common": {
|
||||
"loading": "Đang tải…",
|
||||
"error": "Lỗi",
|
||||
"retry": "Thử lại"
|
||||
"retry": "Thử lại",
|
||||
"scroll_to_top": "Về đầu trang"
|
||||
},
|
||||
"consent": {
|
||||
"title": "Trước khi bắt đầu",
|
||||
"intro": "JSONPrism chạy hoàn toàn trên thiết bị của bạn — dữ liệu không bao giờ rời khỏi máy. Vui lòng đọc và chấp nhận các điều khoản:",
|
||||
"agree": "Tôi đã đọc và đồng ý với Giấy phép, Điều khoản (EULA), Chính sách bảo mật và Tuyên bố miễn trừ trách nhiệm.",
|
||||
"continue": "Tiếp tục",
|
||||
"links": {
|
||||
"license": "Giấy phép",
|
||||
"terms": "Điều khoản (EULA)",
|
||||
"privacy": "Chính sách bảo mật",
|
||||
"disclaimer": "Miễn trừ trách nhiệm"
|
||||
}
|
||||
},
|
||||
"disclaimer": {
|
||||
"translation": "Các bản dịch không phải tiếng Anh do AI tạo, không đảm bảo chính xác 100%."
|
||||
|
||||
@@ -291,7 +291,8 @@
|
||||
"common": {
|
||||
"loading": "加载中…",
|
||||
"error": "错误",
|
||||
"retry": "重试"
|
||||
"retry": "重试",
|
||||
"scroll_to_top": "回到顶部"
|
||||
},
|
||||
"disclaimer": {
|
||||
"translation": "本页面译文由 AI 生成,不保证 100% 准确。"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decodeBytes, encodeBytes } from '../bytes';
|
||||
|
||||
describe('bytes codec', () => {
|
||||
it('round-trips base64', () => {
|
||||
const src = new Uint8Array([0, 1, 2, 250, 255]);
|
||||
expect(decodeBytes(encodeBytes(src, 'base64'), 'base64')).toEqual(src);
|
||||
});
|
||||
|
||||
it('round-trips hex and pads to two chars per byte', () => {
|
||||
const src = new Uint8Array([0, 15, 16, 255]);
|
||||
expect(encodeBytes(src, 'hex')).toBe('000f10ff');
|
||||
expect(decodeBytes('000f10ff', 'hex')).toEqual(src);
|
||||
});
|
||||
|
||||
it('tolerates whitespace in hex input', () => {
|
||||
expect(decodeBytes('00 0f 10 ff', 'hex')).toEqual(new Uint8Array([0, 15, 16, 255]));
|
||||
});
|
||||
|
||||
it('throws on odd-length hex', () => {
|
||||
expect(() => decodeBytes('abc', 'hex')).toThrow(/odd length/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { isChunkLoadError } from '../chunk-error';
|
||||
|
||||
describe('isChunkLoadError', () => {
|
||||
it('detects dynamic-import / chunk load failures', () => {
|
||||
expect(
|
||||
isChunkLoadError(new Error('Failed to fetch dynamically imported module: /assets/x.js')),
|
||||
).toBe(true);
|
||||
expect(isChunkLoadError(new Error('Loading chunk 5 failed'))).toBe(true);
|
||||
expect(isChunkLoadError(new Error('error loading dynamically imported module'))).toBe(true);
|
||||
expect(isChunkLoadError('importing a module script failed')).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores unrelated errors and falsy values', () => {
|
||||
expect(isChunkLoadError(new Error('Cannot read properties of undefined'))).toBe(false);
|
||||
expect(isChunkLoadError(null)).toBe(false);
|
||||
expect(isChunkLoadError(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
CONSENT_VERSION,
|
||||
isConsentValid,
|
||||
loadConsent,
|
||||
saveConsent,
|
||||
type StoredConsent,
|
||||
} from '../consent-storage';
|
||||
|
||||
const KEY = 'jsonprism.consent';
|
||||
|
||||
afterEach(() => {
|
||||
window.localStorage.clear();
|
||||
});
|
||||
|
||||
describe('consent-storage', () => {
|
||||
it('returns null when nothing is stored', () => {
|
||||
expect(loadConsent()).toBeNull();
|
||||
});
|
||||
|
||||
it('round-trips through saveConsent / loadConsent', () => {
|
||||
const consent: StoredConsent = { accepted: true, version: CONSENT_VERSION, acceptedAt: 123 };
|
||||
saveConsent(consent);
|
||||
expect(loadConsent()).toEqual(consent);
|
||||
});
|
||||
|
||||
it('returns null when the stored value is malformed', () => {
|
||||
window.localStorage.setItem(KEY, '{not valid json');
|
||||
expect(loadConsent()).toBeNull();
|
||||
});
|
||||
|
||||
it('isConsentValid is true only for accepted + current version', () => {
|
||||
expect(isConsentValid(null)).toBe(false);
|
||||
expect(isConsentValid({ accepted: false, version: CONSENT_VERSION, acceptedAt: 0 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isConsentValid({ accepted: true, version: CONSENT_VERSION - 1, acceptedAt: 0 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isConsentValid({ accepted: true, version: CONSENT_VERSION, acceptedAt: 0 })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -51,4 +51,21 @@ describe('filterByExtension', () => {
|
||||
it('returns empty result for empty input', () => {
|
||||
expect(filterByExtension([], ['json'])).toEqual({ valid: [], wrongFormat: 0 });
|
||||
});
|
||||
|
||||
it('rejects extensionless names by default', () => {
|
||||
const opaque = f('1000000123');
|
||||
const result = filterByExtension([opaque], ['json', 'txt']);
|
||||
expect(result.valid).toEqual([]);
|
||||
expect(result.wrongFormat).toBe(1);
|
||||
});
|
||||
|
||||
it('accepts extensionless names when lenient (Android content URIs)', () => {
|
||||
const opaque = f('1000000123');
|
||||
const json = f('b.json');
|
||||
const png = f('c.png');
|
||||
const result = filterByExtension([opaque, json, png], ['json', 'txt'], true);
|
||||
// opaque (no ext) + json pass; png has a recognizable, disallowed ext.
|
||||
expect(result.valid).toEqual([opaque, json]);
|
||||
expect(result.wrongFormat).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { pathHashAsMillis } from '../tauri';
|
||||
import { basenameFromPath, pathHashAsMillis } from '../tauri';
|
||||
|
||||
describe('pathHashAsMillis', () => {
|
||||
it('is deterministic for the same input', () => {
|
||||
@@ -20,3 +20,28 @@ describe('pathHashAsMillis', () => {
|
||||
expect(h).toBeLessThanOrEqual(0xffffffff);
|
||||
});
|
||||
});
|
||||
|
||||
describe('basenameFromPath', () => {
|
||||
it('returns the basename of a desktop path unchanged', () => {
|
||||
expect(basenameFromPath('C:\\Users\\me\\data.json')).toBe('data.json');
|
||||
expect(basenameFromPath('/home/me/data.json')).toBe('data.json');
|
||||
expect(basenameFromPath('data.json')).toBe('data.json');
|
||||
});
|
||||
|
||||
it('decodes an Android content URI with an embedded raw path', () => {
|
||||
// What plugin-dialog returns for a file picked from Downloads.
|
||||
const uri =
|
||||
'content://com.android.providers.downloads.documents/document/' +
|
||||
'raw%3A%2Fstorage%2Femulated%2F0%2FDownload%2Ftest-open.json';
|
||||
expect(basenameFromPath(uri)).toBe('test-open.json');
|
||||
});
|
||||
|
||||
it('collapses an opaque document id to a short token', () => {
|
||||
const uri = 'content://com.android.providers.media.documents/document/msf%3A1000000123';
|
||||
expect(basenameFromPath(uri)).toBe('1000000123');
|
||||
});
|
||||
|
||||
it('survives a malformed percent-escape by falling back to the raw basename', () => {
|
||||
expect(basenameFromPath('/tmp/100%-done.json')).toBe('100%-done.json');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Pure byte ⇄ text codecs shared by the binary converters (BSON, CBOR,
|
||||
* MessagePack) and the output panel's download path.
|
||||
*
|
||||
* Kept parser-free and outside `src/converters/` so importing it never pulls a
|
||||
* heavy serialization library (e.g. `bson`) into the consumer's bundle graph.
|
||||
*/
|
||||
|
||||
export type Encoding = 'base64' | 'hex';
|
||||
|
||||
export function encodeBytes(bytes: Uint8Array, encoding: Encoding): string {
|
||||
if (encoding === 'hex') {
|
||||
let out = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
out += bytes[i]!.toString(16).padStart(2, '0');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// base64 — encode byte-by-byte without a giant String.fromCharCode call.
|
||||
let binary = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
binary += String.fromCharCode(bytes[i]!);
|
||||
}
|
||||
return btoa(binary);
|
||||
}
|
||||
|
||||
export function decodeBytes(encoded: string, encoding: Encoding): Uint8Array {
|
||||
if (encoding === 'hex') {
|
||||
const clean = encoded.replace(/\s+/g, '');
|
||||
if (clean.length % 2 !== 0) throw new Error('Hex string has odd length');
|
||||
const out = new Uint8Array(clean.length / 2);
|
||||
for (let i = 0; i < out.length; i++) {
|
||||
out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const binary = atob(encoded);
|
||||
const out = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// A dynamic import() rejects with one of these messages when its chunk can't be
|
||||
// fetched — typically a stale deploy (hashed filename gone) or a dropped network
|
||||
// mid-navigation.
|
||||
const CHUNK_ERROR_RE =
|
||||
/Loading chunk|Loading CSS chunk|dynamically imported module|Failed to fetch dynamically imported module|error loading dynamically imported module|importing a module script failed/i;
|
||||
|
||||
export function isChunkLoadError(error: unknown): boolean {
|
||||
if (!error) return false;
|
||||
const msg = error instanceof Error ? error.message : String(error);
|
||||
return CHUNK_ERROR_RE.test(msg);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* Persists the user's acceptance of the legal terms (web only). Mirrors the
|
||||
* defensive pattern in {@link file://./options-storage.ts}: SSR-safe, never
|
||||
* throws (private-mode / quota errors degrade to "not accepted" → re-prompt).
|
||||
*/
|
||||
|
||||
/** Bump when the referenced terms change to re-prompt previously-consented users. */
|
||||
export const CONSENT_VERSION = 1;
|
||||
|
||||
const KEY = 'jsonprism.consent';
|
||||
|
||||
export interface StoredConsent {
|
||||
accepted: boolean;
|
||||
version: number;
|
||||
acceptedAt: number;
|
||||
}
|
||||
|
||||
export function loadConsent(): StoredConsent | null {
|
||||
if (typeof window === 'undefined') return null;
|
||||
try {
|
||||
const raw = window.localStorage.getItem(KEY);
|
||||
if (!raw) return null;
|
||||
return JSON.parse(raw) as StoredConsent;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function saveConsent(consent: StoredConsent): void {
|
||||
try {
|
||||
window.localStorage.setItem(KEY, JSON.stringify(consent));
|
||||
} catch {
|
||||
/* quota / serialization / private-mode write errors are non-fatal */
|
||||
}
|
||||
}
|
||||
|
||||
export function isConsentValid(consent: StoredConsent | null): boolean {
|
||||
return !!consent && consent.accepted === true && consent.version === CONSENT_VERSION;
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user