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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ shared link always asks before it touches your local dashboard.
| Category | Widgets |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| Generators | Chart Generator, QR Code Generator, UUID Generator |
| Formatting | Cron Expression, Jinja Template Renderer, JSON Formatter, Merge PDFs, Split PDF, Timestamp Converter, XML Formatter, YAML ↔ JSON Converter |
| Formatting | Cron Expression, Jinja Template Renderer, JSON Formatter, Merge PDFs, Split PDF, Timestamp Converter, TOML Formatter, XML Formatter, YAML ↔ JSON Converter |
| Encoding | Base64, JWT Encoder, LZ-String, URL Encoder |
| Security | Certificate Viewer, Hash Generator, JWK Viewer, Password Generator, Unix Permissions |
| Text | Code Snippet, Content Type Detector, Duplicate Remover, Emoji Picker, Log Viewer, Notes, Regex Tester, Text Case Converter, Text Diff |
Expand Down
13 changes: 13 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
"react": "^19.2.8",
"react-dom": "^19.3.0",
"react-grid-layout": "^2.2.4",
"smol-toml": "^1.9.1",
"spark-md5": "^3.0.2",
"tailwind-merge": "^3.6.0",
"uuid": "^14.0.1",
Expand Down
12 changes: 10 additions & 2 deletions src/components/CodeEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { forwardRef, useMemo, useRef, useState, type DragEvent } from 'react'
import CodeMirror, { type ReactCodeMirrorRef } from '@uiw/react-codemirror'
import { EditorView } from '@codemirror/view'
import { HighlightStyle, syntaxHighlighting } from '@codemirror/language'
import { HighlightStyle, StreamLanguage, syntaxHighlighting } from '@codemirror/language'
import { toml } from '@codemirror/legacy-modes/mode/toml'
import { openSearchPanel } from '@codemirror/search'
import { tags } from '@lezer/highlight'
import { json } from '@codemirror/lang-json'
Expand All @@ -14,14 +15,20 @@ import { useIsDarkTheme } from '@/theme/useThemeStore'
import { cn } from '@/lib/utils'
import { isFileDrag, readDroppedFile } from '@/components/codeEditorFileDrop'

export type CodeEditorLanguage = 'json' | 'xml' | 'javascript' | 'plaintext'
export type CodeEditorLanguage = 'json' | 'xml' | 'javascript' | 'toml' | 'plaintext'

/** The legacy TOML mode tags table headers, booleans and dates all as
* `atom`, which the app highlight style below leaves uncolored. Mapping it
* to `bool` gives them the same accent as JSON booleans. */
const tomlLanguage = StreamLanguage.define({ ...toml, tokenTable: { atom: tags.bool } })

