Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { useFetchListItems } from "../../hooks"
import { useEditListItem } from "../../hooks/use-edit-list-item"
import { headerLabels } from "./display-list"
import { HashFieldTTLBadge } from "./hash/hash-field-ttl-badge"
import { toStoredValues } from "./input/format-json"
import { useField } from "./input/use-field"

export const ListEditDisplay = ({
Expand Down Expand Up @@ -66,7 +67,13 @@ const ListEditForm = ({

const [keyLabel, valueLabel] = headerLabels[type]

const onSubmit = form.handleSubmit(async ({ key, value }) => {
const onSubmit = form.handleSubmit(async (values) => {
const { key, value } = toStoredValues(form, values)
// An edit that maps back to the stored item (e.g. whitespace in compact JSON)
if (!isNew && key === itemKey && value === itemValue) {
setSelectedListItem(undefined)
return
}
await editItem({
type: type,
dataKey,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { Spinner } from "@/components/ui/spinner"
import { useFetchSimpleKey } from "../../hooks/use-fetch-simple-key"
import { useSetSimpleKey } from "../../hooks/use-set-simple-key"
import { DisplayHeader } from "./display-header"
import { toStoredValues } from "./input/format-json"
import { useField } from "./input/use-field"
import { KeyDeleted } from "./key-deleted"

Expand Down Expand Up @@ -74,7 +75,13 @@ const EditorDisplayForm = ({

<Button
variant="primary"
onClick={form.handleSubmit(async ({ value }) => {
onClick={form.handleSubmit(async (values) => {
const { value } = toStoredValues(form, values)
// An edit that maps back to the stored value (e.g. whitespace in compact JSON)
if (value === data) {
form.reset({ value: data })
return
}
await setKey(value)
})}
disabled={!form.formState.isValid || !form.formState.isDirty}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useMemo } from "react"
import { useEffect, useMemo, useState } from "react"

import {
Select,
Expand All @@ -9,7 +9,7 @@ import {
SelectValue,
} from "@/components/ui/select"

import { checkIsValidJSON } from "./use-field"
import { checkIsValidJSON } from "./format-json"

export type ContentType = "Text" | "JSON"

Expand All @@ -22,7 +22,13 @@ export const ContentTypeSelect = ({
onChange: (value: ContentType) => void
data: string
}) => {
const isValidJSON = useMemo(() => checkIsValidJSON(data), [data])
// Parsing a large value on every keystroke is slow, so check it once typing pauses
const [checkedData, setCheckedData] = useState(data)
useEffect(() => {
const timer = setTimeout(() => setCheckedData(data), 300)
return () => clearTimeout(timer)
}, [data])
const isValidJSON = useMemo(() => checkIsValidJSON(checkedData), [checkedData])

return (
<Select value={value} onValueChange={onChange}>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { describe, expect, test } from "bun:test"

import {
formatJSON,
getJSONSource,
registerStoredValueMapper,
toStoredValue,
toStoredValues,
} from "./format-json"

describe("formatJSON", () => {
test("matches JSON.stringify indentation", () => {
const value = String.raw`{ "b":[1,{"c":"x, y: [z]"},[ ]],"a":{},"d":null,"e":"\"q\""}`
expect(formatJSON(value)).toBe(JSON.stringify(JSON.parse(value), undefined, 2))
expect(formatJSON(value, 0)).toBe(JSON.stringify(JSON.parse(value)))
})

test("keeps scalars exactly as stored", () => {
expect(formatJSON("12345678901234567890")).toBe("12345678901234567890")
expect(formatJSON("10.00")).toBe("10.00")
expect(formatJSON("1e5")).toBe("1e5")
expect(formatJSON(String.raw`"café"`)).toBe(String.raw`"café"`)
})

test("keeps numbers and key order inside objects", () => {
expect(formatJSON('{ "z": 12345678901234567890, "a": 1.50 }')).toBe(
'{\n "z": 12345678901234567890,\n "a": 1.50\n}'
)
expect(formatJSON('{\n "z": 1.50\n}', 0)).toBe('{"z":1.50}')
})
})

describe("toStoredValue", () => {
test("maps the untouched formatted view back to the stored value", () => {
const source = getJSONSource('{"id":1, "a":2}')!
expect(toStoredValue(source.formatted, source)).toBe('{"id":1, "a":2}')
})

test("compacts edits when the stored value was compact", () => {
const source = getJSONSource('{"id":1}')!
expect(toStoredValue('{\n "id": 2.0\n}', source)).toBe('{"id":2.0}')
expect(toStoredValue('{\n "id": ', source)).toBe('{\n "id": ')
})

test("keeps edits as typed when the stored value was not compact", () => {
const source = getJSONSource('{\n "id": 1\n}')!
expect(toStoredValue('{\n "id": 2\n}', source)).toBe('{\n "id": 2\n}')

const scalar = getJSONSource("42\n")!
expect(scalar.formatted).toBe("42")
expect(toStoredValue("42\n\n", scalar)).toBe("42\n\n")
})
})

describe("getJSONSource", () => {
test("formats canonical compact JSON natively", () => {
expect(getJSONSource('{"a":[1,"x"]}')).toEqual({
data: '{"a":[1,"x"]}',
formatted: '{\n "a": [\n 1,\n "x"\n ]\n}',
isCompact: true,
})
})

test("detects compact JSON that native formatting would change", () => {
const source = getJSONSource(String.raw`{"a":1.50,"b":"\u00e9"}`)!
expect(source.isCompact).toBe(true)
expect(source.formatted).toBe('{\n "a": 1.50,\n "b": "\\u00e9"\n}')
expect(toStoredValue(source.formatted.replace("1.50", "2.50"), source)).toBe(
String.raw`{"a":2.50,"b":"\u00e9"}`
)
})

test("rejects invalid JSON", () => {
expect(getJSONSource("{")).toBeUndefined()
})
})

describe("toStoredValues", () => {
test("maps registered fields when saving and leaves the rest", () => {
const form = { control: {} }
const source = getJSONSource('{"id":1}')!
const unregister = registerStoredValueMapper(form.control, "value", (value) =>
toStoredValue(value, source)
)
const values = { key: '{\n "id": 2\n}', value: '{\n "id": 2\n}' }
expect(toStoredValues(form, values)).toEqual({ key: values.key, value: '{"id":2}' })

unregister()
expect(toStoredValues(form, values)).toEqual(values)
})

test("keeps the newer mapper when an older one unregisters", () => {
const form = { control: {} }
const unregisterOld = registerStoredValueMapper(form.control, "value", () => "old")
registerStoredValueMapper(form.control, "value", () => "new")
unregisterOld()
expect(toStoredValues(form, { value: "x" })).toEqual({ value: "new" })
})
})
148 changes: 148 additions & 0 deletions src/components/databrowser/components/display/input/format-json.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
const WHITESPACE = new Set([" ", "\t", "\n", "\r"])

export const checkIsValidJSON = (value: string) => {
try {
JSON.parse(value)
return true
} catch {
return false
}
}

/**
* Formats valid JSON by only changing whitespace outside of strings, so numbers, escapes, and key
* order are kept exactly as stored (unlike JSON.parse + JSON.stringify). Indent 0 compacts it.
*/
export const formatJSON = (value: string, indent = 2) => {
// Fast path: native formatting is lossless when the value is already canonical compact JSON
try {
const parsed = JSON.parse(value)
if (JSON.stringify(parsed) === value) return JSON.stringify(parsed, undefined, indent)
} catch {
// Falls back to the formatter below
}
return reformatJSON(value, indent)
}

const reformatJSON = (value: string, indent: number) => {
const newline = (depth: number) => (indent ? "\n" + " ".repeat(indent * depth) : "")

let result = ""
let depth = 0

for (let i = 0; i < value.length; i++) {
const char = value[i]

if (WHITESPACE.has(char)) continue

switch (char) {
case '"': {
// Copy the whole string at once, skipping escaped characters
let end = i + 1
while (end < value.length && value[end] !== '"') end += value[end] === "\\" ? 2 : 1
result += value.slice(i, end + 1)
i = end
break
}
case "{":
case "[": {
let next = i + 1
while (WHITESPACE.has(value[next])) next++

if (value[next] === (char === "{" ? "}" : "]")) {
result += char + value[next]
i = next
} else {
depth++
result += char + newline(depth)
}
break
}
case "}":
case "]": {
depth--
result += newline(depth) + char
break
}
case ",": {
result += "," + newline(depth)
break
}
case ":": {
result += indent ? ": " : ":"
break
}
default: {
result += char
}
}
}

return result
}

/** Stored JSON value with its formatted view, used to map editor text back to stored bytes */
export type JSONSource = { data: string; formatted: string; isCompact: boolean }

export const getJSONSource = (data: string): JSONSource | undefined => {
let parsed: unknown
try {
parsed = JSON.parse(data)
} catch {
return
}
// Canonical compact JSON can be formatted natively, which is lossless for it and faster
if (JSON.stringify(parsed) === data) {
return { data, formatted: JSON.stringify(parsed, undefined, 2), isCompact: true }
}
return { data, formatted: reformatJSON(data, 2), isCompact: reformatJSON(data, 0) === data }
}

/**
* Maps editor text to the value to store. The untouched formatted view maps back to the original
* bytes, and edits to compact JSON are compacted again so formatting is not saved. This parses the
* whole text, so call it when saving rather than on every change.
*/
export const toStoredValue = (text: string, source: JSONSource) => {
if (text === source.formatted) return source.data
if (source.isCompact && checkIsValidJSON(text)) return reformatJSON(text, 0)
return text
}

// Per form control, the functions that map each field's editor text to the value to store
const storedValueMappers = new WeakMap<object, Map<string, (value: string) => string>>()

/** Registers how a field's form value maps to the value to store, returns the unregister function */
export const registerStoredValueMapper = (
control: object,
name: string,
mapper: (value: string) => string
) => {
let mappers = storedValueMappers.get(control)
if (!mappers) {
mappers = new Map()
storedValueMappers.set(control, mappers)
}
mappers.set(name, mapper)
return () => {
if (mappers.get(name) === mapper) mappers.delete(name)
}
}

/**
* Maps submitted form values to the values to store. Fields edited as JSON hold the editor text
* until then, since mapping it back to the stored format parses the whole value.
*/
export const toStoredValues = <T extends Record<string, unknown>>(
form: { control: object },
values: T
): T => {
const mappers = storedValueMappers.get(form.control)
if (!mappers) return values
const result: Record<string, unknown> = { ...values }
for (const [name, toStored] of mappers) {
const value = result[name]
if (typeof value === "string") result[name] = toStored(value)
}
return result as T
}
Loading
Loading