Skip to content

Commit

Permalink
penrose: fix issue with globals
Browse files Browse the repository at this point in the history
  • Loading branch information
stereobooster committed Jan 23, 2025
1 parent b252738 commit 7de243a
Show file tree
Hide file tree
Showing 5 changed files with 117 additions and 47 deletions.
27 changes: 9 additions & 18 deletions packages/docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { rehypeGraphviz } from "@beoe/rehype-graphviz";
import { rehypeGnuplot } from "@beoe/rehype-gnuplot";
import { rehypeVizdom } from "@beoe/rehype-vizdom";
import { rehypeD2 } from "@beoe/rehype-d2";
import { rehypePenrose } from "@beoe/rehype-penrose";

const cache = await getCache();
// requerd for correct displaying mobile warning
Expand All @@ -21,23 +22,6 @@ const conf = {
webPath: "/beoe",
};

const rehypePlugins = [
[rehypeGraphviz, { cache, class: className }],
[rehypeVizdom, { cache, class: className }],
[rehypeMermaid, conf],
[rehypeGnuplot, conf],
[rehypeD2, { ...conf, shared: "shared/**/*.d2" }],
];
// this breaks build
// this breaks http://localhost:4321/examples/d2-test/
// if (import.meta.env.DEV) {
// const { rehypePenrose } = await import("@beoe/rehype-penrose");
// rehypePlugins.push([
// rehypePenrose,
// { ...conf, shared: "shared", svgo: false },
// ]);
// }

const sidebar = [
{
label: "Start here",
Expand Down Expand Up @@ -79,7 +63,14 @@ export default defineConfig({
}),
],
markdown: {
rehypePlugins,
rehypePlugins: [
[rehypeGraphviz, { cache, class: className }],
[rehypeVizdom, { cache, class: className }],
[rehypeMermaid, conf],
[rehypeGnuplot, conf],
[rehypeD2, { ...conf, shared: "shared/**/*.d2" }],
[rehypePenrose, { ...conf, shared: "shared", svgo: false }],
],
},
vite: {
plugins: [qrcode()],
Expand Down
58 changes: 58 additions & 0 deletions packages/rehype-penrose/bin/penrose.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
#!/usr/bin/env node

import "global-jsdom/register";
import { compile, optimize, toSVG, showError } from "@penrose/core";
import { readFileSync } from "node:fs";

const pathResolver = (_path) => Promise.resolve(undefined);

// TODO https://github.com/penrose/penrose/blob/main/packages/roger/index.ts
// const resolvePath = (prefix, stylePaths) => {
// const stylePrefixes = stylePaths.map((sty) => join(prefix, sty, ".."));
// if (new Set(stylePrefixes).size > 1) {
// console.warn(
// chalk.yellow(
// "Warning: the styles in this trio are not co-located. The first style will be used for image resolution."
// )
// );
// }
// const stylePrefix = stylePrefixes[0];
// return async (filePath) => {
// // Handle absolute URLs
// if (/^(http|https):\/\/[^ "]+$/.test(filePath)) {
// const fileURL = new URL(filePath).href;
// try {
// const fileReq = await fetch(fileURL);
// return fileReq.text();
// } catch (e) {
// console.error(`Failed to resolve path: ${e}`);
// return undefined;
// }
// }

// // Relative paths
// const joined = resolve(stylePrefix, filePath);
// return fs.readFileSync(joined, "utf8");
// };
// };

const trio = JSON.parse(readFileSync(0, "utf-8"));

const compiled = await compile(trio);
if (compiled.isErr()) {
console.error(showError(compiled.error));
process.exit(1);
}
const optimized = optimize(compiled.value);
if (optimized.isErr()) {
console.error(showError(optimized.error));
process.exit(1);
}
const svg = (await toSVG(optimized.value, pathResolver, "rehype")).outerHTML;
// https://github.com/stereobooster/venn-nodejs/blob/main/bin/venn-nodejs.js
// do we need different serializer
// import serialize from "w3c-xmlserializer";
// const s = new XMLSerializer();
// s.serializeToString(svg);
process.stdout.write(svg);
process.exit(0);
3 changes: 2 additions & 1 deletion packages/rehype-penrose/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
"main": "./dist/index.js",
"module": "./dist/index.js",
"files": [
"dist"
"dist",
"bin"
],
"types": "./dist/index.d.js",
"scripts": {
Expand Down
33 changes: 5 additions & 28 deletions packages/rehype-penrose/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import type { Root } from "hast";
import { rehypeCodeHookImg } from "@beoe/rehype-code-hook-img";
import fs from "node:fs/promises";
import { join } from "node:path";
import { compile, optimize, toSVG } from "@penrose/core";
// TODO
import "global-jsdom/register";
import { penrose } from "./penrose.js";

export type RehypePenroseConfig = {
shared: string;
Expand All @@ -19,17 +17,12 @@ export type RehypePenroseConfig = {
namespace?: string;
};

// TODO https://github.com/penrose/penrose/blob/7b6c7ca6453f55242dff6baac37d8e10a62c5049/packages/roger/index.ts#L69
const pathResolver = (_path: string) => Promise.resolve(undefined);

export const rehypePenrose = rehypeCodeHookImg<RehypePenroseConfig>({
language: "penrose",
render: async (code: string, opts) => {
const trio = {
substance: `
${code}`,
style: `
canvas {
substance: code,
style: `canvas {
width = ${opts.width || 400}
height = ${opts.height || 400}
}
Expand All @@ -39,31 +32,15 @@ export const rehypePenrose = rehypeCodeHookImg<RehypePenroseConfig>({
encoding: "utf-8",
})
: ""
}
`,
}`,
domain: opts.domain
? await fs.readFile(join(opts.shared, opts.domain), {
encoding: "utf-8",
})
: "",
variation: opts.variation || "",
};
const compiled = await compile(trio);
// console.log(trio);
if (compiled.isErr()) {
// console.log(showError(compiled.error));
throw compiled.error;
}
const optimized = optimize(compiled.value);
if (optimized.isErr()) {
// console.log(showError(optimized.error));
throw optimized.error;
}
const svg = (
await toSVG(optimized.value, pathResolver, opts.namespace || "")
).outerHTML;
// const s = new XMLSerializer();
// s.serializeToString(svg);
const svg = await penrose(trio);
return { svg };
},
});
Expand Down
43 changes: 43 additions & 0 deletions packages/rehype-penrose/src/penrose.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// import { type compile } from "@penrose/core";
import { spawn } from "node:child_process";
import { fileURLToPath } from "url";
import { dirname } from "path";
import { resolve } from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const executablePath = resolve(__dirname, `../bin/penrose.js`);

// type CompileOptions = Parameters<typeof compile>[0];
type CompileOptions = {
substance: string;
style: string;
domain: string;
variation: string;
excludeWarnings?: string[];
};

export const penrose = (opts: CompileOptions): Promise<string> => {
return new Promise((resolve, reject) => {
let res = "";

const bin = spawn(executablePath, [], {
windowsHide: true,
});
bin.stdout.on("data", (data: Buffer) => {
res += data.toString();
});
bin.stderr.on("data", (data: Buffer) => {
reject(`stderr: ${data.toString()}`);
});
bin.on("close", (code) => {
if (code === 0) {
resolve(res);
} else {
reject(`child process exited with code ${code}`);
}
});

bin.stdin.write(JSON.stringify(opts));
bin.stdin.end();
});
};

0 comments on commit 7de243a

Please sign in to comment.