Files
mnote/wolai-frontend/src/components/editor/blocks/MindmapCount.tsx
T

73 lines
2.1 KiB
TypeScript

/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useState } from "react";
type CountProps = {
mindmap: any;
};
export const MindmapCount = ({ mindmap }: CountProps) => {
const [counts, setCounts] = useState({ words: 0, nodes: 0 });
useEffect(() => {
if (!mindmap) return;
const calculateCounts = (data: any) => {
let nodes = 0;
let textStr = "";
const walk = (nodeData: any) => {
if (!nodeData) return;
nodes++;
// simple-mind-map node data structure: { data: { text: ... }, children: [...] }
const text = String(nodeData.data?.text || "");
textStr += text;
if (nodeData.children && Array.isArray(nodeData.children)) {
nodeData.children.forEach(walk);
}
};
walk(data);
// Remove HTML tags for word count
const tempDiv = document.createElement("div");
tempDiv.innerHTML = textStr;
const words = tempDiv.textContent?.length || 0;
setCounts({ words, nodes });
};
const onDataChange = (data: any) => {
calculateCounts(data);
};
mindmap.on("data_change", onDataChange);
// Initial calculation if data is available
// mindmap.getData() might return full data object
try {
const initialData = mindmap.getData();
if (initialData) calculateCounts(initialData);
} catch (e) {
console.warn("Failed to get initial mindmap data for count", e);
}
return () => {
mindmap.off("data_change", onDataChange);
};
}, [mindmap]);
return (
<div className="absolute bottom-4 left-4 flex items-center gap-4 rounded-md border border-gray-200 bg-white/90 px-3 py-1 text-xs text-gray-600 shadow-sm backdrop-blur-sm select-none z-10">
<div className="flex items-center gap-1">
<span>字数</span>
<span className="font-medium text-gray-900">{counts.words}</span>
</div>
<div className="flex items-center gap-1">
<span>节点</span>
<span className="font-medium text-gray-900">{counts.nodes}</span>
</div>
</div>
);
};