const LANGUAGE_EXTENSIONS: Record<CodeEditorLanguage, () => Extension[]> = {
json: () => [json()],
xml: () => [xml()],
// TypeScript rather than plain JS: the grammar is a superset, so a .ts
// snippet keeps its highlighting and a .js one loses nothing.
javascript: () => [javascript({ typescript: true })],
toml: () => [tomlLanguage],
// No language grammar to highlight — just wrap long lines instead of
// scrolling horizontally, which matters far more for prose than for the
// structured/single-line inputs the other widgets edit.
Expand Down Expand Up @@ -82,6 +89,7 @@ export function useAppEditorTheme(isDark: boolean): Extension {
{ tag: tags.bool, color: isDark ? 'var(--color-purple-400)' : 'var(--color-purple-600)' },
{ tag: tags.null, color: 'var(--color-muted-foreground)' },
{ tag: tags.punctuation, color: 'var(--color-muted-foreground)' },
{ tag: tags.comment, color: 'var(--color-muted-foreground)', fontStyle: 'italic' },
])
const theme = EditorView.theme(
{
Expand Down
2 changes: 2 additions & 0 deletions src/widgets/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import { jsonYamlDiffDefinition } from './json-yaml-diff/definition'
import { k8sResourceCalculatorDefinition } from './k8s-resource-calculator/definition'
import { todoListDefinition } from './todo-list/definition'
import { scratchpadDefinition } from './scratchpad/definition'
import { tomlFormatterDefinition } from './toml-formatter/definition'

/** Single source of truth for every widget localgrid knows about. The
* dashboard grid, tool browser, and command palette all read from this. */
Expand Down Expand Up @@ -121,6 +122,7 @@ const ALL_WIDGETS: WidgetDefinition[] = [
jsonYamlDiffDefinition,
todoListDefinition,
scratchpadDefinition,
tomlFormatterDefinition,
]

export const WIDGET_REGISTRY: Record<string, WidgetDefinition> = Object.fromEntries(
Expand Down
68 changes: 68 additions & 0 deletions src/widgets/toml-formatter/TomlFormatterWidget.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, expect, it } from 'vitest'
import { render, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { EditorView } from '@codemirror/view'
import TomlFormatterWidget from './TomlFormatterWidget'
import { setCodeMirrorValue } from '@/test/codemirror'

describe('TomlFormatterWidget', () => {
it('starts with the sample TOML shown as a tree', () => {
render(<TomlFormatterWidget instanceId="test" mode="grid" />)

expect(screen.getByRole('textbox', { name: /toml input/i })).toHaveTextContent('localgrid')
expect(within(screen.getByRole('tree')).getByText('"localgrid"')).toBeInTheDocument()
})

it('converts TOML to JSON', async () => {
const user = userEvent.setup()
render(<TomlFormatterWidget instanceId="test" mode="grid" />)

await user.click(screen.getByRole('button', { name: 'To JSON' }))
setCodeMirrorValue(screen.getByRole('textbox', { name: /toml input/i }), 'hello = "world"')

expect(screen.getByRole('textbox', { name: /json output/i })).toHaveValue('{\n "hello": "world"\n}')
})

it('shows an error instead of output for invalid TOML', () => {
render(<TomlFormatterWidget instanceId="test" mode="grid" />)

setCodeMirrorValue(screen.getByRole('textbox', { name: /toml input/i }), 'a = [')

expect(screen.queryByRole('tree')).not.toBeInTheDocument()
expect(screen.getByText(/invalid toml document/i)).toBeInTheDocument()
})

it('carries the document across when switching to From JSON', async () => {
const user = userEvent.setup()
render(<TomlFormatterWidget instanceId="test" mode="grid" />)

setCodeMirrorValue(screen.getByRole('textbox', { name: /toml input/i }), 'hello = "world"')
await user.click(screen.getByRole('button', { name: 'From JSON' }))

// The editor holds back external value changes for a short moment after
// typing, so wait for the carried-over document to land.
const editor = EditorView.findFromDOM(screen.getByRole('textbox', { name: /json input/i }))
await waitFor(() => expect(editor?.state.doc.toString()).toBe('{\n "hello": "world"\n}'))
expect(screen.getByRole('textbox', { name: /toml output/i })).toHaveValue('hello = "world"\n')
})

it('formats TOML in Formatted view', async () => {
const user = userEvent.setup()
render(<TomlFormatterWidget instanceId="test" mode="grid" />)

await user.click(screen.getByRole('button', { name: 'Formatted' }))
setCodeMirrorValue(screen.getByRole('textbox', { name: /toml input/i }), 'a.b = 1')

expect(screen.getByRole('textbox', { name: /toml output/i })).toHaveValue('[a]\nb = 1\n')
})

it('formats integers beyond 2^53 exactly in Formatted view', async () => {
const user = userEvent.setup()
render(<TomlFormatterWidget instanceId="test" mode="grid" />)

await user.click(screen.getByRole('button', { name: 'Formatted' }))
setCodeMirrorValue(screen.getByRole('textbox', { name: /toml input/i }), 'big = 9223372036854775807\nrate = 1.0')

expect(screen.getByRole('textbox', { name: /toml output/i })).toHaveValue('big = 9223372036854775807\nrate = 1.0\n')
})
})
158 changes: 158 additions & 0 deletions src/widgets/toml-formatter/TomlFormatterWidget.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
import { useMemo } from 'react'
import { SegmentedControl } from '@/components/SegmentedControl'
import { CopyButton } from '@/components/CopyButton'
import { ReuseButton } from '@/components/ReuseButton'
import { SplitDirectionToggle, SplitPane, type SplitDirection } from '@/components/SplitPane'
import { ErrorMessage } from '@/components/ErrorMessage'
import { CodeEditor } from '@/components/CodeEditor'
import { DataTree } from '@/components/data-tree/DataTree'
import { buildJsonTree } from '@/components/data-tree/treeModel'
import { Textarea } from '@/components/ui/textarea'
import { InputSlot, OutputSlot } from '@/flow/FlowSlots'
import { useWidgetOutput } from '@/flow/useWidgetOutput'
import { useWidgetDirty } from '@/widgets/useWidgetDirty'
import { useWidgetState } from '@/widgets/useWidgetState'
import type { WidgetProps } from '@/widgets/types'
import {
carryInputAcross,
formatToml,
inputFormatOf,
jsonToToml,
parseTomlDocument,
type TomlMode,
} from './tomlConvert'

/** A small project manifest that shows off what TOML has and JSON lacks:
* comments, dotted keys, dates, tables and an array of tables. */
const SAMPLE = `# Project manifest
name = "localgrid"
version = "0.10.0"
released = 2024-03-18T09:24:00Z
private = false
keywords = ["devtools", "browser", "widgets"]

[build]
target = "es2022"
minify = true
chunks.max-size = 500

[[contributors]]
name = "Ada"
role = "maintainer"

[[contributors]]
name = "Linus"
role = "reviewer"
`

const DEFAULT_MODE: TomlMode = 'tree'

export default function TomlFormatterWidget({ instanceId }: WidgetProps) {
const [input, setInput] = useWidgetState(instanceId, 'input', SAMPLE)
const [mode, setMode] = useWidgetState<TomlMode>(instanceId, 'mode', DEFAULT_MODE)
const [splitDirection, setSplitDirection] = useWidgetState<SplitDirection>(instanceId, 'splitDirection', 'rows')
const [splitRatio, setSplitRatio] = useWidgetState(instanceId, 'splitRatio', 0.5)
useWidgetDirty(instanceId, input !== SAMPLE)

const inputFormat = inputFormatOf(mode)
const parsed = useMemo(() => (mode === 'tree' || mode === 'json' ? parseTomlDocument(input) : null), [input, mode])

const { output, error } = useMemo(() => {
if (mode === 'from-json') return jsonToToml(input)
// Formatted mode parses on its own (BigInt integers), so it must not be
// gated on the JSON-oriented parse, which rejects integers beyond 2^53.
if (mode === 'toml') return formatToml(input)
if (!parsed || parsed.error) return { output: '', error: parsed?.error ?? null }
if (!parsed.data) return { output: '', error: null }
// Tree mode still publishes JSON so a connected widget gets something
// useful downstream.
return { output: JSON.stringify(parsed.data, null, 2), error: null }
}, [mode, input, parsed])
useWidgetOutput(instanceId, output)

const tree = useMemo(() => (mode === 'tree' && parsed?.data ? buildJsonTree(parsed.data) : null), [mode, parsed])

const changeMode = (next: TomlMode) => {
setInput(carryInputAcross(input, mode, next))
setMode(next)
}

// Reusing a converted output flips the direction too, since the input
// editor then holds the other format.
const reuse = (value: string) => {
setInput(value)
if (mode === 'json') setMode('from-json')
else if (mode === 'from-json') setMode('json')
}

const sourceLabel = inputFormat === 'toml' ? 'TOML' : 'JSON'
const targetLabel = mode === 'json' ? 'JSON' : 'TOML'

return (
<div className="flex h-full flex-col gap-2">
<div className="flex flex-wrap items-center gap-2">
<SegmentedControl
value={mode}
onChange={changeMode}
options={[
{ label: 'Tree', value: 'tree' },
{ label: 'Formatted', value: 'toml' },
{ label: 'To JSON', value: 'json' },
{ label: 'From JSON', value: 'from-json' },
]}
/>
<SplitDirectionToggle value={splitDirection} onChange={setSplitDirection} className="ml-auto" />
</div>
<SplitPane
direction={splitDirection}
ratio={splitRatio}
onRatioChange={setSplitRatio}
label="Resize input and output"
className="flex-1"
first={
<InputSlot input="input" className="flex min-h-0 flex-1 flex-col">
<CodeEditor
value={input}
onChange={setInput}
language={inputFormat}
placeholder={`Paste ${sourceLabel}…`}
aria-label={`${sourceLabel} input`}
className="min-h-0 flex-1"
/>
</InputSlot>
}
second={
<OutputSlot className="flex min-h-0 flex-1 flex-col">
<div className="relative flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border bg-background p-2 dark:bg-muted/40">
{error ? (
<div className="min-h-0 flex-1 overflow-auto">
<ErrorMessage>
<span className="whitespace-pre-wrap font-mono">{error}</span>
</ErrorMessage>
</div>
) : !output ? (
<p className="text-xs text-muted-foreground">Output will appear here</p>
) : tree ? (
<DataTree root={tree} label="TOML tree" className="flex-1" />
) : (
<>
<div className="-mr-1 -mt-1 flex shrink-0 justify-end gap-0.5">
<ReuseButton value={output} onReuse={reuse} direction={splitDirection} />
<CopyButton value={output} />
</div>
<Textarea
readOnly
value={output}
spellCheck={false}
aria-label={`${targetLabel} output`}
className="min-h-0 w-full flex-1 resize-none overflow-auto border-0 bg-transparent p-0 font-mono text-xs"
/>
</>
)}
</div>
</OutputSlot>
}
/>
</div>
)
}
19 changes: 19 additions & 0 deletions src/widgets/toml-formatter/definition.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { lazy } from 'react'
import { FileSliders } from 'lucide-react'
import type { WidgetDefinition } from '@/widgets/types'

export const tomlFormatterDefinition: WidgetDefinition = {
id: 'toml-formatter',
name: 'TOML Formatter',
description: 'Validate and format TOML, explore it as a tree, and convert to or from JSON',
category: 'formatting',
icon: FileSliders,
defaultSize: { w: 4, h: 4 },
minSize: { w: 3, h: 3 },
component: lazy(() => import('./TomlFormatterWidget')),
keywords: ['toml', 'json', 'format', 'validate', 'convert', 'cargo', 'pyproject', 'config'],
flow: {
inputs: [{ field: 'input', label: 'Source' }],
output: { label: 'Converted' },
},
}
Loading
Loading