Repository navigation
Expand file tree
/
Copy pathexport.js
More file actions
417 lines (363 loc) · 12.1 KB
/
Copy pathexport.js
File metadata and controls
417 lines (363 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import * as Blockly from "blockly";
import { importSnippet } from "./files.js";
import { getSnippetOption } from "./translation.js";
import w500 from "@fontsource/atkinson-hyperlegible-next/files/atkinson-hyperlegible-next-latin-500-normal.woff2";
async function exportBlockSnippet(block) {
try {
// Save the block and its children to a JSON object
const blockJson = Blockly.serialization.blocks.save(block);
// Convert the JSON object to a pretty-printed JSON string
const jsonString = JSON.stringify(blockJson, null, 2);
// Check if the File System Access API is available
if ("showSaveFilePicker" in window) {
// Define the options for the file picker
const options = {
suggestedName: "blockly_snippet.json",
types: [
{
description: "JSON Files",
accept: {
"application/json": [".json"],
},
},
],
};
// Show the save file picker
const fileHandle = await window.showSaveFilePicker(options);
// Create a writable stream
const writable = await fileHandle.createWritable();
// Write the JSON string to the file
await writable.write(jsonString);
// Close the writable stream
await writable.close();
} else {
// Fallback for browsers that don't support the File System Access API
const filename =
prompt(
"Enter a filename for the snippet:",
"blockly_snippet",
) || "blockly_snippet";
const blob = new Blob([jsonString], { type: "application/json" });
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${filename}.json`;
link.click();
}
} catch (e) {
console.error("Error exporting block:", e);
}
}
export function addExportContextMenuOptions() {
addExportContextMenuOption();
addImportContextMenuOption();
//addExportSVGContextMenuOption();
addExportPNGContextMenuOption();
}
function addExportContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "exportBlock",
weight: 200,
displayText: function () {
return getSnippetOption("export_JSON");
},
preconditionFn: function (scope) {
return scope.block ? "enabled" : "hidden";
},
callback: function (scope) {
exportBlockSnippet(scope.block);
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK,
checkbox: false,
});
}
// Extend Blockly with custom context menu for importing snippets in the workspace
function addImportContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "importSnippet",
weight: 100,
displayText: function () {
return getSnippetOption("import");
},
preconditionFn: function (scope) {
return "enabled";
},
callback: function (scope) {
importSnippet();
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.WORKSPACE,
checkbox: false,
});
}
function addExportPNGContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "exportPNG",
weight: 100,
displayText: function () {
return getSnippetOption("export_PNG");
},
preconditionFn: function (scope) {
return "enabled";
},
callback: function (scope) {
if (scope.block) {
exportBlockAsPNG(scope.block);
} else if (scope.workspace) {
//exportWorkspaceAsPNG(scope.workspace);
}
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK,
checkbox: false,
});
}
// Extend Blockly with custom context menu for exporting SVG of the workspace
function addExportSVGContextMenuOption() {
Blockly.ContextMenuRegistry.registry.register({
id: "exportSVG",
weight: 101,
displayText: function () {
return getSnippetOption("export_SVG");
},
preconditionFn: function (scope) {
return "enabled";
},
callback: function (scope) {
if (scope.block) {
// Export selected block or stack as SVG
exportBlockAsSVG(scope.block);
} else if (scope.workspace) {
// Export the entire workspace as SVG
exportWorkspaceAsSVG(scope.workspace);
}
},
scopeType: Blockly.ContextMenuRegistry.ScopeType.BLOCK,
checkbox: false,
});
}
async function exportWorkspaceAsSVG(workspace) {
// Get the SVG element representing the entire workspace
const svg = workspace.getParentSvg().cloneNode(true);
// Adjust the dimensions to fit the content
const bbox = svg.getBBox();
svg.setAttribute("width", bbox.width);
svg.setAttribute("height", bbox.height);
svg.setAttribute(
"viewBox",
`${bbox.x} ${bbox.y} ${bbox.width} ${bbox.height}`,
);
// Convert the SVG to a data URL
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svg);
const blob = new Blob([svgString], { type: "image/svg+xml;charset=utf-8" });
// Create a download link
const link = document.createElement("a");
link.href = URL.createObjectURL(blob);
link.download = "workspace.svg";
link.click();
document.body.appendChild(link);
document.body.removeChild(link);
}
async function convertFontToBase64(fontUrl) {
const response = await fetch(fontUrl);
const fontBlob = await response.blob();
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader. => {
const base64Data = reader.result.split(",")[
8000
1]; // Remove the data URL prefix
resolve(base64Data);
};
reader.>
reader.readAsDataURL(fontBlob); // Read as data URL and convert to base64
});
}
async function generateSVG(block) {
const svgBlock = block.getSvgRoot().cloneNode(true);
// A) Only neutralise overlays that are safe to blank
svgBlock.querySelectorAll(
'.blocklyPath.blocklyPathSelected, .blocklyHighlightedConnectionPath'
).forEach(el => {
el.setAttribute('fill', 'none'); // prevent covering text
if (!el.getAttribute('stroke')) el.setAttribute('stroke', '#999'); // optional thin outline
el.setAttribute('stroke-width', '1');
});
// B) Do NOT change fills on .blocklyActiveFocus (base path can have it).
// If you want to remove the class (purely cosmetic), do this:
svgBlock.querySelectorAll('.blocklyActiveFocus').forEach(el => {
el.classList.remove('blocklyActiveFocus');
});
// C) Safety net: in each block group, keep only the FIRST path filled
svgBlock.querySelectorAll('g.blocklyBlock, g.start').forEach(g => {
const paths = g.querySelectorAll(':scope > path.blocklyPath');
paths.forEach((p, i) => {
if (i > 0) { // later paths are overlays
p.setAttribute('fill', 'none');
if (!p.getAttribute('stroke')) p.setAttribute('stroke', '#999');
p.setAttribute('stroke-width', '1');
}
});
});
const serializer = new XMLSerializer();
svgBlock.removeAttribute("transform");
const bbox = block.getSvgRoot().getBBox();
const images = svgBlock.querySelectorAll("image");
await Promise.all(
Array.from(images).map(async (img) => {
const href =
img.getAttribute("xlink:href") || img.getAttribute("href");
if (href && !href.startsWith("data:")) {
try {
const response = await fetch(href);
const blob = await response.blob();
const reader = new FileReader();
const dataUrl = await new Promise((resolve) => {
reader. => resolve(reader.result);
reader.readAsDataURL(blob);
});
img.setAttribute("xlink:href", dataUrl);
img.setAttribute("href", dataUrl);
} catch (error) {
console.error(`Failed to embed image: ${href}`, error);
}
}
}),
);
const uiElements = svgBlock.querySelectorAll("rect.blocklyFieldRect");
uiElements.forEach((element) => {
const parentBlock = element.closest(".blocklyDraggable");
if (element.classList.contains("blocklyDropdownRect")) {
const blockFill = parentBlock
?.querySelector(".blocklyPath")
?.getAttribute("fill");
if (blockFill) {
element.setAttribute("fill", blockFill);
}
element.setAttribute("stroke", "#999999");
element.setAttribute("stroke-width", "1px");
} else if (element.classList.contains("blocklyCheckbox")) {
element.setAttribute("style", "fill: #ffffff !important;");
element.setAttribute("stroke", "#999999");
element.setAttribute("stroke-width", "1px");
} else {
element.setAttribute("fill", "none");
element.setAttribute("stroke", "#999999");
element.setAttribute("stroke-width", "1px");
}
});
const uiTexts = svgBlock.querySelectorAll(
"text.blocklyCheckbox, text.blocklyText",
);
uiTexts.forEach((textElement) => {
textElement.setAttribute("style", "fill: #000000 !important;");
textElement.setAttribute("stroke", "none");
textElement.setAttribute("font-weight", "500");
});
const fontBase64 = await convertFontToBase64(w500);
const style = document.createElementNS(
"http://www.w3.org/2000/svg",
"style",
);
style.textContent = `
@font-face {
font-family: "Atkinson Hyperlegible Next";
src: url('data:font/woff2;base64,${fontBase64}') format('woff2');
}
.blocklyText {
font-family: "Atkinson Hyperlegible Next", sans-serif;
font-weight: 500;
}
.blocklyEditableText rect.blocklyFieldRect:not(.blocklyDropdownRect) {
fill: #ffffff !important;
}
`;
svgBlock.insertBefore(style, svgBlock.firstChild);
const wrapperSVG = document.createElementNS(
"http://www.w3.org/2000/svg",
"svg",
);
wrapperSVG.setAttribute("xmlns", "http://www.w3.org/2000/svg");
wrapperSVG.setAttribute("width", bbox.width);
wrapperSVG.setAttribute("height", bbox.height);
wrapperSVG.setAttribute("viewBox", `0 0 ${bbox.width} ${bbox.height}`);
const translationGroup = document.createElementNS(
"http://www.w3.org/2000/svg",
"g",
);
translationGroup.setAttribute(
"transform",
`translate(${-bbox.x}, ${-bbox.y})`,
);
translationGroup.appendChild(svgBlock);
wrapperSVG.appendChild(translationGroup);
// Get the JSON representation of the block
const blockJson = JSON.stringify(Blockly.serialization.blocks.save(block));
const encodedJson = encodeURIComponent(blockJson); // Ensure it is URL-encoded
// Embed the JSON in a <metadata> tag inside the SVG
const metadata = document.createElementNS(
"http://www.w3.org/2000/svg",
"metadata",
);
metadata.textContent = `{"blockJson": "${encodedJson}"}`;
wrapperSVG.appendChild(metadata);
const svgString = serializer.serializeToString(wrapperSVG);
const svgDeclaration = '<?xml version="1.0" encoding="UTF-8"?>';
const finalSVG = `${svgDeclaration}${svgString}`;
return finalSVG;
}
async function exportBlockAsSVG(block) {
const finalSVG = await generateSVG(block);
// Create and download the SVG blob
const blob = new Blob([finalSVG], { type: "image/svg+xml" });
const link = document.createElement("a");
link.download = `${block.type}.svg`;
link.href = URL.createObjectURL(blob);
document.body.appendChild(link);
document.body.removeChild(link);
}
import { addMetadata } from "meta-png";
async function exportBlockAsPNG(block) {
const finalSVG = await generateSVG(block);
const blockJson = JSON.stringify(Blockly.serialization.blocks.save(block));
const encodedJson = encodeURIComponent(blockJson);
const img = new Image();
const svgBlob = new Blob([finalSVG], { type: "image/svg+xml" });
const svgUrl = URL.createObjectURL(svgBlob);
const scale = 2; // Adjust for higher resolution
img. => {
const canvas = document.createElement("canvas");
const scaledWidth = img.width * scale;
const scaledHeight = img.height * scale;
canvas.width = scaledWidth;
canvas.height = scaledHeight;
const ctx = canvas.getContext("2d");
// Improve image quality by setting a higher resolution
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
// Draw at a higher resolution
ctx.drawImage(img, 0, 0, scaledWidth, scaledHeight);
canvas.toBlob(async (pngBlob) => {
if (!pngBlob) {
console.error("Failed to create PNG blob");
return;
}
const arrayBuffer = await pngBlob.arrayBuffer();
const updatedPngBuffer = addMetadata(
new Uint8Array(arrayBuffer),
"blockJson",
encodedJson,
);
const updatedBlob = new Blob([updatedPngBuffer], {
type: "image/png",
});
const updatedUrl = URL.createObjectURL(updatedBlob);
const link = document.createElement("a");
link.download = `${block.type}.png`;
link.href = updatedUrl;
link.click();
URL.revokeObjectURL(svgUrl);
URL.revokeObjectURL(updatedUrl);
}, "image/png");
};
img. => {
console.error("Failed to load SVG image:", error);
};
img.src = svgUrl;
}