Skip to content

Instantly share code, notes, and snippets.

@pengx17
Created April 9, 2024 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pengx17/7b0ce7e56da2dc0fafbd20f12a6b4141 to your computer and use it in GitHub Desktop.
Save pengx17/7b0ce7e56da2dc0fafbd20f12a6b4141 to your computer and use it in GitHub Desktop.
Draw affine workspace graph
function preparePageNodes() {
// id -> links
const pages = Array.from(currentWorkspace.docCollection.meta.docs).filter(p => p.title);
const edges = pages.flatMap((page) =>
getPageLinks(page.id).map((target) => [page.id, target])
);
return {
nodes: pages.map((page) => ({ id: page.id, label: page.title })),
edges: edges.map(([source, target]) => ({ source, target })),
};
}
function getPageLinks(pageId) {
return Object.values(
currentWorkspace.docCollection.indexer.backlink.linkIndexMap[pageId] ?? {}
).flatMap((linkNodes) => linkNodes.map((linkNode) => linkNode.pageId));
}
function run(G6, container, window) {
const width = container.scrollWidth;
const height = container.scrollHeight || 500;
const graph = new G6.Graph({
width,
height,
modes: {
default: ["zoom-canvas", "drag-canvas", "drag-node"],
},
layout: {
type: "force",
preventOverlap: true,
kr: 10,
center: [250, 250],
},
container,
});
const data = preparePageNodes();
graph.data({
nodes: data.nodes,
edges: data.edges.map(function (edge, i) {
edge.id = "edge" + i;
return Object.assign({}, edge);
}),
});
graph.render();
graph.on("node:dragstart", function (e) {
const forceLayout = graph.get("layoutController").layoutMethods[0];
forceLayout.stop?.();
});
graph.on("node:drag", function (e) {
refreshDragedNodePosition(e);
graph.layout();
});
window.onresize = () => {
if (!graph || graph.get("destroyed")) return;
if (!container || !container.scrollWidth || !container.scrollHeight) return;
graph.changeSize(container.scrollWidth, container.scrollHeight);
refreshDragedNodePosition(e);
graph.layout();
};
function refreshDragedNodePosition(e) {
const model = e.item.get("model");
model.fx = e.x;
model.fy = e.y;
model.x = e.x;
model.y = e.y;
}
}
async function main() {
const cw = window.open(
"about:blank",
"" + Math.random(),
"width=1200,height=600"
);
cw.onload = async () => {
await new Promise((res) => {
setTimeout(res, 200);
});
const container = cw.document.createElement("div");
container.id = "container";
container.style.width = "100vw";
container.style.height = "100vw";
container.style.position = "fixed";
container.style.top = 0;
container.style.left = 0;
container.style.border = "1px solid black";
cw.document.body.append(container);
const G6 = await import("https://esm.sh/@antv/g6@4.8.24");
run(G6, container, cw);
};
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment