2025-09-06 20:25:50 +03:00
|
|
|
import { useEffect, useLayoutEffect, useRef } from "preact/hooks";
|
|
|
|
|
import { ColumnDefinition, EventCallBackMethods, Module, Tabulator as VanillaTabulator } from "tabulator-tables";
|
2025-09-06 19:11:39 +03:00
|
|
|
import "tabulator-tables/dist/css/tabulator.css";
|
|
|
|
|
import "../../../../src/stylesheets/table.css";
|
2025-09-06 20:25:50 +03:00
|
|
|
import { RefObject } from "preact";
|
2025-09-06 19:11:39 +03:00
|
|
|
|
2025-09-06 20:25:50 +03:00
|
|
|
interface TableProps<T> extends Partial<EventCallBackMethods> {
|
|
|
|
|
tabulatorRef: RefObject<VanillaTabulator>;
|
2025-09-06 19:11:39 +03:00
|
|
|
className?: string;
|
|
|
|
|
columns: ColumnDefinition[];
|
|
|
|
|
data?: T[];
|
2025-09-06 19:19:52 +03:00
|
|
|
modules?: (new (table: VanillaTabulator) => Module)[];
|
2025-09-06 19:11:39 +03:00
|
|
|
}
|
|
|
|
|
|
2025-09-06 20:25:50 +03:00
|
|
|
export default function Tabulator<T>({ className, columns, data, modules, tabulatorRef: externalTabulatorRef, ...events }: TableProps<T>) {
|
2025-09-06 19:11:39 +03:00
|
|
|
const containerRef = useRef<HTMLDivElement>(null);
|
|
|
|
|
const tabulatorRef = useRef<VanillaTabulator>(null);
|
|
|
|
|
|
2025-09-06 20:25:50 +03:00
|
|
|
useLayoutEffect(() => {
|
2025-09-06 19:19:52 +03:00
|
|
|
if (!modules) return;
|
|
|
|
|
for (const module of modules) {
|
|
|
|
|
VanillaTabulator.registerModule(module);
|
|
|
|
|
}
|
|
|
|
|
}, [modules]);
|
|
|
|
|
|
2025-09-06 20:25:50 +03:00
|
|
|
useLayoutEffect(() => {
|
2025-09-06 19:11:39 +03:00
|
|
|
if (!containerRef.current) return;
|
|
|
|
|
|
|
|
|
|
const tabulator = new VanillaTabulator(containerRef.current, {
|
|
|
|
|
columns,
|
|
|
|
|
data
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
tabulatorRef.current = tabulator;
|
2025-09-06 20:25:50 +03:00
|
|
|
externalTabulatorRef.current = tabulator;
|
2025-09-06 19:11:39 +03:00
|
|
|
|
|
|
|
|
return () => tabulator.destroy();
|
|
|
|
|
}, []);
|
|
|
|
|
|
2025-09-06 20:25:50 +03:00
|
|
|
useEffect(() => {
|
|
|
|
|
const tabulator = tabulatorRef.current;
|
|
|
|
|
if (!tabulator) return;
|
|
|
|
|
|
|
|
|
|
for (const [ eventName, handler ] of Object.entries(events)) {
|
|
|
|
|
tabulator.on(eventName as keyof EventCallBackMethods, handler);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
for (const [ eventName, handler ] of Object.entries(events)) {
|
|
|
|
|
tabulator.off(eventName as keyof EventCallBackMethods, handler);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}, Object.values(events));
|
|
|
|
|
|
2025-09-06 19:11:39 +03:00
|
|
|
return (
|
|
|
|
|
<div ref={containerRef} className={className} />
|
|
|
|
|
);
|
|
|
|
|
}
|