mirror of
https://github.com/ryojerryyu/obsidian-jessiecode.git
synced 2026-07-22 06:43:22 +00:00
97 lines
2.7 KiB
TypeScript
97 lines
2.7 KiB
TypeScript
import { JSXGraph } from 'jsxgraph';
|
|
import log from './utils/log';
|
|
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;
|
|
constructor(
|
|
private settingHeight: number,
|
|
private settingWidth: number,
|
|
) {}
|
|
|
|
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;
|
|
// there is nothing inside of the codeblock
|
|
if (source === null || source === '') {
|
|
log.debug('no source');
|
|
return;
|
|
}
|
|
|
|
// change board values
|
|
if (this.graphInfo.boundingBox === undefined && this.graphInfo.boundingbox === undefined) {
|
|
log.debug('setting bounding box');
|
|
const aspectRatio = this.width / this.height;
|
|
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}`);
|
|
|
|
return;
|
|
}
|
|
|
|
createBoard(graphDiv: HTMLElement): Graph {
|
|
log.debug(`creating board ${graphDiv.id}`);
|
|
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');
|
|
}
|
|
if (this.height) {
|
|
log.debug(`setting height to ${this.height}`);
|
|
graphDiv.style.setProperty('--graph-height', this.height + 'px');
|
|
}
|
|
|
|
if (this.codeContent) {
|
|
board.jc.parse(this.codeContent);
|
|
}
|
|
|
|
return graph;
|
|
}
|
|
}
|