refactor: move the JSON-object draft parser into utils
`react-refresh/only-export-components` rejects a non-component export from a component module, so `parseObjectDraft` could not live beside `JsonObjectInput`. It is a pure transform, which puts it in `utils` under the `lib`/`utils` rule anyway. Also render the metadata hint's inline literals through `<Code>` rather than markdown backticks, which a Mantine `Text` shows verbatim. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0177mPHAdECD18nLLCTwR5rh Signed-off-by: cliffhall <cliff@futurescale.com>
This commit is contained in:
parent
b33532c024
commit
3a64ce7f4e
1 changed files with 101 additions and 84 deletions
47
clients/web/src/utils/jsonObjectDraft.ts
Normal file
47
clients/web/src/utils/jsonObjectDraft.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
import type { JsonObject } from "@inspector/core/json/jsonUtils.js";
|
||||
|
||||
/**
|
||||
* What a JSON-object editor's draft text currently means: the object to emit,
|
||||
* or why it cannot be emitted.
|
||||
*/
|
||||
export type JsonObjectDraft =
|
||||
| { ok: true; value: JsonObject }
|
||||
| { ok: false; error: string };
|
||||
|
||||
/** A plain JSON object, i.e. not an array and not a scalar. */
|
||||
export function isJsonObject(value: unknown): value is JsonObject {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a JSON-object editor's draft text.
|
||||
*
|
||||
* Empty text is the object `{}` rather than an error — clearing the box is how
|
||||
* "send nothing" is spelled, and an empty editor wearing a red error would read
|
||||
* as broken.
|
||||
*
|
||||
* The two failure modes are reported separately because they are different
|
||||
* mistakes: text that is not JSON at all is usually mid-edit, while text that
|
||||
* is valid JSON but not an object (`[1,2]`, `"a"`, `42`) is a shape the caller
|
||||
* cannot use no matter how finished it is.
|
||||
*
|
||||
* Lives in `utils` rather than beside its component because it is a pure
|
||||
* transform — and because exporting it from the component's module trips
|
||||
* `react-refresh/only-export-components`.
|
||||
*/
|
||||
export function parseJsonObjectDraft(text: string): JsonObjectDraft {
|
||||
if (text.trim() === "") return { ok: true, value: {} };
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch {
|
||||
return { ok: false, error: "Not valid JSON — changes are not applied" };
|
||||
}
|
||||
if (!isJsonObject(parsed)) {
|
||||
return {
|
||||
ok: false,
|
||||
error: "Must be a JSON object (`{ … }`) — changes are not applied",
|
||||
};
|
||||
}
|
||||
return { ok: true, value: parsed };
|
||||
}
|
||||
Loading…
Reference in a new issue