Skip to content

Commit 90a04bd

Browse files
swetasanghi2004-progSwetajohannschopplich
authored
feat(docs): add YAML input to Playground with tests (#303)
* feat(docs): add YAML input to Playground with tests - Add input format selector and YAML parsing (YAML 1.2, merge keys off) - Extract parse/stringify helpers for testability and SPEC-aligned encoding - Add Vitest for docs package and playground parse tests - Update Playground copy in package README and ecosystem docs * refactor(docs): simplify Playground YAML support - Inline parse/stringify helpers into the component, drop the separate parse-input module and its tests - Rename input state from `jsonInput`/`formattedJson`/`jsonTokens` to `inputText`/`formattedInput`/`inputTokens` so names no longer lie when YAML is selected - Hide the JSON Baseline selector in YAML mode and make the token-count tooltip conditional on input format - Store input under `state.input` with a fallback read of legacy `state.json` so existing share URLs keep working - Drop redundant YAML parse options (merge/version match library defaults); use lineWidth: 0 for editor display so long scalars do not fold mid-sentence - Remove the duplicated vitest devDep, docs vitest.config.ts, and `test` script – the playground is verified through the dev server * chore(docs): tighten Playground wording and drop empty-string fallback - "in real-time" → "in real time" (real-time only hyphenates as a compound modifier before a noun) - Header copy now matches the ecosystem page: "Convert JSON or YAML to TOON in real time" - Token-count tooltip unified across input formats; the JSON baseline selector is right next to it and already communicates the format - Drop `?? ''` fallback on state.input — decodeState already gates on successful JSON parse; the chain falls through to the legacy state.json field --------- Co-authored-by: Sweta <[email protected]> Co-authored-by: Johann Schopplich <[email protected]>
1 parent 9ac3f9e commit 90a04bd

5 files changed

Lines changed: 78 additions & 32 deletions

File tree

‎docs/.vitepress/theme/components/PlaygroundLayout.vue‎

Lines changed: 71 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,27 @@ import { useClipboard, useDebounceFn } from '@vueuse/core'
44
import { unzlibSync, zlibSync } from 'fflate'
55
import { base64ToUint8Array, stringToUint8Array, uint8ArrayToBase64, uint8ArrayToString } from 'uint8array-extras'
66
import { computed, onMounted, ref, shallowRef, watch } from 'vue'
7+
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml'
78
import { DEFAULT_DELIMITER, encode } from '../../../../packages/toon/src'
89
import VPInput from './VPInput.vue'
910
11+
type InputFormat = 'json' | 'yaml'
1012
type JsonFormat = 'pretty-2' | 'pretty-4' | 'pretty-tab' | 'compact'
1113
1214
interface PlaygroundState extends Required<Pick<EncodeOptions, 'delimiter' | 'indent' | 'keyFolding' | 'flattenDepth'>> {
13-
json: string
15+
input: string
16+
inputFormat: InputFormat
1417
jsonFormat: JsonFormat
18+
/** Pre-YAML share URLs stored input under `json`. Read-only fallback. */
19+
json?: string
20+
}
21+
22+
function parseInput(text: string, format: InputFormat): unknown {
23+
return format === 'yaml' ? parseYaml(text) : JSON.parse(text)
24+
}
25+
26+
function stringifyInputYaml(value: unknown): string {
27+
return stringifyYaml(value, { lineWidth: 0 })
1528
}
1629
1730
const PRESETS = {
@@ -83,17 +96,19 @@ const DEFAULT_JSON = JSON.stringify(PRESETS.hikes, undefined, 2)
8396
const SHARE_URL_LIMIT = 8 * 1024
8497
8598
// Input state
86-
const jsonInput = ref(DEFAULT_JSON)
99+
const inputText = ref(DEFAULT_JSON)
100+
const inputFormat = ref<InputFormat>('json')
87101
const jsonFormat = ref<JsonFormat>('pretty-2')
88102
const currentFormatIndent = computed(() =>
89103
JSON_FORMAT_OPTIONS.find(opt => opt.value === jsonFormat.value)?.indent,
90104
)
91-
const formattedJson = computed(() => {
105+
const formattedInput = computed(() => {
92106
try {
93-
return formatJson(JSON.parse(jsonInput.value))
107+
const data = parseInput(inputText.value, inputFormat.value)
108+
return inputFormat.value === 'yaml' ? stringifyInputYaml(data) : formatJson(data)
94109
}
95110
catch {
96-
return jsonInput.value
111+
return inputText.value
97112
}
98113
})
99114
@@ -106,7 +121,7 @@ const flattenDepth = ref(2)
106121
// Encoding output
107122
const encodingResult = computed(() => {
108123
try {
109-
const parsedInput = JSON.parse(jsonInput.value)
124+
const parsedInput = parseInput(inputText.value, inputFormat.value)
110125
return {
111126
output: encode(parsedInput, {
112127
indent: indent.value,
@@ -118,9 +133,10 @@ const encodingResult = computed(() => {
118133
}
119134
}
120135
catch (error) {
136+
const fallback = inputFormat.value === 'yaml' ? 'Invalid YAML' : 'Invalid JSON'
121137
return {
122138
output: '',
123-
error: error instanceof Error ? error.message : 'Invalid JSON',
139+
error: error instanceof Error ? error.message : fallback,
124140
}
125141
}
126142
})
@@ -129,18 +145,18 @@ const error = computed(() => encodingResult.value.error)
129145
130146
// Token analysis
131147
const tokenizer = shallowRef<typeof import('gpt-tokenizer') | undefined>()
132-
const jsonTokens = computed(() =>
133-
tokenizer.value?.encode(formattedJson.value).length,
148+
const inputTokens = computed(() =>
149+
tokenizer.value?.encode(formattedInput.value).length,
134150
)
135151
const toonTokens = computed(() =>
136152
tokenizer.value && toonOutput.value ? tokenizer.value.encode(toonOutput.value).length : undefined,
137153
)
138154
const tokenSavings = computed(() => {
139-
if (!jsonTokens.value || !toonTokens.value)
155+
if (!inputTokens.value || !toonTokens.value)
140156
return
141157
142-
const diff = jsonTokens.value - toonTokens.value
143-
const percent = Math.abs((diff / jsonTokens.value) * 100).toFixed(1)
158+
const diff = inputTokens.value - toonTokens.value
159+
const percent = Math.abs((diff / inputTokens.value) * 100).toFixed(1)
144160
const sign = diff > 0 ? '−' : '+'
145161
146162
return { diff, percent, sign, isSavings: diff > 0 }
@@ -165,13 +181,25 @@ const updateUrl = useDebounceFn(() => {
165181
window.history.replaceState(null, '', `#${hash}`)
166182
}, 300)
167183
168-
watch([jsonInput, delimiter, indent, keyFolding, flattenDepth, jsonFormat], () => {
184+
watch([inputText, delimiter, indent, keyFolding, flattenDepth, jsonFormat, inputFormat], () => {
169185
updateUrl()
170186
})
171187
172188
watch(jsonFormat, () => {
189+
if (inputFormat.value !== 'json')
190+
return
191+
try {
192+
inputText.value = formatJson(JSON.parse(inputText.value))
193+
}
194+
catch {}
195+
})
196+
197+
watch(inputFormat, (next, prev) => {
198+
if (prev === next)
199+
return
173200
try {
174-
jsonInput.value = formatJson(JSON.parse(jsonInput.value))
201+
const data = parseInput(inputText.value, prev)
202+
inputText.value = next === 'yaml' ? stringifyInputYaml(data) : formatJson(data)
175203
}
176204
catch {}
177205
})
@@ -185,12 +213,13 @@ onMounted(() => {
185213
186214
const state = decodeState(hash)
187215
if (state) {
188-
jsonInput.value = state.json
216+
inputText.value = state.input ?? state.json
189217
delimiter.value = state.delimiter
190218
indent.value = state.indent
191219
keyFolding.value = state.keyFolding ?? 'safe'
192220
flattenDepth.value = state.flattenDepth ?? 2
193221
jsonFormat.value = state.jsonFormat ?? 'pretty-2'
222+
inputFormat.value = state.inputFormat ?? 'json'
194223
}
195224
})
196225
@@ -200,7 +229,8 @@ function formatJson(value: unknown) {
200229
201230
function encodeState() {
202231
const state: PlaygroundState = {
203-
json: jsonInput.value,
232+
input: inputText.value,
233+
inputFormat: inputFormat.value,
204234
delimiter: delimiter.value,
205235
indent: indent.value,
206236
keyFolding: keyFolding.value,
@@ -224,7 +254,8 @@ function decodeState(hash: string) {
224254
}
225255
226256
function loadPreset(name: keyof typeof PRESETS) {
227-
jsonInput.value = formatJson(PRESETS[name])
257+
const data = PRESETS[name]
258+
inputText.value = inputFormat.value === 'yaml' ? stringifyInputYaml(data) : formatJson(data)
228259
}
229260
230261
async function copyShareUrl() {
@@ -247,11 +278,22 @@ async function loadTokenizer() {
247278
<!-- Header -->
248279
<header class="playground-header">
249280
<h1>Playground</h1>
250-
<p>Experiment with JSON to TOON encoding in real-time.</p>
281+
<p>Convert JSON or YAML to TOON in real time.</p>
251282
</header>
252283

253284
<!-- Options Bar -->
254285
<div class="options-bar">
286+
<VPInput id="inputFormat" label="Input format">
287+
<select id="inputFormat" v-model="inputFormat">
288+
<option value="json">
289+
JSON
290+
</option>
291+
<option value="yaml">
292+
YAML
293+
</option>
294+
</select>
295+
</VPInput>
296+
255297
<VPInput id="delimiter" label="Delimiter">
256298
<select id="delimiter" v-model="delimiter">
257299
<option v-for="opt in DELIMITER_OPTIONS" :key="opt.value" :value="opt.value">
@@ -312,7 +354,7 @@ async function loadTokenizer() {
312354
</select>
313355
</VPInput>
314356

315-
<VPInput id="jsonFormat" label="JSON Baseline">
357+
<VPInput v-if="inputFormat === 'json'" id="jsonFormat" label="JSON Baseline">
316358
<select id="jsonFormat" v-model="jsonFormat">
317359
<option v-for="opt in JSON_FORMAT_OPTIONS" :key="opt.value" :value="opt.value">
318360
{{ opt.label }}
@@ -347,24 +389,24 @@ async function loadTokenizer() {
347389

348390
<!-- Editor Container -->
349391
<div class="editor-container">
350-
<!-- JSON Input -->
392+
<!-- Input -->
351393
<div class="editor-pane">
352394
<div class="pane-header">
353-
<span class="pane-title">JSON Input</span>
395+
<span class="pane-title">{{ inputFormat === 'yaml' ? 'YAML Input' : 'JSON Input' }}</span>
354396
<span class="pane-stats">
355-
<span class="stat-primary" title="Token count using selected JSON baseline format">{{ jsonTokens ?? '…' }} tokens</span>
356-
<span class="stat-secondary">{{ formattedJson.length }} chars</span>
397+
<span class="stat-primary" title="Token count of the formatted input">{{ inputTokens ?? '…' }} tokens</span>
398+
<span class="stat-secondary">{{ formattedInput.length }} chars</span>
357399
</span>
358400
</div>
359401
<textarea
360-
id="json-input"
361-
v-model="jsonInput"
402+
id="input"
403+
v-model="inputText"
362404
class="editor-textarea"
363405
spellcheck="false"
364-
aria-label="JSON input"
365-
:aria-describedby="error ? 'json-error' : undefined"
406+
:aria-label="inputFormat === 'yaml' ? 'YAML input' : 'JSON input'"
407+
:aria-describedby="error ? 'parse-error' : undefined"
366408
:aria-invalid="!!error"
367-
placeholder="Enter JSON here…"
409+
:placeholder="inputFormat === 'yaml' ? 'Enter YAML here…' : 'Enter JSON here…'"
368410
/>
369411
</div>
370412

@@ -392,7 +434,7 @@ async function loadTokenizer() {
392434
@click="copy()"
393435
/>
394436
<pre v-if="!error"><code>{{ toonOutput }}</code></pre>
395-
<div v-else id="json-error" role="alert" class="error-message">
437+
<div v-else id="parse-error" role="alert" class="error-message">
396438
{{ error }}
397439
</div>
398440
</div>

‎docs/ecosystem/tools-and-playgrounds.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Experiment with TOON format interactively using these tools for token comparison
1010

1111
### Official Playground
1212

13-
The [TOON Playground](/playground) lets you convert JSON to TOON in real-time, compare token counts, and share your experiments via URL.
13+
The [TOON Playground](/playground) lets you convert JSON or YAML to TOON in real time, compare token counts, and share your experiments via URL.
1414

1515
### Community Playgrounds
1616

‎docs/package.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
"uint8array-extras": "^1.5.0",
1616
"unocss": "^66.6.8",
1717
"vitepress": "^1.6.4",
18-
"vitepress-plugin-llms": "^1.12.2"
18+
"vitepress-plugin-llms": "^1.12.2",
19+
"yaml": "^2.8.4"
1920
}
2021
}

‎packages/toon/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@ Experiment with TOON format interactively using these tools for token comparison
817817

818818
### Official Playground
819819

820-
The [TOON Playground](https://toonformat.dev/playground) lets you convert JSON to TOON in real-time, compare token counts, and share your experiments via URL.
820+
The [TOON Playground](https://toonformat.dev/playground) lets you convert JSON or YAML to TOON in real time, compare token counts, and share your experiments via URL.
821821

822822
### Community Playgrounds
823823

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)