@perses-dev/components 0.55.0-rc.1 → 0.55.1

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.
Files changed (34) hide show
  1. package/dist/FormEditor/form-editor-handle.d.ts +9 -0
  2. package/dist/FormEditor/form-editor-handle.d.ts.map +1 -0
  3. package/dist/FormEditor/form-editor-handle.js +19 -0
  4. package/dist/FormEditor/form-editor-handle.js.map +1 -0
  5. package/dist/FormEditor/index.d.ts +1 -0
  6. package/dist/FormEditor/index.d.ts.map +1 -1
  7. package/dist/FormEditor/index.js +1 -0
  8. package/dist/FormEditor/index.js.map +1 -1
  9. package/dist/Table/TableCell.d.ts.map +1 -1
  10. package/dist/Table/TableCell.js +11 -8
  11. package/dist/Table/TableCell.js.map +1 -1
  12. package/dist/Table/VirtualizedTable.d.ts.map +1 -1
  13. package/dist/Table/VirtualizedTable.js +62 -44
  14. package/dist/Table/VirtualizedTable.js.map +1 -1
  15. package/dist/Table/hooks/useVirtualizedTableKeyboardNav.d.ts.map +1 -1
  16. package/dist/Table/hooks/useVirtualizedTableKeyboardNav.js +60 -55
  17. package/dist/Table/hooks/useVirtualizedTableKeyboardNav.js.map +1 -1
  18. package/dist/TimeRangeSelector/TimeRangeSelector.js +3 -2
  19. package/dist/TimeRangeSelector/TimeRangeSelector.js.map +1 -1
  20. package/dist/TimeSeriesTooltip/utils.d.ts.map +1 -1
  21. package/dist/TimeSeriesTooltip/utils.js +16 -4
  22. package/dist/TimeSeriesTooltip/utils.js.map +1 -1
  23. package/dist/utils/index.d.ts +1 -0
  24. package/dist/utils/index.d.ts.map +1 -1
  25. package/dist/utils/index.js +1 -0
  26. package/dist/utils/index.js.map +1 -1
  27. package/dist/utils/time-series-data.d.ts.map +1 -1
  28. package/dist/utils/time-series-data.js +5 -2
  29. package/dist/utils/time-series-data.js.map +1 -1
  30. package/dist/utils/url.d.ts +17 -0
  31. package/dist/utils/url.d.ts.map +1 -0
  32. package/dist/utils/url.js +56 -0
  33. package/dist/utils/url.js.map +1 -0
  34. package/package.json +3 -3
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Imperative handle exposed by editor forms, allowing their parent to request closing them, e.g. when the user clicks
3
+ * outside of the Drawer containing the form. The form is responsible for closing itself, after asking for confirmation
4
+ * if there are unsaved changes.
5
+ */
6
+ export interface FormEditorHandle {
7
+ requestClose: () => void;
8
+ }
9
+ //# sourceMappingURL=form-editor-handle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form-editor-handle.d.ts","sourceRoot":"","sources":["../../src/FormEditor/form-editor-handle.ts"],"names":[],"mappings":"AAaA;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,YAAY,EAAE,MAAM,IAAI,CAAC;CAC1B"}
@@ -0,0 +1,19 @@
1
+ // Copyright The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ /**
14
+ * Imperative handle exposed by editor forms, allowing their parent to request closing them, e.g. when the user clicks
15
+ * outside of the Drawer containing the form. The form is responsible for closing itself, after asking for confirmation
16
+ * if there are unsaved changes.
17
+ */ export { };
18
+
19
+ //# sourceMappingURL=form-editor-handle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/FormEditor/form-editor-handle.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * Imperative handle exposed by editor forms, allowing their parent to request closing them, e.g. when the user clicks\n * outside of the Drawer containing the form. The form is responsible for closing itself, after asking for confirmation\n * if there are unsaved changes.\n */\nexport interface FormEditorHandle {\n requestClose: () => void;\n}\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC;;;;CAIC,GACD,WAEC"}
@@ -1,2 +1,3 @@
1
1
  export * from './FormActions';
2
+ export * from './form-editor-handle';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/FormEditor/index.ts"],"names":[],"mappings":"AAaA,cAAc,eAAe,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/FormEditor/index.ts"],"names":[],"mappings":"AAaA,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC"}
@@ -11,5 +11,6 @@
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
13
  export * from "./FormActions.js";
14
+ export * from "./form-editor-handle.js";
14
15
 
