1"use client";
2
3import "mind-elixir/style.css";
4import {
5 createContext,
6 useContext,
7 useEffect,
8 useId,
9 useRef,
10 useState,
11 forwardRef,
12 useImperativeHandle,
13 type ReactNode,
14} from "react";
15import {
16 Minus,
17 Plus,
18 Download,
19 Loader2,
20 Maximize,
21 ScanSearch,
22} from "lucide-react";
23
24import { cn } from "@/lib/utils";
25import {
26 type MindElixirInstance,
27 type MindElixirData,
28 type NodeObj,
29 type Options,
30 type Theme as MindElixirTheme,
31} from "mind-elixir";
32import MindElixir from "mind-elixir";
33import { snapdom, SnapdomOptions } from "@zumer/snapdom";
34
35// Check document class for theme (works with next-themes, etc.)
36function getDocumentTheme(): Theme | null {
37 if (typeof document === "undefined") return null;
38 if (document.documentElement.classList.contains("dark")) return "dark";
39 if (document.documentElement.classList.contains("light")) return "light";
40 return null;
41}
42
43// Get system preference
44function getSystemTheme(): Theme {
45 if (typeof window === "undefined") return "light";
46 return window.matchMedia("(prefers-color-scheme: dark)").matches
47 ? "dark"
48 : "light";
49}
50
51function useResolvedTheme(themeProp?: "light" | "dark"): "light" | "dark" {
52 const [detectedTheme, setDetectedTheme] = useState<"light" | "dark">(
53 () => getDocumentTheme() ?? getSystemTheme(),
54 );
55
56 useEffect(() => {
57 if (themeProp) return; // Skip detection if theme is provided via prop
58
59 // Watch for document class changes (e.g., next-themes toggling dark class)
60 const observer = new MutationObserver(() => {
61 const docTheme = getDocumentTheme();
62 if (docTheme) {
63 setDetectedTheme(docTheme);
64 }
65 });
66 observer.observe(document.documentElement, {
67 attributes: true,
68 attributeFilter: ["class"],
69 });
70
71 // Also watch for system preference changes
72 const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
73 const handleSystemChange = (e: MediaQueryListEvent) => {
74 // Only use system preference if no document class is set
75 if (!getDocumentTheme()) {
76 setDetectedTheme(e.matches ? "dark" : "light");
77 }
78 };
79 mediaQuery.addEventListener("change", handleSystemChange);
80
81 return () => {
82 observer.disconnect();
83 mediaQuery.removeEventListener("change", handleSystemChange);
84 };
85 }, [themeProp]);
86
87 return themeProp ?? detectedTheme;
88}
89
90type Theme = "light" | "dark";
91
92// Context for MindMap
93interface MindMapContextValue {
94 mind: MindElixirInstance | null;
95 isLoaded: boolean;
96}
97
98const MindMapContext = createContext<MindMapContextValue | null>(null);
99
100export function useMindMap() {
101 const context = useContext(MindMapContext);
102 if (!context) {
103 throw new Error("useMindMap must be used within a MindMap component");
104 }
105 return context;
106}
107
108// MindMap Props
109type MindMapData = MindElixirData;
110
111// Ref type to expose MindElixir instance to parent components
112export interface MindMapRef {
113 instance: MindElixirInstance | null;
114}
115
116interface MindMapProps {
117 children?: ReactNode;
118 data?: MindMapData;
119 className?: string;
120 direction?: 0 | 1 | 2;
121 contextMenu?: boolean;
122 nodeMenu?: boolean;
123 keypress?: boolean;
124 locale?: "en" | "zh_CN" | "zh_TW" | "ja" | "pt";
125 overflowHidden?: boolean;
126 mainLinkStyle?: number;
127 theme?: "dark" | "light";
128 monochrome?: boolean;
129 fit?: boolean;
130 readonly?: boolean;
131 onChange?: (data: MindMapData, operation: unknown) => void;
132 onOperation?: (operation: unknown) => void;
133 onSelectNodes?: (nodeObj: NodeObj[]) => void;
134 loader?: ReactNode;
135}
136
137function DefaultLoader() {
138 return (
139 <div className="absolute inset-0 flex items-center justify-center bg-background/80 backdrop-blur-sm">
140 <Loader2 className="size-8 animate-spin text-muted-foreground" />
141 </div>
142 );
143}
144
145// Common spacing and layout configuration
146const commonSpacing = {
147 "--node-gap-x": "48px",
148 "--node-gap-y": "16px",
149 "--main-gap-x": "24px",
150 "--main-gap-y": "32px",
151 "--root-radius": "0.625rem",
152 "--main-radius": "0.5rem",
153 "--topic-padding": "8px 16px",
154 "--map-padding": "48px",
155};
156
157// Helper function to create theme
158function createTheme(
159 name: string,
160 type: "light" | "dark",
161 colors: {
162 mainColor: string;
163 mainBgcolor: string;
164 color: string;
165 bgcolor: string;
166 selected: string;
167 accentColor: string;
168 rootColor: string;
169 rootBgcolor: string;
170 rootBorderColor: string;
171 panelColor: string;
172 panelBgcolor: string;
173 panelBorderColor: string;
174 },
175 palette: string[],
176): MindElixirTheme {
177 return {
178 name,
179 type,
180 palette,
181 cssVar: {
182 ...commonSpacing,
183 "--main-color": colors.mainColor,
184 "--main-bgcolor": colors.mainBgcolor,
185 "--main-bgcolor-transparent": `${colors.mainBgcolor.replace(")", " / 95%)")}`,
186 "--color": colors.color,
187 "--bgcolor": colors.bgcolor,
188 "--selected": colors.selected,
189 "--accent-color": colors.accentColor,
190 "--root-color": colors.rootColor,
191 "--root-bgcolor": colors.rootBgcolor,
192 "--root-border-color": colors.rootBorderColor,
193 "--panel-color": colors.panelColor,
194 "--panel-bgcolor": colors.panelBgcolor,
195 "--panel-border-color": colors.panelBorderColor,
196 },
197 };
198}
199
200// Base color configurations
201const lightColors = {
202 mainColor: "oklch(0.145 0 0)", // foreground
203 mainBgcolor: "oklch(1 0 0)", // background (white)
204 color: "oklch(0.145 0 0)", // foreground
205 bgcolor: "oklch(1 0 0)", // card background
206 selected: "oklch(0.205 0 0)", // primary
207 rootColor: "oklch(0.985 0 0)", // primary-foreground
208 rootBgcolor: "oklch(0.205 0 0)", // primary
209 rootBorderColor: "oklch(0.205 0 0)", // primary
210 panelColor: "oklch(0.145 0 0)", // foreground
211 panelBgcolor: "oklch(1 0 0)", // popover
212 panelBorderColor: "oklch(0.922 0 0)", // border
213};
214
215const darkColors = {
216 mainColor: "oklch(0.985 0 0)", // foreground
217 mainBgcolor: "oklch(0.145 0 0)", // background (dark)
218 color: "oklch(0.985 0 0)", // foreground
219 bgcolor: "oklch(0.205 0 0)", // card background
220 selected: "oklch(0.922 0 0)", // primary
221 rootColor: "oklch(0.205 0 0)", // primary-foreground
222 rootBgcolor: "oklch(0.922 0 0)", // primary
223 rootBorderColor: "oklch(0.922 0 0)", // primary
224 panelColor: "oklch(0.985 0 0)", // foreground
225 panelBgcolor: "oklch(0.205 0 0)", // popover
226 panelBorderColor: "oklch(1 0 0 / 10%)", // border
227};
228
229// Shadcn-styled light theme
230const lightTheme: MindElixirTheme = createTheme(
231 "shadcn-light",
232 "light",
233 {
234 ...lightColors,
235 accentColor: "oklch(0.646 0.222 41.116)", // chart-1 (vibrant)
236 },
237 [
238 "oklch(0.646 0.222 41.116)", // chart-1: vibrant orange
239 "oklch(0.6 0.118 184.704)", // chart-2: teal
240 "oklch(0.398 0.07 227.392)", // chart-3: blue
241 "oklch(0.828 0.189 84.429)", // chart-4: yellow-green
242 "oklch(0.769 0.188 70.08)", // chart-5: warm yellow
243 "oklch(0.488 0.243 264.376)", // purple
244 "oklch(0.696 0.17 162.48)", // mint
245 ],
246);
247
248// Shadcn-styled dark theme
249const darkTheme: MindElixirTheme = createTheme(
250 "shadcn-dark",
251 "dark",
252 {
253 ...darkColors,
254 accentColor: "oklch(0.488 0.243 264.376)", // chart-1 (purple)
255 },
256 [
257 "oklch(0.488 0.243 264.376)", // chart-1: purple
258 "oklch(0.696 0.17 162.48)", // chart-2: mint
259 "oklch(0.769 0.188 70.08)", // chart-3: warm yellow
260 "oklch(0.627 0.265 303.9)", // chart-4: pink
261 "oklch(0.645 0.246 16.439)", // chart-5: coral
262 "oklch(0.646 0.222 41.116)", // orange
263 "oklch(0.6 0.118 184.704)", // teal
264 ],
265);
266
267// Monochrome variants - reuse base colors, only change accentColor and palette
268const lightThemeMonochrome: MindElixirTheme = createTheme(
269 "shadcn-light-mono",
270 "light",
271 {
272 ...lightColors,
273 accentColor: "oklch(0.205 0 0)", // primary
274 },
275 ["oklch(0.205 0 0)"], // Single primary color
276);
277
278const darkThemeMonochrome: MindElixirTheme = createTheme(
279 "shadcn-dark-mono",
280 "dark",
281 {
282 ...darkColors,
283 accentColor: "oklch(0.922 0 0)", // primary
284 },
285 ["oklch(0.922 0 0)"], // Single primary color
286);
287
288// Helper function to get the appropriate theme
289function getTheme(isDark: boolean, isMonochrome: boolean): MindElixirTheme {
290 if (isDark) {
291 return isMonochrome ? darkThemeMonochrome : darkTheme;
292 }
293 return isMonochrome ? lightThemeMonochrome : lightTheme;
294}
295
296const SIDE = 2;
297export const MindMap = forwardRef<MindMapRef, MindMapProps>(function MindMap(
298 {
299 children,
300 data,
301 className,
302 direction = SIDE,
303 contextMenu = true,
304 nodeMenu = true,
305 keypress = true,
306 locale = "en",
307 overflowHidden = false,
308 mainLinkStyle = 2,
309 theme: themeProp,
310 monochrome = false,
311 fit = true,
312 readonly = false,
313 onChange,
314 onOperation,
315 onSelectNodes,
316 loader,
317 }: MindMapProps,
318 ref,
319) {
320 const containerRef = useRef<HTMLDivElement>(null);
321 const mindRef = useRef<MindElixirInstance | null>(null);
322 const [isLoaded, setIsLoaded] = useState(false);
323 const [mindInstance, setMindInstance] = useState<MindElixirInstance | null>(
324 null,
325 );
326 const resolvedTheme = useResolvedTheme(themeProp);
327 const id = useId();
328
329 // Expose mind instance to parent component via ref
330 useImperativeHandle(
331 ref,
332 () => ({
333 instance: mindRef.current,
334 }),
335 [],
336 );
337
338 // Store resolvedTheme in a ref for use in effects without triggering re-runs
339 const resolvedThemeRef = useRef(resolvedTheme);
340 useEffect(() => {
341 resolvedThemeRef.current = resolvedTheme;
342 }, [resolvedTheme]);
343
344 // Store callbacks in refs to avoid re-initialization when they change
345 const onChangeRef = useRef(onChange);
346 const onOperationRef = useRef(onOperation);
347 const onSelectNodesRef = useRef(onSelectNodes);
348
349 useEffect(() => {
350 onChangeRef.current = onChange;
351 onOperationRef.current = onOperation;
352 onSelectNodesRef.current = onSelectNodes;
353 }, [onChange, onOperation, onSelectNodes]);
354
355 // Track internal changes to avoid refresh loops
356 const isInternalChangeRef = useRef(false);
357
358 // Store initial data in ref - only used for initialization, not reactive
359 const initialDataRef = useRef(data);
360
361 // Initialize MindElixir (client-side only)
362 useEffect(() => {
363 if (!containerRef.current || mindRef.current) return;
364
365 let isSubscribed = true;
366
367 // Prioritize theme from data, then fall back to component props
368 const initialData = initialDataRef.current || MindElixir.new("Mind Map");
369 const themeToUse =
370 initialData.theme ||
371 getTheme(resolvedThemeRef.current === "dark", monochrome);
372
373 const options = {
374 el: containerRef.current,
375 direction,
376 contextMenu,
377 toolBar: false,
378 nodeMenu,
379 keypress,
380 locale,
381 overflowHidden,
382 mainLinkStyle,
383 editable: !readonly,
384 alignment: "nodes",
385 theme: themeToUse,
386 } as Options;
387
388 try {
389 const mind = new MindElixir(options);
390 mind.init(initialData);
391
392 if (isSubscribed) {
393 mindRef.current = mind;
394 setMindInstance(mind);
395 setIsLoaded(true);
396
397 // Auto-fit if enabled
398 if (fit) {
399 mind.scaleFit();
400 }
401
402 // Event listeners (using refs to avoid re-initialization)
403 mind.bus.addListener("operation", (operation) => {
404 console.log(operation);
405
406 // Call onOperation if provided
407 if (onOperationRef.current) {
408 onOperationRef.current(operation);
409 }
410 // Call onChange if provided
411 if (onChangeRef.current) {
412 const updatedData = mind.getData();
413 // Mark this as an internal change to prevent refresh loop
414 isInternalChangeRef.current = true;
415 onChangeRef.current(updatedData, operation);
416 }
417 });
418
419 if (onSelectNodesRef.current) {
420 mind.bus.addListener("selectNodes", (nodeObj) => {
421 onSelectNodesRef.current?.(nodeObj);
422 });
423 }
424 }
425 } catch (error) {
426 console.error("Failed to initialize MindElixir:", error);
427 }
428
429 return () => {
430 isSubscribed = false;
431 // Note: We intentionally don't clean up the mind instance here
432 // to avoid DOM manipulation conflicts with React
433 // The instance will be garbage collected when the component unmounts
434 mindRef.current = null;
435 };
436 }, [
437 direction,
438 contextMenu,
439 nodeMenu,
440 keypress,
441 locale,
442 overflowHidden,
443 mainLinkStyle,
444 monochrome,
445 readonly,
446 fit,
447 ]);
448
449 // Update data when it changes
450 useEffect(() => {
451 if (mindRef.current && data && isLoaded) {
452 // Skip refresh if this change came from onChange (internal change)
453 if (isInternalChangeRef.current) {
454 isInternalChangeRef.current = false;
455 return;
456 }
457 mindRef.current.refresh(data);
458 }
459 }, [data, isLoaded]);
460
461 // Update theme when resolvedTheme or monochrome changes
462 // BUT only if the data itself doesn't have a theme (data.theme has highest priority)
463 useEffect(() => {
464 if (!mindRef.current || !isLoaded) return;
465
466 // Check if current data has its own theme
467 const currentData = mindRef.current.getData();
468 if (currentData.theme) {
469 // Data has its own theme, don't override it with prop changes
470 return;
471 }
472
473 // No theme in data, apply theme from props
474 const newTheme = getTheme(resolvedTheme === "dark", monochrome);
475 mindRef.current.changeTheme(newTheme);
476 }, [resolvedTheme, monochrome, isLoaded]);
477
478 return (
479 <MindMapContext.Provider value={{ mind: mindInstance, isLoaded }}>
480 <div className={cn("relative w-full h-full", className)}>
481 <div
482 key={id}
483 ref={containerRef}
484 id={`mindmap-${id}`}
485 className="w-full h-full bg-background rounded-lg overflow-hidden"
486 />
487 {!isLoaded ? loader || <DefaultLoader /> : null}
488 {children}
489 </div>
490 </MindMapContext.Provider>
491 );
492});
493
494// MindMap Controls
495interface MindMapControlsProps {
496 position?: "top-left" | "top-right" | "bottom-left" | "bottom-right";
497 showZoom?: boolean;
498 showFit?: boolean;
499 showExport?: boolean;
500 className?: string;
501 onExport?: (file: Blob, filename: string) => void;
502}
503
504export function MindMapControls({
505 position = "top-right",
506 showZoom = true,
507 showFit = true,
508 showExport = true,
509 className,
510 onExport,
511}: MindMapControlsProps) {
512 const { mind, isLoaded } = useMindMap();
513 const [mounted, setMounted] = useState(false);
514 const [isFullscreen, setIsFullscreen] = useState(false);
515
516 useEffect(() => {
517 const timer = setTimeout(() => setMounted(true), 0);
518 return () => clearTimeout(timer);
519 }, []);
520
521 const handleZoomIn = () => {
522 if (mind) {
523 const currentScale = mind.scaleVal || 1;
524 mind.scale(currentScale + 0.2);
525 }
526 };
527
528 const handleZoomOut = () => {
529 if (mind) {
530 const currentScale = mind.scaleVal || 1;
531 mind.scale(Math.max(0.2, currentScale - 0.2));
532 }
533 };
534
535 const handleFit = () => {
536 if (mind) {
537 mind.scaleFit();
538 }
539 };
540
541 const handleExport = async () => {
542 if (mind) {
543 try {
544 // Export as image using snapdom
545 const result = await snapdom(mind.nodes);
546 // Use root node's topic as filename
547 const rootTopic = mind.nodeData.topic || "mindmap";
548 const filename = `${rootTopic}.jpg`;
549 const options = {
550 type: "jpg",
551 filename: rootTopic,
552 quality: 1,
553 backgroundColor: mind.theme.cssVar["--bgcolor"],
554 } as SnapdomOptions;
555
556 // Get the blob for the callback
557 if (onExport) {
558 const blob = await result.toBlob(options);
559 onExport(blob, filename);
560 }
561
562 // Download the file
563 await result.download(options);
564 } catch (error) {
565 console.error("Failed to export mind map:", error);
566 }
567 }
568 };
569
570 const handleFullscreen = () => {
571 const container = mind?.container?.parentElement;
572 if (!container) return;
573
574 if (!document.fullscreenElement) {
575 container
576 .requestFullscreen()
577 .then(() => {
578 setIsFullscreen(true);
579 })
580 .catch((err) => {
581 console.error("Failed to enter fullscreen:", err);
582 });
583 } else {
584 document.exitFullscreen().then(() => {
585 setIsFullscreen(false);
586 });
587 }
588 };
589
590 // Listen for fullscreen changes
591 useEffect(() => {
592 const handleFullscreenChange = () => {
593 const isNowFullscreen = !!document.fullscreenElement;
594 setIsFullscreen(isNowFullscreen);
595
596 // When exiting fullscreen, call scaleFit to ensure content is visible
597 if (!isNowFullscreen && mind) {
598 mind.scaleFit();
599 }
600 };
601
602 document.addEventListener("fullscreenchange", handleFullscreenChange);
603 return () => {
604 document.removeEventListener("fullscreenchange", handleFullscreenChange);
605 };
606 }, [mind]);
607
608 if (!mounted || !isLoaded) return null;
609
610 const positionClasses = {
611 "top-left": "top-3 left-3",
612 "top-right": "top-3 right-3",
613 "bottom-left": "bottom-3 left-3",
614 "bottom-right": "bottom-3 right-3",
615 };
616
617 return (
618 <div
619 className={cn(
620 "absolute z-10 flex flex-col gap-1",
621 positionClasses[position],
622 className,
623 )}
624 >
625 {showZoom && (
626 <>
627 <button
628 onClick={handleZoomIn}
629 className="size-8 rounded-md bg-background/95 backdrop-blur-md border border-border/50 shadow-lg flex items-center justify-center hover:bg-accent transition-colors"
630 aria-label="Zoom in"
631 >
632 <Plus className="size-4" />
633 </button>
634 <button
635 onClick={handleZoomOut}
636 className="size-8 rounded-md bg-background/95 backdrop-blur-md border border-border/50 shadow-lg flex items-center justify-center hover:bg-accent transition-colors"
637 aria-label="Zoom out"
638 >
639 <Minus className="size-4" />
640 </button>
641 </>
642 )}
643 {showFit && (
644 <button
645 onClick={handleFit}
646 className="size-8 rounded-md bg-background/95 backdrop-blur-md border border-border/50 shadow-lg flex items-center justify-center hover:bg-accent transition-colors"
647 aria-label="Fit to screen"
648 >
649 <ScanSearch className="size-4" />
650 </button>
651 )}
652 <button
653 onClick={handleFullscreen}
654 className="size-8 rounded-md bg-background/95 backdrop-blur-md border border-border/50 shadow-lg flex items-center justify-center hover:bg-accent transition-colors"
655 aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
656 >
657 <Maximize className="size-4" />
658 </button>
659 {showExport && (
660 <button
661 onClick={handleExport}
662 className="size-8 rounded-md bg-background/95 backdrop-blur-md border border-border/50 shadow-lg flex items-center justify-center hover:bg-accent transition-colors"
663 aria-label="Download as image"
664 >
665 <Download className="size-4" />
666 </button>
667 )}
668 </div>
669 );
670}
671
672// Export components
673