@evergis/react 4.0.73 → 4.0.76

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,
@@ -8964,6 +8989,11 @@ const OverlayHeaderMixin = (overlay) => css `
8964
8989
  }
8965
8990
  }
8966
8991
  `;
8992
+ const NoFeatureHeaderMixin = css `
8993
+ &&& {
8994
+ min-height: 5.5rem;
8995
+ }
8996
+ `;
8967
8997
  const Header = styled(Flex) `
8968
8998
  z-index: 1;
8969
8999
  position: relative;
@@ -8976,6 +9006,8 @@ const Header = styled(Flex) `
8976
9006
  ${({ $isRow }) => $isRow && RowHeaderMixin};
8977
9007
 
8978
9008
  ${({ $overlay }) => $overlay && OverlayHeaderMixin($overlay)};
9009
+
9010
+ ${({ $noFeature }) => $noFeature && NoFeatureHeaderMixin};
8979
9011
  `;
8980
9012
  const DefaultHeaderWrapper = styled.div `
8981
9013
  width: ${({ withPadding }) => (withPadding ? "100%" : "calc(100% + 1rem)")};
@@ -8984,6 +9016,12 @@ const DefaultHeaderWrapper = styled.div `
8984
9016
  background: url(${img$4}) 50% -2rem no-repeat;
8985
9017
  border-radius: ${({ theme: { borderRadius } }) => borderRadius.medium};
8986
9018
 
9019
+ ${({ $noFeature }) => $noFeature &&
9020
+ css `
9021
+ background-position: center;
9022
+ background-size: cover;
9023
+ `};
9024
+
8987
9025
  ${({ fontColor }) => !!fontColor && HeaderFontColorMixin};
8988
9026
  `;
8989
9027
 