15
16
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/FormEditor/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './FormActions';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,mBAAgB"}
1
+ {"version":3,"sources":["../../src/FormEditor/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './FormActions';\nexport * from './form-editor-handle';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,mBAAgB;AAC9B,cAAc,0BAAuB"}
@@ -1 +1 @@
1
- {"version":3,"file":"TableCell.d.ts","sourceRoot":"","sources":["../../src/Table/TableCell.tsx"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,cAAc,IAAI,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAEzE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAI1C,OAAO,KAAK,EAAE,QAAQ,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAoBtF,MAAM,WAAW,cAAe,SAAQ,IAAI,CAAC,iBAAiB,EAAE,UAAU,GAAG,OAAO,CAAC;IACnF,OAAO,E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AAE,UAAU,GAAG,OAAO,CAAC;IACnF,OAAO,EAAE,YAAY,CAAC;IACtB,mBAAmB,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAGtC,YAAY,EAAE,OAAO,CAAC;IACtB,aAAa,EAAE,OAAO,CAAC;IAEvB,KAAK,CAAC,EAAE,kBAAkB,CAAC;IAE3B;;;;;;;;OAQG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;;;;;;OAOG;IACH,UAAU,CAAC,EAAE,eAAe,GAAG,YAAY,GAAG,MAAM,CAAC;IACrD,cAAc,CAAC,EAAE,CAAC,CAAC,EAAE,KAAK,CAAC,UAAU,CAAC,oBAAoB,CAAC,GAAG,KAAK,CAAC,aAAa,CAAC,oBAAoB,CAAC,KAAK,IAAI,CAAC;IACjH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,sBAAsB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjD;AAED,wBAAgB,SAAS,CAAC,EACxB,QAAQ,EACR,OAAO,EACP,OAAO,EACP,KAAK,EACL,mBAAmB,EACnB,UAAmB,EACnB,cAAc,EACd,aAAa,EACb,YAAY,EACZ,WAAW,EACX,KAAK,EACL,KAAK,EACL,eAAe,EACf,QAAQ,EACR,sBAAsB,EACtB,GAAG,UAAU,EACd,EAAE,cAAc,GAAG,YAAY,CAmH/B"}
@@ -14,6 +14,7 @@ import { jsx as _jsx } from "react/jsx-runtime";
14
14
  import { Box, Link, TableCell as MuiTableCell, styled, useTheme } from "@mui/material";
15
15
  import { useEffect, useMemo, useRef } from "react";
16
16
  import { hasDataFieldPatterns, replaceDataFields } from "../utils/data-field-interpolation.js";
17
+ import { sanitizeUrl } from "../utils/url.js";
17
18
  import { getTableCellLayout } from "./model/table-model.js";
18
19
  const StyledMuiTableCell = styled(MuiTableCell)(({ theme })=>({
19
20
  padding: 0,
@@ -60,16 +61,18 @@ export function TableCell({ children, density, variant, width, defaultColumnHeig
60
61
  };
61
62
  const modifiedDataLink = useMemo(()=>{
62
63
  if (!dataLink) return undefined;
63
- if (adjacentCellsValuesMap && hasDataFieldPatterns(dataLink.url)) {
64
- const { text } = replaceDataFields(dataLink.url, adjacentCellsValuesMap, {
64
+ let url = dataLink.url;
65
+ if (adjacentCellsValuesMap && hasDataFieldPatterns(url)) {
66
+ url = replaceDataFields(url, adjacentCellsValuesMap, {
65
67
  urlEncode: true
66
- });
67
- return {
68
- ...dataLink,
69
- url: text
70
- };
68
+ }).text;
71
69
  }
72
- return dataLink;
70
+ const safeUrl = sanitizeUrl(url);
71
+ if (safeUrl === undefined) return undefined;
72
+ return {
73
+ ...dataLink,
74
+ url: safeUrl
75
+ };
73
76
  }, [
74
77
  dataLink,
75
78
  adjacentCellsValuesMap
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Table/TableCell.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { TableCellProps as MuiTableCellProps } from '@mui/material';\nimport { Box, Link, TableCell as MuiTableCell, styled, useTheme } from '@mui/material';\nimport type { ReactElement } from 'react';\nimport { useEffect, useMemo, useRef } from 'react';\n\nimport { hasDataFieldPatterns, replaceDataFields } from '../utils/data-field-interpolation';\nimport type { DataLink, TableCellAlignment, TableDensity } from './model/table-model';\nimport { getTableCellLayout } from './model/table-model';\n\nconst StyledMuiTableCell = styled(MuiTableCell)(({ theme }) => ({\n padding: 0,\n backgroundColor: 'inherit',\n\n '&.MuiTableCell-head': {\n // Important to avoid scrolling behind the header showing through.\n backgroundColor: theme.palette.background.default,\n },\n '&:focus-visible': {\n outline: `solid 1px ${theme.palette.primary.main}`,\n // Move inward a little to avoid getting cut off when focusing on items\n // at the edge of the table.\n outlineOffset: '-1px',\n borderRadius: 0,\n },\n}));\n\nexport interface TableCellProps extends Omit<MuiTableCellProps, 'tabIndex' | 'align'> {\n density: TableDensity;\n defaultColumnHeight?: 'auto' | number;\n\n // These values are used to adjust the spacing for the first/last columns.\n isLastColumn: boolean;\n isFirstColumn: boolean;\n\n align?: TableCellAlignment;\n\n /**\n * Additional information to be displayed when hovering over the cell. This\n * may be the full cell value (e.g. to enable the user to see the full value\n * if it is ellipsized to fit into the space) or some other descriptive text\n * that is useful for the user.\n *\n * The hover behavior is currently managed with the `title` attribute, but this\n * may be changed to a tooltip in the future.\n */\n description?: string;\n\n /**\n * How the cell should behave related to focus.\n * - `trigger-focus`: the cell should be auto-focused when it renders.\n * - `focus-next`: the cell should have tabindex=\"0\", so that it will be\n * focused the next time someone tabs with a keyboard.\n * - `none`: the cell should have tabindex=\"-1\", so it is not focused by\n * keyboard interactions at this time.\n */\n focusState?: 'trigger-focus' | 'focus-next' | 'none';\n onFocusTrigger?: (e: React.MouseEvent<HTMLTableCellElement> | React.KeyboardEvent<HTMLTableCellElement>) => void;\n color?: string;\n backgroundColor?: string;\n dataLink?: DataLink;\n adjacentCellsValuesMap?: Record<string, string>;\n}\n\nexport function TableCell({\n children,\n density,\n variant,\n width,\n defaultColumnHeight,\n focusState = 'none',\n onFocusTrigger,\n isFirstColumn,\n isLastColumn,\n description,\n align,\n color,\n backgroundColor,\n dataLink,\n adjacentCellsValuesMap,\n ...otherProps\n}: TableCellProps): ReactElement {\n const theme = useTheme();\n const elRef = useRef<HTMLTableCellElement>();\n\n const isHeader = variant === 'head';\n\n useEffect(() => {\n if (focusState === 'trigger-focus' && elRef.current) {\n elRef.current.focus();\n }\n }, [focusState]);\n\n const handleFocus: React.FocusEventHandler<HTMLTableCellElement> = (e) => {\n // From https://zellwk.com/blog/keyboard-focusable-elements/\n const nestedFocusTarget = e.currentTarget?.querySelector<HTMLElement>(\n 'a[href], button, input, textarea, select, details,[role=\"button\"]',\n );\n if (nestedFocusTarget) {\n // If the cell has a focusable child, focus it instead. Mostly used for\n // checkbox cells, but could have other uses.\n nestedFocusTarget.focus();\n }\n };\n\n const handleInteractionFocusTrigger: TableCellProps['onFocusTrigger'] = (e) => {\n // We use `onClick` and `onKeyUp` events instead of `onFocus` because of\n // some ordering issues with when the browser calls events and how this\n // plays with the triggering of focus with keyboard interactions.\n // These report that a focus event happened, so we can adjust the current\n // tabindex and focuses to the right cell.\n onFocusTrigger?.(e);\n };\n\n const modifiedDataLink = useMemo((): DataLink | undefined => {\n if (!dataLink) return undefined;\n\n if (adjacentCellsValuesMap && hasDataFieldPatterns(dataLink.url)) {\n const { text } = replaceDataFields(dataLink.url, adjacentCellsValuesMap, { urlEncode: true });\n return { ...dataLink, url: text };\n }\n return dataLink;\n }, [dataLink, adjacentCellsValuesMap]);\n\n return (\n <StyledMuiTableCell\n {...otherProps}\n // Modify the tab index based on the currently focused cell. It's important\n // to avoid having tabindex 0 on everything because it essentially traps\n // a keyboard user in the table until they hit \"tab\" for every single\n // cell.\n tabIndex={focusState !== 'none' ? 0 : -1}\n onFocus={handleFocus}\n onClick={handleInteractionFocusTrigger}\n onKeyUp={handleInteractionFocusTrigger}\n style={{ width: width }}\n sx={{\n position: 'relative',\n borderBottom: isHeader ? `solid 1px ${theme.palette.grey[100]}` : `solid 1px ${theme.palette.grey[50]}`,\n '&:hover #original-cell': {\n position: 'absolute',\n top: 0,\n left: 0,\n zIndex: 10,\n width: 'fit-content',\n minWidth: '100%',\n whiteSpace: 'nowrap',\n overflow: 'visible',\n backgroundColor: `${backgroundColor ?? theme.palette.background.default} !important`,\n outline: `solid 1px ${theme.palette.info.main}`,\n outlineOffset: '-1px',\n },\n }}\n ref={elRef}\n >\n <Box\n id=\"original-cell\"\n sx={{\n ...getTableCellLayout(theme, density, { isHeader, isLastColumn, isFirstColumn, defaultColumnHeight }),\n position: 'relative',\n\n // Text truncation. Currently enforced on all cells. We may control\n // this with a prop on column config in the future.\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n\n // Need to inherit from the MUI cell because this manages some ordering\n // that the `TableSortLabel` uses to determine the location of the icon\n // in headers.\n flexDirection: 'inherit',\n }}\n style={{\n backgroundColor: backgroundColor ?? 'inherit',\n color: color ?? 'inherit',\n }}\n title={description}\n aria-label={description}\n textAlign={align}\n >\n {modifiedDataLink ? (\n <Link\n href={modifiedDataLink.url}\n target={modifiedDataLink.targetBlank ? '_blank' : '_self'}\n rel={modifiedDataLink.targetBlank ? 'noopener noreferrer' : undefined}\n >\n {children}\n </Link>\n ) : (\n children\n )}\n </Box>\n </StyledMuiTableCell>\n );\n}\n"],"names":["Box","Link","TableCell","MuiTableCell","styled","useTheme","useEffect","useMemo","useRef","hasDataFieldPatterns","replaceDataFields","getTableCellLayout","StyledMuiTableCell","theme","padding","backgroundColor","palette","background","default","outline","primary","main","outlineOffset","borderRadius","children","density","variant","width","defaultColumnHeight","focusState","onFocusTrigger","isFirstColumn","isLastColumn","description","align","color","dataLink","adjacentCellsValuesMap","otherProps","elRef","isHeader","current","focus","handleFocus","e","nestedFocusTarget","currentTarget","querySelector","handleInteractionFocusTrigger","modifiedDataLink","undefined","url","text","urlEncode","tabIndex","onFocus","onClick","onKeyUp","style","sx","position","borderBottom","grey","top","left","zIndex","minWidth","whiteSpace","overflow","info","ref","id","textOverflow","flexDirection","title","aria-label","textAlign","href","target","targetBlank","rel"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,SAASA,GAAG,EAAEC,IAAI,EAAEC,aAAaC,YA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AAeH;gBAAoB,EAAE;gBACrGgC,UAAU;gBAEV,mEAAmE;gBACnE,mDAAmD;gBACnDO,YAAY;gBACZC,UAAU;gBACVI,cAAc;gBAEd,uEAAuE;gBACvE,uEAAuE;gBACvE,cAAc;gBACdC,eAAe;YACjB;YACAf,OAAO;gBACL3C,iBAAiBA,mBAAmB;gBACpCoB,OAAOA,SAAS;YAClB;YACAuC,OAAOzC;YACP0C,cAAY1C;YACZ2C,WAAW1C;sBAEVe,iCACC,KAAChD;gBACC4E,MAAM5B,iBAAiBE,GAAG;gBAC1B2B,QAAQ7B,iBAAiB8B,WAAW,GAAG,WAAW;gBAClDC,KAAK/B,iBAAiB8B,WAAW,GAAG,wBAAwB7B;0BAE3D1B;iBAGHA;;;AAKV"}
1
+ {"version":3,"sources":["../../src/Table/TableCell.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { TableCellProps as MuiTableCellProps } from '@mui/material';\nimport { Box, Link, TableCell as MuiTableCell, styled, useTheme } from '@mui/material';\nimport type { ReactElement } from 'react';\nimport { useEffect, useMemo, useRef } from 'react';\n\nimport { hasDataFieldPatterns, replaceDataFields } from '../utils/data-field-interpolation';\nimport { sanitizeUrl } from '../utils/url';\nimport type { DataLink, TableCellAlignment, TableDensity } from './model/table-model';\nimport { getTableCellLayout } from './model/table-model';\n\nconst StyledMuiTableCell = styled(MuiTableCell)(({ theme }) => ({\n padding: 0,\n backgroundColor: 'inherit',\n\n '&.MuiTableCell-head': {\n // Important to avoid scrolling behind the header showing through.\n backgroundColor: theme.palette.background.default,\n },\n '&:focus-visible': {\n outline: `solid 1px ${theme.palette.primary.main}`,\n // Move inward a little to avoid getting cut off when focusing on items\n // at the edge of the table.\n outlineOffset: '-1px',\n borderRadius: 0,\n },\n}));\n\nexport interface TableCellProps extends Omit<MuiTableCellProps, 'tabIndex' | 'align'> {\n density: TableDensity;\n defaultColumnHeight?: 'auto' | number;\n\n // These values are used to adjust the spacing for the first/last columns.\n isLastColumn: boolean;\n isFirstColumn: boolean;\n\n align?: TableCellAlignment;\n\n /**\n * Additional information to be displayed when hovering over the cell. This\n * may be the full cell value (e.g. to enable the user to see the full value\n * if it is ellipsized to fit into the space) or some other descriptive text\n * that is useful for the user.\n *\n * The hover behavior is currently managed with the `title` attribute, but this\n * may be changed to a tooltip in the future.\n */\n description?: string;\n\n /**\n * How the cell should behave related to focus.\n * - `trigger-focus`: the cell should be auto-focused when it renders.\n * - `focus-next`: the cell should have tabindex=\"0\", so that it will be\n * focused the next time someone tabs with a keyboard.\n * - `none`: the cell should have tabindex=\"-1\", so it is not focused by\n * keyboard interactions at this time.\n */\n focusState?: 'trigger-focus' | 'focus-next' | 'none';\n onFocusTrigger?: (e: React.MouseEvent<HTMLTableCellElement> | React.KeyboardEvent<HTMLTableCellElement>) => void;\n color?: string;\n backgroundColor?: string;\n dataLink?: DataLink;\n adjacentCellsValuesMap?: Record<string, string>;\n}\n\nexport function TableCell({\n children,\n density,\n variant,\n width,\n defaultColumnHeight,\n focusState = 'none',\n onFocusTrigger,\n isFirstColumn,\n isLastColumn,\n description,\n align,\n color,\n backgroundColor,\n dataLink,\n adjacentCellsValuesMap,\n ...otherProps\n}: TableCellProps): ReactElement {\n const theme = useTheme();\n const elRef = useRef<HTMLTableCellElement>();\n\n const isHeader = variant === 'head';\n\n useEffect(() => {\n if (focusState === 'trigger-focus' && elRef.current) {\n elRef.current.focus();\n }\n }, [focusState]);\n\n const handleFocus: React.FocusEventHandler<HTMLTableCellElement> = (e) => {\n // From https://zellwk.com/blog/keyboard-focusable-elements/\n const nestedFocusTarget = e.currentTarget?.querySelector<HTMLElement>(\n 'a[href], button, input, textarea, select, details,[role=\"button\"]',\n );\n if (nestedFocusTarget) {\n // If the cell has a focusable child, focus it instead. Mostly used for\n // checkbox cells, but could have other uses.\n nestedFocusTarget.focus();\n }\n };\n\n const handleInteractionFocusTrigger: TableCellProps['onFocusTrigger'] = (e) => {\n // We use `onClick` and `onKeyUp` events instead of `onFocus` because of\n // some ordering issues with when the browser calls events and how this\n // plays with the triggering of focus with keyboard interactions.\n // These report that a focus event happened, so we can adjust the current\n // tabindex and focuses to the right cell.\n onFocusTrigger?.(e);\n };\n\n const modifiedDataLink = useMemo((): DataLink | undefined => {\n if (!dataLink) return undefined;\n\n let url = dataLink.url;\n if (adjacentCellsValuesMap && hasDataFieldPatterns(url)) {\n url = replaceDataFields(url, adjacentCellsValuesMap, { urlEncode: true }).text;\n }\n const safeUrl = sanitizeUrl(url);\n if (safeUrl === undefined) return undefined;\n return { ...dataLink, url: safeUrl };\n }, [dataLink, adjacentCellsValuesMap]);\n\n return (\n <StyledMuiTableCell\n {...otherProps}\n // Modify the tab index based on the currently focused cell. It's important\n // to avoid having tabindex 0 on everything because it essentially traps\n // a keyboard user in the table until they hit \"tab\" for every single\n // cell.\n tabIndex={focusState !== 'none' ? 0 : -1}\n onFocus={handleFocus}\n onClick={handleInteractionFocusTrigger}\n onKeyUp={handleInteractionFocusTrigger}\n style={{ width: width }}\n sx={{\n position: 'relative',\n borderBottom: isHeader ? `solid 1px ${theme.palette.grey[100]}` : `solid 1px ${theme.palette.grey[50]}`,\n '&:hover #original-cell': {\n position: 'absolute',\n top: 0,\n left: 0,\n zIndex: 10,\n width: 'fit-content',\n minWidth: '100%',\n whiteSpace: 'nowrap',\n overflow: 'visible',\n backgroundColor: `${backgroundColor ?? theme.palette.background.default} !important`,\n outline: `solid 1px ${theme.palette.info.main}`,\n outlineOffset: '-1px',\n },\n }}\n ref={elRef}\n >\n <Box\n id=\"original-cell\"\n sx={{\n ...getTableCellLayout(theme, density, { isHeader, isLastColumn, isFirstColumn, defaultColumnHeight }),\n position: 'relative',\n\n // Text truncation. Currently enforced on all cells. We may control\n // this with a prop on column config in the future.\n whiteSpace: 'nowrap',\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n\n // Need to inherit from the MUI cell because this manages some ordering\n // that the `TableSortLabel` uses to determine the location of the icon\n // in headers.\n flexDirection: 'inherit',\n }}\n style={{\n backgroundColor: backgroundColor ?? 'inherit',\n color: color ?? 'inherit',\n }}\n title={description}\n aria-label={description}\n textAlign={align}\n >\n {modifiedDataLink ? (\n <Link\n href={modifiedDataLink.url}\n target={modifiedDataLink.targetBlank ? '_blank' : '_self'}\n rel={modifiedDataLink.targetBlank ? 'noopener noreferrer' : undefined}\n >\n {children}\n </Link>\n ) : (\n children\n )}\n </Box>\n </StyledMuiTableCell>\n );\n}\n"],"names":["Box","Link","TableCell","MuiTableCell","styled","useTheme","useEffect","useMemo","useRef","hasDataFieldPatterns","replaceDataFields","sanitizeUrl","getTableCellLayout","StyledMuiTableCell","theme","padding","backgroundColor","palette","background","default","outline","primary","main","outlineOffset","borderRadius","children","density","variant","width","defaultColumnHeight","focusState","onFocusTrigger","isFirstColumn","isLastColumn","description","align","color","dataLink","adjacentCellsValuesMap","otherProps","elRef","isHeader","current","focus","handleFocus","e","nestedFocusTarget","currentTarget","querySelector","handleInteractionFocusTrigger","modifiedDataLink","undefined","url","urlEncode","text","safeUrl","tabIndex","onFocus","onClick","onKeyUp","style","sx","position","borderBottom","grey","top","left","zIndex","minWidth","whiteSpace","overflow","info","ref","id","textOverflow","flexDirection","title","aria-label","textAlign","href","target","targetBlank","rel"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,SAASA,GAAG,EAAEC,IAAI,EAAEC,aAAaC,YA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,OAAO,EACP,OAAO,EACP,WAAW,EACX,UAAU,EACV,kBAAkB,EAClB,QAAQ,EACR,aAAa,GACd,EAAE,qBAAqB,CAAC,SAAS,CAAC,GAAG,YAAY,CAmPjD"}
@@ -13,7 +13,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
13
13
  // limitations under the License.
14
14
  import { Box, TablePagination, TableRow as MuiTableRow } from "@mui/material";
15
15
  import { flexRender } from "@tanstack/react-table";
16
- import { useMemo, useRef } from "react";
16
+ import { forwardRef, useMemo, useRef } from "react";
17
17
  import { TableVirtuoso } from "react-virtuoso";
18
18
  import { useVirtualizedTableKeyboardNav } from "./hooks/useVirtualizedTableKeyboardNav.js";
19
19
  import { InnerTable } from "./InnerTable.js";
@@ -25,6 +25,54 @@ import { TableHeaderCell } from "./TableHeaderCell.js";
25
25
  import { TableRow } from "./TableRow.js";
26
26
  import { TableToolbar } from "./TableToolbar.js";
27
27
  import { VirtualizedTableContainer } from "./VirtualizedTableContainer.js";
28
+ // Defined outside VirtualizedTable so the object reference is stable and
29
+ // TableVirtuoso never remounts its internal components due to a changed prop.
30
+ // Props that vary per-render are passed via the `context` prop instead.
31
+ const VirtuosoTableComponents = {
32
+ Scroller: /*#__PURE__*/ forwardRef(({ context: _, ...props }, ref)=>/*#__PURE__*/ _jsx(VirtualizedTableContainer, {
33
+ ...props,
34
+ ref: ref
35
+ })),
36
+ Table: ({ context, ...props })=>/*#__PURE__*/ _jsx(InnerTable, {
37
+ ...props,
38
+ width: context.width,
39
+ density: context.density,
40
+ onKeyDown: context.onTableKeyDown,
41
+ onBlur: context.onTableBlur
42
+ }),
43
+ TableHead: /*#__PURE__*/ forwardRef(({ context: _, ...props }, ref)=>/*#__PURE__*/ _jsx(TableHead, {
44
+ ...props,
45
+ ref: ref
46
+ })),
47
+ TableFoot: /*#__PURE__*/ forwardRef(({ context: _, ...props }, ref)=>/*#__PURE__*/ _jsx(TableFoot, {
48
+ ...props,
49
+ ref: ref
50
+ })),
51
+ TableRow: ({ item, context, ...props })=>{
52
+ if (!item) {
53
+ return null;
54
+ }
55
+ const rowEventOpts = {
56
+ id: item.id,
57
+ index: item.index
58
+ };
59
+ return /*#__PURE__*/ _jsx(TableRow, {
60
+ ...props,
61
+ onClick: (e)=>context.onRowClick(e, item.id),
62
+ density: context.density,
63
+ onMouseOver: (e)=>{
64
+ context.onRowMouseOver?.(e, rowEventOpts);
65
+ },
66
+ onMouseOut: (e)=>{
67
+ context.onRowMouseOut?.(e, rowEventOpts);
68
+ }
69
+ });
70
+ },
71
+ TableBody: /*#__PURE__*/ forwardRef(({ context: _, ...props }, ref)=>/*#__PURE__*/ _jsx(TableBody, {
72
+ ...props,
73
+ ref: ref
74
+ }))
75
+ };
28
76
  // Separating out the virtualized table because we may want a paginated table
29
77
  // in the future that does not need virtualization, and we'd likely lay them
30
78
  // out differently.
@@ -54,53 +102,22 @@ export function VirtualizedTable({ width, height, density, defaultColumnWidth, d
54
102
  }
55
103
  return 'none';
56
104
  };
57
- const VirtuosoTableComponents = useMemo(()=>{
58
- return {
59
- Scroller: VirtualizedTableContainer,
60
- Table: (props)=>{
61
- return /*#__PURE__*/ _jsx(InnerTable, {
62
- ...props,
63
- width: width,
64
- density: density,
65
- onKeyDown: keyboardNav.onTableKeyDown,
66
- onBlur: keyboardNav.onTableBlur
67
- });
68
- },
69
- TableHead,
70
- TableFoot,
71
- TableRow: ({ item: _item, ...props })=>{
72
- const index = props['data-index'];
73
- const row = rows[index];
74
- if (!row) {
75
- return null;
76
- }
77
- const rowEventOpts = {
78
- id: row.id,
79
- index: row.index
80
- };
81
- return /*#__PURE__*/ _jsx(TableRow, {
82
- ...props,
83
- onClick: (e)=>onRowClick(e, row.id),
84
- density: density,
85
- onMouseOver: (e)=>{
86
- onRowMouseOver?.(e, rowEventOpts);
87
- },
88
- onMouseOut: (e)=>{
89
- onRowMouseOut?.(e, rowEventOpts);
90
- }
91
- });
92
- },
93
- TableBody
94
- };
95
- }, [
105
+ const tableContext = useMemo(()=>({
106
+ width,
107
+ density,
108
+ onTableKeyDown: keyboardNav.onTableKeyDown,
109
+ onTableBlur: keyboardNav.onTableBlur,
110
+ onRowClick,
111
+ onRowMouseOver,
112
+ onRowMouseOut
113
+ }), [
114
+ width,
96
115
  density,
97
116
  keyboardNav.onTableKeyDown,
98
117
  keyboardNav.onTableBlur,
99
118
  onRowClick,
100
- onRowMouseOut,
101
119
  onRowMouseOver,
102
- rows,
103
- width
120
+ onRowMouseOut
104
121
  ]);
105
122
  const handleChangePage = (_event, newPage)=>{
106
123
  if (!pagination || !onPaginationChange) return;
@@ -141,8 +158,9 @@ export function VirtualizedTable({ width, height, density, defaultColumnWidth, d
141
158
  }),
142
159
  /*#__PURE__*/ _jsx(TableVirtuoso, {
143
160
  ref: virtuosoRef,
144
- totalCount: rows.length,
161
+ data: rows,
145
162
  components: VirtuosoTableComponents,
163
+ context: tableContext,
146
164
  // Note: this value is impacted by overscan. See this issue if overscan
147
165
  // is added.
148
166
  // https://github.com/petyosi/react-virtuoso/issues/118#issuecomment-642156138
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/Table/VirtualizedTable.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Box, TablePagination, TableRow as MuiTableRow } from '@mui/material';\nimport type { Column, ColumnSizingInfoState, ColumnSizingState, HeaderGroup, Row } from '@tanstack/react-table';\nimport { flexRender } from '@tanstack/react-table';\nimport type { ReactElement } from 'react';\nimport { useMemo, useRef } from 'react';\nimport type { TableComponents, TableVirtuosoHandle, TableVirtuosoProps } from 'react-virtuoso';\nimport { TableVirtuoso } from 'react-virtuoso';\n\nimport { useVirtualizedTableKeyboardNav } from './hooks/useVirtualizedTableKeyboardNav';\nimport { InnerTable } from './InnerTable';\nimport type { TableCellConfigs, TableProps, TableRowEventOpts } from './model/table-model';\nimport { TableBody } from './TableBody';\nimport type { TableCellProps } from './TableCell';\nimport { TableCell } from './TableCell';\nimport { TableFoot } from './TableFoot';\nimport { TableHead } from './TableHead';\nimport { TableHeaderCell } from './TableHeaderCell';\nimport { TableRow } from './TableRow';\nimport type { TableToolbarProps } from './TableToolbar';\nimport { TableToolbar } from './TableToolbar';\nimport { VirtualizedTableContainer } from './VirtualizedTableContainer';\n\ntype TableCellPosition = {\n row: number;\n column: number;\n};\n\nexport type VirtualizedTableProps<TableData> = Required<\n Pick<TableProps<TableData>, 'height' | 'width' | 'density' | 'defaultColumnHeight' | 'defaultColumnWidth'>\n> &\n Pick<TableProps<TableData>, 'onRowMouseOver' | 'onRowMouseOut' | 'pagination' | 'onPaginationChange'> & {\n onRowClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>, id: string) => void;\n rows: Array<Row<TableData>>;\n columns: Array<Column<TableData, unknown>>;\n headers: Array<HeaderGroup<TableData>>;\n columnSizing: ColumnSizingState;\n columnSizingInfo: ColumnSizingInfoState;\n cellConfigs?: TableCellConfigs;\n rowCount: number;\n toolbarConfig: Pick<\n TableToolbarProps<TableData>,\n | 'isSearchEnabled'\n | 'globalFilter'\n | 'onGlobalFilterChange'\n | 'isColumnFilterEnabled'\n | 'columns'\n | 'columnFilterMenuMaxHeight'\n | 'isExpandAllEnabled'\n | 'isAllExpanded'\n | 'onExpandAllChange'\n >;\n };\n\n// Separating out the virtualized table because we may want a paginated table\n// in the future that does not need virtualization, and we'd likely lay them\n// out differently.\nexport function VirtualizedTable<TableData>({\n width,\n height,\n density,\n defaultColumnWidth,\n defaultColumnHeight,\n onRowClick,\n onRowMouseOver,\n onRowMouseOut,\n rows,\n columns,\n headers,\n cellConfigs,\n pagination,\n onPaginationChange,\n rowCount,\n toolbarConfig,\n}: VirtualizedTableProps<TableData>): ReactElement {\n 'use no memo'; // TanStack Table row and column getters read mutable state behind stable identities.\n\n const virtuosoRef = useRef<TableVirtuosoHandle>(null);\n // Use a ref for these values because they are only needed for keyboard\n // focus interactions and setting them on state will lead to a significant\n // amount of unnecessary re-renders.\n const visibleRange = useRef({\n startIndex: 0,\n endIndex: 0,\n });\n\n const setVisibleRange: TableVirtuosoProps<TableData, unknown>['rangeChanged'] = (newVisibleRange) => {\n visibleRange.current = newVisibleRange;\n };\n\n const keyboardNav = useVirtualizedTableKeyboardNav({\n visibleRange: visibleRange,\n virtualTable: virtuosoRef,\n\n // We add 1 here for the header.\n maxRows: rows.length + 1,\n maxColumns: columns.length,\n });\n\n const getFocusState = (cellPosition: TableCellPosition): TableCellProps['focusState'] => {\n if (cellPosition.row === keyboardNav.activeCell.row && cellPosition.column === keyboardNav.activeCell.column) {\n return keyboardNav.isActive ? 'trigger-focus' : 'focus-next';\n }\n\n return 'none';\n };\n\n const VirtuosoTableComponents: TableComponents<TableData> = useMemo(() => {\n return {\n Scroller: VirtualizedTableContainer,\n Table: (props): ReactElement => {\n return (\n <InnerTable\n {...props}\n width={width}\n density={density}\n onKeyDown={keyboardNav.onTableKeyDown}\n onBlur={keyboardNav.onTableBlur}\n />\n );\n },\n TableHead,\n TableFoot,\n TableRow: ({ item: _item, ...props }): ReactElement | null => {\n const index = props['data-index'];\n const row = rows[index];\n if (!row) {\n return null;\n }\n\n const rowEventOpts: TableRowEventOpts = { id: row.id, index: row.index };\n\n return (\n <TableRow\n {...props}\n onClick={(e) => onRowClick(e, row.id)}\n density={density}\n onMouseOver={(e) => {\n onRowMouseOver?.(e, rowEventOpts);\n }}\n onMouseOut={(e) => {\n onRowMouseOut?.(e, rowEventOpts);\n }}\n />\n );\n },\n TableBody,\n };\n }, [\n density,\n keyboardNav.onTableKeyDown,\n keyboardNav.onTableBlur,\n onRowClick,\n onRowMouseOut,\n onRowMouseOver,\n rows,\n width,\n ]);\n\n const handleChangePage = (_event: React.MouseEvent<HTMLButtonElement> | null, newPage: number): void => {\n if (!pagination || !onPaginationChange) return;\n onPaginationChange({ ...pagination, pageIndex: newPage });\n };\n\n const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {\n if (!pagination || !onPaginationChange) return;\n onPaginationChange({ pageIndex: 0, pageSize: parseInt(event.target.value, 10) });\n };\n\n /**\n * Instead of calling `column.getSize()` on every render for every header\n * and especially every data cell (very expensive),\n * we calculate all column sizes once per render at the root table level\n * and pass the column sizes down as CSS variables to the <table> element.\n */\n const columnSizeVars: { [key: string]: number } = {};\n headers.forEach((headerGroup) => {\n headerGroup.headers\n .filter((header) => header.column.getCanResize())\n .forEach((header) => {\n columnSizeVars[`--header-${header.id}-size`] = header.getSize();\n columnSizeVars[`--col-${header.column.id}-size`] = header.column.getSize();\n });\n });\n\n return (\n <Box style={{ width, height, ...columnSizeVars }}>\n <TableToolbar {...toolbarConfig} width={width} />\n <TableVirtuoso\n ref={virtuosoRef}\n totalCount={rows.length}\n components={VirtuosoTableComponents}\n // Note: this value is impacted by overscan. See this issue if overscan\n // is added.\n // https://github.com/petyosi/react-virtuoso/issues/118#issuecomment-642156138\n rangeChanged={setVisibleRange}\n fixedHeaderContent={() => {\n return (\n <>\n {headers.map((headerGroup) => {\n return (\n <TableRow key={headerGroup.id} density={density}>\n {headerGroup.headers.map((header, i, headers) => {\n const column = header.column;\n const position: TableCellPosition = {\n row: 0,\n column: i,\n };\n\n const isSorted = column.getIsSorted();\n const nextSorting = column.getNextSortingOrder();\n\n return (\n <TableHeaderCell\n key={header.id}\n onSort={column.getCanSort() ? column.getToggleSortingHandler() : undefined}\n sortDirection={typeof isSorted === 'string' ? isSorted : undefined}\n nextSortDirection={typeof nextSorting === 'string' ? nextSorting : undefined}\n width={\n header.column.getCanResize()\n ? `calc(var(--header-${header?.id}-size) * 1px)`\n : column.getSize() || defaultColumnWidth\n }\n defaultColumnHeight={defaultColumnHeight}\n align={column.columnDef.meta?.align}\n variant=\"head\"\n density={density}\n description={column.columnDef.meta?.headerDescription}\n focusState={getFocusState(position)}\n onFocusTrigger={() => keyboardNav.onCellFocus(position)}\n isFirstColumn={i === 0}\n isLastColumn={i === headers.length - 1}\n resizeConfig={\n header.column.getCanResize()\n ? {\n resizeHandler: header.getResizeHandler(),\n resetSizeHandler: header.column.resetSize,\n isResizing: header.column.getIsResizing(),\n }\n : undefined\n }\n >\n {flexRender(column.columnDef.header, header.getContext())}\n </TableHeaderCell>\n );\n })}\n </TableRow>\n );\n })}\n </>\n );\n }}\n fixedFooterContent={\n pagination\n ? (): ReactElement => (\n <MuiTableRow sx={{ backgroundColor: (theme) => theme.palette.background.default }}>\n <TablePagination\n colSpan={columns.length}\n count={rowCount}\n page={pagination.pageIndex}\n rowsPerPage={pagination.pageSize}\n onPageChange={handleChangePage}\n onRowsPerPageChange={handleChangeRowsPerPage}\n />\n </MuiTableRow>\n )\n : undefined\n }\n itemContent={(index) => {\n const row = rows[index];\n if (!row) {\n return null;\n }\n\n return (\n <>\n {row.getVisibleCells().map((cell, i, cells) => {\n const position: TableCellPosition = {\n row: index + 1,\n column: i,\n };\n\n const cellContext = cell.getContext();\n const cellConfig = cellConfigs?.[cellContext.cell.id];\n\n const cellRenderFn = cell.column.columnDef.cell;\n const cellContent = typeof cellRenderFn === 'function' ? cellRenderFn(cellContext) : null;\n\n /*\n IMPORTANT:\n If Variables exist in the link, they should have been translated by the plugin already. (Being developed at the moment)\n Components have no access to any context (Which is intentional and correct)\n We may want to add parameters to a link from neighboring cells in the future as well.\n If this is the case, the value of the neighboring cells should be read from here and be replaced. (Bing discussed at the moment, not decided yet)\n */\n\n const cellDescriptionDef = cell.column.columnDef.meta?.cellDescription;\n let description: string | undefined = undefined;\n if (typeof cellDescriptionDef === 'function') {\n // If the cell description is a function, set the value using\n // the function.\n description = cellDescriptionDef(cellContext);\n } else if (cellDescriptionDef && typeof cellContent === 'string') {\n // If the cell description is `true` AND the cell content is\n // a string (and thus viable as a `title` attribute), use the\n // cell content.\n description = cellContent;\n }\n\n /* this has been specifically added for the data link,\n therefore, non string and numeric values should be excluded\n */\n const adjacentCellsValuesMap = Object.entries(row.original as Record<string, unknown>)\n ?.filter(([_, value]) => ['string', 'number'].includes(typeof value))\n .reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: String(value),\n }),\n {},\n );\n\n return (\n <TableCell\n key={cell.id}\n data-testid={cell.id}\n title={description || cellConfig?.text || cellContent}\n width={\n cell.column.getCanResize()\n ? `calc(var(--col-${cell.column.id}-size) * 1px)`\n : cell.column.getSize() || defaultColumnWidth\n }\n defaultColumnHeight={defaultColumnHeight}\n align={cell.column.columnDef.meta?.align}\n density={density}\n focusState={getFocusState(position)}\n onFocusTrigger={() => keyboardNav.onCellFocus(position)}\n isFirstColumn={i === 0}\n isLastColumn={i === cells.length - 1}\n description={description}\n color={cellConfig?.textColor ?? undefined}\n backgroundColor={cellConfig?.backgroundColor ?? undefined}\n dataLink={cell.column.columnDef.meta?.dataLink}\n adjacentCellsValuesMap={adjacentCellsValuesMap}\n >\n {cellConfig?.text || cellContent}\n </TableCell>\n );\n })}\n </>\n );\n }}\n />\n </Box>\n );\n}\n"],"names":["Box","TablePagination","TableRow","MuiTableRow","flexRender","useMemo","useRef","TableVirtuoso","useVirtualizedTableKeyboardNav","InnerTable","TableBody","TableCell","TableFoot","TableHead","TableHeaderCell","TableToolbar","VirtualizedTableContainer","VirtualizedTable","width","height","density","defaultColumnWidth","defaultColumnHeight","onRowClick","onRowMouseOver","onRowMouseOut","rows","columns","headers","cellConfigs","pagination","onPaginationChange","rowCount","toolbarConfig","virtuosoRef","visibleRange","startIndex","endIndex","setVisibleRange","newVisibleRange","current","keyboardNav","virtualTable","maxRows","length","maxColumns","getFocusState","cellPosition","row","activeCell","column","isActive","VirtuosoTableComponents","Scroller","Table","props","onKeyDown","onTableKeyDown","onBlur","onTableBlur","item","_item","index","rowEventOpts","id","onClick","e","onMouseOver","onMouseOut","handleChangePage","_event","newPage","pageIndex","handleChangeRowsPerPage","event","pageSize","parseInt","target","value","columnSizeVars","forEach","headerGroup","filter","header","getCanResize","getSize","style","ref","totalCount","components","rangeChanged","fixedHeaderContent","map","i","position","isSorted","getIsSorted","nextSorting","getNextSortingOrder","onSort","getCanSort","getToggleSortingHandler","undefined","sortDirection","nextSortDirection","align","columnDef","meta","variant","description","headerDescription","focusState","onFocusTrigger","onCellFocus","isFirstColumn","isLastColumn","resizeConfig","resizeHandler","getResizeHandler","resetSizeHandler","resetSize","isResizing","getIsResizing","getContext","fixedFooterContent","sx","backgroundColor","theme","palette","background","default","colSpan","count","page","rowsPerPage","onPageChange","onRowsPerPageChange","itemContent","getVisibleCells","cell","cells","cellContext","cellConfig","cellRenderFn","cellContent","cellDescriptionDef","cellDescription","adjacentCellsValuesMap","Object","entries","original","_","includes","reduce","acc","key","String","data-testid","title","text","color","textColor","dataLink"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,GAAG,EAAEC,eAAe,EAAEC,YAAYC,WAAW,QAAQ,gBAAgB;AAE9E,SAASC,UAAU,QAAQ,wBAAwB;AAEnD,SAASC,OAAO,EAAEC,MAAM,QAAQ,QAAQ;AAExC,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,SAASC,8BAA8B,QAAQ,4CAAyC;AACxF,SAASC,UAAU,QAAQ,kBAAe;AAE1C,SAASC,SAAS,QAAQ,iBAAc;AAExC,SAASC,SAAS,QAAQ,iBAAc;AACxC,SAASC,SAAS,QAAQ,iBAAc;AACxC,SAASC,SAAS,QAAQ,iBAAc;AACxC,SAASC,eAAe,QAAQ,uBAAoB;AACpD,SAASZ,QAAQ,QAAQ,gBAAa;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I,EAAEuD;gCACtCf,wBAAwBA;0CAEvBL,YAAYiB,QAAQf;+BArBhBL,KAAK3E,EAAE;wBAwBlB;;gBAGN;;;;AAIR"}
1
+ {"version":3,"sources":["../../src/Table/VirtualizedTable.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Box, TablePagination, TableRow as MuiTableRow } from '@mui/material';\nimport type { Column, ColumnSizingInfoState, ColumnSizingState, HeaderGroup, Row } from '@tanstack/react-table';\nimport { flexRender } from '@tanstack/react-table';\nimport type { ReactElement } from 'react';\nimport { forwardRef, useMemo, useRef } from 'react';\nimport type { TableComponents, TableVirtuosoHandle, TableVirtuosoProps } from 'react-virtuoso';\nimport { TableVirtuoso } from 'react-virtuoso';\n\nimport { useVirtualizedTableKeyboardNav } from './hooks/useVirtualizedTableKeyboardNav';\nimport { InnerTable } from './InnerTable';\nimport type { TableCellConfigs, TableProps, TableRowEventOpts } from './model/table-model';\nimport { TableBody } from './TableBody';\nimport type { TableCellProps } from './TableCell';\nimport { TableCell } from './TableCell';\nimport { TableFoot } from './TableFoot';\nimport { TableHead } from './TableHead';\nimport { TableHeaderCell } from './TableHeaderCell';\nimport { TableRow } from './TableRow';\nimport type { TableToolbarProps } from './TableToolbar';\nimport { TableToolbar } from './TableToolbar';\nimport { VirtualizedTableContainer } from './VirtualizedTableContainer';\n\ntype TableCellPosition = {\n row: number;\n column: number;\n};\n\ntype TableContext<TableData> = {\n width: number | string;\n density: VirtualizedTableProps<TableData>['density'];\n onTableKeyDown: React.KeyboardEventHandler<HTMLTableElement>;\n onTableBlur: React.FocusEventHandler<HTMLTableElement>;\n onRowClick: VirtualizedTableProps<TableData>['onRowClick'];\n onRowMouseOver: VirtualizedTableProps<TableData>['onRowMouseOver'];\n onRowMouseOut: VirtualizedTableProps<TableData>['onRowMouseOut'];\n};\n\n// Defined outside VirtualizedTable so the object reference is stable and\n// TableVirtuoso never remounts its internal components due to a changed prop.\n// Props that vary per-render are passed via the `context` prop instead.\nconst VirtuosoTableComponents: TableComponents<Row<unknown>, TableContext<unknown>> = {\n Scroller: forwardRef(({ context: _, ...props }, ref) => <VirtualizedTableContainer {...props} ref={ref} />),\n Table: ({ context, ...props }): ReactElement => (\n <InnerTable\n {...props}\n width={context.width}\n density={context.density}\n onKeyDown={context.onTableKeyDown}\n onBlur={context.onTableBlur}\n />\n ),\n TableHead: forwardRef(({ context: _, ...props }, ref) => <TableHead {...props} ref={ref} />),\n TableFoot: forwardRef(({ context: _, ...props }, ref) => <TableFoot {...props} ref={ref} />),\n TableRow: ({ item, context, ...props }): ReactElement | null => {\n if (!item) {\n return null;\n }\n\n const rowEventOpts: TableRowEventOpts = { id: item.id, index: item.index };\n\n return (\n <TableRow\n {...props}\n onClick={(e) => context.onRowClick(e, item.id)}\n density={context.density}\n onMouseOver={(e) => {\n context.onRowMouseOver?.(e, rowEventOpts);\n }}\n onMouseOut={(e) => {\n context.onRowMouseOut?.(e, rowEventOpts);\n }}\n />\n );\n },\n TableBody: forwardRef(({ context: _, ...props }, ref) => <TableBody {...props} ref={ref} />),\n};\n\nexport type VirtualizedTableProps<TableData> = Required<\n Pick<TableProps<TableData>, 'height' | 'width' | 'density' | 'defaultColumnHeight' | 'defaultColumnWidth'>\n> &\n Pick<TableProps<TableData>, 'onRowMouseOver' | 'onRowMouseOut' | 'pagination' | 'onPaginationChange'> & {\n onRowClick: (e: React.MouseEvent<HTMLDivElement, MouseEvent>, id: string) => void;\n rows: Array<Row<TableData>>;\n columns: Array<Column<TableData, unknown>>;\n headers: Array<HeaderGroup<TableData>>;\n columnSizing: ColumnSizingState;\n columnSizingInfo: ColumnSizingInfoState;\n cellConfigs?: TableCellConfigs;\n rowCount: number;\n toolbarConfig: Pick<\n TableToolbarProps<TableData>,\n | 'isSearchEnabled'\n | 'globalFilter'\n | 'onGlobalFilterChange'\n | 'isColumnFilterEnabled'\n | 'columns'\n | 'columnFilterMenuMaxHeight'\n | 'isExpandAllEnabled'\n | 'isAllExpanded'\n | 'onExpandAllChange'\n >;\n };\n\n// Separating out the virtualized table because we may want a paginated table\n// in the future that does not need virtualization, and we'd likely lay them\n// out differently.\nexport function VirtualizedTable<TableData>({\n width,\n height,\n density,\n defaultColumnWidth,\n defaultColumnHeight,\n onRowClick,\n onRowMouseOver,\n onRowMouseOut,\n rows,\n columns,\n headers,\n cellConfigs,\n pagination,\n onPaginationChange,\n rowCount,\n toolbarConfig,\n}: VirtualizedTableProps<TableData>): ReactElement {\n 'use no memo'; // TanStack Table row and column getters read mutable state behind stable identities.\n\n const virtuosoRef = useRef<TableVirtuosoHandle>(null);\n // Use a ref for these values because they are only needed for keyboard\n // focus interactions and setting them on state will lead to a significant\n // amount of unnecessary re-renders.\n const visibleRange = useRef({\n startIndex: 0,\n endIndex: 0,\n });\n\n const setVisibleRange: TableVirtuosoProps<TableData, unknown>['rangeChanged'] = (newVisibleRange) => {\n visibleRange.current = newVisibleRange;\n };\n\n const keyboardNav = useVirtualizedTableKeyboardNav({\n visibleRange: visibleRange,\n virtualTable: virtuosoRef,\n\n // We add 1 here for the header.\n maxRows: rows.length + 1,\n maxColumns: columns.length,\n });\n\n const getFocusState = (cellPosition: TableCellPosition): TableCellProps['focusState'] => {\n if (cellPosition.row === keyboardNav.activeCell.row && cellPosition.column === keyboardNav.activeCell.column) {\n return keyboardNav.isActive ? 'trigger-focus' : 'focus-next';\n }\n\n return 'none';\n };\n\n const tableContext: TableContext<TableData> = useMemo(\n () => ({\n width,\n density,\n onTableKeyDown: keyboardNav.onTableKeyDown,\n onTableBlur: keyboardNav.onTableBlur,\n onRowClick,\n onRowMouseOver,\n onRowMouseOut,\n }),\n [width, density, keyboardNav.onTableKeyDown, keyboardNav.onTableBlur, onRowClick, onRowMouseOver, onRowMouseOut],\n );\n\n const handleChangePage = (_event: React.MouseEvent<HTMLButtonElement> | null, newPage: number): void => {\n if (!pagination || !onPaginationChange) return;\n onPaginationChange({ ...pagination, pageIndex: newPage });\n };\n\n const handleChangeRowsPerPage = (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {\n if (!pagination || !onPaginationChange) return;\n onPaginationChange({ pageIndex: 0, pageSize: parseInt(event.target.value, 10) });\n };\n\n /**\n * Instead of calling `column.getSize()` on every render for every header\n * and especially every data cell (very expensive),\n * we calculate all column sizes once per render at the root table level\n * and pass the column sizes down as CSS variables to the <table> element.\n */\n const columnSizeVars: { [key: string]: number } = {};\n headers.forEach((headerGroup) => {\n headerGroup.headers\n .filter((header) => header.column.getCanResize())\n .forEach((header) => {\n columnSizeVars[`--header-${header.id}-size`] = header.getSize();\n columnSizeVars[`--col-${header.column.id}-size`] = header.column.getSize();\n });\n });\n\n return (\n <Box style={{ width, height, ...columnSizeVars }}>\n <TableToolbar {...toolbarConfig} width={width} />\n <TableVirtuoso\n ref={virtuosoRef}\n data={rows}\n components={VirtuosoTableComponents as TableComponents<Row<TableData>, TableContext<TableData>>}\n context={tableContext}\n // Note: this value is impacted by overscan. See this issue if overscan\n // is added.\n // https://github.com/petyosi/react-virtuoso/issues/118#issuecomment-642156138\n rangeChanged={setVisibleRange}\n fixedHeaderContent={() => {\n return (\n <>\n {headers.map((headerGroup) => {\n return (\n <TableRow key={headerGroup.id} density={density}>\n {headerGroup.headers.map((header, i, headers) => {\n const column = header.column;\n const position: TableCellPosition = {\n row: 0,\n column: i,\n };\n\n const isSorted = column.getIsSorted();\n const nextSorting = column.getNextSortingOrder();\n\n return (\n <TableHeaderCell\n key={header.id}\n onSort={column.getCanSort() ? column.getToggleSortingHandler() : undefined}\n sortDirection={typeof isSorted === 'string' ? isSorted : undefined}\n nextSortDirection={typeof nextSorting === 'string' ? nextSorting : undefined}\n width={\n header.column.getCanResize()\n ? `calc(var(--header-${header?.id}-size) * 1px)`\n : column.getSize() || defaultColumnWidth\n }\n defaultColumnHeight={defaultColumnHeight}\n align={column.columnDef.meta?.align}\n variant=\"head\"\n density={density}\n description={column.columnDef.meta?.headerDescription}\n focusState={getFocusState(position)}\n onFocusTrigger={() => keyboardNav.onCellFocus(position)}\n isFirstColumn={i === 0}\n isLastColumn={i === headers.length - 1}\n resizeConfig={\n header.column.getCanResize()\n ? {\n resizeHandler: header.getResizeHandler(),\n resetSizeHandler: header.column.resetSize,\n isResizing: header.column.getIsResizing(),\n }\n : undefined\n }\n >\n {flexRender(column.columnDef.header, header.getContext())}\n </TableHeaderCell>\n );\n })}\n </TableRow>\n );\n })}\n </>\n );\n }}\n fixedFooterContent={\n pagination\n ? (): ReactElement => (\n <MuiTableRow sx={{ backgroundColor: (theme) => theme.palette.background.default }}>\n <TablePagination\n colSpan={columns.length}\n count={rowCount}\n page={pagination.pageIndex}\n rowsPerPage={pagination.pageSize}\n onPageChange={handleChangePage}\n onRowsPerPageChange={handleChangeRowsPerPage}\n />\n </MuiTableRow>\n )\n : undefined\n }\n itemContent={(index) => {\n const row = rows[index];\n if (!row) {\n return null;\n }\n\n return (\n <>\n {row.getVisibleCells().map((cell, i, cells) => {\n const position: TableCellPosition = {\n row: index + 1,\n column: i,\n };\n\n const cellContext = cell.getContext();\n const cellConfig = cellConfigs?.[cellContext.cell.id];\n\n const cellRenderFn = cell.column.columnDef.cell;\n const cellContent = typeof cellRenderFn === 'function' ? cellRenderFn(cellContext) : null;\n\n /*\n IMPORTANT:\n If Variables exist in the link, they should have been translated by the plugin already. (Being developed at the moment)\n Components have no access to any context (Which is intentional and correct)\n We may want to add parameters to a link from neighboring cells in the future as well.\n If this is the case, the value of the neighboring cells should be read from here and be replaced. (Bing discussed at the moment, not decided yet)\n */\n\n const cellDescriptionDef = cell.column.columnDef.meta?.cellDescription;\n let description: string | undefined = undefined;\n if (typeof cellDescriptionDef === 'function') {\n // If the cell description is a function, set the value using\n // the function.\n description = cellDescriptionDef(cellContext);\n } else if (cellDescriptionDef && typeof cellContent === 'string') {\n // If the cell description is `true` AND the cell content is\n // a string (and thus viable as a `title` attribute), use the\n // cell content.\n description = cellContent;\n }\n\n /* this has been specifically added for the data link,\n therefore, non string and numeric values should be excluded\n */\n const adjacentCellsValuesMap = Object.entries(row.original as Record<string, unknown>)\n ?.filter(([_, value]) => ['string', 'number'].includes(typeof value))\n .reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: String(value),\n }),\n {},\n );\n\n return (\n <TableCell\n key={cell.id}\n data-testid={cell.id}\n title={description || cellConfig?.text || cellContent}\n width={\n cell.column.getCanResize()\n ? `calc(var(--col-${cell.column.id}-size) * 1px)`\n : cell.column.getSize() || defaultColumnWidth\n }\n defaultColumnHeight={defaultColumnHeight}\n align={cell.column.columnDef.meta?.align}\n density={density}\n focusState={getFocusState(position)}\n onFocusTrigger={() => keyboardNav.onCellFocus(position)}\n isFirstColumn={i === 0}\n isLastColumn={i === cells.length - 1}\n description={description}\n color={cellConfig?.textColor ?? undefined}\n backgroundColor={cellConfig?.backgroundColor ?? undefined}\n dataLink={cell.column.columnDef.meta?.dataLink}\n adjacentCellsValuesMap={adjacentCellsValuesMap}\n >\n {cellConfig?.text || cellContent}\n </TableCell>\n );\n })}\n </>\n );\n }}\n />\n </Box>\n );\n}\n"],"names":["Box","TablePagination","TableRow","MuiTableRow","flexRender","forwardRef","useMemo","useRef","TableVirtuoso","useVirtualizedTableKeyboardNav","InnerTable","TableBody","TableCell","TableFoot","TableHead","TableHeaderCell","TableToolbar","VirtualizedTableContainer","VirtuosoTableComponents","Scroller","context","_","props","ref","Table","width","density","onKeyDown","onTableKeyDown","onBlur","onTableBlur","item","rowEventOpts","id","index","onClick","e","onRowClick","onMouseOver","onRowMouseOver","onMouseOut","onRowMouseOut","VirtualizedTable","height","defaultColumnWidth","defaultColumnHeight","rows","columns","headers","cellConfigs","pagination","onPaginationChange","rowCount","toolbarConfig","virtuosoRef","visibleRange","startIndex","endIndex","setVisibleRange","newVisibleRange","current","keyboardNav","virtualTable","maxRows","length","maxColumns","getFocusState","cellPosition","row","activeCell","column","isActive","tableContext","handleChangePage","_event","newPage","pageIndex","handleChangeRowsPerPage","event","pageSize","parseInt","target","value","columnSizeVars","forEach","headerGroup","filter","header","getCanResize","getSize","style","data","components","rangeChanged","fixedHeaderContent","map","i","position","isSorted","getIsSorted","nextSorting","getNextSortingOrder","onSort","getCanSort","getToggleSortingHandler","undefined","sortDirection","nextSortDirection","align","columnDef","meta","variant","description","headerDescription","focusState","onFocusTrigger","onCellFocus","isFirstColumn","isLastColumn","resizeConfig","resizeHandler","getResizeHandler","resetSizeHandler","resetSize","isResizing","getIsResizing","getContext","fixedFooterContent","sx","backgroundColor","theme","palette","background","default","colSpan","count","page","rowsPerPage","onPageChange","onRowsPerPageChange","itemContent","getVisibleCells","cell","cells","cellContext","cellConfig","cellRenderFn","cellContent","cellDescriptionDef","cellDescription","adjacentCellsValuesMap","Object","entries","original","includes","reduce","acc","key","String","data-testid","title","text","color","textColor","dataLink"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,GAAG,EAAEC,eAAe,EAAEC,YAAYC,WAAW,QAAQ,gBAAgB;AAE9E,SAASC,UAAU,QAAQ,wBAAwB;AAEnD,SAASC,UAAU,EAAEC,OAAO,EAAEC,MAAM,QAAQ,QAAQ;AAEpD,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,SAASC,8BAA8B,QAAQ,4CAAyC;AACxF,SAASC,UAAU,QAAQ,kBAAe;AAE1C,SAASC,SAAS,QAAQ,iBAAc;AAExC,SAASC,SAAS,QAAQ,iBAAc;AACxC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AAK,CAACC,KAAK3E,MAAM,GAAM,CAAA;oCACtB,GAAG0E,GAAG;oCACN,CAACC,IAAI,EAAEC,OAAO5E;gCAChB,CAAA,GACA,CAAC;4BAGL,qBACE,KAACtE;gCAECmJ,eAAajB,KAAK7G,EAAE;gCACpB+H,OAAOhD,eAAeiC,YAAYgB,QAAQd;gCAC1C1H,OACEqH,KAAKxE,MAAM,CAACkB,YAAY,KACpB,CAAC,eAAe,EAAEsD,KAAKxE,MAAM,CAACrC,EAAE,CAAC,aAAa,CAAC,GAC/C6G,KAAKxE,MAAM,CAACmB,OAAO,MAAM7C;gCAE/BC,qBAAqBA;gCACrB+D,OAAOkC,KAAKxE,MAAM,CAACuC,SAAS,CAACC,IAAI,EAAEF;gCACnClF,SAASA;gCACTwF,YAAYhD,cAAc+B;gCAC1BkB,gBAAgB,IAAMtD,YAAYuD,WAAW,CAACnB;gCAC9CoB,eAAerB,MAAM;gCACrBsB,cAActB,MAAM+C,MAAM/E,MAAM,GAAG;gCACnCgD,aAAaA;gCACbkD,OAAOjB,YAAYkB,aAAa1D;gCAChCwB,iBAAiBgB,YAAYhB,mBAAmBxB;gCAChD2D,UAAUtB,KAAKxE,MAAM,CAACuC,SAAS,CAACC,IAAI,EAAEsD;gCACtCd,wBAAwBA;0CAEvBL,YAAYgB,QAAQd;+BArBhBL,KAAK7G,EAAE;wBAwBlB;;gBAGN;;;;AAIR"}
@@ -1 +1 @@
1
- {"version":3,"file":"useVirtualizedTableKeyboardNav.d.ts","sourceRoot":"","sources":["../../../src/Table/hooks/useVirtualizedTableKeyboardNav.tsx"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,gBAAgB,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAClG,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAE1D,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAGtE,UAAU,mCAAo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AC;KAClB,CAAC,CAAC;IACH,YAAY,EAAE,SAAS,CAAC,mBAAmB,CAAC,CAAC;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,KAAK,iBAAiB,GAAG;IACvB,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF;;GAEG;AACH,wBAAgB,8BAA8B,CAAC,EAC7C,YAAY,EACZ,YAAY,EACZ,OAAO,EACP,UAAU,GACX,EAAE,mCAAmC,GAAG;IACvC,UAAU,EAAE,iBAAiB,CAAC;IAC9B,QAAQ,EAAE,OAAO,CAAC;IAClB,cAAc,EAAE,oBAAoB,CAAC,gBAAgB,CAAC,CAAC;IACvD,WAAW,EAAE,CAAC,YAAY,EAAE,iBAAiB,KAAK,IAAI,CAAC;IACvD,WAAW,EAAE,iBAAiB,CAAC,gBAAgB,CAAC,CAAC;CAClD,CAmFA"}
@@ -10,74 +10,79 @@
10
10
  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
11
  // See the License for the specific language governing permissions and
12
12
  // limitations under the License.
13
+ import React, { useCallback } from "react";
13
14
  import { useTableKeyboardNav } from "./useTableKeyboardNav.js";
14
15
  /**
15
16
  * Hook for managing keyboard navigation when using a virtualized table.
16
17
  */ export function useVirtualizedTableKeyboardNav({ visibleRange, virtualTable, maxRows, maxColumns }) {
17
- const baseKeyboard = useTableKeyboardNav({
18
- maxRows,
19
- maxColumns,
20
- onActiveCellChange: (e, currentPosition, defaultNewPosition)=>{
21
- const key = e.key;
22
- const defaultValueChanged = defaultNewPosition && (currentPosition.column !== defaultNewPosition.column || currentPosition.row !== defaultNewPosition.row);
23
- const nextRow = defaultNewPosition?.row ?? currentPosition.row;
24
- if (key === 'ArrowDown' && defaultValueChanged) {
25
- // Use default cell position. Shift the virtual table scroll position
26
- // when needed to make the active cell visible.
27
- if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {
28
- virtualTable.current?.scrollToIndex({
29
- index: nextRow - 1,
30
- align: 'end'
31
- });
32
- }
33
- } else if (key === 'ArrowUp' && defaultValueChanged) {
34
- // Use default cell position. Shift the virtual table scroll position
35
- // when needed to make the active cell visible.
36
- if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {
37
- virtualTable.current?.scrollToIndex({
38
- index: nextRow - 1,
39
- align: 'start'
40
- });
41
- }
42
- } else if (defaultValueChanged && (key === 'Home' || key === 'End')) {
43
- // Use default cell position. Shift the virtual table scroll position
44
- // when needed to make the active cell visible.
45
- virtualTable.current?.scrollToIndex({
46
- index: Math.max(nextRow - 1, 0),
47
- align: 'start'
48
- });
49
- } else if (key === 'PageDown') {
50
- // Full handling of logic for `PageDown` because there is no default.
51
- e.preventDefault();
52
- let nextRow = currentPosition.row;
53
- // Add 1 to account for header
54
- nextRow = Math.min(maxRows - 1, visibleRange.current.endIndex + 1);
18
+ const onActiveCellChange = useCallback((e, currentPosition, defaultNewPosition)=>{
19
+ const key = e.key;
20
+ const defaultValueChanged = defaultNewPosition && (currentPosition.column !== defaultNewPosition.column || currentPosition.row !== defaultNewPosition.row);
21
+ const nextRow = defaultNewPosition?.row ?? currentPosition.row;
22
+ if (key === 'ArrowDown' && defaultValueChanged) {
23
+ // Use default cell position. Shift the virtual table scroll position
24
+ // when needed to make the active cell visible.
25
+ if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {
55
26
  virtualTable.current?.scrollToIndex({
56
27
  index: nextRow - 1,
57
- align: 'start'
28
+ align: 'end'
58
29
  });
59
- return {
60
- row: nextRow,
61
- column: currentPosition.column
62
- };
63
- } else if (key === 'PageUp') {
64
- // Full handling of logic for `PageUp` because there is no default.
65
- let nextRow = currentPosition.row;
66
- // Minus 1 to account for header
67
- nextRow = Math.max(0, visibleRange.current.startIndex - 1);
30
+ }
31
+ } else if (key === 'ArrowUp' && defaultValueChanged) {
32
+ // Use default cell position. Shift the virtual table scroll position
33
+ // when needed to make the active cell visible.
34
+ if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {
68
35
  virtualTable.current?.scrollToIndex({
69
36
  index: nextRow - 1,
70
- align: 'end'
37
+ align: 'start'
71
38
  });
72
- return {
73
- row: nextRow,
74
- column: currentPosition.column
75
- };
76
39
  }
77
- return defaultNewPosition;
40
+ } else if (defaultValueChanged && (key === 'Home' || key === 'End')) {
41
+ // Use default cell position. Shift the virtual table scroll position
42
+ // when needed to make the active cell visible.
43
+ virtualTable.current?.scrollToIndex({
44
+ index: Math.max(nextRow - 1, 0),
45
+ align: 'start'
46
+ });
47
+ } else if (key === 'PageDown') {
48
+ // Full handling of logic for `PageDown` because there is no default.
49
+ e.preventDefault();
50
+ let nextRow = currentPosition.row;
51
+ // Add 1 to account for header
52
+ nextRow = Math.min(maxRows - 1, visibleRange.current.endIndex + 1);
53
+ virtualTable.current?.scrollToIndex({
54
+ index: nextRow - 1,
55
+ align: 'start'
56
+ });
57
+ return {
58
+ row: nextRow,
59
+ column: currentPosition.column
60
+ };
61
+ } else if (key === 'PageUp') {
62
+ // Full handling of logic for `PageUp` because there is no default.
63
+ let nextRow = currentPosition.row;
64
+ // Minus 1 to account for header
65
+ nextRow = Math.max(0, visibleRange.current.startIndex - 1);
66
+ virtualTable.current?.scrollToIndex({
67
+ index: nextRow - 1,
68
+ align: 'end'
69
+ });
70
+ return {
71
+ row: nextRow,
72
+ column: currentPosition.column
73
+ };
78
74
  }
75
+ return defaultNewPosition;
76
+ }, [
77
+ maxRows,
78
+ visibleRange,
79
+ virtualTable
80
+ ]);
81
+ return useTableKeyboardNav({
82
+ maxRows,
83
+ maxColumns,
84
+ onActiveCellChange
79
85
  });
80
- return baseKeyboard;
81
86
  }
82
87
 
83
88
  //# sourceMappingURL=useVirtualizedTableKeyboardNav.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/Table/hooks/useVirtualizedTableKeyboardNav.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { FocusEventHandler, KeyboardEventHandler, MutableRefObject, RefObject } from 'react';\nimport type { TableVirtuosoHandle } from 'react-virtuoso';\n\nimport type { UseTableKeyboardNavProps } from './useTableKeyboardNav';\nimport { useTableKeyboardNav } from './useTableKeyboardNav';\n\ninterface UseVirtualizedTableKeyboardNavProps extends Omit<UseTableKeyboardNavProps, 'onActiveCellChange'> {\n visibleRange: MutableRefObject<{\n startIndex: number;\n endIndex: number;\n }>;\n virtualTable: RefObject<TableVirtuosoHandle>;\n maxRows: number;\n maxColumns: number;\n}\n\ntype TableCellPosition = {\n row: number;\n column: number;\n};\n\n/**\n * Hook for managing keyboard navigation when using a virtualized table.\n */\nexport function useVirtualizedTableKeyboardNav({\n visibleRange,\n virtualTable,\n maxRows,\n maxColumns,\n}: UseVirtualizedTableKeyboardNavProps): {\n activeCell: TableCellPosition;\n isActive: boolean;\n onTableKeyDown: KeyboardEventHandler<HTMLTableElement>;\n onCellFocus: (cellPosition: TableCellPosition) => void;\n onTableBlur: FocusEventHandler<HTMLTableElement>;\n} {\n const baseKeyboard = useTableKeyboardNav({\n maxRows,\n maxColumns,\n onActiveCellChange: (e, currentPosition, defaultNewPosition) => {\n const key = e.key;\n\n const defaultValueChanged =\n defaultNewPosition &&\n (currentPosition.column !== defaultNewPosition.column || currentPosition.row !== defaultNewPosition.row);\n const nextRow = defaultNewPosition?.row ?? currentPosition.row;\n\n if (key === 'ArrowDown' && defaultValueChanged) {\n // Use default cell position. Shift the virtual table scroll position\n // when needed to make the active cell visible.\n if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'end',\n });\n }\n } else if (key === 'ArrowUp' && defaultValueChanged) {\n // Use default cell position. Shift the virtual table scroll position\n // when needed to make the active cell visible.\n if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'start',\n });\n }\n } else if (defaultValueChanged && (key === 'Home' || key === 'End')) {\n // Use default cell position. Shift the virtual table scroll position\n // when needed to make the active cell visible.\n virtualTable.current?.scrollToIndex({\n index: Math.max(nextRow - 1, 0),\n align: 'start',\n });\n } else if (key === 'PageDown') {\n // Full handling of logic for `PageDown` because there is no default.\n e.preventDefault();\n\n let nextRow = currentPosition.row;\n // Add 1 to account for header\n\n nextRow = Math.min(maxRows - 1, visibleRange.current.endIndex + 1);\n\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'start',\n });\n\n return {\n row: nextRow,\n column: currentPosition.column,\n };\n } else if (key === 'PageUp') {\n // Full handling of logic for `PageUp` because there is no default.\n let nextRow = currentPosition.row;\n // Minus 1 to account for header\n nextRow = Math.max(0, visibleRange.current.startIndex - 1);\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'end',\n });\n\n return {\n row: nextRow,\n column: currentPosition.column,\n };\n }\n\n return defaultNewPosition;\n },\n });\n\n return baseKeyboard;\n}\n"],"names":["useTableKeyboardNav","useVirtualizedTableKeyboardNav","visibleRange","virtualTable","maxRows","maxColumns","baseKeyboard","onActiveCellChange","e","currentPosition","defaultNewPosition","key","defaultValueChanged","column","row","nextRow","current","startIndex","endIndex","scrollToIndex","index","align","Math","max","preventDefault","min"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,s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AAIV,QAAQ,YAAY;gBAC7B,qEAAqE;gBACrEH,EAAEgB,cAAc;gBAEhB,IAAIT,UAAUN,gBAAgBK,GAAG;gBACjC,8BAA8B;gBAE9BC,UAAUO,KAAKG,GAAG,CAACrB,UAAU,GAAGF,aAAac,OAAO,CAACE,QAAQ,GAAG;gBAEhEf,aAAaa,OAAO,EAAEG,cAAc;oBAClCC,OAAOL,UAAU;oBACjBM,OAAO;gBACT;gBAEA,OAAO;oBACLP,KAAKC;oBACLF,QAAQJ,gBAAgBI,MAAM;gBAChC;YACF,OAAO,IAAIF,QAAQ,UAAU;gBAC3B,mEAAmE;gBACnE,IAAII,UAAUN,gBAAgBK,GAAG;gBACjC,gCAAgC;gBAChCC,UAAUO,KAAKC,GAAG,CAAC,GAAGrB,aAAac,OAAO,CAACC,UAAU,GAAG;gBACxDd,aAAaa,OAAO,EAAEG,cAAc;oBAClCC,OAAOL,UAAU;oBACjBM,OAAO;gBACT;gBAEA,OAAO;oBACLP,KAAKC;oBACLF,QAAQJ,gBAAgBI,MAAM;gBAChC;YACF;YAEA,OAAOH;QACT;IACF;IAEA,OAAOJ;AACT"}
1
+ {"version":3,"sources":["../../../src/Table/hooks/useVirtualizedTableKeyboardNav.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { FocusEventHandler, KeyboardEventHandler, MutableRefObject, RefObject } from 'react';\nimport React, { useCallback } from 'react';\nimport type { TableVirtuosoHandle } from 'react-virtuoso';\n\nimport type { UseTableKeyboardNavProps } from './useTableKeyboardNav';\nimport { useTableKeyboardNav } from './useTableKeyboardNav';\n\ninterface UseVirtualizedTableKeyboardNavProps extends Omit<UseTableKeyboardNavProps, 'onActiveCellChange'> {\n visibleRange: MutableRefObject<{\n startIndex: number;\n endIndex: number;\n }>;\n virtualTable: RefObject<TableVirtuosoHandle>;\n maxRows: number;\n maxColumns: number;\n}\n\ntype TableCellPosition = {\n row: number;\n column: number;\n};\n\n/**\n * Hook for managing keyboard navigation when using a virtualized table.\n */\nexport function useVirtualizedTableKeyboardNav({\n visibleRange,\n virtualTable,\n maxRows,\n maxColumns,\n}: UseVirtualizedTableKeyboardNavProps): {\n activeCell: TableCellPosition;\n isActive: boolean;\n onTableKeyDown: KeyboardEventHandler<HTMLTableElement>;\n onCellFocus: (cellPosition: TableCellPosition) => void;\n onTableBlur: FocusEventHandler<HTMLTableElement>;\n} {\n const onActiveCellChange = useCallback(\n (\n e: React.KeyboardEvent<HTMLTableElement>,\n currentPosition: TableCellPosition,\n defaultNewPosition: TableCellPosition | undefined,\n ) => {\n const key = e.key;\n\n const defaultValueChanged =\n defaultNewPosition &&\n (currentPosition.column !== defaultNewPosition.column || currentPosition.row !== defaultNewPosition.row);\n const nextRow = defaultNewPosition?.row ?? currentPosition.row;\n\n if (key === 'ArrowDown' && defaultValueChanged) {\n // Use default cell position. Shift the virtual table scroll position\n // when needed to make the active cell visible.\n if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'end',\n });\n }\n } else if (key === 'ArrowUp' && defaultValueChanged) {\n // Use default cell position. Shift the virtual table scroll position\n // when needed to make the active cell visible.\n if (nextRow - 1 < visibleRange.current.startIndex || nextRow - 1 > visibleRange.current.endIndex) {\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'start',\n });\n }\n } else if (defaultValueChanged && (key === 'Home' || key === 'End')) {\n // Use default cell position. Shift the virtual table scroll position\n // when needed to make the active cell visible.\n virtualTable.current?.scrollToIndex({\n index: Math.max(nextRow - 1, 0),\n align: 'start',\n });\n } else if (key === 'PageDown') {\n // Full handling of logic for `PageDown` because there is no default.\n e.preventDefault();\n\n let nextRow = currentPosition.row;\n // Add 1 to account for header\n\n nextRow = Math.min(maxRows - 1, visibleRange.current.endIndex + 1);\n\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'start',\n });\n\n return {\n row: nextRow,\n column: currentPosition.column,\n };\n } else if (key === 'PageUp') {\n // Full handling of logic for `PageUp` because there is no default.\n let nextRow = currentPosition.row;\n // Minus 1 to account for header\n nextRow = Math.max(0, visibleRange.current.startIndex - 1);\n virtualTable.current?.scrollToIndex({\n index: nextRow - 1,\n align: 'end',\n });\n\n return {\n row: nextRow,\n column: currentPosition.column,\n };\n }\n\n return defaultNewPosition;\n },\n [maxRows, visibleRange, virtualTable],\n );\n\n return useTableKeyboardNav({\n maxRows,\n maxColumns,\n onActiveCellChange,\n });\n}\n"],"names":["React","useCallback","useTableKeyboardNav","useVirtualizedTableKeyboardNav","visibleRange","virtualTable","maxRows","maxColumns","onActiveCellChange","e","currentPosition","defaultNewPosition","key","defaultValueChanged","column","row","nextRow","current","startIndex","endIndex","scrollToIndex","index","align","Math","max","preventDefault","min"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,OAAOA,SAASC,WAAW,QAAQ,QAAQ;AAI3C,SAASC,mBAAmB,QAAQ,2BAAwB;AAiB5D;;CAEC,GACD,OAAO,SAASC,+BAA+B,EAC7CC,YAAY,EACZC,YAAY,EACZC,OAAO,EACPC,UAAU,EAC0B;IAOpC,MAAMC,qBAAqBP,YACzB,CACEQ,GACAC,iBACAC;QAEA,MAAMC,MAAMH,EAAEG,GAAG;QAEjB,MAAMC,sBACJF,sBACCD,CAAAA,gBAAgBI,MAAM,K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E;YACnE,IAAII,UAAUN,gBAAgBK,GAAG;YACjC,gCAAgC;YAChCC,UAAUO,KAAKC,GAAG,CAAC,GAAGpB,aAAaa,OAAO,CAACC,UAAU,GAAG;YACxDb,aAAaY,OAAO,EAAEG,cAAc;gBAClCC,OAAOL,UAAU;gBACjBM,OAAO;YACT;YAEA,OAAO;gBACLP,KAAKC;gBACLF,QAAQJ,gBAAgBI,MAAM;YAChC;QACF;QAEA,OAAOH;IACT,GACA;QAACL;QAASF;QAAcC;KAAa;IAGvC,OAAOH,oBAAoB;QACzBI;QACAC;QACAC;IACF;AACF"}
@@ -53,6 +53,7 @@ import { buildCustomTimeOption, formatTimeRange } from "./utils.js";
53
53
  label: o.display
54
54
  }));
55
55
  const tzAutocompleteValue = tzAutocompleteOptions.find((option)=>option.id === timeZone);
56
+ const displayValue = timeOptions.find((opt)=>formatTimeRange(opt.value, timeZone) === formatTimeRange(value, timeZone))?.display ?? formatTimeRange(value, timeZone);
56
57
  return /*#__PURE__*/ _jsxs(_Fragment, {
57
58
  children: [
58
59
  /*#__PURE__*/ _jsx(Popover, {
@@ -132,7 +133,7 @@ import { buildCustomTimeOption, formatTimeRange } from "./utils.js";
132
133
  spacing: 1,
133
134
  children: [
134
135
  /*#__PURE__*/ _jsx("span", {
135
- children: timeOptions.find((opt)=>formatTimeRange(opt.value, timeZone) === formatTimeRange(value, timeZone))?.display ?? formatTimeRange(value, timeZone)
136
+ children: displayValue
136
137
  }),
137
138
  tzOffset !== localOffset && /*#__PURE__*/ _jsxs(Box, {
138
139
  sx: {
@@ -147,7 +148,7 @@ import { buildCustomTimeOption, formatTimeRange } from "./utils.js";
147
148
  ]
148
149
  }),
149
150
  inputProps: {
150
- 'aria-label': `Select time range. Currently set to ${value}`
151
+ 'aria-label': `Select time range. Currently set to ${displayValue}`
151
152
  },
152
153
  sx: {
153
154
  '.MuiSelect-icon': {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/TimeRangeSelector/TimeRangeSelector.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Box, MenuItem, Popover, Select, IconButton, TextField, Stack } from '@mui/material';\nimport type { TimeRangeValue, AbsoluteTimeRange } from '@perses-dev/spec';\nimport { isRelativeTimeRange, toAbsoluteTimeRange } from '@perses-dev/spec';\nimport Calendar from 'mdi-material-ui/Calendar';\nimport EarthIcon from 'mdi-material-ui/Earth';\nimport type { ReactElement } from 'react';\nimport { useMemo, useState } from 'react';\n\nimport { useTimeZone } from '../context';\nimport type { TimeOption } from '../model';\nimport type { TimeZoneOption } from '../model/timeZoneOption';\nimport { getTimeZoneOptions } from '../model/timeZoneOption';\nimport { SettingsAutocomplete } from '../SettingsAutocomplete';\nimport { getGMTOffset } from '../utils/format';\nimport { DateTimeRangePicker } from './DateTimeRangePicker';\nimport { buildCustomTimeOption, formatTimeRange } from './utils';\n\ninterface TimeRangeSelectorProps {\n /**\n * The current value of the time range.\n */\n value: TimeRangeValue;\n /**\n * The list of time options to display in the dropdown.\n * The component will automatically add the last two options as a zoom out x2 and a custom absolute time range.\n */\n timeOptions: TimeOption[];\n /**\n * The callback to call when the time range changes.\n */\n onChange: (value: TimeRangeValue) => void;\n /**\n * Custom line height for the select component.\n */\n height?: string;\n /**\n * Whether to show the custom time range option.\n * Defaults to true.\n */\n showCustomTimeRange?: boolean;\n /** Optional explicit timezone and change handler to enable changing tz from the selector */\n timeZone?: string;\n timeZoneOptions?: TimeZoneOption[];\n onTimeZoneChange?: (timeZone: TimeZoneOption) => void;\n}\n\n/**\n * Date & time selection component to customize what data renders on dashboard.\n * This includes relative shortcuts and the ability to pick absolute start and end times.\n * @param props\n * @constructor\n */\nexport function TimeRangeSelector({\n value,\n timeOptions,\n onChange,\n height,\n showCustomTimeRange = true,\n timeZone: timeZoneProp,\n timeZoneOptions,\n onTimeZoneChange,\n}: TimeRangeSelectorProps): ReactElement {\n const { timeZone: ctxTimeZone } = useTimeZone();\n const timeZone = timeZoneProp ?? ctxTimeZone;\n\n const [anchorEl, setAnchorEl] = useState<HTMLDivElement | null>(null);\n const [showCustomDateSelector, setShowCustomDateSelector] = useState(false);\n\n const convertedTimeRange = useMemo(() => {\n return isRelativeTimeRange(value) ? toAbsoluteTimeRange(value) : value;\n }, [value]);\n\n const lastOption = useMemo(\n () => buildCustomTimeOption(isRelativeTimeRange(value) ? undefined : value, timeZone),\n [value, timeZone],\n );\n\n const [open, setOpen] = useState(false);\n const tzOptions = timeZoneOptions ?? getTimeZoneOptions();\n const [tzAnchorEl, setTzAnchorEl] = useState<HTMLElement | null>(null);\n const tzOpen = Boolean(tzAnchorEl);\n const tzLabel = tzOptions.find((o) => o.value === timeZone)?.display ?? timeZone;\n const tzOffset = getGMTOffset(timeZone);\n const localOffset = getGMTOffset('local');\n const tzAutocompleteOptions = tzOptions.map((o) => ({ id: o.value, label: o.display }));\n const tzAutocompleteValue = tzAutocompleteOptions.find((option) => option.id === timeZone);\n\n return (\n <>\n <Popover\n anchorEl={tzAnchorEl}\n anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}\n transformOrigin={{ vertical: 'top', horizontal: 'right' }}\n open={tzOpen}\n onClose={() => setTzAnchorEl(null)}\n sx={(theme) => ({ padding: theme.spacing(1) })}\n >\n <Box\n sx={{ p: 1, minWidth: 260 }}\n onClick={(e) => {\n e.stopPropagation();\n }}\n >\n <SettingsAutocomplete\n options={tzAutocompleteOptions}\n value={tzAutocompleteValue}\n onChange={(_e, option) => {\n if (option) {\n const selected = tzOptions.find((o) => o.value === option.id);\n if (selected) onTimeZoneChange?.(selected);\n }\n setTzAnchorEl(null);\n }}\n disableClearable\n renderInput={(params) => <TextField {...params} placeholder=\"Search timezones\" size=\"small\" />}\n />\n </Box>\n </Popover>\n <Popover\n anchorEl={anchorEl}\n anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}\n open={showCustomDateSelector}\n onClose={() => setShowCustomDateSelector(false)}\n sx={(theme) => ({ padding: theme.spacing(2) })}\n >\n <DateTimeRangePicker\n initialTimeRange={convertedTimeRange}\n onChange={(value: AbsoluteTimeRange) => {\n onChange(value);\n setShowCustomDateSelector(false);\n setOpen(false);\n }}\n onCancel={() => setShowCustomDateSelector(false)}\n timeZone={timeZone}\n />\n </Popover>\n <Box ref={setAnchorEl}>\n <Select\n open={open}\n value={formatTimeRange(value, timeZone)}\n onClick={() => setOpen(!open)}\n IconComponent={Calendar}\n renderValue={() => (\n <Stack direction=\"row\" alignItems=\"center\" spacing={1}>\n <span>\n {timeOptions.find((opt) => formatTimeRange(opt.value, timeZone) === formatTimeRange(value, timeZone))\n ?.display ?? formatTimeRange(value, timeZone)}\n </span>\n {tzOffset !== localOffset && (\n <Box sx={{ typography: 'caption', color: 'text.secondary' }}>· {tzOffset}</Box>\n )}\n </Stack>\n )}\n inputProps={{ 'aria-label': `Select time range. Currently set to ${value}` }}\n sx={{\n '.MuiSelect-icon': { marginTop: '1px', transform: 'none' },\n '.MuiSelect-select.MuiSelect-outlined.MuiInputBase-input': { paddingRight: '36px' },\n '.MuiSelect-select': height ? { lineHeight: height, paddingY: 0 } : {},\n }}\n >\n <MenuItem\n disableRipple\n onClick={(e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n sx={{ cursor: 'default', '&:hover': { backgroundColor: 'transparent' }, py: 0.5, px: 1 }}\n >\n <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'space-between' }}>\n <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>\n <Box sx={{ typography: 'subtitle1' }}>Time Range</Box>\n <Box sx={{ color: 'text.secondary', typography: 'caption', mt: 0.25 }}>Timezone: {tzLabel}</Box>\n </Box>\n <Box sx={{ display: 'flex', alignItems: 'center', pr: 1, ml: 1.5 }}>\n <IconButton\n size=\"small\"\n aria-label=\"Select timezone\"\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n setTzAnchorEl(e.currentTarget);\n }}\n >\n <EarthIcon fontSize=\"small\" />\n </IconButton>\n </Box>\n </Box>\n </MenuItem>\n {timeOptions.map((item, idx) => (\n <MenuItem\n key={idx}\n value={formatTimeRange(item.value, timeZone)}\n onClick={() => {\n onChange(item.value);\n }}\n >\n {item.display}\n </MenuItem>\n ))}\n {showCustomTimeRange && (\n <MenuItem\n value={formatTimeRange(lastOption.value, timeZone)}\n onClick={() => setShowCustomDateSelector(true)}\n >\n {lastOption.display}\n </MenuItem>\n )}\n </Select>\n </Box>\n </>\n );\n}\n"],"names":["Box","MenuItem","Popover","Select","IconButton","TextField","Stack","isRelativeTimeRange","toAbsoluteTimeRange","Calendar","EarthIcon","useMemo","useState","useTimeZone","getTimeZoneOptions","SettingsAutocomplete","getGMTOffset","DateTimeRangePicker","buildCustomTimeOption","formatTimeRange","TimeRangeSelector","value","timeOptions","onChange","height","showCustomTimeRange","timeZone","timeZoneProp","timeZoneOptions","onTimeZoneChange","ctxTimeZone","anchorEl","setAnchorEl","showCustomDateSelector","setShowCustomDateSelector","convertedTimeRange","lastOption","undefined","open","setOpen","tzOptions","tzAnchorEl","setTzAnchorEl","tzOpen","Boolean","tzLabel","find","o","display","tzOffset","localOffset","tzAutocompleteOptions","map","id","label","tzAutocompleteValue","option","anchorOrigin","vertical","horizontal","transformOrigin","onClose","sx","theme","padding","spacing","p","minWidth","onClick","e","stopPropagation","options","_e","selected","disableClearable","renderInput","params","placeholder","size","initialTimeRange","onCancel","ref","IconComponent","renderValue","direction","alignItems","span","opt","typography","color","inputProps","marginTop","transform","paddingRight","lineHeight","paddingY","disableRipple","preventDefault","cursor","backgroundColor","py","px","width","justifyContent","flexDirection","mt","pr","ml","aria-label","current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yright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Box, MenuItem, Popover, Select, IconButton, TextField, Stack } from '@mui/material';\nimport type { TimeRangeValue, AbsoluteTimeRange } from '@perses-dev/spec';\nimport { isRelativeTimeRange, toAbsoluteTimeRange } from '@perses-dev/spec';\nimport Calendar from 'mdi-material-ui/Calendar';\nimport EarthIcon from 'mdi-material-ui/Earth';\nimport type { ReactElement } from 'react';\nimport { useMemo, useState } from 'react';\n\nimport { useTimeZone } from '../context';\nimport type { TimeOption } from '../model';\nimport type { TimeZoneOption } from '../model/timeZoneOption';\nimport { getTimeZoneOptions } from '../model/timeZoneOption';\nimport { SettingsAutocomplete } from '../SettingsAutocomplete';\nimport { getGMTOffset } from '../utils/format';\nimport { DateTimeRangePicker } from './DateTimeRangePicker';\nimport { buildCustomTimeOption, formatTimeRange } from './utils';\n\ninterface TimeRangeSelectorProps {\n /**\n * The current value of the time range.\n */\n value: TimeRangeValue;\n /**\n * The list of time options to display in the dropdown.\n * The component will automatically add the last two options as a zoom out x2 and a custom absolute time range.\n */\n timeOptions: TimeOption[];\n /**\n * The callback to call when the time range changes.\n */\n onChange: (value: TimeRangeValue) => void;\n /**\n * Custom line height for the select component.\n */\n height?: string;\n /**\n * Whether to show the custom time range option.\n * Defaults to true.\n */\n showCustomTimeRange?: boolean;\n /** Optional explicit timezone and change handler to enable changing tz from the selector */\n timeZone?: string;\n timeZoneOptions?: TimeZoneOption[];\n onTimeZoneChange?: (timeZone: TimeZoneOption) => void;\n}\n\n/**\n * Date & time selection component to customize what data renders on dashboard.\n * This includes relative shortcuts and the ability to pick absolute start and end times.\n * @param props\n * @constructor\n */\nexport function TimeRangeSelector({\n value,\n timeOptions,\n onChange,\n height,\n showCustomTimeRange = true,\n timeZone: timeZoneProp,\n timeZoneOptions,\n onTimeZoneChange,\n}: TimeRangeSelectorProps): ReactElement {\n const { timeZone: ctxTimeZone } = useTimeZone();\n const timeZone = timeZoneProp ?? ctxTimeZone;\n\n const [anchorEl, setAnchorEl] = useState<HTMLDivElement | null>(null);\n const [showCustomDateSelector, setShowCustomDateSelector] = useState(false);\n\n const convertedTimeRange = useMemo(() => {\n return isRelativeTimeRange(value) ? toAbsoluteTimeRange(value) : value;\n }, [value]);\n\n const lastOption = useMemo(\n () => buildCustomTimeOption(isRelativeTimeRange(value) ? undefined : value, timeZone),\n [value, timeZone],\n );\n\n const [open, setOpen] = useState(false);\n const tzOptions = timeZoneOptions ?? getTimeZoneOptions();\n const [tzAnchorEl, setTzAnchorEl] = useState<HTMLElement | null>(null);\n const tzOpen = Boolean(tzAnchorEl);\n const tzLabel = tzOptions.find((o) => o.value === timeZone)?.display ?? timeZone;\n const tzOffset = getGMTOffset(timeZone);\n const localOffset = getGMTOffset('local');\n const tzAutocompleteOptions = tzOptions.map((o) => ({ id: o.value, label: o.display }));\n const tzAutocompleteValue = tzAutocompleteOptions.find((option) => option.id === timeZone);\n const displayValue =\n timeOptions.find((opt) => formatTimeRange(opt.value, timeZone) === formatTimeRange(value, timeZone))?.display ??\n formatTimeRange(value, timeZone);\n\n return (\n <>\n <Popover\n anchorEl={tzAnchorEl}\n anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}\n transformOrigin={{ vertical: 'top', horizontal: 'right' }}\n open={tzOpen}\n onClose={() => setTzAnchorEl(null)}\n sx={(theme) => ({ padding: theme.spacing(1) })}\n >\n <Box\n sx={{ p: 1, minWidth: 260 }}\n onClick={(e) => {\n e.stopPropagation();\n }}\n >\n <SettingsAutocomplete\n options={tzAutocompleteOptions}\n value={tzAutocompleteValue}\n onChange={(_e, option) => {\n if (option) {\n const selected = tzOptions.find((o) => o.value === option.id);\n if (selected) onTimeZoneChange?.(selected);\n }\n setTzAnchorEl(null);\n }}\n disableClearable\n renderInput={(params) => <TextField {...params} placeholder=\"Search timezones\" size=\"small\" />}\n />\n </Box>\n </Popover>\n <Popover\n anchorEl={anchorEl}\n anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}\n open={showCustomDateSelector}\n onClose={() => setShowCustomDateSelector(false)}\n sx={(theme) => ({ padding: theme.spacing(2) })}\n >\n <DateTimeRangePicker\n initialTimeRange={convertedTimeRange}\n onChange={(value: AbsoluteTimeRange) => {\n onChange(value);\n setShowCustomDateSelector(false);\n setOpen(false);\n }}\n onCancel={() => setShowCustomDateSelector(false)}\n timeZone={timeZone}\n />\n </Popover>\n <Box ref={setAnchorEl}>\n <Select\n open={open}\n value={formatTimeRange(value, timeZone)}\n onClick={() => setOpen(!open)}\n IconComponent={Calendar}\n renderValue={() => (\n <Stack direction=\"row\" alignItems=\"center\" spacing={1}>\n <span>{displayValue}</span>\n {tzOffset !== localOffset && (\n <Box sx={{ typography: 'caption', color: 'text.secondary' }}>· {tzOffset}</Box>\n )}\n </Stack>\n )}\n inputProps={{ 'aria-label': `Select time range. Currently set to ${displayValue}` }}\n sx={{\n '.MuiSelect-icon': { marginTop: '1px', transform: 'none' },\n '.MuiSelect-select.MuiSelect-outlined.MuiInputBase-input': { paddingRight: '36px' },\n '.MuiSelect-select': height ? { lineHeight: height, paddingY: 0 } : {},\n }}\n >\n <MenuItem\n disableRipple\n onClick={(e: React.MouseEvent) => {\n e.preventDefault();\n e.stopPropagation();\n }}\n sx={{ cursor: 'default', '&:hover': { backgroundColor: 'transparent' }, py: 0.5, px: 1 }}\n >\n <Box sx={{ display: 'flex', alignItems: 'center', width: '100%', justifyContent: 'space-between' }}>\n <Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>\n <Box sx={{ typography: 'subtitle1' }}>Time Range</Box>\n <Box sx={{ color: 'text.secondary', typography: 'caption', mt: 0.25 }}>Timezone: {tzLabel}</Box>\n </Box>\n <Box sx={{ display: 'flex', alignItems: 'center', pr: 1, ml: 1.5 }}>\n <IconButton\n size=\"small\"\n aria-label=\"Select timezone\"\n onClick={(e) => {\n e.preventDefault();\n e.stopPropagation();\n setTzAnchorEl(e.currentTarget);\n }}\n >\n <EarthIcon fontSize=\"small\" />\n </IconButton>\n </Box>\n </Box>\n </MenuItem>\n {timeOptions.map((item, idx) => (\n <MenuItem\n key={idx}\n value={formatTimeRange(item.value, timeZone)}\n onClick={() => {\n onChange(item.value);\n }}\n >\n {item.display}\n </MenuItem>\n ))}\n {showCustomTimeRange && (\n <MenuItem\n value={formatTimeRange(lastOption.value, timeZone)}\n onClick={() => setShowCustomDateSelector(true)}\n >\n {lastOption.display}\n </MenuItem>\n )}\n </Select>\n </Box>\n </>\n );\n}\n"],"names":["Box","MenuItem","Popover","Select","IconButton","TextField","Stack","isRelativeTimeRange","toAbsoluteTimeRange","Calendar","EarthIcon","useMemo","useState","useTimeZone","getTimeZoneOptions","SettingsAutocomplete","getGMTOffset","DateTimeRangePicker","buildCustomTimeOption","formatTimeRange","TimeRangeSelector","value","timeOptions","onChange","height","showCustomTimeRange","timeZone","timeZoneProp","timeZoneOptions","onTimeZoneChange","ctxTimeZone","anchorEl","setAnchorEl","showCustomDateSelector","setShowCustomDateSelector","convertedTimeRange","lastOption","undefined","open","setOpen","tzOptions","tzAnchorEl","setTzAnchorEl","tzOpen","Boolean","tzLabel","find","o","display","tzOffset","localOffset","tzAutocompleteOptions","map","id","label","tzAutocompleteValue","option","displayValue","opt","anchorOrigin","vertical","horizontal","transformOrigin","onClose","sx","theme","padding","spacing","p","minWidth","onClick","e","stopPropagation","options","_e","selected","disableClearable","renderInput","params","placeholder","size","initialTimeRange","onCancel","ref","IconComponent","renderValue","direction","alignItems","span","typography","color","inputProps","marginTop","transform","paddingRight","lineHeight","paddingY","disableRipple","preventDefault","cursor","backgroundColor","py","px","width","justifyContent","flexDirection","mt","pr","ml","a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,EAAE,MAAM,EACd,aAAa,EAAE,sBAAsB,EACrC,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GAC/B,MAAM,CAcR;AAED,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,EAAE,EAAE,KAAK,EAAE,eAAe,GAAG,MAAM,CAiCnH;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CACvC,cAAc,EAAE,MAAM,EACtB,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,MAAM,GACf;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAQjC;AAED,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,MAAM,EAClB,KAAK,EAAE,eAAe,GACrB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAexC"}
@@ -28,20 +28,32 @@ import { TOOLTIP_MAX_WIDTH, TOOLTIP_MAX_HEIGHT, TOOLTIP_MIN_WIDTH, TOOLTIP_BG_CO
28
28
  const effectiveWidth = tooltipWidth > 0 ? tooltipWidth : TOOLTIP_MAX_WIDTH;
29
29
  let x = mousePos.page.x + cursorPaddingX; // Default to right side of the cursor
30
30
  let y = mousePos.page.y + cursorPaddingY;
31
+ let cursorBaseY = mousePos.page.y;
31
32
  // If containerElement is defined, adjust coordinates relative to the container
32
33
  if (containerElement) {
33
34
  const containerRect = containerElement.getBoundingClientRect();
34
35
  x = x - containerRect.left + containerElement.scrollLeft;
35
36
  y = y - containerRect.top + containerElement.scrollTop;
36
- // Ensure tooltip does not go out of the container's bottom
37
+ cursorBaseY = cursorBaseY - containerRect.top + containerElement.scrollTop;
38
+ // Ensure tooltip does not go out of the container's bottom: flip it above the
39
+ // cursor so it keeps pointing at the hovered marker instead of covering it.
37
40
  const containerBottom = containerRect.top + containerElement.scrollHeight;
38
41
  if (y + effectiveHeight > containerBottom) {
39
- y = Math.max(containerBottom - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);
42
+ y = cursorBaseY - effectiveHeight - cursorPaddingY;
43
+ // When it does not fit above the cursor either, fall back to the container bottom.
44
+ if (y < containerElement.scrollTop + TOOLTIP_PADDING / 2 || y + effectiveHeight > containerBottom) {
45
+ y = Math.max(containerBottom - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);
46
+ }
40
47
  }
41
48
  } else {
42
- // Ensure tooltip does not go out of the screen on the bottom
49
+ // Ensure tooltip does not go out of the screen on the bottom: flip it above the
50
+ // cursor so it keeps pointing at the hovered marker instead of covering it.
43
51
  if (y + effectiveHeight > window.innerHeight + window.scrollY) {
44
- y = Math.max(window.innerHeight + window.scrollY - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);
52
+ y = cursorBaseY - effectiveHeight - cursorPaddingY;
53
+ // When it does not fit above the cursor either, fall back to the screen bottom.
54
+ if (y < window.scrollY + TOOLTIP_PADDING / 2 || y + effectiveHeight > window.innerHeight + window.scrollY) {
55
+ y = Math.max(window.innerHeight + window.scrollY - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);
56
+ }
45
57
  }
46
58
  }
47
59
  // Ensure tooltip does not go out of the screen on the right
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/TimeSeriesTooltip/utils.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { Theme } from '@mui/material';\nimport type { BarSeriesOption, LineSeriesOption } from 'echarts/charts';\nimport type { ECharts as EChartsInstance } from 'echarts/core';\n\nimport type { TimeChartSeriesMapping } from '../model';\nimport type { CursorCoordinates, CursorData } from './tooltip-model';\nimport {\n TOOLTIP_MAX_WIDTH,\n TOOLTIP_MAX_HEIGHT,\n TOOLTIP_MIN_WIDTH,\n TOOLTIP_BG_COLOR_FALLBACK,\n TOOLTIP_PADDING,\n} from './tooltip-model';\n\n/**\n * Determine position of tooltip depending on chart dimensions and the number of focused series.\n */\nexport function assembleTransform(\n mousePos: CursorData['coords'],\n pinnedPos: CursorCoordinates | null,\n tooltipHeight: number,\n tooltipWidth: number,\n containerElement?: Element | null,\n): string | undefined {\n if (mousePos === null) {\n return undefined;\n }\n\n const cursorPaddingX = 32;\n const cursorPaddingY = 16;\n\n if (pinnedPos !== null) {\n mousePos = pinnedPos;\n }\n\n if (mousePos.plotCanvas.x === undefined) return undefined;\n\n // Fall back to max size before the resize observer reports a real measurement.\n const effectiveHeight = tooltipHeight > 0 ? tooltipHeight : TOOLTIP_MAX_HEIGHT;\n const effectiveWidth = tooltipWidth > 0 ? tooltipWidth : TOOLTIP_MAX_WIDTH;\n\n let x = mousePos.page.x + cursorPaddingX; // Default to right side of the cursor\n let y = mousePos.page.y + cursorPaddingY;\n\n // If containerElement is defined, adjust coordinates relative to the container\n if (containerElement) {\n const containerRect = containerElement.getBoundingClientRect();\n x = x - containerRect.left + containerElement.scrollLeft;\n y = y - containerRect.top + containerElement.scrollTop;\n\n // Ensure tooltip does not go out of the container's bottom\n const containerBottom = containerRect.top + containerElement.scrollHeight;\n if (y + effectiveHeight > containerBottom) {\n y = Math.max(containerBottom - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);\n }\n } else {\n // Ensure tooltip does not go out of the screen on the bottom\n if (y + effectiveHeight > window.innerHeight + window.scrollY) {\n y = Math.max(window.innerHeight + window.scrollY - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);\n }\n }\n\n // Ensure tooltip does not go out of the screen on the right\n if (x + effectiveWidth > window.innerWidth) {\n x = mousePos.page.x - effectiveWidth - cursorPaddingX; // Move to the left of the cursor\n }\n\n // Ensure tooltip does not go out of the screen on the left\n if (x < cursorPaddingX) {\n x = cursorPaddingX;\n }\n\n // Ensure tooltip does not go out of the screen on the top\n if (y < TOOLTIP_PADDING / 2) {\n y = TOOLTIP_PADDING / 2;\n }\n\n return `translate3d(${x}px, ${y}px, 0)`;\n}\n\n/**\n * Stacking level of a pinned tooltip. It must cover the table legend's sticky header, which\n * react-virtuoso renders at z-index 2, and stay below PanelHeader (5, in @perses-dev/dashboards),\n * the drawer and the sticky dashboard header.\n */\nconst PINNED_TOOLTIP_Z_INDEX = 3;\n\n/**\n * Helper for tooltip positioning styles\n */\nexport function getTooltipStyles(\n theme: Theme,\n pinnedPos: CursorCoordinates | null,\n maxHeight?: number,\n): Record<string, unknown> {\n const adjustedMaxHeight = maxHeight ? maxHeight - TOOLTIP_PADDING : undefined;\n return {\n minWidth: TOOLTIP_MIN_WIDTH,\n maxWidth: TOOLTIP_MAX_WIDTH,\n maxHeight: adjustedMaxHeight ?? TOOLTIP_MAX_HEIGHT,\n padding: 0,\n position: 'absolute',\n top: 0,\n left: 0,\n backgroundColor: theme.palette.designSystem?.grey[800] ?? TOOLTIP_BG_COLOR_FALLBACK,\n borderRadius: '6px',\n color: '#fff',\n fontSize: '11px',\n visibility: 'visible',\n opacity: 1,\n // Animating transform causes intermediate positions outside the viewport; animate opacity/visibility instead.\n transition: 'opacity 0.1s ease-out, visibility 0.1s ease-out',\n zIndex: pinnedPos !== null ? PINNED_TOOLTIP_Z_INDEX : theme.zIndex.tooltip,\n overflow: 'hidden',\n '&:hover': {\n overflowY: 'auto',\n },\n };\n}\n\nexport function getPixelXFromGrid(timestamp: number, chart: EChartsInstance): number | null {\n try {\n const pixelCoords = chart.convertToPixel('grid', [timestamp, 0]);\n return pixelCoords?.[0] ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the cumulative (visual) Y for a series, accumulating stack totals in-place.\n * For non-stacked series, returns the raw yValue unchanged.\n * Mutates `stackTotals` — pass a fresh Map for each cursor evaluation.\n */\nexport function calculateVisualYForSeries(\n seriesIdx: number,\n yValue: number,\n seriesMapping: TimeChartSeriesMapping,\n stackTotals: Map<string, number>,\n): number {\n const currentSeries = seriesMapping[seriesIdx];\n if (!currentSeries) return yValue;\n\n const stackId = (currentSeries as LineSeriesOption | BarSeriesOption).stack;\n if (!stackId) {\n return yValue;\n }\n\n const stackIdStr = stackId.toString();\n const currentTotal = stackTotals.get(stackIdStr) ?? 0;\n const newTotal = currentTotal + yValue;\n stackTotals.set(stackIdStr, newTotal);\n return newTotal;\n}\n\nexport function calculateBarBandwidth(timestamp: number, sortedTimestamps: number[], chart: EChartsInstance): number {\n const currentIdx = sortedTimestamps.indexOf(timestamp);\n if (currentIdx === -1) {\n return 20;\n }\n\n const prevTimestamp = currentIdx > 0 ? (sortedTimestamps[currentIdx - 1] ?? null) : null;\n const nextTimestamp = currentIdx < sortedTimestamps.length - 1 ? (sortedTimestamps[currentIdx + 1] ?? null) : null;\n\n const currentPixelX = getPixelXFromGrid(timestamp, chart);\n if (currentPixelX === null) return 20;\n\n let leftBound: number;\n let rightBound: number;\n\n if (prevTimestamp !== null && nextTimestamp !== null) {\n const prevPixelX = getPixelXFromGrid(prevTimestamp, chart) ?? currentPixelX;\n const nextPixelX = getPixelXFromGrid(nextTimestamp, chart) ?? currentPixelX;\n leftBound = (currentPixelX + prevPixelX) / 2;\n rightBound = (currentPixelX + nextPixelX) / 2;\n } else if (prevTimestamp !== null) {\n const prevPixelX = getPixelXFromGrid(prevTimestamp, chart) ?? currentPixelX;\n leftBound = (currentPixelX + prevPixelX) / 2;\n rightBound = currentPixelX + (currentPixelX - leftBound);\n } else if (nextTimestamp !== null) {\n const nextPixelX = getPixelXFromGrid(nextTimestamp, chart) ?? currentPixelX;\n rightBound = (currentPixelX + nextPixelX) / 2;\n leftBound = currentPixelX - (rightBound - currentPixelX);\n } else {\n return 20;\n }\n\n return Math.max(1, rightBound - leftBound);\n}\n\n/**\n * Computes the pixel left/right bounds of one bar segment within a group.\n * @param barRelativeIdx - zero-based index among bar-only series\n * @param bandwidth - total pixel width for the bar group\n * @param centerPixelX - pixel X of the bar group centre\n * @param barCount - total bar series count (lines excluded)\n */\nexport function calculateBarSegmentBounds(\n barRelativeIdx: number,\n bandwidth: number,\n centerPixelX: number,\n barCount: number,\n): { left: number; right: number } {\n const count = Math.max(1, barCount);\n const segmentWidth = bandwidth / count;\n const segmentLeft = centerPixelX - bandwidth / 2 + barRelativeIdx * segmentWidth;\n return {\n left: segmentLeft,\n right: segmentLeft + segmentWidth,\n };\n}\n\nexport function calculateBarYBounds(\n visualYBottom: number,\n visualYTop: number,\n chart: EChartsInstance,\n): { top: number; bottom: number } | null {\n try {\n const bottomPixel = chart.convertToPixel('grid', [0, visualYBottom]);\n const topPixel = chart.convertToPixel('grid', [0, visualYTop]);\n\n if (!bottomPixel || !topPixel || bottomPixel[1] === undefined || topPixel[1] === undefined) return null;\n\n // Y increases downward in pixels; min/max normalizes the mapping for negative bar values.\n return {\n top: Math.min(topPixel[1], bottomPixel[1]),\n bottom: Math.max(topPixel[1], bottomPixel[1]),\n };\n } catch {\n return null;\n }\n}\n"],"names":["TOOLTIP_MAX_WIDTH","TOOLTIP_MAX_HEIGHT","TOOLTIP_MIN_WIDTH","TOOLTIP_BG_COLOR_FALLBACK","TOOLTIP_PADDING","assembleTransform","mousePos","pinnedPos","tooltipHeight","tooltipWidth","containerElement","undefined","cursorPaddingX","cursorPaddingY","plotCanvas","x","effectiveHeight","effectiveWidth","page","y","containerRect","getBoundingClientRect","left","scrollLeft","top","scrollTop","containerBottom","scrollHeight","Math","max","window","innerHeight","scrollY","innerWidth","PINNED_TOOLTIP_Z_INDEX","getTooltipStyles","theme","maxHeight","adjustedMaxHeight","minWidth","maxWidth","padding","position","backgroundColor","palette","designSystem","grey","borderRadius","color","fontSize","visibility","opacity","transition","zIndex","tooltip","overflow","overflowY","getPixelXFromGrid","timestamp","chart","pixelCoords","convertToPixel","calculateVisualYForSeries","seriesIdx","yValue","seriesMapping","stackTotals","currentSeries","stackId","stack","stackIdStr","toString","currentTotal","get","newTotal","set","calculateBarBandwidth","sortedTimestamps","currentIdx","indexOf","prevTimestamp","nextTimestamp","length","currentPixelX","leftBound","rightBound","prevPixelX","nextPixelX","calculateBarSegmentBounds","barRelativeIdx","bandwidth","centerPixelX","barCount","count","segmentWidth","segmentLeft","right","calculateBarYBounds","visualYBottom","visualYTop","bottomPixel","topPixel","min","bottom"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAQjC,SACEA,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,yBAAyB,EACzBC,eAAe,QACV,qBAAkB;AAEzB;;CAEC,GACD,OAAO,SAASC,kBACdC,QAA8B,EAC9BC,SAAmC,EACnCC,aAAqB,EACrBC,YAAoB,EACpBC,gBAAiC;IAEjC,IAAIJ,aAAa,MAAM;QACrB,OAAOK;IACT;IAEA,MAAMC,iBAAiB;IACvB,MAAMC,iBAAiB;IAEvB,IAAIN,cAAc,MAAM;QACtBD,WAAWC;IACb;IAEA,IAAID,SAASQ,UAAU,CAACC,CAAC,KAAKJ,WAAW,OAAOA;IAEhD,+EAA+E;IAC/E,MAAMK,kBAAkBR,gBAAgB,IAAIA,gBAAgBP;IAC5D,MAAMgB,iBAAiBR,eAAe,IAAIA,eAAeT;IAEzD,IAAIe,IAAIT,SAASY,IAAI,CAACH,CAAC,GAAGH,gBAAgB,sCAAsC;IAChF,IAAIO,IAAIb,SAASY,IAAI,CAACC,CAAC,GAAGN;IAE1B,+EAA+E;IAC/E,IAAIH,kBAAkB;QACpB,MAAMU,gBAAgBV,iBAAiBW,qBAAqB;QAC5D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,CAACC,YAAYD,WAAW,CAAC,EAAE,KAAKzF,aAAa0F,QAAQ,CAAC,EAAE,KAAK1F,WAAW,OAAO;QAEnG,0FAA0F;QAC1F,OAAO;YACLa,KAAKI,KAAK0E,GAAG,CAACD,QAAQ,CAAC,EAAE,EAAED,WAAW,CAAC,EAAE;YACzCG,QAAQ3E,KAAKC,GAAG,CAACwE,QAAQ,CAAC,EAAE,EAAED,WAAW,CAAC,EAAE;QAC9C;IACF,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/TimeSeriesTooltip/utils.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { Theme } from '@mui/material';\nimport type { BarSeriesOption, LineSeriesOption } from 'echarts/charts';\nimport type { ECharts as EChartsInstance } from 'echarts/core';\n\nimport type { TimeChartSeriesMapping } from '../model';\nimport type { CursorCoordinates, CursorData } from './tooltip-model';\nimport {\n TOOLTIP_MAX_WIDTH,\n TOOLTIP_MAX_HEIGHT,\n TOOLTIP_MIN_WIDTH,\n TOOLTIP_BG_COLOR_FALLBACK,\n TOOLTIP_PADDING,\n} from './tooltip-model';\n\n/**\n * Determine position of tooltip depending on chart dimensions and the number of focused series.\n */\nexport function assembleTransform(\n mousePos: CursorData['coords'],\n pinnedPos: CursorCoordinates | null,\n tooltipHeight: number,\n tooltipWidth: number,\n containerElement?: Element | null,\n): string | undefined {\n if (mousePos === null) {\n return undefined;\n }\n\n const cursorPaddingX = 32;\n const cursorPaddingY = 16;\n\n if (pinnedPos !== null) {\n mousePos = pinnedPos;\n }\n\n if (mousePos.plotCanvas.x === undefined) return undefined;\n\n // Fall back to max size before the resize observer reports a real measurement.\n const effectiveHeight = tooltipHeight > 0 ? tooltipHeight : TOOLTIP_MAX_HEIGHT;\n const effectiveWidth = tooltipWidth > 0 ? tooltipWidth : TOOLTIP_MAX_WIDTH;\n\n let x = mousePos.page.x + cursorPaddingX; // Default to right side of the cursor\n let y = mousePos.page.y + cursorPaddingY;\n let cursorBaseY = mousePos.page.y;\n\n // If containerElement is defined, adjust coordinates relative to the container\n if (containerElement) {\n const containerRect = containerElement.getBoundingClientRect();\n x = x - containerRect.left + containerElement.scrollLeft;\n y = y - containerRect.top + containerElement.scrollTop;\n cursorBaseY = cursorBaseY - containerRect.top + containerElement.scrollTop;\n\n // Ensure tooltip does not go out of the container's bottom: flip it above the\n // cursor so it keeps pointing at the hovered marker instead of covering it.\n const containerBottom = containerRect.top + containerElement.scrollHeight;\n if (y + effectiveHeight > containerBottom) {\n y = cursorBaseY - effectiveHeight - cursorPaddingY;\n // When it does not fit above the cursor either, fall back to the container bottom.\n if (y < containerElement.scrollTop + TOOLTIP_PADDING / 2 || y + effectiveHeight > containerBottom) {\n y = Math.max(containerBottom - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);\n }\n }\n } else {\n // Ensure tooltip does not go out of the screen on the bottom: flip it above the\n // cursor so it keeps pointing at the hovered marker instead of covering it.\n if (y + effectiveHeight > window.innerHeight + window.scrollY) {\n y = cursorBaseY - effectiveHeight - cursorPaddingY;\n // When it does not fit above the cursor either, fall back to the screen bottom.\n if (y < window.scrollY + TOOLTIP_PADDING / 2 || y + effectiveHeight > window.innerHeight + window.scrollY) {\n y = Math.max(window.innerHeight + window.scrollY - effectiveHeight - cursorPaddingY, TOOLTIP_PADDING / 2);\n }\n }\n }\n\n // Ensure tooltip does not go out of the screen on the right\n if (x + effectiveWidth > window.innerWidth) {\n x = mousePos.page.x - effectiveWidth - cursorPaddingX; // Move to the left of the cursor\n }\n\n // Ensure tooltip does not go out of the screen on the left\n if (x < cursorPaddingX) {\n x = cursorPaddingX;\n }\n\n // Ensure tooltip does not go out of the screen on the top\n if (y < TOOLTIP_PADDING / 2) {\n y = TOOLTIP_PADDING / 2;\n }\n\n return `translate3d(${x}px, ${y}px, 0)`;\n}\n\n/**\n * Stacking level of a pinned tooltip. It must cover the table legend's sticky header, which\n * react-virtuoso renders at z-index 2, and stay below PanelHeader (5, in @perses-dev/dashboards),\n * the drawer and the sticky dashboard header.\n */\nconst PINNED_TOOLTIP_Z_INDEX = 3;\n\n/**\n * Helper for tooltip positioning styles\n */\nexport function getTooltipStyles(\n theme: Theme,\n pinnedPos: CursorCoordinates | null,\n maxHeight?: number,\n): Record<string, unknown> {\n const adjustedMaxHeight = maxHeight ? maxHeight - TOOLTIP_PADDING : undefined;\n return {\n minWidth: TOOLTIP_MIN_WIDTH,\n maxWidth: TOOLTIP_MAX_WIDTH,\n maxHeight: adjustedMaxHeight ?? TOOLTIP_MAX_HEIGHT,\n padding: 0,\n position: 'absolute',\n top: 0,\n left: 0,\n backgroundColor: theme.palette.designSystem?.grey[800] ?? TOOLTIP_BG_COLOR_FALLBACK,\n borderRadius: '6px',\n color: '#fff',\n fontSize: '11px',\n visibility: 'visible',\n opacity: 1,\n // Animating transform causes intermediate positions outside the viewport; animate opacity/visibility instead.\n transition: 'opacity 0.1s ease-out, visibility 0.1s ease-out',\n zIndex: pinnedPos !== null ? PINNED_TOOLTIP_Z_INDEX : theme.zIndex.tooltip,\n overflow: 'hidden',\n '&:hover': {\n overflowY: 'auto',\n },\n };\n}\n\nexport function getPixelXFromGrid(timestamp: number, chart: EChartsInstance): number | null {\n try {\n const pixelCoords = chart.convertToPixel('grid', [timestamp, 0]);\n return pixelCoords?.[0] ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Returns the cumulative (visual) Y for a series, accumulating stack totals in-place.\n * For non-stacked series, returns the raw yValue unchanged.\n * Mutates `stackTotals` — pass a fresh Map for each cursor evaluation.\n */\nexport function calculateVisualYForSeries(\n seriesIdx: number,\n yValue: number,\n seriesMapping: TimeChartSeriesMapping,\n stackTotals: Map<string, number>,\n): number {\n const currentSeries = seriesMapping[seriesIdx];\n if (!currentSeries) return yValue;\n\n const stackId = (currentSeries as LineSeriesOption | BarSeriesOption).stack;\n if (!stackId) {\n return yValue;\n }\n\n const stackIdStr = stackId.toString();\n const currentTotal = stackTotals.get(stackIdStr) ?? 0;\n const newTotal = currentTotal + yValue;\n stackTotals.set(stackIdStr, newTotal);\n return newTotal;\n}\n\nexport function calculateBarBandwidth(timestamp: number, sortedTimestamps: number[], chart: EChartsInstance): number {\n const currentIdx = sortedTimestamps.indexOf(timestamp);\n if (currentIdx === -1) {\n return 20;\n }\n\n const prevTimestamp = currentIdx > 0 ? (sortedTimestamps[currentIdx - 1] ?? null) : null;\n const nextTimestamp = currentIdx < sortedTimestamps.length - 1 ? (sortedTimestamps[currentIdx + 1] ?? null) : null;\n\n const currentPixelX = getPixelXFromGrid(timestamp, chart);\n if (currentPixelX === null) return 20;\n\n let leftBound: number;\n let rightBound: number;\n\n if (prevTimestamp !== null && nextTimestamp !== null) {\n const prevPixelX = getPixelXFromGrid(prevTimestamp, chart) ?? currentPixelX;\n const nextPixelX = getPixelXFromGrid(nextTimestamp, chart) ?? currentPixelX;\n leftBound = (currentPixelX + prevPixelX) / 2;\n rightBound = (currentPixelX + nextPixelX) / 2;\n } else if (prevTimestamp !== null) {\n const prevPixelX = getPixelXFromGrid(prevTimestamp, chart) ?? currentPixelX;\n leftBound = (currentPixelX + prevPixelX) / 2;\n rightBound = currentPixelX + (currentPixelX - leftBound);\n } else if (nextTimestamp !== null) {\n const nextPixelX = getPixelXFromGrid(nextTimestamp, chart) ?? currentPixelX;\n rightBound = (currentPixelX + nextPixelX) / 2;\n leftBound = currentPixelX - (rightBound - currentPixelX);\n } else {\n return 20;\n }\n\n return Math.max(1, rightBound - leftBound);\n}\n\n/**\n * Computes the pixel left/right bounds of one bar segment within a group.\n * @param barRelativeIdx - zero-based index among bar-only series\n * @param bandwidth - total pixel width for the bar group\n * @param centerPixelX - pixel X of the bar group centre\n * @param barCount - total bar series count (lines excluded)\n */\nexport function calculateBarSegmentBounds(\n barRelativeIdx: number,\n bandwidth: number,\n centerPixelX: number,\n barCount: number,\n): { left: number; right: number } {\n const count = Math.max(1, barCount);\n const segmentWidth = bandwidth / count;\n const segmentLeft = centerPixelX - bandwidth / 2 + barRelativeIdx * segmentWidth;\n return {\n left: segmentLeft,\n right: segmentLeft + segmentWidth,\n };\n}\n\nexport function calculateBarYBounds(\n visualYBottom: number,\n visualYTop: number,\n chart: EChartsInstance,\n): { top: number; bottom: number } | null {\n try {\n const bottomPixel = chart.convertToPixel('grid', [0, visualYBottom]);\n const topPixel = chart.convertToPixel('grid', [0, visualYTop]);\n\n if (!bottomPixel || !topPixel || bottomPixel[1] === undefined || topPixel[1] === undefined) return null;\n\n // Y increases downward in pixels; min/max normalizes the mapping for negative bar values.\n return {\n top: Math.min(topPixel[1], bottomPixel[1]),\n bottom: Math.max(topPixel[1], bottomPixel[1]),\n };\n } catch {\n return null;\n }\n}\n"],"names":["TOOLTIP_MAX_WIDTH","TOOLTIP_MAX_HEIGHT","TOOLTIP_MIN_WIDTH","TOOLTIP_BG_COLOR_FALLBACK","TOOLTIP_PADDING","assembleTransform","mousePos","pinnedPos","tooltipHeight","tooltipWidth","containerElement","undefined","cursorPaddingX","cursorPaddingY","plotCanvas","x","effectiveHeight","effectiveWidth","page","y","cursorBaseY","containerRect","getBoundingClientRect","left","scrollLeft","top","scrollTop","containerBottom","scrollHeight","Math","max","window","innerHeight","scrollY","innerWidth","PINNED_TOOLTIP_Z_INDEX","getTooltipStyles","theme","maxHeight","adjustedMaxHeight","minWidth","maxWidth","padding","position","backgroundColor","palette","designSystem","grey","borderRadius","color","fontSize","visibility","opacity","transition","zIndex","tooltip","overflow","overflowY","getPixelXFromGrid","timestamp","chart","pixelCoords","convertToPixel","calculateVisualYForSeries","seriesIdx","yValue","seriesMapping","stackTotals","currentSeries","stackId","stack","stackIdStr","toString","currentTotal","get","newTotal","set","calculateBarBandwidth","sortedTimestamps","currentIdx","indexOf","prevTimestamp","nextTimestamp","length","currentPixelX","leftBound","rightBound","prevPixelX","nextPixelX","calculateBarSegmentBounds","barRelativeIdx","bandwidth","centerPixelX","barCount","count","segmentWidth","segmentLeft","right","calculateBarYBounds","visualYBottom","visualYTop","bottomPixel","topPixel","min","bottom"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAQjC,SACEA,iBAAiB,EACjBC,kBAAkB,EAClBC,iBAAiB,EACjBC,yBAAyB,EACzBC,eAAe,QACV,qBAAkB;AAEzB;;CAEC,GACD,OAAO,SAASC,kBACdC,QAA8B,EAC9BC,SAAmC,EACnCC,aAAqB,EACrBC,YAAoB,EACpBC,gBAAiC;IAEjC,IAAIJ,aAAa,MAAM;QACrB,OAAOK;IACT;IAEA,MAAMC,iBAAiB;IACvB,MAAMC,iBAAiB;IAEvB,IAAIN,cAAc,MAAM;QACtBD,WAAWC;IACb;IAEA,IAAID,SAASQ,UAAU,CAACC,CAAC,KAAKJ,WAAW,OAAOA;IAEhD,+EAA+E;IAC/E,MAAMK,kBAAkBR,gBAAgB,IAAIA,gBAAgBP;IAC5D,MAAMgB,iBAAiBR,eAAe,IAAIA,eAAeT;IAEzD,IAAIe,IAAIT,SAASY,IAAI,CAACH,CAAC,GAAGH,gBAAgB,sCAAsC;IAChF,IAAIO,IAAIb,SAASY,IAAI,CAACC,CAAC,GAAGN;IAC1B,IAAIO,cAAcd,SAASY,IAAI,CAACC,CAAC;IAEjC,+EAA+E;IAC/E,IAAIT,kBAAkB;QACpB,MAAMW,gBAAgBX,iBAAiBY,qBAAqB;QAC5DP,IAAIA,IAAIM,cAAcE,IAAI,GAAGb,iBAAiBc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,YAAYG;IACjC,MAAME,cAAcJ,eAAeD,YAAY,IAAID,iBAAiBK;IACpE,OAAO;QACLxE,MAAMyE;QACNC,OAAOD,cAAcD;IACvB;AACF;AAEA,OAAO,SAASG,oBACdC,aAAqB,EACrBC,UAAkB,EAClBxC,KAAsB;IAEtB,IAAI;QACF,MAAMyC,cAAczC,MAAME,cAAc,CAAC,QAAQ;YAAC;YAAGqC;SAAc;QACnE,MAAMG,WAAW1C,MAAME,cAAc,CAAC,QAAQ;YAAC;YAAGsC;SAAW;QAE7D,IAAI,CAACC,eAAe,CAACC,YAAYD,WAAW,CAAC,EAAE,KAAK1F,aAAa2F,QAAQ,CAAC,EAAE,KAAK3F,WAAW,OAAO;QAEnG,0FAA0F;QAC1F,OAAO;YACLc,KAAKI,KAAK0E,GAAG,CAACD,QAAQ,CAAC,EAAE,EAAED,WAAW,CAAC,EAAE;YACzCG,QAAQ3E,KAAKC,GAAG,CAACwE,QAAQ,CAAC,EAAE,EAAED,WAAW,CAAC,EAAE;QAC9C;IACF,EAAE,OAAM;QACN,OAAO;IACT;AACF"}
@@ -15,4 +15,5 @@ export * from './time-series-data';
15
15
  export * from './trace-data';
16
16
  export * from './types';
17
17
  export * from './text';
18
+ export * from './url';
18
19
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAaA,cAAc,QAAQ,CAAC;AACvB,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,UAAU,CAAC;AACzB,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/utils/index.ts"],"names":[],"mappings":"AAaA,cAAc,QAAQ,CAAC;AACvB,cAAc,mBAAmB,CAAC;AAClC,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC;AAC7B,cAAc,4BAA4B,CAAC;AAC3C,cAAc,UAAU,CAAC;AACzB,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,aAAa,CAAC;AAC5B,cAAc,0BAA0B,CAAC;AACzC,cAAc,iBAAiB,CAAC;AAChC,cAAc,UAAU,CAAC;AACzB,cAAc,kBAAkB,CAAC;AACjC,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,SAAS,CAAC;AACxB,cAAc,QAAQ,CAAC;AACvB,cAAc,OAAO,CAAC"}
@@ -27,5 +27,6 @@ export * from "./time-series-data.js";
27
27
  export * from "./trace-data.js";
28
28
  export * from "./types.js";
29
29
  export * from "./text.js";
30
+ export * from "./url.js";
30
31
 
31
32
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './axis';\nexport * from './browser-storage';\nexport * from './chart-actions';\nexport * from './combine-sx';\nexport * from './data-field-interpolation';\nexport * from './format';\nexport * from './request-interpolation';\nexport * from './selection-interpolation';\nexport * from './theme-gen';\nexport * from './variable-interpolation';\nexport * from './value-mapping';\nexport * from './regexp';\nexport * from './transform-data';\nexport * from './time-series-data';\nexport * from './trace-data';\nexport * from './types';\nexport * from './text';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,YAAS;AACvB,cAAc,uBAAoB;AAClC,cAAc,qBAAkB;AAChC,cAAc,kBAAe;AAC7B,cAAc,gCAA6B;AAC3C,cAAc,cAAW;AACzB,cAAc,6BAA0B;AACxC,cAAc,+BAA4B;AAC1C,cAAc,iBAAc;AAC5B,cAAc,8BAA2B;AACzC,cAAc,qBAAkB;AAChC,cAAc,cAAW;AACzB,cAAc,sBAAmB;AACjC,cAAc,wBAAqB;AACnC,cAAc,kBAAe;AAC7B,cAAc,aAAU;AACxB,cAAc,YAAS"}
1
+ {"version":3,"sources":["../../src/utils/index.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nexport * from './axis';\nexport * from './browser-storage';\nexport * from './chart-actions';\nexport * from './combine-sx';\nexport * from './data-field-interpolation';\nexport * from './format';\nexport * from './request-interpolation';\nexport * from './selection-interpolation';\nexport * from './theme-gen';\nexport * from './variable-interpolation';\nexport * from './value-mapping';\nexport * from './regexp';\nexport * from './transform-data';\nexport * from './time-series-data';\nexport * from './trace-data';\nexport * from './types';\nexport * from './text';\nexport * from './url';\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,cAAc,YAAS;AACvB,cAAc,uBAAoB;AAClC,cAAc,qBAAkB;AAChC,cAAc,kBAAe;AAC7B,cAAc,gCAA6B;AAC3C,cAAc,cAAW;AACzB,cAAc,6BAA0B;AACxC,cAAc,+BAA4B;AAC1C,cAAc,iBAAc;AAC5B,cAAc,8BAA2B;AACzC,cAAc,qBAAkB;AAChC,cAAc,cAAW;AACzB,cAAc,sBAAmB;AACjC,cAAc,wBAAqB;AACnC,cAAc,kBAAe;AAC7B,cAAc,aAAU;AACxB,cAAc,YAAS;AACvB,cAAc,WAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"time-series-data.d.ts","sourceRoot":"","sources":["../../src/utils/time-series-data.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAqB,SAAS,EAAE,UAAU,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAIvH,eAAO,MAAM,oBAAoB,KAAK,CAAC;AAEvC;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,GAAG,oBAAoB,EAAE,CAyBpG;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,KAAK,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,GAAG,SAAS,CAAC,GACzE,SAAS,GAAG,SAAS,CAgFvB"}
1
+ {"version":3,"file":"time-series-data.d.ts","sourceRoot":"","sources":["../../src/utils/time-series-data.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAqB,SAAS,EAAE,UAAU,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,kBAAkB,CAAC;AAIvH,eAAO,MAAM,oBAAoB,KAAK,CAAC;AAEvC;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,GAAG,oBAAoB,EAAE,CAyBpG;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,KAAK,CAAC,cAAc,GAAG,IAAI,CAAC,UAAU,EAAE,QAAQ,CAAC,GAAG,SAAS,CAAC,GACzE,SAAS,GAAG,SAAS,CAiFvB"}
@@ -58,9 +58,12 @@ export const MIN_STEP_INTERVAL_MS = 10;
58
58
  if (data === undefined || data.timeRange === undefined || data.stepMs === undefined) continue;
59
59
  // Keep track of query steps so we can calculate a common one for the graph
60
60
  steps.push(data.stepMs);
61
- // If we don't have an overall time range yet, just start with this one
61
+ // If we don't have an overall time range yet, start with a copy of this one.
62
+ // Copy to avoid mutating the input (e.g. cached query results) when widening the range below.
62
63
  if (timeRange === undefined) {
63
- timeRange = data.timeRange;
64
+ timeRange = {
65
+ ...data.timeRange
66
+ };
64
67
  continue;
65
68
  }
66
69
  // Otherwise, see if this query has a start or end outside of the current
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/time-series-data.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { AbsoluteTimeRange, TimeScale, TimeSeries, TimeSeriesData, TimeSeriesValueTuple } from '@perses-dev/spec';\n\nimport { gcd } from './mathjs';\n\nexport const MIN_STEP_INTERVAL_MS = 10;\n\n/**\n * Given a TimeSeries from a query and a common time scale (see `getCommonTimeScale`),\n * processes the time series values, filling in any timestamps that are missing\n * from the time series data with `null` values.\n */\nexport function getTimeSeriesValues(series: TimeSeries, timeScale: TimeScale): TimeSeriesValueTuple[] {\n let timestamp = timeScale.startMs;\n\n const values = series.values;\n const processedValues: TimeSeriesValueTuple[] = [];\n\n for (const valueTuple of values) {\n // Fill in values up to the current series value timestamp with nulls\n while (timestamp < valueTuple[0]) {\n processedValues.push([timestamp, null]);\n timestamp += timeScale.stepMs;\n }\n\n // Now add the current value since timestamp should match\n processedValues.push([timestamp, valueTuple[1]]);\n timestamp += timeScale.stepMs;\n }\n\n // Add null values at the end of the series if necessary\n while (timestamp <= timeScale.endMs) {\n processedValues.push([timestamp, null]);\n timestamp += timeScale.stepMs;\n }\n\n return processedValues;\n}\n\n/**\n * Given a list of running queries, calculates a common time scale for use on\n * the x axis (i.e. start/end dates and a step that is divisible into all of\n * the queries' steps).\n */\nexport function getCommonTimeScale(\n seriesData: Array<TimeSeriesData | Pick<TimeSeries, 'values'> | undefined>,\n): TimeScale | undefined {\n let timeRange: AbsoluteTimeRange | undefined = undefined;\n const steps: number[] = [];\n\n for (const data of seriesData) {\n if (data && 'timeRange' in data) {\n if (data === undefined || data.timeRange === undefined || data.stepMs === undefined) continue;\n\n // Keep track of query steps so we can calculate a common one for the graph\n steps.push(data.stepMs);\n\n // If we don't have an overall time range yet, just start with this one\n if (timeRange === undefined) {\n timeRange = data.timeRange;\n continue;\n }\n\n // Otherwise, see if this query has a start or end outside of the current\n // time range\n if (data.timeRange.start < timeRange.start) {\n timeRange.start = data.timeRange.start;\n }\n if (data.timeRange.end > timeRange.end) {\n timeRange.end = data.timeRange.end;\n }\n } else if (data && 'values' in data) {\n for (let i = 0; i < data.values.length; i++) {\n const values = data.values[i];\n if (values === undefined) {\n continue;\n }\n\n const [timestamp] = values;\n const start = new Date(timestamp);\n const end = new Date(timestamp);\n\n if (timeRange === undefined) {\n timeRange = {\n start,\n end,\n };\n continue;\n }\n\n if (start < timeRange.start) {\n timeRange.start = start;\n }\n\n if (end > timeRange.end) {\n timeRange.end = end;\n }\n }\n\n if (timeRange === undefined) return undefined;\n\n const startMs = timeRange.start.valueOf();\n const endMs = timeRange.end.valueOf();\n const rangeMs = endMs - startMs;\n\n return { startMs, endMs, rangeMs, stepMs: MIN_STEP_INTERVAL_MS };\n }\n }\n\n if (timeRange === undefined) return undefined;\n\n // Use the greatest common divisor of all step values as the overall step\n // for the x axis (or if only one query, just use that query's step value)\n let stepMs: number;\n if (steps.length === 1) {\n stepMs = steps[0] as number;\n } else {\n const calculatedStepMs = gcd(...steps);\n stepMs = calculatedStepMs < MIN_STEP_INTERVAL_MS ? MIN_STEP_INTERVAL_MS : calculatedStepMs;\n }\n\n const startMs = timeRange.start.valueOf();\n const endMs = timeRange.end.valueOf();\n const rangeMs = endMs - startMs;\n\n return { startMs, endMs, stepMs, rangeMs };\n}\n"],"names":["gcd","MIN_STEP_INTERVAL_MS","getTimeSeriesValues","series","timeScale","timestamp","startMs","values","processedValues","valueTuple","push","stepMs","endMs","getCommonTimeScale","seriesData","timeRange","undefined","steps","data","start","end","i","length","Date","valueOf","rangeMs","calculatedStepMs"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,SAASA,GAAG,QAAQ,cAAW;AAE/B,OAAO,MAAMC,uBAAuB,GAAG;AAEvC;;;;CAIC,GACD,OAAO,SAASC,oBAAoBC,MAAkB,EAAEC,SAAoB;IAC1E,IAAIC,YAAYD,UAAUE,OAAO;IAEjC,MAAMC,SAASJ,OAAOI,MAAM;IAC5B,MAAMC,kBAA0C,EAAE;IAElD,KAAK,MAAMC,cAAcF,OAAQ;QAC/B,qEAAqE;QACrE,MAAOF,YAAYI,UAAU,CAAC,EAAE,CAAE;YAChCD,gBAAgBE,IAAI,CAAC;gBAACL;gB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Y,QAAQ,IAAII,KAAKlB;gBACvB,MAAMe,MAAM,IAAIG,KAAKlB;gBAErB,IAAIU,cAAcC,WAAW;oBAC3BD,YAAY;wBACVI;wBACAC;oBACF;oBACA;gBACF;gBAEA,IAAID,QAAQJ,UAAUI,KAAK,EAAE;oBAC3BJ,UAAUI,KAAK,GAAGA;gBACpB;gBAEA,IAAIC,MAAML,UAAUK,GAAG,EAAE;oBACvBL,UAAUK,GAAG,GAAGA;gBAClB;YACF;YAEA,IAAIL,cAAcC,WAAW,OAAOA;YAEpC,MAAMV,UAAUS,UAAUI,KAAK,CAACK,OAAO;YACvC,MAAMZ,QAAQG,UAAUK,GAAG,CAACI,OAAO;YACnC,MAAMC,UAAUb,QAAQN;YAExB,OAAO;gBAAEA;gBAASM;gBAAOa;gBAASd,QAAQV;YAAqB;QACjE;IACF;IAEA,IAAIc,cAAcC,WAAW,OAAOA;IAEpC,yEAAyE;IACzE,0EAA0E;IAC1E,IAAIL;IACJ,IAAIM,MAAMK,MAAM,KAAK,GAAG;QACtBX,SAASM,KAAK,CAAC,EAAE;IACnB,OAAO;QACL,MAAMS,mBAAmB1B,OAAOiB;QAChCN,SAASe,mBAAmBzB,uBAAuBA,uBAAuByB;IAC5E;IAEA,MAAMpB,UAAUS,UAAUI,KAAK,CAACK,OAAO;IACvC,MAAMZ,QAAQG,UAAUK,GAAG,CAACI,OAAO;IACnC,MAAMC,UAAUb,QAAQN;IAExB,OAAO;QAAEA;QAASM;QAAOD;QAAQc;IAAQ;AAC3C"}
1
+ {"version":3,"sources":["../../src/utils/time-series-data.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { AbsoluteTimeRange, TimeScale, TimeSeries, TimeSeriesData, TimeSeriesValueTuple } from '@perses-dev/spec';\n\nimport { gcd } from './mathjs';\n\nexport const MIN_STEP_INTERVAL_MS = 10;\n\n/**\n * Given a TimeSeries from a query and a common time scale (see `getCommonTimeScale`),\n * processes the time series values, filling in any timestamps that are missing\n * from the time series data with `null` values.\n */\nexport function getTimeSeriesValues(series: TimeSeries, timeScale: TimeScale): TimeSeriesValueTuple[] {\n let timestamp = timeScale.startMs;\n\n const values = series.values;\n const processedValues: TimeSeriesValueTuple[] = [];\n\n for (const valueTuple of values) {\n // Fill in values up to the current series value timestamp with nulls\n while (timestamp < valueTuple[0]) {\n processedValues.push([timestamp, null]);\n timestamp += timeScale.stepMs;\n }\n\n // Now add the current value since timestamp should match\n processedValues.push([timestamp, valueTuple[1]]);\n timestamp += timeScale.stepMs;\n }\n\n // Add null values at the end of the series if necessary\n while (timestamp <= timeScale.endMs) {\n processedValues.push([timestamp, null]);\n timestamp += timeScale.stepMs;\n }\n\n return processedValues;\n}\n\n/**\n * Given a list of running queries, calculates a common time scale for use on\n * the x axis (i.e. start/end dates and a step that is divisible into all of\n * the queries' steps).\n */\nexport function getCommonTimeScale(\n seriesData: Array<TimeSeriesData | Pick<TimeSeries, 'values'> | undefined>,\n): TimeScale | undefined {\n let timeRange: AbsoluteTimeRange | undefined = undefined;\n const steps: number[] = [];\n\n for (const data of seriesData) {\n if (data && 'timeRange' in data) {\n if (data === undefined || data.timeRange === undefined || data.stepMs === undefined) continue;\n\n // Keep track of query steps so we can calculate a common one for the graph\n steps.push(data.stepMs);\n\n // If we don't have an overall time range yet, start with a copy of this one.\n // Copy to avoid mutating the input (e.g. cached query results) when widening the range below.\n if (timeRange === undefined) {\n timeRange = { ...data.timeRange };\n continue;\n }\n\n // Otherwise, see if this query has a start or end outside of the current\n // time range\n if (data.timeRange.start < timeRange.start) {\n timeRange.start = data.timeRange.start;\n }\n if (data.timeRange.end > timeRange.end) {\n timeRange.end = data.timeRange.end;\n }\n } else if (data && 'values' in data) {\n for (let i = 0; i < data.values.length; i++) {\n const values = data.values[i];\n if (values === undefined) {\n continue;\n }\n\n const [timestamp] = values;\n const start = new Date(timestamp);\n const end = new Date(timestamp);\n\n if (timeRange === undefined) {\n timeRange = {\n start,\n end,\n };\n continue;\n }\n\n if (start < timeRange.start) {\n timeRange.start = start;\n }\n\n if (end > timeRange.end) {\n timeRange.end = end;\n }\n }\n\n if (timeRange === undefined) return undefined;\n\n const startMs = timeRange.start.valueOf();\n const endMs = timeRange.end.valueOf();\n const rangeMs = endMs - startMs;\n\n return { startMs, endMs, rangeMs, stepMs: MIN_STEP_INTERVAL_MS };\n }\n }\n\n if (timeRange === undefined) return undefined;\n\n // Use the greatest common divisor of all step values as the overall step\n // for the x axis (or if only one query, just use that query's step value)\n let stepMs: number;\n if (steps.length === 1) {\n stepMs = steps[0] as number;\n } else {\n const calculatedStepMs = gcd(...steps);\n stepMs = calculatedStepMs < MIN_STEP_INTERVAL_MS ? MIN_STEP_INTERVAL_MS : calculatedStepMs;\n }\n\n const startMs = timeRange.start.valueOf();\n const endMs = timeRange.end.valueOf();\n const rangeMs = endMs - startMs;\n\n return { startMs, endMs, stepMs, rangeMs };\n}\n"],"names":["gcd","MIN_STEP_INTERVAL_MS","getTimeSeriesValues","series","timeScale","timestamp","startMs","values","processedValues","valueTuple","push","stepMs","endMs","getCommonTimeScale","seriesData","timeRange","undefined","steps","data","start","end","i","length","Date","valueOf","rangeMs","calculatedStepMs"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,SAASA,GAAG,QAAQ,cAAW;AAE/B,OAAO,MAAMC,uBAAuB,GAAG;AAEvC;;;;CAIC,GACD,OAA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AQ;AAC3C"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Returns true when the URL is relative or uses one of the allowed schemes (`http:`, `https:`, `mailto:`, `tel:`,
3
+ * `sms:`, `slack:`, `msteams:`, `vscode:`, `vscode-insiders:`, `zoommtg:`),
4
+ * i.e. when it is safe to use as the `href` of a link built from user-provided data.
5
+ * Any other scheme, such as `javascript:`, `data:` or `vbscript:`, is considered unsafe.
6
+ *
7
+ * The check relies on the WHATWG URL parser, the one browsers use to resolve an `href`,
8
+ * so obfuscated schemes (mixed case, leading whitespace or control characters, tabs or newlines inside the scheme, ...)
9
+ * are normalized before being verified.
10
+ */
11
+ export declare function isSafeUrl(url: string): boolean;
12
+ /**
13
+ * Returns the URL when it is safe to use as the `href` of a link (see {@link isSafeUrl}), undefined otherwise.
14
+ * It must be applied to the final URL, after any interpolation (variables, data fields, ...).
15
+ */
16
+ export declare function sanitizeUrl(url: string | undefined): string | undefined;
17
+ //# sourceMappingURL=url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"url.d.ts","sourceRoot":"","sources":["../../src/utils/url.ts"],"names":[],"mappings":"AAgCA;;;;;;;;;GASG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAM9C;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAKvE"}
@@ -0,0 +1,56 @@
1
+ // Copyright The Perses Authors
2
+ // Licensed under the Apache License, Version 2.0 (the "License");
3
+ // you may not use this file except in compliance with the License.
4
+ // You may obtain a copy of the License at
5
+ //
6
+ // http://www.apache.org/licenses/LICENSE-2.0
7
+ //
8
+ // Unless required by applicable law or agreed to in writing, software
9
+ // distributed under the License is distributed on an "AS IS" BASIS,
10
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ // See the License for the specific language governing permissions and
12
+ // limitations under the License.
13
+ // None of these schemes can execute a script in the current origin. Besides the web and communication schemes, it
14
+ // includes the deep links of applications commonly used from dashboards, which are handed off to the operating system.
15
+ // Keep it aligned with the list of the Perses API (internal/api/validate/link.go in perses/perses).
16
+ const SAFE_URL_PROTOCOLS = new Set([
17
+ 'http:',
18
+ 'https:',
19
+ 'mailto:',
20
+ 'tel:',
21
+ 'sms:',
22
+ 'slack:',
23
+ 'msteams:',
24
+ 'vscode:',
25
+ 'vscode-insiders:',
26
+ 'zoommtg:'
27
+ ]);
28
+ // Only used to resolve relative URLs, so that they are parsed the way a browser resolves them against the page.
29
+ const RELATIVE_URL_BASE = 'http://perses.local';
30
+ /**
31
+ * Returns true when the URL is relative or uses one of the allowed schemes (`http:`, `https:`, `mailto:`, `tel:`,
32
+ * `sms:`, `slack:`, `msteams:`, `vscode:`, `vscode-insiders:`, `zoommtg:`),
33
+ * i.e. when it is safe to use as the `href` of a link built from user-provided data.
34
+ * Any other scheme, such as `javascript:`, `data:` or `vbscript:`, is considered unsafe.
35
+ *
36
+ * The check relies on the WHATWG URL parser, the one browsers use to resolve an `href`,
37
+ * so obfuscated schemes (mixed case, leading whitespace or control characters, tabs or newlines inside the scheme, ...)
38
+ * are normalized before being verified.
39
+ */ export function isSafeUrl(url) {
40
+ try {
41
+ return SAFE_URL_PROTOCOLS.has(new URL(url, RELATIVE_URL_BASE).protocol);
42
+ } catch {
43
+ return false;
44
+ }
45
+ }
46
+ /**
47
+ * Returns the URL when it is safe to use as the `href` of a link (see {@link isSafeUrl}), undefined otherwise.
48
+ * It must be applied to the final URL, after any interpolation (variables, data fields, ...).
49
+ */ export function sanitizeUrl(url) {
50
+ if (url === undefined || !isSafeUrl(url)) {
51
+ return undefined;
52
+ }
53
+ return url;
54
+ }
55
+
56
+ //# sourceMappingURL=url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/url.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n// None of these schemes can execute a script in the current origin. Besides the web and communication schemes, it\n// includes the deep links of applications commonly used from dashboards, which are handed off to the operating system.\n// Keep it aligned with the list of the Perses API (internal/api/validate/link.go in perses/perses).\nconst SAFE_URL_PROTOCOLS = new Set([\n 'http:',\n 'https:',\n 'mailto:',\n 'tel:',\n 'sms:',\n 'slack:',\n 'msteams:',\n 'vscode:',\n 'vscode-insiders:',\n 'zoommtg:',\n]);\n\n// Only used to resolve relative URLs, so that they are parsed the way a browser resolves them against the page.\nconst RELATIVE_URL_BASE = 'http://perses.local';\n\n/**\n * Returns true when the URL is relative or uses one of the allowed schemes (`http:`, `https:`, `mailto:`, `tel:`,\n * `sms:`, `slack:`, `msteams:`, `vscode:`, `vscode-insiders:`, `zoommtg:`),\n * i.e. when it is safe to use as the `href` of a link built from user-provided data.\n * Any other scheme, such as `javascript:`, `data:` or `vbscript:`, is considered unsafe.\n *\n * The check relies on the WHATWG URL parser, the one browsers use to resolve an `href`,\n * so obfuscated schemes (mixed case, leading whitespace or control characters, tabs or newlines inside the scheme, ...)\n * are normalized before being verified.\n */\nexport function isSafeUrl(url: string): boolean {\n try {\n return SAFE_URL_PROTOCOLS.has(new URL(url, RELATIVE_URL_BASE).protocol);\n } catch {\n return false;\n }\n}\n\n/**\n * Returns the URL when it is safe to use as the `href` of a link (see {@link isSafeUrl}), undefined otherwise.\n * It must be applied to the final URL, after any interpolation (variables, data fields, ...).\n */\nexport function sanitizeUrl(url: string | undefined): string | undefined {\n if (url === undefined || !isSafeUrl(url)) {\n return undefined;\n }\n return url;\n}\n"],"names":["SAFE_URL_PROTOCOLS","Set","RELATIVE_URL_BASE","isSafeUrl","url","has","URL","protocol","sanitizeUrl","undefined"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,kHAAkH;AAClH,uHAAuH;AACvH,oGAAoG;AACpG,MAAMA,qBAAqB,IAAIC,IAAI;IACjC;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;CACD;AAED,gHAAgH;AAChH,MAAMC,oBAAoB;AAE1B;;;;;;;;;CASC,GACD,OAAO,SAASC,UAAUC,GAAW;IACnC,IAAI;QACF,OAAOJ,mBAAmBK,GAAG,CAAC,IAAIC,IAAIF,KAAKF,mBAAmBK,QAAQ;IACxE,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAEA;;;CAGC,GACD,OAAO,SAASC,YAAYJ,GAAuB;IACjD,IAAIA,QAAQK,aAAa,CAACN,UAAUC,MAAM;QACxC,OAAOK;IACT;IACA,OAAOL;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perses-dev/components",
3
- "version": "0.55.0-rc.1",
3
+ "version": "0.55.1",
4
4
  "description": "Common UI components used across Perses features",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/perses/perses/blob/main/README.md",
@@ -34,8 +34,8 @@
34
34
  "@date-fns/tz": "^1.4.1",
35
35
  "@fontsource/inter": "^5.0.0",
36
36
  "@mui/x-date-pickers": "^7.23.1",
37
- "@perses-dev/spec": "0.3.0-rc.1",
38
- "@perses-dev/client": "0.55.0-rc.1",
37
+ "@perses-dev/spec": "0.3.0",
38
+ "@perses-dev/client": "0.55.1",
39
39
  "numbro": "^2.3.6",
40
40
  "@tanstack/match-sorter-utils": "^8.19.4",
41
41
  "@tanstack/react-table": "^8.20.5",