Repository navigation
Expand file tree
/
Copy pathnode-ssr.js
More file actions
88 lines (82 loc) · 2.24 KB
/
Copy pathnode-ssr.js
File metadata and controls
88 lines (82 loc) · 2.24 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
import init from "./index.js"
import { parse } from "./syntax/index.js"
let nodeWindow
try {
const { JSDOM } = await import("jsdom")
const dom = new JSDOM()
nodeWindow = dom.window
} catch {
try {
let createCanvas
const { DOMParser, XMLSerializer, DOMImplementation } =
await import("@xmldom/xmldom")
const nodeDocument = new DOMImplementation().createDocument(
"http://www.w3.org/2000/svg",
null,
null,
)
try {
createCanvas = (await import("@napi-rs/canvas")).createCanvas
} catch {
try {
createCanvas = (await import("canvas")).createCanvas
} catch {
// pass
}
}
if (createCanvas) {
const origCreateElement = nodeDocument.createElement.bind(nodeDocument)
nodeDocument.createElement = tagName =>
tagName === "canvas"
? createCanvas(300, 150)
: origCreateElement(tagName)
}
nodeWindow = {
document: nodeDocument,
DOMParser,
XMLSerializer,
}
} catch {
// pass
}
}
const sb = init(nodeWindow)
export const {
allLanguages,
loadLanguages,
Label,
Icon,
Input,
Block,
Comment,
Script,
Document,
newView,
render,
registerExtension,
registerIcon,
registerCategory,
registerBlock,
registerBlockTranslation,
} = sb
export { parse }
/**
* Parse Scratch block code and render it directly to an SVG XML string.
*
* @param {string} code - Scratch block source, e.g. "move (10) steps"
* @param {object} [options] - Same options accepted by scratchblocks.render()
* - style: "scratch3" | "scratch3-high-contrast" | "scratch3-outline" | "scratch2" (default: "scratch3")
* - languages: string[] (default: ["en"])
* - scale: number (default: 1)
* - fontFamily: string CSS font-family value (default: style font)
* - catHats: boolean render Scratch 3 hat blocks as cat hats (default: false)
* @returns {string} Complete SVG XML string
*/
export function renderToSVGString(code, options = {}) {
options = { style: "scratch3", ...options }
const doc = parse(code, options)
const view = sb.newView(doc, options)
const svg = view.render()
svg.setAttribute("class", `scratchblocks-style-${options.style}`)
return view.exportSVGString()
}