d2js: support unicode characters

This commit is contained in:
delfino 2025-02-28 17:04:45 +00:00
parent 80f560a844
commit 9a751d5fa1
No known key found for this signature in database
GPG key ID: CFE0DD6A770BF48C
4 changed files with 20 additions and 2 deletions

View file

@ -27,3 +27,4 @@
- fixes panic when comment lines appear in arrays [#2378](https://github.com/terrastruct/d2/pull/2378)
- fixes inconsistencies when objects were double quoted [#2390](https://github.com/terrastruct/d2/pull/2390)
- CLI: fetch and render remote images of mimetype octet-stream correctly [#2370](https://github.com/terrastruct/d2/pull/2370)
- d2js: handle unicode characters (PR pending)

View file

@ -54,7 +54,10 @@ export function setupMessageHandler(isNode, port, initWasm) {
const result = await d2.render(JSON.stringify(data));
const response = JSON.parse(result);
if (response.error) throw new Error(response.error.message);
currentPort.postMessage({ type: "result", data: atob(response.data) });
const decoded = new TextDecoder().decode(
Uint8Array.from(atob(response.data), (c) => c.charCodeAt(0))
);
currentPort.postMessage({ type: "result", data: decoded });
} catch (err) {
currentPort.postMessage({ type: "error", error: err.message });
}

View file

@ -49,7 +49,10 @@ export function setupMessageHandler(isNode, port, initWasm) {
const result = await d2.render(JSON.stringify(data));
const response = JSON.parse(result);
if (response.error) throw new Error(response.error.message);
currentPort.postMessage({ type: "result", data: atob(response.data) });
const decoded = new TextDecoder().decode(
Uint8Array.from(atob(response.data), (c) => c.charCodeAt(0))
);
currentPort.postMessage({ type: "result", data: decoded });
} catch (err) {
currentPort.postMessage({ type: "error", error: err.message });
}

View file

@ -171,6 +171,17 @@ layers: {
await d2.worker.terminate();
}, 20000);
test("unicode characters work", async () => {
const d2 = new D2();
const result = await d2.compile("こんにちは -> ♒️");
const svg = await d2.render(result.diagram);
expect(svg).toContain("<svg");
expect(svg).toContain("</svg>");
expect(svg).toContain("こんにちは");
expect(svg).toContain("♒️");
await d2.worker.terminate();
}, 20000);
test("handles syntax errors correctly", async () => {
const d2 = new D2();
try {