@evergis/react 4.0.74 → 4.0.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/react.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { jsx, jsxs, Fragment as Fragment$1 } from 'react/jsx-runtime';
2
- import { IconButton, Flex, transition, Chip, Icon, Description, FlexSpan, IconToggle, Popup, Menu, DraggableTree, shadows, Divider, LegendToggler, Tooltip as Tooltip$1, DropdownField, MultiSelectContainer, IconButtonButton, FlatButton, DraggableTreeContainer, Dialog, DialogTitle, ThemeProvider, darkTheme, DialogContent, CircularProgress, Switch, AutoComplete, Input, Slider, Dropdown, Checkbox, DatePicker, getLocale, IconToggleButton, LinearProgress, ActionsGroup, DialogActions, RaisedButton, Preview, H2, Blank, Popover, UploaderItemArea, UploaderTitleWrapper, Uploader, NumberRangeSlider, useAsyncAutocomplete, RangeNumberInput, defaultTheme, dateFormat } from '@evergis/uilib-gl';
2
+ import { IconButton, Flex, transition, Chip, Icon, Description, FlexSpan, IconToggle, Popup, Menu, DraggableTree, shadows, Divider, LegendToggler, Tooltip as Tooltip$1, DropdownField, MultiSelectContainer, IconButtonButton, FlatButton, DraggableTreeContainer, Dialog, DialogTitle, ThemeProvider, darkTheme, DialogContent, CircularProgress, Switch, AutoComplete, Input, Slider, Dropdown, Checkbox, DatePicker, getLocale, IconToggleButton, LinearProgress, ActionsGroup, DialogActions, RaisedButton, Preview, H2, Blank, Popover, UploaderItemArea, UploaderTitleWrapper, Uploader, NumberRangeSlider, useAsyncAutocomplete, RangeNumberInput, TreeDropdown, defaultTheme, dateFormat } from '@evergis/uilib-gl';
3
3
  import { createContext, memo, useRef, useState, useCallback, useEffect, useContext, useMemo, isValidElement, Fragment, createElement } from 'react';
4
4
  import styled, { createGlobalStyle, css, useTheme } from 'styled-components';
5
5
  import { lineChartClassNames, BarChart as BarChart$1, barChartClassNames, LineChart, PieChart } from '@evergis/charts';
@@ -4675,33 +4675,6 @@ const createConfigPage = (props) => {
4675
4675
  };
4676
4676
  };
4677
4677
 
4678
- const getAttributesConfiguration = (layer) => {
4679
- const layerAttributeConfiguration = layer?.configuration?.attributesConfiguration ?? {};
4680
- const { geometryAttribute, idAttribute } = layerAttributeConfiguration;
4681
- const emptyLayerDefinition = {
4682
- attributes: [],
4683
- geometryAttribute: geometryAttribute ?? GEOMETRY_ATTRIBUTE,
4684
- idAttribute: idAttribute ?? DEFAULT_ID_ATTRIBUTE_NAME,
4685
- titleAttribute: "",
4686
- };
4687
- if (!isLayerService(layer)) {
4688
- return emptyLayerDefinition;
4689
- }
4690
- return {
4691
- ...emptyLayerDefinition,
4692
- ...layerAttributeConfiguration,
4693
- attributes: layerAttributeConfiguration?.attributes ||
4694
- emptyLayerDefinition.attributes,
4695
- };
4696
- };
4697
-
4698
- const formatChartRelatedValue = (t, value, layerInfo, relatedAttributes) => {
4699
- const layerDefinition = getAttributesConfiguration(layerInfo);
4700
- const relatedAxis = relatedAttributes.find(({ chartAxis }) => chartAxis === "y");
4701
- const attribute = layerDefinition.attributes[relatedAxis.attributeName];
4702
- return attribute ? formatAttributeValue({ t, type: attribute.type, value, stringFormat: attribute.stringFormat }) : value;
4703
- };
4704
-
4705
4678
  const isEmptyValue = (value) => value === "" || value === null || value === undefined;
4706
4679
 
4707
4680
  const checkIsDateFormat = (value) => value.startsWith("#'") && value.endsWith("'");
