mirror of
https://github.com/Tria-plc/edr-platform.git
synced 2026-08-28 16:00:56 +00:00
92 lines
2.3 KiB
TypeScript
92 lines
2.3 KiB
TypeScript
import React, { createContext, useContext, useState, useCallback } from "react";
|
|
|
|
/**
|
|
* Context for managing breadcrumb labels
|
|
* Allows components to register human-readable labels for IDs
|
|
*/
|
|
|
|
interface BreadcrumbLabel {
|
|
id: string;
|
|
label: string;
|
|
type: "year" | "plan" | "position" | "employee" | "service" | "other";
|
|
}
|
|
|
|
interface BreadcrumbContextType {
|
|
labels: Map<string, BreadcrumbLabel>;
|
|
registerLabel: (id: string, label: string, type: BreadcrumbLabel["type"]) => void;
|
|
getLabel: (id: string) => string | null;
|
|
clearLabels: () => void;
|
|
}
|
|
|
|
const BreadcrumbContext = createContext<BreadcrumbContextType | undefined>(
|
|
undefined
|
|
);
|
|
|
|
export const BreadcrumbProvider: React.FC<{ children: React.ReactNode }> = ({
|
|
children,
|
|
}) => {
|
|
const [labels, setLabels] = useState<Map<string, BreadcrumbLabel>>(
|
|
new Map()
|
|
);
|
|
|
|
const registerLabel = useCallback(
|
|
(id: string, label: string, type: BreadcrumbLabel["type"]) => {
|
|
setLabels((prev) => {
|
|
const newMap = new Map(prev);
|
|
newMap.set(id, { id, label, type });
|
|
return newMap;
|
|
});
|
|
},
|
|
[]
|
|
);
|
|
|
|
const getLabel = useCallback(
|
|
(id: string): string | null => {
|
|
return labels.get(id)?.label || null;
|
|
},
|
|
[labels]
|
|
);
|
|
|
|
const clearLabels = useCallback(() => {
|
|
setLabels(new Map());
|
|
}, []);
|
|
|
|
return (
|
|
<BreadcrumbContext.Provider
|
|
value={{ labels, registerLabel, getLabel, clearLabels }}>
|
|
{children}
|
|
</BreadcrumbContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useBreadcrumbContext = () => {
|
|
const context = useContext(BreadcrumbContext);
|
|
if (!context) {
|
|
throw new Error(
|
|
"useBreadcrumbContext must be used within BreadcrumbProvider"
|
|
);
|
|
}
|
|
return context;
|
|
};
|
|
|
|
/**
|
|
* Hook to register a breadcrumb label when a component mounts
|
|
* Usage in components:
|
|
*
|
|
* const { data: planData } = usePlan(planId);
|
|
* useBreadcrumbLabel(planId, localizedName(planData?.name), "plan");
|
|
*/
|
|
export const useBreadcrumbLabel = (
|
|
id: string | undefined,
|
|
label: string | undefined,
|
|
type: BreadcrumbLabel["type"]
|
|
) => {
|
|
const { registerLabel } = useBreadcrumbContext();
|
|
|
|
React.useEffect(() => {
|
|
if (id && label) {
|
|
registerLabel(id, label, type);
|
|
}
|
|
}, [id, label, type, registerLabel]);
|
|
};
|