ryojerryyu_obsidian-jessiecode/src/graphBuilderJessieCode.ts

98 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-10-08 17:53:36 +00:00
import { JSXGraph } from 'jsxgraph';
import log from './utils/log';
2025-10-08 17:53:36 +00:00
import { Graph, GraphInfo } from './types';
import { GraphBuilder } from './types';
import matter from 'gray-matter';
export class GraphBuilderJessieCode implements GraphBuilder {
codeContent: string;
graphInfo: GraphInfo;
width: number;
height: number;
2025-10-08 17:53:36 +00:00
constructor(
private settingHeight: number,
private settingWidth: number,
) {}
2025-10-08 17:53:36 +00:00
parseCodeBlock(source: string): void {
const frontMatter = matter(source);
this.codeContent = frontMatter.content;
this.width = this.settingWidth;
this.height = this.settingHeight;
// matter returns a cached object, so we need to copy it for modifications
const graphInfo = Object.assign({}, frontMatter.data) as GraphInfo;
if (graphInfo.width) {
log.debug(`width from frontmatter: ${graphInfo.width}`);
this.width = graphInfo.width;
delete graphInfo.width;
}
if (graphInfo.height) {
log.debug(`height from frontmatter: ${graphInfo.height}`);
this.height = graphInfo.height;
delete graphInfo.height;
}
this.graphInfo = graphInfo;
2025-10-08 17:53:36 +00:00
// there is nothing inside of the codeblock
if (source === null || source === '') {
log.debug('no source');
2025-10-08 17:53:36 +00:00
return;
}
// change board values
if (this.graphInfo.boundingBox === undefined && this.graphInfo.boundingbox === undefined) {
log.debug('setting bounding box');
const aspectRatio = this.width / this.height;
2025-10-08 17:53:36 +00:00
let boundX = 10;
let boundY = 10;
if (aspectRatio > 1) {
boundX = 10 * aspectRatio;
} else {
boundY = 10 / aspectRatio;
}
this.graphInfo.boundingBox = [-boundX, boundY, boundX, -boundY];
}
log.debug(`final graphInfo: ${this.graphInfo}`);
2025-10-08 17:53:36 +00:00
return;
}
createBoard(graphDiv: HTMLElement): Graph {
log.debug(`creating board ${graphDiv.id}`);
2025-10-08 17:53:36 +00:00
const board = JSXGraph.initBoard(graphDiv, {
//@ts-ignore
theme: 'obsidian',
axis: true,
showNavigation: true,
drag: { enabled: true },
defaultAxes: JXG.Options.board.defaultAxes,
maxBoundingBox: JXG.Options.board.maxBoundingBox,
...this.graphInfo,
});
const graph: Graph = {
board: board,
view3d: undefined,
};
// set graph width and height if specified
if (this.width) {
log.debug(`setting width to ${this.width}`);
graphDiv.style.setProperty('--graph-width', this.width + 'px');
2025-10-08 17:53:36 +00:00
}
if (this.height) {
log.debug(`setting height to ${this.height}`);
graphDiv.style.setProperty('--graph-height', this.height + 'px');
2025-10-08 17:53:36 +00:00
}
if (this.codeContent) {
board.jc.parse(this.codeContent);
}
return graph;
}
}