UNPKG

analytica-frontend-lib

Version:

Repositório público dos componentes utilizados nas plataformas da Analytica Ensino

236 lines (233 loc) 7.97 kB
// src/components/Filter/useTableFilter.ts import { useEffect, useState, useCallback, useMemo } from "react"; // src/components/CheckBoxGroup/CheckBoxGroup.helpers.ts var areSelectedIdsEqual = (ids1, ids2) => { if (ids1 === ids2) return true; if (!ids1 || !ids2) return ids1 === ids2; if (ids1.length !== ids2.length) return false; for (let i = 0; i < ids1.length; i++) { if (ids1[i] !== ids2[i]) return false; } return true; }; var isCategoryEnabled = (category, allCategories) => { if (!category.dependsOn || category.dependsOn.length === 0) { return true; } return category.dependsOn.every((depKey) => { const depCat = allCategories.find((c) => c.key === depKey); return depCat?.selectedIds && depCat.selectedIds.length > 0; }); }; var isItemMatchingFilter = (item, filter, allCategories) => { const parentCat = allCategories.find((c) => c.key === filter.key); const parentSelectedIds = parentCat?.selectedIds || []; const itemFieldValue = item[filter.internalField]; return parentSelectedIds.includes(String(itemFieldValue)); }; var getBadgeText = (category, formattedItems) => { const visibleIds = formattedItems.flatMap((group) => group.itens || []).map((i) => i.id); const selectedVisibleCount = visibleIds.filter( (id) => category.selectedIds?.includes(id) ).length; const totalVisible = visibleIds.length; return `${selectedVisibleCount} de ${totalVisible} ${selectedVisibleCount === 1 ? "selecionado" : "selecionados"}`; }; var handleAccordionValueChange = (value, categories, isCategoryEnabledFn) => { if (typeof value !== "string") { if (!value) { return ""; } return null; } if (!value) { return ""; } const category = categories.find((c) => c.key === value); if (!category) { return null; } const isEnabled = isCategoryEnabledFn(category); if (!isEnabled) { return null; } return value; }; var calculateFormattedItemsForAutoSelection = (category, allCategories) => { if (!category?.dependsOn || category.dependsOn.length === 0) { return category?.itens || []; } const isEnabled = isCategoryEnabled(category, allCategories); if (!isEnabled) { return []; } const filters = category.filteredBy || []; if (filters.length === 0) { return category?.itens || []; } const selectedIdsArr = filters.map((f) => { const parentCat = allCategories.find((c) => c.key === f.key); if (!parentCat?.selectedIds?.length) { return []; } return parentCat.selectedIds; }); if (selectedIdsArr.some((arr) => arr.length === 0)) { return []; } const filteredItems = (category.itens || []).filter( (item) => filters.every((filter) => isItemMatchingFilter(item, filter, allCategories)) ); return filteredItems; }; // src/components/Filter/useTableFilter.ts var mergeConfigsWithSelections = (newConfigs, prevConfigs) => { let changed = false; const result = newConfigs.map((newConfig, i) => ({ ...newConfig, categories: newConfig.categories.map((newCat, j) => { const prevCat = prevConfigs[i]?.categories[j]; const prevItems = prevCat?.itens ?? []; const newItems = newCat.itens ?? []; if (prevItems.length !== newItems.length) { changed = true; } if (prevCat?.key === newCat.key && prevCat?.selectedIds?.length) { const availableIds = new Set(newItems.map((item) => item.id)); const selectedIds = prevCat.selectedIds.filter( (id) => availableIds.has(id) ); if (selectedIds.length !== prevCat.selectedIds.length) { changed = true; } return { ...newCat, selectedIds }; } return newCat; }) })); return changed ? result : prevConfigs; }; var useTableFilter = (initialConfigs, options = {}) => { const { syncWithUrl = false } = options; const getInitialState = useCallback(() => { if (!syncWithUrl || globalThis.window === void 0) { return initialConfigs; } const params = new URLSearchParams(globalThis.window.location.search); const configsWithUrlState = initialConfigs.map((config) => ({ ...config, categories: config.categories.map((category) => { const urlValue = params.get(`filter_${category.key}`); const selectedIds = urlValue ? urlValue.split(",").filter(Boolean) : []; return { ...category, selectedIds }; }) })); return configsWithUrlState; }, [initialConfigs, syncWithUrl]); const [filterConfigs, setFilterConfigs] = useState(getInitialState); const activeFilters = useMemo(() => { const filters = {}; for (const config of filterConfigs) { for (const category of config.categories) { if (category.selectedIds && category.selectedIds.length > 0) { filters[category.key] = category.selectedIds; } } } return filters; }, [filterConfigs]); const hasActiveFilters = Object.keys(activeFilters).length > 0; const activeFiltersCount = useMemo(() => { const allCategories = filterConfigs.flatMap((config) => config.categories); let count = 0; for (const category of allCategories) { if (!category.selectedIds || category.selectedIds.length === 0) continue; const availableItems = calculateFormattedItemsForAutoSelection( category, allCategories ); const isAutoSelected = availableItems.length === 1 && category.selectedIds.length === 1 && category.selectedIds[0] === availableItems[0]?.id; if (!isAutoSelected) { count++; } } return count; }, [filterConfigs]); const updateFilters = useCallback((configs) => { setFilterConfigs(configs); }, []); const applyFilters = useCallback(() => { if (!syncWithUrl || globalThis.window === void 0) { return; } const url = new URL(globalThis.window.location.href); const params = url.searchParams; for (const config of filterConfigs) { for (const category of config.categories) { const paramKey = `filter_${category.key}`; if (category.selectedIds && category.selectedIds.length > 0) { params.set(paramKey, category.selectedIds.join(",")); } else { params.delete(paramKey); } } } globalThis.window.history.replaceState({}, "", url.toString()); }, [filterConfigs, syncWithUrl]); const clearFilters = useCallback(() => { const clearedConfigs = filterConfigs.map((config) => ({ ...config, categories: config.categories.map((category) => ({ ...category, selectedIds: [] })) })); setFilterConfigs(clearedConfigs); if (syncWithUrl && globalThis.window !== void 0) { const url = new URL(globalThis.window.location.href); const params = url.searchParams; for (const config of filterConfigs) { for (const category of config.categories) { params.delete(`filter_${category.key}`); } } globalThis.window.history.replaceState({}, "", url.toString()); } }, [filterConfigs, syncWithUrl]); useEffect(() => { setFilterConfigs( (prev) => mergeConfigsWithSelections(initialConfigs, prev) ); }, [initialConfigs]); useEffect(() => { if (!syncWithUrl || globalThis.window === void 0) { return; } const handlePopState = () => { setFilterConfigs(getInitialState()); }; globalThis.window.addEventListener("popstate", handlePopState); return () => globalThis.window.removeEventListener("popstate", handlePopState); }, [syncWithUrl, getInitialState]); return { filterConfigs, activeFilters, hasActiveFilters, activeFiltersCount, updateFilters, applyFilters, clearFilters }; }; export { areSelectedIdsEqual, isCategoryEnabled, getBadgeText, handleAccordionValueChange, calculateFormattedItemsForAutoSelection, useTableFilter }; //# sourceMappingURL=chunk-45LJRS7N.mjs.map