@@ -4731,7 +4704,59 @@ const formatConditionValue = ({ value, attributeType, defaultValue, checkQuotes
4731
4704
  return checkQuotes && checkIfNeedQuotes(stringValue, attributeType) ? `'${stringValue}'` : stringValue;
4732
4705
  };
4733
4706
 
4707
+ /**
4708
+ * Объектное значение иерархического фильтра "tree" («уровень → массив id»),
4709
+ * в отличие от скалярных/массивных значений остальных фильтров.
4710
+ */
4711
+ const isTreeFilterValue = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && !(value instanceof Date);
4712
+ /**
4713
+ * Подставляет плейсхолдеры уровней `%name.l{N}` значениями id соответствующего уровня
4714
+ * (формат `[id1,id2,...]` для оператора IN). Уровни, отсутствующие в значении (или пустые),
4715
+ * не подставляются — плейсхолдер остаётся нетронутым, как и любой пустой `%`-плейсхолдер.
4716
+ */
4717
+ const applyTreeFilterToCondition = (condition, name, value, isSingle) => {
4718
+ const filterName = `${FILTER_PREFIX}${name}`;
4719
+ return Object.keys(value).reduce((result, level) => {
4720
+ const formatted = formatConditionValue({ value: value[level], checkQuotes: !isSingle });
4721
+ if (!formatted) {
4722
+ return result;
4723
+ }
4724
+ return result.replace(new RegExp(`${filterName}\\.${level}\\b`, "g"), formatted);
4725
+ }, condition);
4726
+ };
4727
+
4728
+ const getAttributesConfiguration = (layer) => {
4729
+ const layerAttributeConfiguration = layer?.configuration?.attributesConfiguration ?? {};
4730
+ const { geometryAttribute, idAttribute } = layerAttributeConfiguration;
4731
+ const emptyLayerDefinition = {
4732
+ attributes: [],
4733
+ geometryAttribute: geometryAttribute ?? GEOMETRY_ATTRIBUTE,
4734
+ idAttribute: idAttribute ?? DEFAULT_ID_ATTRIBUTE_NAME,
4735
+ titleAttribute: "",
4736
+ };
4737
+ if (!isLayerService(layer)) {
4738
+ return emptyLayerDefinition;
4739
+ }
4740
+ return {
4741
+ ...emptyLayerDefinition,
4742
+ ...layerAttributeConfiguration,
4743
+ attributes: layerAttributeConfiguration?.attributes ||
4744
+ emptyLayerDefinition.attributes,
4745
+ };
4746
+ };
4747
+
4748
+ const formatChartRelatedValue = (t, value, layerInfo, relatedAttributes) => {
4749
+ const layerDefinition = getAttributesConfiguration(layerInfo);
4750
+ const relatedAxis = relatedAttributes.find(({ chartAxis }) => chartAxis === "y");
4751
+ const attribute = layerDefinition.attributes[relatedAxis.attributeName];
4752
+ return attribute ? formatAttributeValue({ t, type: attribute.type, value, stringFormat: attribute.stringFormat }) : value;
4753
+ };
4754
+
4734
4755
  const applyFiltersToCondition = ({ condition, name, defaultValue, filters, isSingle, isSetParams, }) => {
4756
+ const rawValue = filters[name] !== undefined ? filters[name].value : defaultValue;
4757
+ if (isTreeFilterValue(rawValue)) {
4758
+ return applyTreeFilterToCondition(condition, name, rawValue, isSingle);
4759
+ }
4735
4760
  const hasFilter = filters[name] !== undefined && !!filters[name].value?.toString().length;
4736
4761
  const min = formatConditionValue({
4737
4762
  value: hasFilter ? filters[name].min : null,
@@ -11341,7 +11366,7 @@ const ChipsFilter = ({ type, filter, elementConfig, }) => {
11341
11366
  icon: chipIcon,
11342
11367
  };
11343
11368
  });
11344
- }, [configFilter, dataSources, colorAttribute, iconAttribute, theme]);
11369
+ }, [variants, configFilter, dataSources, iconAttribute, colorAttribute, theme]);
11345
11370
  const isChipActive = useCallback((chipValue) => {
11346
11371
  const currentValue = filters?.[filterName]?.value;
11347
11372
  if (currentValue === undefined) {
@@ -11417,6 +11442,373 @@ function getIconFromAttribute(option, iconAttribute) {
11417
11442
  return getResourceUrl(iconValue);
11418
11443
  }
11419
11444
 
11445
+ const MAX_ANCESTOR_DEPTH = 50;
11446
+ const buildLevelOneCondition = (attributeLevel) => `${attributeLevel} = 1`;
11447
+ const buildChildrenCondition = (attributeParentName, parentName) => `${attributeParentName} = ${formatConditionValue({ value: parentName })}`;
11448
+ const buildSearchCondition = (attributeAlias, query) => `${attributeAlias} LIKE '%${query.replace(/'/g, "''")}%'`;
11449
+ /** Запрос пачки записей по их именам (`attributeName`) — для достройки предков. */
11450
+ const buildNamesCondition = (attributeName, names) => `${attributeName} in ${formatConditionValue({ value: names })}`;
11451
+ /** Запрос пачки записей по их значениям (`attributeValue`) — для восстановления `defaultValue`. */
11452
+ const buildValuesCondition = (attributeValue, values) => `${attributeValue} in ${formatConditionValue({ value: values })}`;
11453
+ /** Группирует выбранные id по уровню в объектное значение фильтра `{ l{N}: [ids] }`. */
11454
+ const buildFilterValue = (selected) => {
11455
+ const result = {};
11456
+ selected.forEach((level, id) => {
11457
+ const key = `l${level}`;
11458
+ if (!result[key]) {
11459
+ result[key] = [];
11460
+ }
11461
+ result[key].push(id);
11462
+ });
11463
+ return result;
11464
+ };
11465
+ /** Разбирает объектное значение фильтра в карту `id → level`. */
11466
+ const parseFilterValue = (value) => {
11467
+ const result = new Map();
11468
+ if (!value) {
11469
+ return result;
11470
+ }
11471
+ Object.keys(value).forEach(levelKey => {
11472
+ const level = Number(levelKey.replace(/^l/, ""));
11473
+ value[levelKey]?.forEach(id => result.set(id, level));
11474
+ });
11475
+ return result;
11476
+ };
11477
+ /** Стабильная сериализация выбора для сравнения (порядок не важен). */
11478
+ const serializeSelection = (selected) => [...selected.entries()]
11479
+ .map(([id, level]) => `${id}:${level}`)
11480
+ .sort()
11481
+ .join(",");
11482
+ /**
11483
+ * Дозапрашивает цепочку предков вверх по `parentName` уровень за уровнем (батч `attributeName in
11484
+ * (...)`), пока не достигнет уровня 1. Связь идёт по именам (`name`/`parentName`), т.к. `node.id`
11485
+ * хранит значение (`attributeValue`). Возвращает исходные узлы вместе с предками.
11486
+ */
11487
+ const collectAncestors = async (nodes, loadByNames) => {
11488
+ const byName = new Map();
11489
+ nodes.forEach(node => byName.set(node.data.name, node));
11490
+ let frontier = nodes;
11491
+ for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth++) {
11492
+ const missingParents = new Set();
11493
+ frontier.forEach(node => {
11494
+ const { parentName, level } = node.data ?? {};
11495
+ if (parentName != null && level > 1 && !byName.has(parentName)) {
11496
+ missingParents.add(parentName);
11497
+ }
11498
+ });
11499
+ if (!missingParents.size) {
11500
+ break;
11501
+ }
11502
+ const parents = await loadByNames([...missingParents]);
11503
+ if (!parents.length) {
11504
+ break;
11505
+ }
11506
+ parents.forEach(parent => byName.set(parent.data.name, parent));
11507
+ frontier = parents;
11508
+ }
11509
+ return [...byName.values()];
11510
+ };
11511
+ /**
11512
+ * Собирает плоский набор узлов в дерево по связи `parentName` ↔ `name`. Узлы с подгруженными
11513
+ * потомками раскрываются (`expanded` хранит `node.id` = значение); листья-папки без потомков
11514
+ * получают `children = null` (ленивая подгрузка).
11515
+ */
11516
+ const assembleTree = (nodes) => {
11517
+ const nodesByName = new Map();
11518
+ nodes.forEach(node => nodesByName.set(node.data.name, node));
11519
+ const childrenMap = new Map();
11520
+ nodesByName.forEach(node => {
11521
+ const parentName = node.data?.parentName;
11522
+ if (parentName != null && nodesByName.has(parentName)) {
11523
+ const siblings = childrenMap.get(parentName) ?? [];
11524
+ siblings.push(node);
11525
+ childrenMap.set(parentName, siblings);
11526
+ }
11527
+ });
11528
+ const roots = [];
11529
+ const expanded = [];
11530
+ nodesByName.forEach(node => {
11531
+ const { name, parentName } = node.data;
11532
+ const kids = childrenMap.get(name);
11533
+ if (kids?.length) {
11534
+ node.children = kids;
11535
+ expanded.push(node.id);
11536
+ }
11537
+ else if (node.isLeaf) {
11538
+ node.children = null;
11539
+ }
11540
+ if (parentName == null || !nodesByName.has(parentName)) {
11541
+ roots.push(node);
11542
+ }
11543
+ });
11544
+ return { roots, expanded };
11545
+ };
11546
+
11547
+ const useTreeFilterData = (type, filterName) => {
11548
+ const { api } = useGlobalContext();
11549
+ const { currentPage } = useWidgetPage(type);
11550
+ const configFilter = useMemo(() => getConfigFilter(filterName, currentPage?.filters), [filterName, currentPage?.filters]);
11551
+ const { relatedDataSource, attributeName = DEFAULT_ATTRIBUTE_NAME, attributeValue, attributeAlias = DEFAULT_ATTRIBUTE_NAME, attributeParentName, attributeLevel, attributeHasChildren, limit = DEFAULT_DATA_SOURCE_LIMIT, } = configFilter ?? {};
11552
+ const valueAttribute = attributeValue ?? attributeName;
11553
+ const layerName = useMemo(() => currentPage?.dataSources?.find(({ name }) => name === relatedDataSource)?.layerName, [currentPage?.dataSources, relatedDataSource]);
11554
+ const mapNode = useCallback(({ properties }) => {
11555
+ const hasChildren = attributeHasChildren ? !!properties[attributeHasChildren] : false;
11556
+ const data = {
11557
+ name: properties[attributeName],
11558
+ parentName: attributeParentName ? properties[attributeParentName] ?? null : null,
11559
+ level: attributeLevel ? Number(properties[attributeLevel]) : 1,
11560
+ };
11561
+ return {
11562
+ id: properties[valueAttribute],
11563
+ text: String(properties[attributeAlias] ?? ""),
11564
+ isLeaf: hasChildren,
11565
+ children: hasChildren ? null : undefined,
11566
+ data,
11567
+ };
11568
+ }, [valueAttribute, attributeName, attributeAlias, attributeParentName, attributeLevel, attributeHasChildren]);
11569
+ const runQuery = useCallback(async (condition) => {
11570
+ if (!layerName) {
11571
+ return [];
11572
+ }
11573
+ const response = await api.layers.getFeatures(layerName, { withGeom: false, limit, conditions: [condition] });
11574
+ return response.features ?? [];
11575
+ }, [api, layerName, limit]);
11576
+ const loadLevelOne = useCallback(async () => {
11577
+ if (!attributeLevel) {
11578
+ return [];
11579
+ }
11580
+ const features = await runQuery(buildLevelOneCondition(attributeLevel));
11581
+ return features.map(mapNode);
11582
+ }, [attributeLevel, runQuery, mapNode]);
11583
+ const loadChildren = useCallback(async (item) => {
11584
+ if (!attributeParentName) {
11585
+ return { children: [] };
11586
+ }
11587
+ const features = await runQuery(buildChildrenCondition(attributeParentName, item.data.name));
11588
+ return { children: features.map(mapNode) };
11589
+ }, [attributeParentName, runQuery, mapNode]);
11590
+ const searchNodes = useCallback(async (query) => {
11591
+ const features = await runQuery(buildSearchCondition(attributeAlias, query));
11592
+ return features.map(mapNode);
11593
+ }, [attributeAlias, runQuery, mapNode]);
11594
+ const loadByNames = useCallback(async (names) => {
11595
+ if (!names.length) {
11596
+ return [];
11597
+ }
11598
+ const features = await runQuery(buildNamesCondition(attributeName, names));
11599
+ return features.map(mapNode);
11600
+ }, [attributeName, runQuery, mapNode]);
11601
+ const loadByValues = useCallback(async (values) => {
11602
+ if (!values.length) {
11603
+ return [];
11604
+ }
11605
+ const features = await runQuery(buildValuesCondition(valueAttribute, values));
11606
+ return features.map(mapNode);
11607
+ }, [valueAttribute, runQuery, mapNode]);
11608
+ return { configFilter, layerName, loadLevelOne, loadChildren, searchNodes, loadByNames, loadByValues };
11609
+ };
11610
+
11611
+ const SEARCH_MIN_LENGTH = 3;
11612
+ const SEARCH_DEBOUNCE = 300;
11613
+ const useTreeFilterSearch = ({ searchNodes, loadByNames }) => {
11614
+ const [searchValue, setSearchValue] = useState("");
11615
+ const [searchData, setSearchData] = useState([]);
11616
+ const [searchExpanded, setSearchExpanded] = useState([]);
11617
+ const [searching, setSearching] = useState(false);
11618
+ const timer = useRef();
11619
+ const requestId = useRef(0);
11620
+ const isSearchActive = searchValue.trim().length >= SEARCH_MIN_LENGTH;
11621
+ const runSearch = useCallback(async (query) => {
11622
+ const id = ++requestId.current;
11623
+ setSearching(true);
11624
+ try {
11625
+ const results = await searchNodes(query);
11626
+ const withAncestors = await collectAncestors(results, loadByNames);
11627
+ const { roots, expanded } = assembleTree(withAncestors);
11628
+ if (id !== requestId.current) {
11629
+ return;
11630
+ }
11631
+ setSearchData(roots);
11632
+ setSearchExpanded(expanded);
11633
+ }
11634
+ finally {
11635
+ if (id === requestId.current) {
11636
+ setSearching(false);
11637
+ }
11638
+ }
11639
+ }, [searchNodes, loadByNames]);
11640
+ const clearSearchState = useCallback(() => {
11641
+ requestId.current++;
11642
+ setSearchData([]);
11643
+ setSearchExpanded([]);
11644
+ setSearching(false);
11645
+ }, []);
11646
+ const onSearchChange = useCallback((value) => {
11647
+ setSearchValue(value);
11648
+ if (timer.current) {
11649
+ clearTimeout(timer.current);
11650
+ }
11651
+ const query = value.trim();
11652
+ if (query.length < SEARCH_MIN_LENGTH) {
11653
+ clearSearchState();
11654
+ return;
11655
+ }
11656
+ timer.current = setTimeout(() => runSearch(query), SEARCH_DEBOUNCE);
11657
+ }, [runSearch, clearSearchState]);
11658
+ const resetSearch = useCallback(() => {
11659
+ if (timer.current) {
11660
+ clearTimeout(timer.current);
11661
+ }
11662
+ setSearchValue("");
11663
+ clearSearchState();
11664
+ }, [clearSearchState]);
11665
+ return {
11666
+ searchValue,
11667
+ isSearchActive,
11668
+ searching,
11669
+ searchData,
11670
+ setSearchData,
11671
+ searchExpanded,
11672
+ setSearchExpanded,
11673
+ onSearchChange,
11674
+ resetSearch,
11675
+ };
11676
+ };
11677
+
11678
+ const useTreeFilterSelection = (type, filterName, configFilter) => {
11679
+ const { filters, changeFilters } = useWidgetContext(type);
11680
+ const [selected, setSelected] = useState(() => parseFilterValue(configFilter?.defaultValue));
11681
+ const [selectedLabel, setSelectedLabel] = useState();
11682
+ const selectedIds = useMemo(() => new Set(selected.keys()), [selected]);
11683
+ /** Уже применённый (в redux) выбор — база для `dirty`. */
11684
+ const committed = useMemo(() => parseFilterValue((filters[filterName]?.value ?? configFilter?.defaultValue)), [filters, filterName, configFilter?.defaultValue]);
11685
+ const dirty = useMemo(() => serializeSelection(selected) !== serializeSelection(committed), [selected, committed]);
11686
+ const commit = useCallback((next) => {
11687
+ setSelected(next);
11688
+ changeFilters({ [filterName]: { value: buildFilterValue(next) } }, configFilter?.resetFilters);
11689
+ }, [changeFilters, filterName, configFilter?.resetFilters]);
11690
+ const onToggleSelect = useCallback((item, multiSelect) => {
11691
+ const level = item.data?.level ?? 1;
11692
+ const next = new Map(selected);
11693
+ if (next.has(item.id)) {
11694
+ next.delete(item.id);
11695
+ if (!multiSelect) {
11696
+ setSelectedLabel(undefined);
11697
+ }
11698
+ }
11699
+ else {
11700
+ if (!multiSelect) {
11701
+ next.clear();
11702
+ setSelectedLabel(item.text);
11703
+ }
11704
+ next.set(item.id, level);
11705
+ }
11706
+ // Мультивыбор не коммитит в redux — сохранение по кнопке (onSave). Single — сразу.
11707
+ if (multiSelect) {
11708
+ setSelected(next);
11709
+ }
11710
+ else {
11711
+ commit(next);
11712
+ }
11713
+ }, [selected, commit]);
11714
+ const onSave = useCallback(() => {
11715
+ changeFilters({ [filterName]: { value: buildFilterValue(selected) } }, configFilter?.resetFilters);
11716
+ }, [changeFilters, filterName, selected, configFilter?.resetFilters]);
11717
+ const onReset = useCallback(() => {
11718
+ setSelectedLabel(undefined);
11719
+ commit(new Map());
11720
+ }, [commit]);
11721
+ const initRef = useRef(false);
11722
+ useEffect(() => {
11723
+ if (initRef.current) {
11724
+ return;
11725
+ }
11726
+ initRef.current = true;
11727
+ if (selected.size && filters[filterName] === undefined) {
11728
+ changeFilters({ [filterName]: { value: buildFilterValue(selected) } });
11729
+ }
11730
+ }, [filters, filterName, changeFilters, selected]);
11731
+ return { selected, selectedIds, selectedLabel, dirty, onToggleSelect, onReset, onSave };
11732
+ };
11733
+
11734
+ const useTreeFilterTree = ({ selected, loadLevelOne, loadByValues, loadByNames }) => {
11735
+ const [treeData, setTreeData] = useState([]);
11736
+ const [treeExpanded, setTreeExpanded] = useState([]);
11737
+ const [loading, setLoading] = useState(false);
11738
+ const loadedRef = useRef(false);
11739
+ const selectedRef = useRef(selected);
11740
+ selectedRef.current = selected;
11741
+ const onOpen = useCallback(async () => {
11742
+ if (loadedRef.current) {
11743
+ return;
11744
+ }
11745
+ loadedRef.current = true;
11746
+ setLoading(true);
11747
+ try {
11748
+ const roots = await loadLevelOne();
11749
+ const preselected = [...selectedRef.current.keys()];
11750
+ if (!preselected.length) {
11751
+ setTreeData(roots);
11752
+ return;
11753
+ }
11754
+ const selectedNodes = await loadByValues(preselected);
11755
+ const withAncestors = await collectAncestors([...roots, ...selectedNodes], loadByNames);
11756
+ const { roots: assembled, expanded } = assembleTree(withAncestors);
11757
+ setTreeData(assembled);
11758
+ setTreeExpanded(expanded);
11759
+ }
11760
+ finally {
11761
+ setLoading(false);
11762
+ }
11763
+ }, [loadLevelOne, loadByValues, loadByNames]);
11764
+ return { treeData, setTreeData, treeExpanded, setTreeExpanded, loading, onOpen };
11765
+ };
11766
+
11767
+ const useTreeFilter = (type, filter) => {
11768
+ const { filterName, multiSelect, placeholder, width } = filter.options ?? {};
11769
+ const { configFilter, loadLevelOne, loadChildren, searchNodes, loadByNames, loadByValues } = useTreeFilterData(type, filterName ?? "");
11770
+ const { selected, selectedIds, selectedLabel, dirty, onToggleSelect: toggleSelect, onReset, onSave, } = useTreeFilterSelection(type, filterName ?? "", configFilter);
11771
+ const { treeData, setTreeData, treeExpanded, setTreeExpanded, loading, onOpen } = useTreeFilterTree({
11772
+ selected,
11773
+ loadLevelOne,
11774
+ loadByValues,
11775
+ loadByNames,
11776
+ });
11777
+ const search = useTreeFilterSearch({ searchNodes, loadByNames });
11778
+ const onToggleSelect = useCallback(item => toggleSelect(item, multiSelect), [toggleSelect, multiSelect]);
11779
+ const onClose = useCallback(() => search.resetSearch(), [search]);
11780
+ const view = useMemo(() => search.isSearchActive
11781
+ ? { data: search.searchData, setData: search.setSearchData, expanded: search.searchExpanded, setExpanded: search.setSearchExpanded }
11782
+ : { data: treeData, setData: setTreeData, expanded: treeExpanded, setExpanded: setTreeExpanded }, [search.isSearchActive, search.searchData, search.setSearchData, search.searchExpanded, search.setSearchExpanded, treeData, setTreeData, treeExpanded, setTreeExpanded]);
11783
+ return {
11784
+ width: width ? `${width}px` : undefined,
11785
+ placeholder,
11786
+ multiSelect,
11787
+ loading: loading || search.searching,
11788
+ data: view.data,
11789
+ setData: view.setData,
11790
+ expanded: view.expanded,
11791
+ setExpanded: view.setExpanded,
11792
+ onLoadChildren: loadChildren,
11793
+ selectedIds,
11794
+ selectedCount: selectedIds.size,
11795
+ selectedLabel,
11796
+ searchValue: search.searchValue,
11797
+ onSearchChange: search.onSearchChange,
11798
+ onOpen,
11799
+ onClose,
11800
+ onToggleSelect,
11801
+ onReset,
11802
+ onSave,
11803
+ dirty,
11804
+ };
11805
+ };
11806
+
11807
+ const TreeFilter = ({ type, filter }) => {
11808
+ const { width, placeholder, multiSelect, loading, data, setData, expanded, setExpanded, onLoadChildren, selectedIds, selectedCount, selectedLabel, searchValue, onSearchChange, onOpen, onClose, onToggleSelect, onReset, onSave, dirty, } = useTreeFilter(type, filter);
11809
+ return (jsx(TreeDropdown, { zIndex: 100, width: width, placeholder: placeholder, multiSelect: multiSelect, loading: loading, data: data, setData: setData, expanded: expanded, setExpanded: setExpanded, onLoadChildren: onLoadChildren, selectedIds: selectedIds, selectedCount: selectedCount, selectedLabel: selectedLabel, searchValue: searchValue, onSearchChange: onSearchChange, onOpen: onOpen, onClose: onClose, onToggleSelect: onToggleSelect, onReset: onReset, onSave: onSave, dirty: dirty }));
11810
+ };
11811
+
11420
11812
  const getFilterComponent = (filterType) => {
11421
11813
  switch (filterType) {
11422
11814
  case "checkbox":
@@ -11431,6 +11823,8 @@ const getFilterComponent = (filterType) => {
11431
11823
  return TextFilter;
11432
11824
  case "chips":
11433
11825
  return ChipsFilter;
11826
+ case "tree":
11827
+ return TreeFilter;
11434
11828
  case "dropdown":
11435
11829
  default:
11436
11830
  return DropdownFilter;
@@ -12403,11 +12797,18 @@ const useDataSources = ({ type: widgetType, config, attributes, filters, layerPa
12403
12797
  ]);
12404
12798
  const getUpdatingDataSources = useCallback(() => {
12405
12799
  const diffFilterNames = filters
12406
- ? Object.keys(filters).filter(key => Array.isArray(filters[key].value)
12407
- ? filters[key].value.length !==
12408
- prevFilters.current[key]?.value?.length ||
12409
- filters[key].value.some((item, index) => item !== prevFilters.current[key]?.value?.[index])
12410
- : filters[key].value !== prevFilters.current[key]?.value)
12800
+ ? Object.keys(filters).filter(key => {
12801
+ const { value } = filters[key];
12802
+ const prevValue = prevFilters.current[key]?.value;
12803
+ if (isTreeFilterValue(value) || isTreeFilterValue(prevValue)) {
12804
+ return JSON.stringify(value) !== JSON.stringify(prevValue);
12805
+ }
12806
+ if (Array.isArray(value)) {
12807
+ return (value.length !== prevValue?.length ||
12808
+ value.some((item, index) => item !== prevValue?.[index]));
12809
+ }
12810
+ return value !== prevValue;
12811
+ })
12411
12812
  : [];
12412
12813
  if (!diffFilterNames.length)
12413
12814
  return;
@@ -13938,5 +14339,5 @@ const Map$1 = ({ zIndex, lowerSiblings, upperSiblings, onError, children, ...res
13938
14339
  }, children: children }), upperSiblings] }));
13939
14340
  };
13940
14341
 
13941
- export { ALIGNMENTS, AddFeatureButton, AddFeatureContainer, AlertIconContainer, AttachmentContainer, AttributeGalleryContainer, AttributeLabel, BASE_CONTAINER_STYLE, BaseMapTheme, CHART_TYPES, CONFIG_PAGES_ID, CONFIG_PAGE_ID, CameraContainer, Chart, ChartContainer, ChartLegend, ChartLoading, Container, ContainerChildren, ContainerLoading, ContainerTemplate, ContainerWrapper, ContainersGroupContainer, DEFAULT_ATTRIBUTE_NAME, DEFAULT_BARCHART_RADIUS, DEFAULT_BASE_MAP, DEFAULT_CHART_ANGLE, DEFAULT_CHART_HEIGHT, DEFAULT_CHART_WIDTH, DEFAULT_CIRCLE_PAINT, DEFAULT_DASHBOARD_CONFIG, DEFAULT_DATA_SOURCE_LIMIT, DEFAULT_DROPDOWN_WIDTH, DEFAULT_FILL_EXTRUSION_PAINT, DEFAULT_FILL_PAINT, DEFAULT_FILTER_PADDING, DEFAULT_ID_ATTRIBUTE_NAME, DEFAULT_LAT, DEFAULT_LINE_PAINT, DEFAULT_LNG, DEFAULT_PAGES_CONFIG, DEFAULT_PIECHART_RADIUS, DEFAULT_ZOOM, Dashboard, DashboardCheckbox, DashboardChip, DashboardContent, DashboardContext, DashboardDefaultHeader, DashboardHeader, DashboardLoading, DashboardPlaceholder, DashboardPlaceholderWrap, DashboardProvider, DashboardWrapper, DataSourceContainer, DataSourceError, DataSourceErrorContainer, DataSourceInnerContainer, DataSourceProgressContainer, DateFormat, DefaultAttributesContainer, DefaultHeaderContainer, DefaultHeaderWrapper, DividerContainer, EditGeometryType, ElementButton, ElementCamera, ElementChart, ElementChips, ElementControl, ElementIcon, ElementImage, ElementLegend, ElementLink, ElementMarkdown, ElementSlideshow, ElementSvg, ElementTooltip, ElementValueWrapper, ExpandableTitle, FEATURE_CARD_DEFAULT_COLORS, FEATURE_CARD_OTHER_COLOR, FILTERED_VALUE_OPACITY, FILTER_PREFIX, FeatureCardBackgroundHeader, FeatureCardButtons, FeatureCardContext, FeatureCardDefaultHeader, FeatureCardHeader, FeatureCardProvider, FeatureCardSlideshowHeader, FeatureCardTitle, FeatureControls, FeatureTitleContainer, FiltersContainer, GEOMETRY_ATTRIBUTE, GlobalContext, GlobalProvider, Header, HeaderContainer, HeaderFontColorMixin, HeaderFrontView, HeaderTemplate, HeaderTitleContainer, HiddenTitleItems, IconContainer, ImageContainer, LEFT_PANEL_HEADER_HEIGHT, Layer, LayerDescription, LayerGroup, LayerGroupList, LayerIcon, LayerIconContainer, LayerListContainer, LayerTree, LayersContainer, LayersListWrapper, LinearProgressContainer, LogTerminal, LogoContainer, MAX_CHART_WIDTH, Map$1 as Map, MapContext, MapProvider, NO_CONTENT_VALUE, NUMERIC_ATTRIBUTE_TYPES, NoLiveSnapshotContainer, OneColumnContainer, POLL_SUBTASK_INTERVAL_MS, POLL_SUBTASK_TIMEOUT_MS, PROVIDER_PREFIX, PageNavigator, PageTitle, PageTitleContainer, PagesContainer, Pagination, PresentationHeader, PresentationHeaderButtons, PresentationHeaderTools, PresentationPanelContainer, PresentationPanelWrapper, PresentationWrapper, ProgressContainer, ProviderPrefix, RoundedBackgroundContainer, SAVE_HOOK_RESULT_DURATION, SERVER_NOTIFICATION_EVENT, STACK_BAR_TOTAL_HEIGHT, ScalingFactor, ServerNotificationsContext, ServerNotificationsProvider, SlideshowContainer, SmallPreviewContainer$1 as SmallPreviewContainer, SmallPreviewControl, SmallPreviewCounter, SmallPreviewImages, SmallPreviewLeft, SmallPreviewRight, StackBar, SvgImage, TIME_ZONE_FORMAT, TabsContainer, TextTrim, ThemeName, TitleContainer, TopContainer, TopContainerButtons, TwoColumnContainer, UploadContainer, VIEW_MODES, WidgetType, addDataSource, addDataSources, adjustColor, applyFiltersToCondition, applyQueryFilters, applyVarsToCondition, asAttributeName, asChartId, asContainerId, asDataSourceName, asFilterName, asLayerName, asModalId, asResourceId, asTabId, checkEqualOrIncludes, checkIsLoading, createConfigLayer, createConfigPage, createNewPageId, createSaveNotificationId, createTreeNode, dateOptions, debounce, decimalOpacityToHex, eqlParametersToPayload, findAttributeInExpression, formatArea, formatAttributeValue, formatChartRelatedValue, formatConditionValue, formatDataSourceCondition, formatDate$1 as formatDate, formatElementValue, formatLength, formatNumber, formatPolygonMeasure, geometryToEwkt, getActualExtrusionHeight, getAttributeByName, getAttributeValue, getAttributesConfiguration, getChartAxes, getChartFilterName, getChartMarkers, getConfigFilter, getContainerComponent, getDashboardHeader, getDataFromAttributes, getDataFromRelatedFeatures, getDataSource, getDataSourceFilterValue, getDate, getDefaultConfig, getDisplayTemplateNameFromAttribute, getElementValue, getFeatureAttributes, getFeatureCardHeader, getFilterComponent, getFilterSelectedItems, getFilterValue, getFormattedAttributes, getGradientColors, getLayerInfo, getLayerInfoFromDataSources, getPagesFromConfig, getPagesFromProjectInfo, getProxyService, getRelatedAttribute, getRenderElement, getResourceUrl, getRootElementId, getSelectedFilterValue, getSlideshowImages, getSvgUrl, getTemplateNameFromAttribute, getThemeByName, getTotalFromAttributes, getTotalFromRelatedFeatures, hexToRgba, isEmptyElementValue, isEmptyValue, isHiddenEmptyValue, isHookActive, isLayerService, isNotValidSelectedTab, isNumeric, isObject, isProxyService, isVisibleContainer, metersPerPixel, numberOptions, parseClientStyle, parseIconNames, parseIconNamesFromClientStyle, pieChartTooltipFromAttributes, pieChartTooltipFromRelatedFeatures, pointOptions, removeDataSource, rgbToHex, roundTotalSum, sliceShownOtherItems, timeOptions, toRenderableValue, tooltipNameFromAttributes, tooltipValueFromAttributes, tooltipValueFromRelatedFeatures, transparentizeColor, treeNodesToProjectItems, updateDataSource, useAfterSave, useAppHeight, useAttachmentItems, useAttachmentPreviewImages, useAutoCompleteControl, useBeforeSave, useChartChange, useChartData, useContainerAttributes, useCurrentPageLayers, useCustomFeatureSelect, useDashboardHeader, useDataSources, useDebouncedCallback, useDiffPage, useEditGroupAttributes, useExpandableContainers, useExportPdf, useFeatureSaveHooks, useFetchImageWithAuth, useFetchWithAuth, useGetConfigLayer, useGlobalContext, useHeaderRender, useHideIfEmptyDataSource, useIconsFromLayers, useLayerHiddenAttributes, useLayerParams, useMapContext, useMapDraw, useMapImages, useMaxZoomTo, useProjectDashboardInit, usePythonSandbox, usePythonTask, useRedrawLayer, useRelatedDataSourceAttributes, useRemoteTask, useRenderElement, useSavePrototypeBuilder, useServerNotificationsContext, useShownOtherItems, useToggle, useUpdateDataSource, useVisibleProjectItems, useWidgetConfig, useWidgetContext, useWidgetFilters, useWidgetPage, useWindowResize, useZoomToFeatures, useZoomToPoint };
14342
+ export { ALIGNMENTS, AddFeatureButton, AddFeatureContainer, AlertIconContainer, AttachmentContainer, AttributeGalleryContainer, AttributeLabel, BASE_CONTAINER_STYLE, BaseMapTheme, CHART_TYPES, CONFIG_PAGES_ID, CONFIG_PAGE_ID, CameraContainer, Chart, ChartContainer, ChartLegend, ChartLoading, Container, ContainerChildren, ContainerLoading, ContainerTemplate, ContainerWrapper, ContainersGroupContainer, DEFAULT_ATTRIBUTE_NAME, DEFAULT_BARCHART_RADIUS, DEFAULT_BASE_MAP, DEFAULT_CHART_ANGLE, DEFAULT_CHART_HEIGHT, DEFAULT_CHART_WIDTH, DEFAULT_CIRCLE_PAINT, DEFAULT_DASHBOARD_CONFIG, DEFAULT_DATA_SOURCE_LIMIT, DEFAULT_DROPDOWN_WIDTH, DEFAULT_FILL_EXTRUSION_PAINT, DEFAULT_FILL_PAINT, DEFAULT_FILTER_PADDING, DEFAULT_ID_ATTRIBUTE_NAME, DEFAULT_LAT, DEFAULT_LINE_PAINT, DEFAULT_LNG, DEFAULT_PAGES_CONFIG, DEFAULT_PIECHART_RADIUS, DEFAULT_ZOOM, Dashboard, DashboardCheckbox, DashboardChip, DashboardContent, DashboardContext, DashboardDefaultHeader, DashboardHeader, DashboardLoading, DashboardPlaceholder, DashboardPlaceholderWrap, DashboardProvider, DashboardWrapper, DataSourceContainer, DataSourceError, DataSourceErrorContainer, DataSourceInnerContainer, DataSourceProgressContainer, DateFormat, DefaultAttributesContainer, DefaultHeaderContainer, DefaultHeaderWrapper, DividerContainer, EditGeometryType, ElementButton, ElementCamera, ElementChart, ElementChips, ElementControl, ElementIcon, ElementImage, ElementLegend, ElementLink, ElementMarkdown, ElementSlideshow, ElementSvg, ElementTooltip, ElementValueWrapper, ExpandableTitle, FEATURE_CARD_DEFAULT_COLORS, FEATURE_CARD_OTHER_COLOR, FILTERED_VALUE_OPACITY, FILTER_PREFIX, FeatureCardBackgroundHeader, FeatureCardButtons, FeatureCardContext, FeatureCardDefaultHeader, FeatureCardHeader, FeatureCardProvider, FeatureCardSlideshowHeader, FeatureCardTitle, FeatureControls, FeatureTitleContainer, FiltersContainer, GEOMETRY_ATTRIBUTE, GlobalContext, GlobalProvider, Header, HeaderContainer, HeaderFontColorMixin, HeaderFrontView, HeaderTemplate, HeaderTitleContainer, HiddenTitleItems, IconContainer, ImageContainer, LEFT_PANEL_HEADER_HEIGHT, Layer, LayerDescription, LayerGroup, LayerGroupList, LayerIcon, LayerIconContainer, LayerListContainer, LayerTree, LayersContainer, LayersListWrapper, LinearProgressContainer, LogTerminal, LogoContainer, MAX_CHART_WIDTH, Map$1 as Map, MapContext, MapProvider, NO_CONTENT_VALUE, NUMERIC_ATTRIBUTE_TYPES, NoLiveSnapshotContainer, OneColumnContainer, POLL_SUBTASK_INTERVAL_MS, POLL_SUBTASK_TIMEOUT_MS, PROVIDER_PREFIX, PageNavigator, PageTitle, PageTitleContainer, PagesContainer, Pagination, PresentationHeader, PresentationHeaderButtons, PresentationHeaderTools, PresentationPanelContainer, PresentationPanelWrapper, PresentationWrapper, ProgressContainer, ProviderPrefix, RoundedBackgroundContainer, SAVE_HOOK_RESULT_DURATION, SERVER_NOTIFICATION_EVENT, STACK_BAR_TOTAL_HEIGHT, ScalingFactor, ServerNotificationsContext, ServerNotificationsProvider, SlideshowContainer, SmallPreviewContainer$1 as SmallPreviewContainer, SmallPreviewControl, SmallPreviewCounter, SmallPreviewImages, SmallPreviewLeft, SmallPreviewRight, StackBar, SvgImage, TIME_ZONE_FORMAT, TabsContainer, TextTrim, ThemeName, TitleContainer, TopContainer, TopContainerButtons, TwoColumnContainer, UploadContainer, VIEW_MODES, WidgetType, addDataSource, addDataSources, adjustColor, applyFiltersToCondition, applyQueryFilters, applyTreeFilterToCondition, applyVarsToCondition, asAttributeName, asChartId, asContainerId, asDataSourceName, asFilterName, asLayerName, asModalId, asResourceId, asTabId, checkEqualOrIncludes, checkIsLoading, createConfigLayer, createConfigPage, createNewPageId, createSaveNotificationId, createTreeNode, dateOptions, debounce, decimalOpacityToHex, eqlParametersToPayload, findAttributeInExpression, formatArea, formatAttributeValue, formatChartRelatedValue, formatConditionValue, formatDataSourceCondition, formatDate$1 as formatDate, formatElementValue, formatLength, formatNumber, formatPolygonMeasure, geometryToEwkt, getActualExtrusionHeight, getAttributeByName, getAttributeValue, getAttributesConfiguration, getChartAxes, getChartFilterName, getChartMarkers, getConfigFilter, getContainerComponent, getDashboardHeader, getDataFromAttributes, getDataFromRelatedFeatures, getDataSource, getDataSourceFilterValue, getDate, getDefaultConfig, getDisplayTemplateNameFromAttribute, getElementValue, getFeatureAttributes, getFeatureCardHeader, getFilterComponent, getFilterSelectedItems, getFilterValue, getFormattedAttributes, getGradientColors, getLayerInfo, getLayerInfoFromDataSources, getPagesFromConfig, getPagesFromProjectInfo, getProxyService, getRelatedAttribute, getRenderElement, getResourceUrl, getRootElementId, getSelectedFilterValue, getSlideshowImages, getSvgUrl, getTemplateNameFromAttribute, getThemeByName, getTotalFromAttributes, getTotalFromRelatedFeatures, hexToRgba, isEmptyElementValue, isEmptyValue, isHiddenEmptyValue, isHookActive, isLayerService, isNotValidSelectedTab, isNumeric, isObject, isProxyService, isTreeFilterValue, isVisibleContainer, metersPerPixel, numberOptions, parseClientStyle, parseIconNames, parseIconNamesFromClientStyle, pieChartTooltipFromAttributes, pieChartTooltipFromRelatedFeatures, pointOptions, removeDataSource, rgbToHex, roundTotalSum, sliceShownOtherItems, timeOptions, toRenderableValue, tooltipNameFromAttributes, tooltipValueFromAttributes, tooltipValueFromRelatedFeatures, transparentizeColor, treeNodesToProjectItems, updateDataSource, useAfterSave, useAppHeight, useAttachmentItems, useAttachmentPreviewImages, useAutoCompleteControl, useBeforeSave, useChartChange, useChartData, useContainerAttributes, useCurrentPageLayers, useCustomFeatureSelect, useDashboardHeader, useDataSources, useDebouncedCallback, useDiffPage, useEditGroupAttributes, useExpandableContainers, useExportPdf, useFeatureSaveHooks, useFetchImageWithAuth, useFetchWithAuth, useGetConfigLayer, useGlobalContext, useHeaderRender, useHideIfEmptyDataSource, useIconsFromLayers, useLayerHiddenAttributes, useLayerParams, useMapContext, useMapDraw, useMapImages, useMaxZoomTo, useProjectDashboardInit, usePythonSandbox, usePythonTask, useRedrawLayer, useRelatedDataSourceAttributes, useRemoteTask, useRenderElement, useSavePrototypeBuilder, useServerNotificationsContext, useShownOtherItems, useToggle, useUpdateDataSource, useVisibleProjectItems, useWidgetConfig, useWidgetContext, useWidgetFilters, useWidgetPage, useWindowResize, useZoomToFeatures, useZoomToPoint };
13942
14343
  //# sourceMappingURL=react.esm.js.map