skip to content
MeliPlug by doi, ywbird

그래프 생성 플러그인 만들기

/ 4 min read

JSXGraph

아래같은 수학 그래프를 삽입할 수 있는 플러그인

view source

Desmos같은 방안도 있지만, desmos는 꽤 무거운 편

구현 방법, 아이디어

포스트 파일

```graph
/* code */
```

Embed

AstroJS 에서 html 보내는 api 만들어서 url parameter로 js 내용 보내면 decode해서 embed html 보내게 할 생각.

1. remark plugin

아래 형식을 따라 코드를 작성하도록 했다.

```graph widthxheight
javascript code
```

어짜피 AstroJS는 static build를 거치기 때문에 코드를 간결하게 하거나 최적화하지는 않았다.

remark-jsxgraph.ts
import {visit} from 'unist-util-visit';
export const remarkJSXGraph = () => (tree) => {
visit(tree, function (node,index,parent) {
if (!(node.type === "code") || !(node.lang === "graph")) return;
const data = node.data || (node.data = {})
const attributes = node.attributes || {}
const code = btoa(node.value)
const [w, h] = !!node.meta?.length && node.meta.split("x").length == 2
? node.meta.split("x") : ["400","400"]
data.hName = "iframe"
data.hProperties = {
src: `/graph/${code}.html?w=${w}&h=${h}`,
width: w,
height: h,
frameBorder: 0,
allowTransparency: true
}
node.type = "paragraph"
});
}

graph api

아래 형식으로 request를 보내면 code를 decode해서 넘겨준다.
사실 작동방식으로 보면 그냥 javascript 실행기(jsxgraph cdn을 import한) 이나 다름없다.
뭔가 잘못하면 악용할 수도 있어보이지만, 그것도 내 블로그는 거의 개인 블로그이기 때문에(…) 상관 없을 듯 하다.

/<code base64 encode>.html?w=너비&h=높이

AstroJS on-demend api를 사용했기 때문에, 기존의 github page에서 호스팅하지 못하고, vercel에서 호스팅해야한다.

[code].html.ts
import type { APIContext, InferGetStaticPropsType } from "astro";
type Props = InferGetStaticPropsType<typeof getStaticPaths>;
export const prerender = false;
export async function GET({params, request}: APIContext) {
const urlParams = new URL(request.url).searchParams;
return new Response(`
<link rel="stylesheet" type="text/css" href="https://jsxgraph.org/distrib/jsxgraph.css" />
<script type="text/javascript" src="https://jsxgraph.org/distrib/jsxgraphcore.js"></script>
<style type="text/css">
body, html
{
background: none transparent;
margin: 0;
}
</style>
<body style="background-color: transparent;">
<div id="box" class="jxgbox" style="width:${parseInt(urlParams.get('w'))-2}px; height:${parseInt(urlParams.get('h'))-2}px;"></div>
<script type="text/javascript">
${atob(params.code)}
</script>
</body>
`, { headers: {
"Content-Type": "text/html;charset=utf-8"
}})
}

Source View 버튼 만들기

실제 사용 예시

https://jsxgraph.org/wiki/index.php?title=Documentation

엄청나게 디테일하고 많은 기능을 제공하는 것 같다.

사이트에 있던 예시.
https://jsxgraph.org/wiki/index.php?title=Euler_line_source_code

view source

ㅁㅁㄹ

마무리 라는 뜻