Skip to content

Commit

Permalink
IT WORKS
Browse files Browse the repository at this point in the history
  • Loading branch information
lovettbarron committed Jul 5, 2024
1 parent 9ed08ea commit 1ec826d
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 34 deletions.
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const md = await unified()
.use(mdast2hast)
.use(remarkGfm)
.use(remarkRehype)
.use(rehypeJsonCanvas)
.use(rehypeJsonCanvas, { assetPath: "public" })
.use(compiler, production)
.process(markdown);
```
Expand Down
4 changes: 2 additions & 2 deletions src/embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { toHast } from "mdast-util-to-hast";

import { GenericNode } from "@trbn/jsoncanvas";
// import { applyDefaults, Options } from "./options";
import { getCanvasFromEmbed } from "./plugin";

const imagesLoaded = [] as Array<any>;

Expand Down Expand Up @@ -39,8 +40,7 @@ export async function drawEmbedded(svg: Element, node: GenericNode | any) {
export async function drawMarkdownEmbed(svg: Element, node: GenericNode | any) {
if (node.type === "file" && svg) {
if (node.file.match(/\.(md|mdx)$/i)) {
const resp = await fetch(node.file);
const mdFile = await resp.text();
const mdFile = await getCanvasFromEmbed(node.file);

const mdast = fromMarkdown(mdFile);
const hast = toHast(mdast);
Expand Down
10 changes: 8 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { rehypeJsonCanvas } from "./plugin";

// export { Options } from "./options";
export { rehypeJsonCanvas };
export type { Options } from "./options";

export { rehypeJsonCanvas };
export default rehypeJsonCanvas;

// CommonJS default export hack
/* eslint-env commonjs */
// if (typeof module === "object" && typeof module.exports === "object") {
// module.exports = Object.assign(module.exports.default, module.exports);
// }
21 changes: 12 additions & 9 deletions src/jsoncanvas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export function validate(jsonCanvasData: JSONCanvas) {
export function render(
jsc: JSONCanvas,
config?: Partial<Options>
): String | any | null {
): Element | null {
const options = applyDefaults(config);

const { canvasWidth, canvasHeight, offsetX, offsetY } =
Expand All @@ -62,10 +62,10 @@ export function render(
return checkImagesLoaded(() => renderToBuffer(svg));
}

function renderToBuffer(svg: Element, config?: Partial<Options>) {
function renderToBuffer(svg: Element, config?: Partial<Options>): Element {
const options = applyDefaults(config);
console.log("Rendering", svg, options);
return null;
return svg;
}

function initRender(
Expand All @@ -89,9 +89,12 @@ function initRender(

const props = {
...BASE_SVG_PROPS,
width: width as number,
height: height as number,
width: "100%",
height: "100%",
renWidth: width as number,
renHeight: height as number,
viewBox: `0 0 ${width} ${height}`,
preserveAspectRatio: "none",
};

const svg = s("svg", props);
Expand Down Expand Up @@ -132,8 +135,8 @@ async function drawNode(
const group = s("g");

const rect = s("rect", {
x: node.x + <number>svg.properties!.width / 2,
y: node.y + <number>svg.properties!.height / 2,
x: node.x + <number>svg.properties!.renWidth / 2,
y: node.y + <number>svg.properties!.renHeight / 2,
width: node.width,
height: node.height,
rx: 5,
Expand Down Expand Up @@ -178,8 +181,8 @@ function drawEdge(
const options = applyDefaults(config);
if (svg === null || svg == undefined) return;

const cWidth = <number>svg.properties.width || (1 as number);
const cHeight = <number>svg.properties.height || (1 as number);
const cWidth = <number>svg.properties.renWidth || (1 as number);
const cHeight = <number>svg.properties.renHeight || (1 as number);

if (fromNode && toNode) {
let startX =
Expand Down
8 changes: 8 additions & 0 deletions src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ export interface Options {
*/
openEmbededInNewTab: boolean;

/**
* Define an asset path where the .canvas files exists. This will add the asset path before the filename. Otherwise uses cwd.process() path + filename
*
* Defaults to null
*/
assetPath: string | null;

/**
* Render mode. Determines the canvas output mode
*
Expand Down Expand Up @@ -47,6 +54,7 @@ export function applyDefaults(config: Partial<Options> = {}): Options {
config.openEmbededInNewTab === undefined
? true
: config.openEmbededInNewTab,
assetPath: config.assetPath === undefined ? "public" : config.assetPath,
renderMode: config.renderMode === undefined ? "canvas" : config.renderMode,
canvasBuffer: config.canvasBuffer === undefined ? 30 : config.canvasBuffer,
nodeStrokeWidth:
Expand Down
54 changes: 34 additions & 20 deletions src/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import path from "path";
import fs from "fs";
import type { Plugin } from "unified";
import type { Element, ElementContent, Root } from "hast";
import { fromHtmlIsomorphic } from "hast-util-from-html-isomorphic";
import type { Element, Root } from "hast";
// import { fromHtmlIsomorphic } from "hast-util-from-html-isomorphic";
import { visit } from "unist-util-visit";
import fs from "fs";
import { validate, render } from "./jsoncanvas";
import JSONCanvas from "@trbn/jsoncanvas";
import { h } from "hastscript";

import { applyDefaults, Options } from "./options";
/*
Let's think this through.
Expand Down Expand Up @@ -46,51 +49,62 @@ export const rehypeJsonCanvas: Plugin<[], Root> = () => {

for (const node of nodesToReplace) {
const canvasPath = node.properties.src as string;
console.log("Detected", canvasPath);
let canvasMarkdown = await getCanvasFromEmbed(canvasPath);

console.log("Got markdown", canvasMarkdown);
const jsonCanvasFromString = JSONCanvas.fromString(canvasMarkdown);

let canvas;

if (validate(jsonCanvasFromString)) {
canvas = render(jsonCanvasFromString, {});
} else {
canvas = "<div>Not a properly formatted JsonCanvas</div>";
canvas = h("div", "<div>Not a properly formatted JsonCanvas</div>");
}

console.log(canvas);

const canvasHast = fromHtmlIsomorphic(
`<img alt='' src='${canvas}' style='width:100%' />`,
{
fragment: true,
}
);
// const canvasHast = fromHtmlIsomorphic(
// `<img alt='' src='${canvas}' style='width:100%' />`,
// {
// fragment: true,
// }
// );
node.properties = {
...node.properties,
};
node.tagName = "div";
node.children = canvasHast.children as ElementContent[];
node.children = [];
node.children.push(canvas!); //canvasHast.children as ElementContent[];
}
};
};

async function getCanvasFromEmbed(path: string): Promise<string> {
export async function getCanvasFromEmbed(
markdownPath: string,
config?: Partial<Options>
): Promise<string> {
const options = applyDefaults(config);
let canvasMarkdown = "Loading";
const webcheck = path.trim().toLowerCase();
const webcheck = markdownPath.trim().toLowerCase();

if (webcheck.startsWith("https://") || typeof window !== "undefined") {
await fetch(path)
await fetch(markdownPath)
.then((res) => res.text())
.then((text) => (canvasMarkdown = text));
} else {
// To accomodate ssr
canvasMarkdown = fs.readFileSync(path, {
encoding: "utf8",
flag: "r",
});
const ssrPath = options.assetPath
? path.join(process.cwd(), options.assetPath, markdownPath)
: path.join(process.cwd(), markdownPath);
console.log("File Path", ssrPath);
try {
canvasMarkdown = fs.readFileSync(ssrPath, {
encoding: "utf8",
flag: "r",
});
} catch (err) {
console.log("No Canvas File Found. Try using the assetPath option!", err);
}
}
if (canvasMarkdown === null) return "";

Expand Down

0 comments on commit 1ec826d

Please sign in to comment.