@@ -8992,7 +9030,9 @@ const HeaderTitle = ({ noFeature }) => {
8992
9030
  const { attributes, layerInfo, feature } = useWidgetContext(WidgetType.FeatureCard);
8993
9031
  const zoomToFeatures = useZoomToFeatures();
8994
9032
  const { configuration } = layerInfo || {};
8995
- const resultDescription = configuration?.alias || configuration?.name || "";
9033
+ const resultDescription = noFeature
9034
+ ? t("allLayers", { ns: "dashboard", defaultValue: "Все слои" })
9035
+ : configuration?.alias || configuration?.name || "";
8996
9036
  const resultTitle = useMemo(() => {
8997
9037
  const layerDefinitionAttribute = configuration && attributes?.length
8998
9038
  ? attributes.find(item => item.attributeName === configuration?.attributesConfiguration?.titleAttribute)
@@ -9073,14 +9113,32 @@ const LayerIconClickable = styled.div `
9073
9113
  align-items: center;
9074
9114
  cursor: pointer;
9075
9115
  `;
9116
+ const NoFeatureIcon = styled.div `
9117
+ display: flex;
9118
+ align-items: center;
9119
+ justify-content: center;
9120
+ min-width: 1.5rem;
9121
+ height: 1.5rem;
9122
+ margin-top: 0.25rem;
9123
+ margin-right: 1rem;
9124
+ margin-left: 0.25rem;
9125
+
9126
+ ${Icon}::after {
9127
+ font-size: 1.5rem;
9128
+ color: ${({ theme: { palette } }) => palette.iconDisabled};
9129
+ }
9130
+ `;
9076
9131
 
9077
- const HeaderLayerIcon = () => {
9132
+ const HeaderLayerIcon = ({ noFeature }) => {
9078
9133
  const { t } = useGlobalContext();
9079
9134
  const { layerInfo, feature } = useWidgetContext(WidgetType.FeatureCard);
9080
9135
  const zoomToFeatures = useZoomToFeatures();
9081
9136
  const getMaxZoomTo = useMaxZoomTo();
9082
9137
  const [optionsMaxZoomTo, layerMaxZoomTo] = useMemo(() => getMaxZoomTo(layerInfo?.name), [layerInfo?.name, getMaxZoomTo]);
9083
9138
  const handleIconClick = useCallback(() => zoomToFeatures([feature], { maxZoom: layerMaxZoomTo ?? optionsMaxZoomTo }), [zoomToFeatures, feature, layerMaxZoomTo, optionsMaxZoomTo]);
9139
+ if (noFeature) {
9140
+ return (jsx(NoFeatureIcon, { children: jsx(Icon, { kind: "no_geom" }) }));
9141
+ }
9084
9142
  return (jsx(LayerIconClickable, { onClick: handleIconClick, children: jsx(Tooltip$1, { arrow: true, placement: "top", content: t("zoomToFeature", { ns: "dashboard", defaultValue: "Приблизить к объекту" }), delay: [600, 0], children: ref => (jsx(LayerIcon, { innerRef: ref, layerInfo: layerInfo })) }) }));
9085
9143
  };
9086
9144
 
@@ -9089,7 +9147,7 @@ const FeatureCardDefaultHeader = ({ noFeature }) => {
9089
9147
  const { header } = config || {};
9090
9148
  const { options } = header || {};
9091
9149
  const { themeName, withPadding, column, height, overlay } = options || {};
9092
- return (jsx(DefaultHeaderWrapper, { withPadding: withPadding, height: height, children: jsx(ThemeProvider, { theme: getThemeByName(themeName), children: jsx(Header, { "$overlay": overlay, "$isRow": !column, children: jsxs(HeaderFrontView, { isDefault: !column, children: [jsxs(HeaderContainer, { children: [jsx(HeaderLayerIcon, {}), jsx(HeaderTitle, { noFeature: noFeature })] }), jsx(FeatureCardButtons, {})] }) }) }) }));
9150
+ return (jsx(DefaultHeaderWrapper, { withPadding: withPadding, height: height, "$noFeature": noFeature, children: jsx(ThemeProvider, { theme: getThemeByName(themeName), children: jsx(Header, { "$overlay": overlay, "$isRow": !column, "$noFeature": noFeature, children: jsxs(HeaderFrontView, { isDefault: !column, children: [jsxs(HeaderContainer, { children: [jsx(HeaderLayerIcon, { noFeature: noFeature }), jsx(HeaderTitle, { noFeature: noFeature })] }), jsx(FeatureCardButtons, {})] }) }) }) }));
9093
9151
  };
9094
9152
 
9095
9153
  const ImageContainerButton = styled(FlatButton) `
@@ -11308,7 +11366,7 @@ const ChipsFilter = ({ type, filter, elementConfig, }) => {
11308
11366
  icon: chipIcon,
11309
11367
  };
11310
11368
  });
11311
- }, [configFilter, dataSources, colorAttribute, iconAttribute, theme]);
11369
+ }, [variants, configFilter, dataSources, iconAttribute, colorAttribute, theme]);
11312
11370
  const isChipActive = useCallback((chipValue) => {
11313
11371
  const currentValue = filters?.[filterName]?.value;
11314
11372
  if (currentValue === undefined) {
@@ -11384,6 +11442,339 @@ function getIconFromAttribute(option, iconAttribute) {
11384
11442
  return getResourceUrl(iconValue);
11385
11443
  }
11386
11444
 
11445
+ const MAX_ANCESTOR_DEPTH = 50;
11446
+ const buildLevelOneCondition = (attributeLevel) => `${attributeLevel} = 1`;
11447
+ const buildChildrenCondition = (attributeParentValue, parentId) => `${attributeParentValue} = ${formatConditionValue({ value: parentId })}`;
11448
+ const buildSearchCondition = (attributeAlias, query) => `${attributeAlias} LIKE '%${query.replace(/'/g, "''")}%'`;
11449
+ const buildIdsCondition = (attributeValue, ids) => `${attributeValue} in ${formatConditionValue({ value: ids })}`;
11450
+ /** Группирует выбранные id по уровню в объектное значение фильтра `{ l{N}: [ids] }`. */
11451
+ const buildFilterValue = (selected) => {
11452
+ const result = {};
11453
+ selected.forEach((level, id) => {
11454
+ const key = `l${level}`;
11455
+ if (!result[key]) {
11456
+ result[key] = [];
11457
+ }
11458
+ result[key].push(id);
11459
+ });
11460
+ return result;
11461
+ };
11462
+ /** Разбирает объектное значение фильтра в карту `id → level`. */
11463
+ const parseFilterValue = (value) => {
11464
+ const result = new Map();
11465
+ if (!value) {
11466
+ return result;
11467
+ }
11468
+ Object.keys(value).forEach(levelKey => {
11469
+ const level = Number(levelKey.replace(/^l/, ""));
11470
+ value[levelKey]?.forEach(id => result.set(id, level));
11471
+ });
11472
+ return result;
11473
+ };
11474
+ /**
11475
+ * Дозапрашивает цепочку предков вверх по `parentId` уровень за уровнем (батч `id in (...)`),
11476
+ * пока не достигнет уровня 1. Возвращает исходные узлы вместе с предками.
11477
+ */
11478
+ const collectAncestors = async (nodes, loadByIds) => {
11479
+ const byId = new Map();
11480
+ nodes.forEach(node => byId.set(node.id, node));
11481
+ let frontier = nodes;
11482
+ for (let depth = 0; depth < MAX_ANCESTOR_DEPTH; depth++) {
11483
+ const missingParents = new Set();
11484
+ frontier.forEach(node => {
11485
+ const { parentId, level } = node.data ?? {};
11486
+ if (parentId != null && level > 1 && !byId.has(parentId)) {
11487
+ missingParents.add(parentId);
11488
+ }
11489
+ });
11490
+ if (!missingParents.size) {
11491
+ break;
11492
+ }
11493
+ const parents = await loadByIds([...missingParents]);
11494
+ if (!parents.length) {
11495
+ break;
11496
+ }
11497
+ parents.forEach(parent => byId.set(parent.id, parent));
11498
+ frontier = parents;
11499
+ }
11500
+ return [...byId.values()];
11501
+ };
11502
+ /**
11503
+ * Собирает плоский набор узлов в дерево по `parentId`. Узлы с подгруженными потомками
11504
+ * раскрываются; листья-папки без потомков получают `children = null` (ленивая подгрузка).
11505
+ */
11506
+ const assembleTree = (nodes) => {
11507
+ const nodesById = new Map();
11508
+ nodes.forEach(node => nodesById.set(node.id, node));
11509
+ const childrenMap = new Map();
11510
+ nodesById.forEach(node => {
11511
+ const parentId = node.data?.parentId;
11512
+ if (parentId != null && nodesById.has(parentId)) {
11513
+ const siblings = childrenMap.get(parentId) ?? [];
11514
+ siblings.push(node);
11515
+ childrenMap.set(parentId, siblings);
11516
+ }
11517
+ });
11518
+ const roots = [];
11519
+ const expanded = [];
11520
+ nodesById.forEach(node => {
11521
+ const kids = childrenMap.get(node.id);
11522
+ if (kids?.length) {
11523
+ node.children = kids;
11524
+ expanded.push(node.id);
11525
+ }
11526
+ else if (node.isLeaf) {
11527
+ node.children = null;
11528
+ }
11529
+ const parentId = node.data?.parentId;
11530
+ if (parentId == null || !nodesById.has(parentId)) {
11531
+ roots.push(node);
11532
+ }
11533
+ });
11534
+ return { roots, expanded };
11535
+ };
11536
+
11537
+ const useTreeFilterData = (type, filterName) => {
11538
+ const { api } = useGlobalContext();
11539
+ const { currentPage } = useWidgetPage(type);
11540
+ const configFilter = useMemo(() => getConfigFilter(filterName, currentPage?.filters), [filterName, currentPage?.filters]);
11541
+ const { relatedDataSource, attributeValue = DEFAULT_ATTRIBUTE_NAME, attributeAlias = DEFAULT_ATTRIBUTE_NAME, attributeParentValue, attributeLevel, attributeHasChildren, limit = DEFAULT_DATA_SOURCE_LIMIT, } = configFilter ?? {};
11542
+ const layerName = useMemo(() => currentPage?.dataSources?.find(({ name }) => name === relatedDataSource)?.layerName, [currentPage?.dataSources, relatedDataSource]);
11543
+ const mapNode = useCallback(({ properties }) => {
11544
+ const hasChildren = attributeHasChildren ? !!properties[attributeHasChildren] : false;
11545
+ const data = {
11546
+ parentId: attributeParentValue ? properties[attributeParentValue] ?? null : null,
11547
+ level: attributeLevel ? Number(properties[attributeLevel]) : 1,
11548
+ };
11549
+ return {
11550
+ id: properties[attributeValue],
11551
+ text: String(properties[attributeAlias] ?? ""),
11552
+ isLeaf: hasChildren,
11553
+ children: hasChildren ? null : undefined,
11554
+ data,
11555
+ };
11556
+ }, [attributeValue, attributeAlias, attributeParentValue, attributeLevel, attributeHasChildren]);
11557
+ const runQuery = useCallback(async (condition) => {
11558
+ if (!layerName) {
11559
+ return [];
11560
+ }
11561
+ const response = await api.layers.getFeatures(layerName, { withGeom: false, limit, conditions: [condition] });
11562
+ return response.features ?? [];
11563
+ }, [api, layerName, limit]);
11564
+ const loadLevelOne = useCallback(async () => {
11565
+ if (!attributeLevel) {
11566
+ return [];
11567
+ }
11568
+ const features = await runQuery(buildLevelOneCondition(attributeLevel));
11569
+ return features.map(mapNode);
11570
+ }, [attributeLevel, runQuery, mapNode]);
11571
+ const loadChildren = useCallback(async (item) => {
11572
+ if (!attributeParentValue) {
11573
+ return { children: [] };
11574
+ }
11575
+ const features = await runQuery(buildChildrenCondition(attributeParentValue, item.id));
11576
+ return { children: features.map(mapNode) };
11577
+ }, [attributeParentValue, runQuery, mapNode]);
11578
+ const searchNodes = useCallback(async (query) => {
11579
+ const features = await runQuery(buildSearchCondition(attributeAlias, query));
11580
+ return features.map(mapNode);
11581
+ }, [attributeAlias, runQuery, mapNode]);
11582
+ const loadByIds = useCallback(async (ids) => {
11583
+ if (!ids.length) {
11584
+ return [];
11585
+ }
11586
+ const features = await runQuery(buildIdsCondition(attributeValue, ids));
11587
+ return features.map(mapNode);
11588
+ }, [attributeValue, runQuery, mapNode]);
11589
+ return { configFilter, layerName, loadLevelOne, loadChildren, searchNodes, loadByIds };
11590
+ };
11591
+
11592
+ const SEARCH_MIN_LENGTH = 3;
11593
+ const SEARCH_DEBOUNCE = 300;
11594
+ const useTreeFilterSearch = ({ searchNodes, loadByIds }) => {
11595
+ const [searchValue, setSearchValue] = useState("");
11596
+ const [searchData, setSearchData] = useState([]);
11597
+ const [searchExpanded, setSearchExpanded] = useState([]);
11598
+ const [searching, setSearching] = useState(false);
11599
+ const timer = useRef();
11600
+ const requestId = useRef(0);
11601
+ const isSearchActive = searchValue.trim().length >= SEARCH_MIN_LENGTH;
11602
+ const runSearch = useCallback(async (query) => {
11603
+ const id = ++requestId.current;
11604
+ setSearching(true);
11605
+ try {
11606
+ const results = await searchNodes(query);
11607
+ const withAncestors = await collectAncestors(results, loadByIds);
11608
+ const { roots, expanded } = assembleTree(withAncestors);
11609
+ if (id !== requestId.current) {
11610
+ return;
11611
+ }
11612
+ setSearchData(roots);
11613
+ setSearchExpanded(expanded);
11614
+ }
11615
+ finally {
11616
+ if (id === requestId.current) {
11617
+ setSearching(false);
11618
+ }
11619
+ }
11620
+ }, [searchNodes, loadByIds]);
11621
+ const clearSearchState = useCallback(() => {
11622
+ requestId.current++;
11623
+ setSearchData([]);
11624
+ setSearchExpanded([]);
11625
+ setSearching(false);
11626
+ }, []);
11627
+ const onSearchChange = useCallback((value) => {
11628
+ setSearchValue(value);
11629
+ if (timer.current) {
11630
+ clearTimeout(timer.current);
11631
+ }
11632
+ const query = value.trim();
11633
+ if (query.length < SEARCH_MIN_LENGTH) {
11634
+ clearSearchState();
11635
+ return;
11636
+ }
11637
+ timer.current = setTimeout(() => runSearch(query), SEARCH_DEBOUNCE);
11638
+ }, [runSearch, clearSearchState]);
11639
+ const resetSearch = useCallback(() => {
11640
+ if (timer.current) {
11641
+ clearTimeout(timer.current);
11642
+ }
11643
+ setSearchValue("");
11644
+ clearSearchState();
11645
+ }, [clearSearchState]);
11646
+ return {
11647
+ searchValue,
11648
+ isSearchActive,
11649
+ searching,
11650
+ searchData,
11651
+ setSearchData,
11652
+ searchExpanded,
11653
+ setSearchExpanded,
11654
+ onSearchChange,
11655
+ resetSearch,
11656
+ };
11657
+ };
11658
+
11659
+ const useTreeFilterSelection = (type, filterName, configFilter) => {
11660
+ const { filters, changeFilters } = useWidgetContext(type);
11661
+ const [selected, setSelected] = useState(() => parseFilterValue(configFilter?.defaultValue));
11662
+ const [selectedLabel, setSelectedLabel] = useState();
11663
+ const selectedIds = useMemo(() => new Set(selected.keys()), [selected]);
11664
+ const commit = useCallback((next) => {
11665
+ setSelected(next);
11666
+ changeFilters({ [filterName]: { value: buildFilterValue(next) } }, configFilter?.resetFilters);
11667
+ }, [changeFilters, filterName, configFilter?.resetFilters]);
11668
+ const onToggleSelect = useCallback((item, multiSelect) => {
11669
+ const level = item.data?.level ?? 1;
11670
+ const next = new Map(selected);
11671
+ if (next.has(item.id)) {
11672
+ next.delete(item.id);
11673
+ if (!multiSelect) {
11674
+ setSelectedLabel(undefined);
11675
+ }
11676
+ }
11677
+ else {
11678
+ if (!multiSelect) {
11679
+ next.clear();
11680
+ setSelectedLabel(item.text);
11681
+ }
11682
+ next.set(item.id, level);
11683
+ }
11684
+ commit(next);
11685
+ }, [selected, commit]);
11686
+ const onReset = useCallback(() => {
11687
+ setSelectedLabel(undefined);
11688
+ commit(new Map());
11689
+ }, [commit]);
11690
+ const initRef = useRef(false);
11691
+ useEffect(() => {
11692
+ if (initRef.current) {
11693
+ return;
11694
+ }
11695
+ initRef.current = true;
11696
+ if (selected.size && filters[filterName] === undefined) {
11697
+ changeFilters({ [filterName]: { value: buildFilterValue(selected) } });
11698
+ }
11699
+ }, [filters, filterName, changeFilters, selected]);
11700
+ return { selected, selectedIds, selectedLabel, onToggleSelect, onReset };
11701
+ };
11702
+
11703
+ const useTreeFilterTree = ({ selected, loadLevelOne, loadByIds }) => {
11704
+ const [treeData, setTreeData] = useState([]);
11705
+ const [treeExpanded, setTreeExpanded] = useState([]);
11706
+ const [loading, setLoading] = useState(false);
11707
+ const loadedRef = useRef(false);
11708
+ const selectedRef = useRef(selected);
11709
+ selectedRef.current = selected;
11710
+ const onOpen = useCallback(async () => {
11711
+ if (loadedRef.current) {
11712
+ return;
11713
+ }
11714
+ loadedRef.current = true;
11715
+ setLoading(true);
11716
+ try {
11717
+ const roots = await loadLevelOne();
11718
+ const preselected = [...selectedRef.current.keys()];
11719
+ if (!preselected.length) {
11720
+ setTreeData(roots);
11721
+ return;
11722
+ }
11723
+ const selectedNodes = await loadByIds(preselected);
11724
+ const withAncestors = await collectAncestors([...roots, ...selectedNodes], loadByIds);
11725
+ const { roots: assembled, expanded } = assembleTree(withAncestors);
11726
+ setTreeData(assembled);
11727
+ setTreeExpanded(expanded);
11728
+ }
11729
+ finally {
11730
+ setLoading(false);
11731
+ }
11732
+ }, [loadLevelOne, loadByIds]);
11733
+ return { treeData, setTreeData, treeExpanded, setTreeExpanded, loading, onOpen };
11734
+ };
11735
+
11736
+ const useTreeFilter = (type, filter) => {
11737
+ const { filterName, multiSelect, placeholder, width } = filter.options ?? {};
11738
+ const { configFilter, loadLevelOne, loadChildren, searchNodes, loadByIds } = useTreeFilterData(type, filterName ?? "");
11739
+ const { selected, selectedIds, selectedLabel, onToggleSelect: toggleSelect, onReset } = useTreeFilterSelection(type, filterName ?? "", configFilter);
11740
+ const { treeData, setTreeData, treeExpanded, setTreeExpanded, loading, onOpen } = useTreeFilterTree({
11741
+ selected,
11742
+ loadLevelOne,
11743
+ loadByIds,
11744
+ });
11745
+ const search = useTreeFilterSearch({ searchNodes, loadByIds });
11746
+ const onToggleSelect = useCallback(item => toggleSelect(item, multiSelect), [toggleSelect, multiSelect]);
11747
+ const onClose = useCallback(() => search.resetSearch(), [search]);
11748
+ const view = useMemo(() => search.isSearchActive
11749
+ ? { data: search.searchData, setData: search.setSearchData, expanded: search.searchExpanded, setExpanded: search.setSearchExpanded }
11750
+ : { data: treeData, setData: setTreeData, expanded: treeExpanded, setExpanded: setTreeExpanded }, [search.isSearchActive, search.searchData, search.setSearchData, search.searchExpanded, search.setSearchExpanded, treeData, setTreeData, treeExpanded, setTreeExpanded]);
11751
+ return {
11752
+ width: width ? `${width}px` : undefined,
11753
+ placeholder,
11754
+ multiSelect,
11755
+ loading: loading || search.searching,
11756
+ data: view.data,
11757
+ setData: view.setData,
11758
+ expanded: view.expanded,
11759
+ setExpanded: view.setExpanded,
11760
+ onLoadChildren: loadChildren,
11761
+ selectedIds,
11762
+ selectedCount: selectedIds.size,
11763
+ selectedLabel,
11764
+ searchValue: search.searchValue,
11765
+ onSearchChange: search.onSearchChange,
11766
+ onOpen,
11767
+ onClose,
11768
+ onToggleSelect,
11769
+ onReset,
11770
+ };
11771
+ };
11772
+
11773
+ const TreeFilter = ({ type, filter }) => {
11774
+ const { width, placeholder, multiSelect, loading, data, setData, expanded, setExpanded, onLoadChildren, selectedIds, selectedCount, selectedLabel, searchValue, onSearchChange, onOpen, onClose, onToggleSelect, onReset, } = useTreeFilter(type, filter);
11775
+ return (jsx(TreeDropdown, { 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 }));
11776
+ };
11777
+
11387
11778
  const getFilterComponent = (filterType) => {
11388
11779
  switch (filterType) {
11389
11780
  case "checkbox":
@@ -11398,6 +11789,8 @@ const getFilterComponent = (filterType) => {
11398
11789
  return TextFilter;
11399
11790
  case "chips":
11400
11791
  return ChipsFilter;
11792
+ case "tree":
11793
+ return TreeFilter;
11401
11794
  case "dropdown":
11402
11795
  default:
11403
11796
  return DropdownFilter;
@@ -12370,11 +12763,18 @@ const useDataSources = ({ type: widgetType, config, attributes, filters, layerPa
12370
12763
  ]);
12371
12764
  const getUpdatingDataSources = useCallback(() => {
12372
12765
  const diffFilterNames = filters
12373
- ? Object.keys(filters).filter(key => Array.isArray(filters[key].value)
12374
- ? filters[key].value.length !==
12375
- prevFilters.current[key]?.value?.length ||
12376
- filters[key].value.some((item, index) => item !== prevFilters.current[key]?.value?.[index])
12377
- : filters[key].value !== prevFilters.current[key]?.value)
12766
+ ? Object.keys(filters).filter(key => {
12767
+ const { value } = filters[key];
12768
+ const prevValue = prevFilters.current[key]?.value;
12769
+ if (isTreeFilterValue(value) || isTreeFilterValue(prevValue)) {
12770
+ return JSON.stringify(value) !== JSON.stringify(prevValue);
12771
+ }
12772
+ if (Array.isArray(value)) {
12773
+ return (value.length !== prevValue?.length ||
12774
+ value.some((item, index) => item !== prevValue?.[index]));
12775
+ }
12776
+ return value !== prevValue;
12777
+ })
12378
12778
  : [];
12379
12779
  if (!diffFilterNames.length)
12380
12780
  return;
@@ -13905,5 +14305,5 @@ const Map$1 = ({ zIndex, lowerSiblings, upperSiblings, onError, children, ...res
13905
14305
  }, children: children }), upperSiblings] }));
13906
14306
  };
13907
14307
 
13908
- 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 };
14308
+ 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 };
13909
14309
  //# sourceMappingURL=react.esm.js.map