|
| 1 | +import { Identifier, ItemStack, Json, NbtCompound, NbtString, NbtTag, StringReader } from 'deepslate' |
| 2 | +import { route } from 'preact-router' |
| 3 | +import { useCallback, useEffect, useMemo, useState } from 'preact/hooks' |
| 4 | +import config from '../../config.json' |
| 5 | +import { Footer, Octicon } from '../components/index.js' |
| 6 | +import { useLocale } from '../contexts/Locale.jsx' |
| 7 | +import { useTitle } from '../contexts/Title.jsx' |
| 8 | +import { useActiveTimeout } from '../hooks/useActiveTimout.js' |
| 9 | +import { useLocalStorage } from '../hooks/useLocalStorage.js' |
| 10 | +import type { VersionId } from '../services/Versions.js' |
| 11 | +import { checkVersion } from '../services/Versions.js' |
| 12 | +import { jsonToNbt } from '../Utils.js' |
| 13 | + |
| 14 | +const FORMATS = ['give-command', 'loot-table'] as const |
| 15 | +type Format = typeof FORMATS[number] |
| 16 | + |
| 17 | +interface Props { |
| 18 | + path?: string, |
| 19 | + formats?: string, |
| 20 | +} |
| 21 | +export function Convert({ formats }: Props) { |
| 22 | + const {locale} = useLocale() |
| 23 | + |
| 24 | + const [source, setSource] = useState<Format>() |
| 25 | + const [target, setTarget] = useState<Format>() |
| 26 | + |
| 27 | + useEffect(() => { |
| 28 | + const match = formats?.match(/^([a-z0-9-]+)-to-([a-z0-9-]+)/) |
| 29 | + if (match && FORMATS.includes(match[1] as Format)) { |
| 30 | + setSource(match[1] as Format) |
| 31 | + } |
| 32 | + if (match && FORMATS.includes(match[2] as Format)) { |
| 33 | + setTarget(match[2] as Format) |
| 34 | + } |
| 35 | + }, [formats]) |
| 36 | + |
| 37 | + const supportedVersions = useMemo(() => { |
| 38 | + return config.versions |
| 39 | + .filter(v => checkVersion(v.id, '1.20.5')) |
| 40 | + .map(v => v.id as VersionId) |
| 41 | + .reverse() |
| 42 | + }, []) |
| 43 | + |
| 44 | + const title = !source || !target |
| 45 | + ? locale('title.convert') |
| 46 | + : locale('title.convert.formats', locale(`convert.format.${source}`), locale(`convert.format.${target}`)) |
| 47 | + useTitle(title, supportedVersions) |
| 48 | + |
| 49 | + const [input, setInput] = useLocalStorage('misode_convert_input', '') |
| 50 | + |
| 51 | + const convertFn = useMemo(() => { |
| 52 | + if (!source || !target) { |
| 53 | + return undefined |
| 54 | + } |
| 55 | + if (source === target) { |
| 56 | + return (input: string) => input |
| 57 | + } |
| 58 | + return CONVERSIONS[source][target] |
| 59 | + }, [source, target]) |
| 60 | + |
| 61 | + const { output, error } = useMemo(() => { |
| 62 | + if (!convertFn) { |
| 63 | + return { output: '' } |
| 64 | + } |
| 65 | + try { |
| 66 | + return { output: convertFn(input) } |
| 67 | + } catch (e) { |
| 68 | + return { output: '', error: e instanceof Error ? e : undefined } |
| 69 | + } |
| 70 | + }, [convertFn, input]) |
| 71 | + |
| 72 | + const changeSource = useCallback((newSource: Format) => { |
| 73 | + setSource(newSource) |
| 74 | + if (target === newSource) { |
| 75 | + setTarget(source) |
| 76 | + setInput(output) |
| 77 | + } |
| 78 | + if (target) { |
| 79 | + route(`/convert/${newSource}-to-${target === newSource ? source : target}`) |
| 80 | + } |
| 81 | + }, [source, target]) |
| 82 | + |
| 83 | + const changeTarget = useCallback((newTarget: Format) => { |
| 84 | + setTarget(newTarget) |
| 85 | + if (source === newTarget) { |
| 86 | + setSource(target) |
| 87 | + setInput(output) |
| 88 | + } |
| 89 | + if (source) { |
| 90 | + route(`/convert/${source === newTarget ? target : source}-to-${newTarget}`) |
| 91 | + } |
| 92 | + }, [source]) |
| 93 | + |
| 94 | + const onSwap = useCallback(() => { |
| 95 | + setSource(target) |
| 96 | + setTarget(source) |
| 97 | + if (output.length > 0) { |
| 98 | + setInput(output) |
| 99 | + } |
| 100 | + if (source && target) { |
| 101 | + route(`/convert/${target}-to-${source}`) |
| 102 | + } |
| 103 | + }, [source, target, output]) |
| 104 | + |
| 105 | + const [copyActive, setCopyActive] = useActiveTimeout() |
| 106 | + const onCopyOutput = useCallback(async () => { |
| 107 | + await navigator.clipboard.writeText(output) |
| 108 | + setCopyActive() |
| 109 | + }, [output]) |
| 110 | + |
| 111 | + return <main> |
| 112 | + <div class="legacy-container"> |
| 113 | + <div class="flex my-4 justify-center"> |
| 114 | + <FormatSelect value={source} onChange={changeSource} /> |
| 115 | + <button class="mx-3 tooltipped tip-s" aria-label={locale('convert.swap')} onClick={onSwap}>{Octicon.arrow_switch}</button> |
| 116 | + <FormatSelect value={target} onChange={changeTarget} /> |
| 117 | + </div> |
| 118 | + <div class="flex"> |
| 119 | + <div class="relative w-full mr-2"> |
| 120 | + <textarea class="convert-textarea block resize-none w-full font-mono text-sm px-2 py-1 rounded" value={input} onInput={(e) => setInput((e.target as HTMLTextAreaElement).value)}></textarea> |
| 121 | + {error && <div class="convert-error absolute bottom-0 left-0 w-full p-2 pr-6">{error.message}</div>} |
| 122 | + </div> |
| 123 | + <div class="relative w-full ml-2"> |
| 124 | + <textarea class="convert-textarea block resize-none w-full font-mono text-sm px-2 py-1 rounded" value={output} readonly></textarea> |
| 125 | + <button class={`absolute top-0 right-0 m-4 mr-5 tooltipped tip-s ${copyActive ? 'status-icon active' : ''}`} aria-label={locale(copyActive ? 'copied' : 'copy')} onClick={onCopyOutput}>{copyActive ? Octicon.check : Octicon.copy}</button> |
| 126 | + </div> |
| 127 | + </div> |
| 128 | + </div> |
| 129 | + <Footer /> |
| 130 | + </main> |
| 131 | +} |
| 132 | + |
| 133 | +interface FormatSelectProps { |
| 134 | + value: string | undefined |
| 135 | + onChange: (newValue: Format) => void |
| 136 | +} |
| 137 | +function FormatSelect({ value, onChange }: FormatSelectProps) { |
| 138 | + const { locale } = useLocale() |
| 139 | + return <select class="convert-select text-xl px-3 py-1 rounded" value={value} onChange={(e) => onChange((e.target as HTMLSelectElement).value as Format)}> |
| 140 | + {value === undefined && <option value={undefined}>{locale('convert.select')}</option>} |
| 141 | + {FORMATS.map(format => <option value={format}>{locale(`convert.format.${format}`)}</option>)} |
| 142 | + </select> |
| 143 | +} |
| 144 | + |
| 145 | +const CONVERSIONS: Record<Format, Partial<Record<Format, (input: string) => string>>> = { |
| 146 | + 'give-command': { |
| 147 | + 'loot-table': (input) => { |
| 148 | + const itemStack = parseGiveCommand(new StringReader(input)) |
| 149 | + const lootTable = createLootTable(itemStack) |
| 150 | + return JSON.stringify(lootTable, null, 2) |
| 151 | + }, |
| 152 | + }, |
| 153 | + 'loot-table': { |
| 154 | + 'give-command': (input) => { |
| 155 | + const lootTable = JSON.parse(input) |
| 156 | + const itemStack = getItemFromLootTable(lootTable) |
| 157 | + return `give @s ${stringifyItemStack(itemStack)}` |
| 158 | + }, |
| 159 | + }, |
| 160 | +} |
| 161 | + |
| 162 | +function parseGiveCommand(reader: StringReader) { |
| 163 | + if (reader.peek() === '/') { |
| 164 | + reader.skip() |
| 165 | + } |
| 166 | + if (reader.peek() === 'g' && reader.peek(1) === 'i' && reader.peek(2) === 'v' && reader.peek(3) === 'e') { |
| 167 | + reader.cursor += 4 |
| 168 | + reader.expect(' ') |
| 169 | + reader.expect('@') |
| 170 | + if (reader.peek().match(/[parsen]/)) { |
| 171 | + reader.skip() |
| 172 | + } else { |
| 173 | + throw reader.createError("Expected 'p', 'a', 'r', 's', 'e', or 'n'") |
| 174 | + } |
| 175 | + reader.expect(' ') |
| 176 | + } |
| 177 | + const item = parseIdentifier(reader) |
| 178 | + const components = parseComponents(reader) |
| 179 | + let count = 1 |
| 180 | + if (reader.peek() === ' ') { |
| 181 | + reader.skip() |
| 182 | + count = reader.readInt() |
| 183 | + } |
| 184 | + return new ItemStack(item, count, components) |
| 185 | +} |
| 186 | + |
| 187 | + |
| 188 | +function parseComponents(reader: StringReader) { |
| 189 | + const components = new Map<string, NbtTag>() |
| 190 | + if (reader.peek() !== '[') { |
| 191 | + return components |
| 192 | + } |
| 193 | + reader.skip() |
| 194 | + reader.skipWhitespace() |
| 195 | + while (reader.peek() !== ']') { |
| 196 | + if (reader.peek() === '!') { |
| 197 | + reader.skip() |
| 198 | + reader.skipWhitespace() |
| 199 | + const key = parseIdentifier(reader) |
| 200 | + components.set('!' + key, new NbtCompound()) |
| 201 | + reader.skipWhitespace() |
| 202 | + } else { |
| 203 | + const key = parseIdentifier(reader) |
| 204 | + reader.skipWhitespace() |
| 205 | + reader.expect('=') |
| 206 | + reader.skipWhitespace() |
| 207 | + const tag = NbtTag.fromString(reader) |
| 208 | + reader.skipWhitespace() |
| 209 | + if (key.is('custom_data')) { |
| 210 | + components.set(key.toString(), new NbtString(tag.toString())) |
| 211 | + } else { |
| 212 | + components.set(key.toString(), tag) |
| 213 | + } |
| 214 | + } |
| 215 | + if (reader.peek() === ']') { |
| 216 | + break |
| 217 | + } else if (reader.peek() === ',') { |
| 218 | + reader.skip() |
| 219 | + reader.skipWhitespace() |
| 220 | + continue |
| 221 | + } |
| 222 | + throw reader.createError("Expected ',' or ']'") |
| 223 | + } |
| 224 | + reader.skip() |
| 225 | + return components |
| 226 | +} |
| 227 | + |
| 228 | +function parseIdentifier(reader: StringReader) { |
| 229 | + const start = reader.cursor |
| 230 | + while (reader.canRead() && reader.peek().match(/[a-z0-9_.:\/-]/)) { |
| 231 | + reader.skip() |
| 232 | + } |
| 233 | + const result = reader.getRead(start) |
| 234 | + if (result.length === 0) { |
| 235 | + throw reader.createError('Expected a resource location') |
| 236 | + } |
| 237 | + return Identifier.parse(result) |
| 238 | +} |
| 239 | + |
| 240 | +function createLootTable(item: ItemStack) { |
| 241 | + return { |
| 242 | + pools: [ |
| 243 | + { |
| 244 | + rolls: 1, |
| 245 | + entries: [ |
| 246 | + { |
| 247 | + type: 'minecraft:item', |
| 248 | + name: item.id.toString(), |
| 249 | + functions: (item.components.size > 0 || item.count > 1) |
| 250 | + ? [ |
| 251 | + ...item.components.size > 0 ? [{ |
| 252 | + function: 'minecraft:set_components', |
| 253 | + components: Object.fromEntries([...item.components.entries()].map(([key, value]) => { |
| 254 | + return [key, value.toSimplifiedJson()] |
| 255 | + })), |
| 256 | + }] : [], |
| 257 | + ...item.count > 1 ? [{ |
| 258 | + function: 'minecraft:set_count', |
| 259 | + count: item.count, |
| 260 | + }]: [], |
| 261 | + ] |
| 262 | + : undefined, |
| 263 | + }, |
| 264 | + ], |
| 265 | + }, |
| 266 | + ], |
| 267 | + } |
| 268 | +} |
| 269 | + |
| 270 | +function getItemFromLootTable(data: unknown): ItemStack { |
| 271 | + const root = Json.readObject(data) ?? {} |
| 272 | + const pools = Json.readArray(root.pools, e => Json.readObject(e) ?? {}) ?? [] |
| 273 | + if (pools.length === 0) { |
| 274 | + throw new Error('Expected a pool') |
| 275 | + } |
| 276 | + const pool = pools[0] |
| 277 | + const entries = Json.readArray(pool.entries, e => Json.readObject(e) ?? {}) ?? [] |
| 278 | + if (entries.length === 0) { |
| 279 | + throw new Error('Expected an entry') |
| 280 | + } |
| 281 | + const entry = entries[0] |
| 282 | + const type = Json.readString(entry.type) |
| 283 | + if (type?.replace(/^minecraft:/, '') !== 'item') { |
| 284 | + throw new Error('Expected "type" to be "minecraft:item"') |
| 285 | + } |
| 286 | + const name = Json.readString(entry.name) |
| 287 | + if (!name) { |
| 288 | + throw new Error('Expected "name"') |
| 289 | + } |
| 290 | + const functions = [ |
| 291 | + ...Json.readArray(entry.functions, e => Json.readObject(e) ?? {}) ?? [], |
| 292 | + ...Json.readArray(pool.functions, e => Json.readObject(e) ?? {}) ?? [], |
| 293 | + ...Json.readArray(root.functions, e => Json.readObject(e) ?? {}) ?? [], |
| 294 | + ] |
| 295 | + let count = 1 |
| 296 | + const components = new Map<string, NbtTag>() |
| 297 | + for (const fn of functions) { |
| 298 | + const type = Json.readString(fn.function)?.replace(/^minecraft:/, '') |
| 299 | + switch (type) { |
| 300 | + case 'set_count': |
| 301 | + const value = Json.readInt(fn.count) |
| 302 | + if (value) { |
| 303 | + count = value |
| 304 | + } |
| 305 | + break |
| 306 | + case 'set_components': |
| 307 | + const newComponents = Json.readObject(fn.components) ?? {} |
| 308 | + for (const [key, value] of Object.entries(newComponents)) { |
| 309 | + components.set(key, jsonToNbt(value)) |
| 310 | + } |
| 311 | + } |
| 312 | + } |
| 313 | + return new ItemStack(Identifier.parse(name), count, components) |
| 314 | +} |
| 315 | + |
| 316 | +function stringifyItemStack(itemStack: ItemStack) { |
| 317 | + let result = itemStack.id.toString() |
| 318 | + if (itemStack.components.size > 0) { |
| 319 | + result += `[${[...itemStack.components.entries()].map(([k, v]) => { |
| 320 | + return k.startsWith('!') ? k : `${k}=${v.toString()}` |
| 321 | + }).join(',')}]` |
| 322 | + } |
| 323 | + if (itemStack.count > 1) { |
| 324 | + result += ` ${itemStack.count}` |
| 325 | + } |
| 326 | + return result |
| 327 | +} |
0 commit comments