@vitessce/feature-list 2.0.3 → 3.0.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 (38) hide show
  1. package/dist/{index.mjs → index.js} +21949 -13431
  2. package/dist-tsc/FeatureList.d.ts +2 -0
  3. package/dist-tsc/FeatureList.d.ts.map +1 -0
  4. package/dist-tsc/FeatureList.js +76 -0
  5. package/dist-tsc/FeatureListOptions.d.ts +2 -0
  6. package/dist-tsc/FeatureListOptions.d.ts.map +1 -0
  7. package/dist-tsc/FeatureListOptions.js +23 -0
  8. package/dist-tsc/FeatureListSubscriber.d.ts +34 -0
  9. package/dist-tsc/FeatureListSubscriber.d.ts.map +1 -0
  10. package/dist-tsc/FeatureListSubscriber.js +66 -0
  11. package/dist-tsc/constants.d.ts +3 -0
  12. package/dist-tsc/constants.d.ts.map +1 -0
  13. package/dist-tsc/constants.js +5 -0
  14. package/dist-tsc/index.d.ts +3 -0
  15. package/dist-tsc/index.d.ts.map +1 -0
  16. package/dist-tsc/index.js +2 -2
  17. package/dist-tsc/selectable-table/SelectableTable.d.ts +21 -0
  18. package/dist-tsc/selectable-table/SelectableTable.d.ts.map +1 -0
  19. package/dist-tsc/selectable-table/SelectableTable.js +137 -0
  20. package/dist-tsc/selectable-table/SelectableTable.test.d.ts +2 -0
  21. package/dist-tsc/selectable-table/SelectableTable.test.d.ts.map +1 -0
  22. package/dist-tsc/selectable-table/SelectableTable.test.js +94 -0
  23. package/dist-tsc/selectable-table/index.d.ts +2 -0
  24. package/dist-tsc/selectable-table/index.d.ts.map +1 -0
  25. package/dist-tsc/selectable-table/index.js +1 -0
  26. package/dist-tsc/selectable-table/styles.d.ts +2 -0
  27. package/dist-tsc/selectable-table/styles.d.ts.map +1 -0
  28. package/dist-tsc/selectable-table/styles.js +73 -0
  29. package/package.json +23 -11
  30. package/src/FeatureList.js +53 -16
  31. package/src/FeatureListOptions.js +101 -0
  32. package/src/FeatureListSubscriber.js +44 -17
  33. package/src/constants.js +6 -0
  34. package/src/index.js +2 -2
  35. package/src/selectable-table/SelectableTable.js +14 -12
  36. package/src/selectable-table/SelectableTable.test.jsx +47 -7
  37. package/src/selectable-table/index.js +1 -1
  38. package/src/selectable-table/styles.js +8 -4
@@ -0,0 +1,2 @@
1
+ export default function FeatureList(props: any): JSX.Element;
2
+ //# sourceMappingURL=FeatureList.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FeatureList.d.ts","sourceRoot":"","sources":["../src/FeatureList.js"],"names":[],"mappings":"AAeA,6DAgHC"}
@@ -0,0 +1,76 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import React, { useEffect, useState, useMemo } from 'react';
3
+ import { every } from 'lodash-es';
4
+ import { makeStyles } from '@material-ui/core';
5
+ import { SelectableTable } from './selectable-table/index.js';
6
+ import { ALT_COLNAME } from './constants.js';
7
+ const useStyles = makeStyles(() => ({
8
+ searchBar: {
9
+ marginBottom: '4px',
10
+ border: '0',
11
+ padding: '2px',
12
+ borderRadius: '2px',
13
+ },
14
+ }));
15
+ export default function FeatureList(props) {
16
+ const { hasColorEncoding, geneList = [], featureLabelsMap, geneSelection = [], geneFilter = null, setGeneSelection, enableMultiSelect, showFeatureTable, featureListSort, featureListSortKey, hasFeatureLabels, primaryColumnName, } = props;
17
+ const classes = useStyles();
18
+ const [searchTerm, setSearchTerm] = useState('');
19
+ const [searchResults, setSearchResults] = useState(geneList);
20
+ // In FeatureListSubscriber, we think in terms of 'featureIndex' and 'featureLabels'.
21
+ // Here in FeatureList, we need to map these to 'key' or 'name' before
22
+ // passing to the SelectableTable component.
23
+ const selectableTableSortKey = (featureListSortKey === 'featureIndex' ? 'key' : 'name');
24
+ useEffect(() => {
25
+ const results = geneList
26
+ .filter(gene => (gene.toLowerCase().includes(searchTerm.toLowerCase())
27
+ || featureLabelsMap?.get(gene)?.toLowerCase().includes(searchTerm.toLowerCase())));
28
+ setSearchResults(results);
29
+ }, [searchTerm, geneList, featureLabelsMap]);
30
+ function onChange(selection) {
31
+ if (setGeneSelection && selection) {
32
+ if (Array.isArray(selection)) {
33
+ if (selection.length > 0 && every(selection, s => s.key)) {
34
+ setGeneSelection(selection.map(s => s.key));
35
+ }
36
+ else {
37
+ setGeneSelection(null);
38
+ }
39
+ }
40
+ else if (selection.key) {
41
+ setGeneSelection([selection.key]);
42
+ }
43
+ }
44
+ }
45
+ const data = useMemo(() => {
46
+ const preSortedData = searchResults
47
+ .filter(gene => (geneFilter ? geneFilter.includes(gene) : true))
48
+ .map(gene => ({
49
+ key: gene,
50
+ name: featureLabelsMap?.get(gene) || gene,
51
+ value: (geneSelection ? geneSelection.includes(gene) : false),
52
+ }));
53
+ if (preSortedData && featureListSort === 'alphabetical' && preSortedData.length > 0) {
54
+ return preSortedData.sort((a, b) => a[selectableTableSortKey].localeCompare(b[selectableTableSortKey]));
55
+ }
56
+ return preSortedData;
57
+ }, [featureListSort, selectableTableSortKey, searchResults,
58
+ geneFilter, featureLabelsMap, geneSelection,
59
+ ]);
60
+ const handleChange = (event) => {
61
+ setSearchTerm(event.target.value);
62
+ };
63
+ const [columns, columnLabels] = useMemo(() => {
64
+ if (showFeatureTable && hasFeatureLabels) {
65
+ return [
66
+ ['name', 'key'],
67
+ [primaryColumnName, ALT_COLNAME],
68
+ ];
69
+ }
70
+ return [
71
+ ['name'],
72
+ [primaryColumnName],
73
+ ];
74
+ }, [showFeatureTable, primaryColumnName, hasFeatureLabels]);
75
+ return (_jsxs(_Fragment, { children: [_jsx("input", { className: classes.searchBar, type: "text", placeholder: "Search", value: searchTerm, onChange: handleChange }), _jsx(SelectableTable, { columns: columns, columnLabels: columnLabels, data: data, hasColorEncoding: hasColorEncoding, idKey: "key", valueKey: "value", onChange: onChange, allowMultiple: enableMultiSelect, allowUncheck: enableMultiSelect, showTableHead: columnLabels.length > 1 })] }));
76
+ }
@@ -0,0 +1,2 @@
1
+ export default function FeatureListOptions(props: any): JSX.Element;
2
+ //# sourceMappingURL=FeatureListOptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FeatureListOptions.d.ts","sourceRoot":"","sources":["../src/FeatureListOptions.js"],"names":[],"mappings":"AAMA,oEA8FC"}
@@ -0,0 +1,23 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import React from 'react';
3
+ import { OptionsContainer, OptionSelect, usePlotOptionsStyles } from '@vitessce/vit-s';
4
+ import { TableCell, TableRow, Checkbox } from '@material-ui/core';
5
+ import { FEATURELIST_SORT_OPTIONS, ALT_COLNAME } from './constants.js';
6
+ export default function FeatureListOptions(props) {
7
+ const { children, featureListSort, setFeatureListSort, featureListSortKey, setFeatureListSortKey, showFeatureTable, setShowFeatureTable, hasFeatureLabels, primaryColumnName, } = props;
8
+ function handleFeatureListSortChange(event) {
9
+ setFeatureListSort(event.target.value);
10
+ }
11
+ function handleFeatureListSortKeyChange(event) {
12
+ setFeatureListSortKey(event.target.value);
13
+ }
14
+ function handleShowTableChange(event) {
15
+ setShowFeatureTable(event.target.checked);
16
+ }
17
+ const classes = usePlotOptionsStyles();
18
+ return (_jsxs(OptionsContainer, { children: [children, _jsxs(TableRow, { children: [_jsx(TableCell, { className: classes.labelCell, htmlFor: "feature-list-sort-option-select", children: "Sort Ordering" }), _jsx(TableCell, { children: _jsx(OptionSelect, { className: classes.select, value: featureListSort, onChange: handleFeatureListSortChange, inputProps: {
19
+ id: 'feature-list-sort-option-select',
20
+ }, children: FEATURELIST_SORT_OPTIONS.map(option => (_jsx("option", { value: option, children: option }, option))) }) })] }), hasFeatureLabels ? (_jsxs(_Fragment, { children: [_jsxs(TableRow, { children: [_jsx(TableCell, { className: classes.labelCell, htmlFor: "feature-list-sort-key-select", children: "Sort Key" }), _jsx(TableCell, { children: _jsx(OptionSelect, { className: classes.select, disabled: featureListSort === 'original', value: featureListSortKey, onChange: handleFeatureListSortKeyChange, inputProps: {
21
+ id: 'feature-list-sort-key-select',
22
+ }, children: hasFeatureLabels ? (_jsxs(_Fragment, { children: [_jsx("option", { value: "featureLabels", children: primaryColumnName }), _jsx("option", { value: "featureIndex", children: ALT_COLNAME })] })) : (_jsx("option", { value: "featureIndex", children: primaryColumnName })) }) })] }), _jsxs(TableRow, { children: [_jsx(TableCell, { className: classes.labelCell, children: "Show Alternate IDs" }), _jsx(TableCell, { className: classes.inputCell, children: _jsx(Checkbox, { className: classes.tableCheckbox, checked: showFeatureTable, onChange: handleShowTableChange, name: "feature-list-show-table", color: "default" }) })] })] })) : null] }));
23
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * A subscriber component for a gene listing component.
3
+ * @param {object} props
4
+ * @param {string} props.theme The current theme name.
5
+ * @param {object} props.coordinationScopes The mapping from coordination types to coordination
6
+ * scopes.
7
+ * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,
8
+ * to call when the component has been removed from the grid.
9
+ * @param {string} props.title The component title.
10
+ * @param {string} props.variablesLabelOverride The singular form
11
+ * of the name of the variable.
12
+ * @param {string} props.variablesPluralLabelOverride The plural
13
+ * form of the name of the variable.
14
+ * @param {boolean} props.enableMultiSelect If true, allow
15
+ * shift-clicking to select multiple genes.
16
+ * @param {boolean} props.showTable If true, shows a table with the feature name and id.
17
+ * @param {'alphabetical'|'original'} props.sort The sort order of the genes. If sort is defined and
18
+ * it is not equal to `alphabetical`, the genes will be displayed in the feature list in
19
+ * the original order.
20
+ * @param {'featureIndex'|'featureLabels'|null} props.sortKey The information to use for sorting.
21
+ */
22
+ export function FeatureListSubscriber(props: {
23
+ theme: string;
24
+ coordinationScopes: object;
25
+ removeGridComponent: Function;
26
+ title: string;
27
+ variablesLabelOverride: string;
28
+ variablesPluralLabelOverride: string;
29
+ enableMultiSelect: boolean;
30
+ showTable: boolean;
31
+ sort: 'alphabetical' | 'original';
32
+ sortKey: 'featureIndex' | 'featureLabels' | null;
33
+ }): JSX.Element;
34
+ //# sourceMappingURL=FeatureListSubscriber.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"FeatureListSubscriber.d.ts","sourceRoot":"","sources":["../src/FeatureListSubscriber.js"],"names":[],"mappings":"AAcA;;;;;;;;;;;;;;;;;;;;GAoBG;AACH;IAlByB,KAAK,EAAnB,MAAM;IACQ,kBAAkB,EAAhC,MAAM;IAEU,mBAAmB;IAErB,KAAK,EAAnB,MAAM;IACQ,sBAAsB,EAApC,MAAM;IAEQ,4BAA4B,EAA1C,MAAM;IAES,iBAAiB,EAAhC,OAAO;IAEQ,SAAS,EAAxB,OAAO;IAC0B,IAAI,EAArC,cAAc,GAAC,UAAU;IAGkB,OAAO,EAAlD,cAAc,GAAC,eAAe,GAAC,IAAI;gBAgH7C"}
@@ -0,0 +1,66 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import React, { useState } from 'react';
3
+ import plur from 'plur';
4
+ import { capitalize, commaNumber } from '@vitessce/utils';
5
+ import { TitleInfo, useReady, useUrls, useFeatureLabelsData, useObsFeatureMatrixIndices, useCoordination, useLoaders, } from '@vitessce/vit-s';
6
+ import { ViewType, COMPONENT_COORDINATION_TYPES } from '@vitessce/constants-internal';
7
+ import FeatureList from './FeatureList.js';
8
+ import FeatureListOptions from './FeatureListOptions.js';
9
+ /**
10
+ * A subscriber component for a gene listing component.
11
+ * @param {object} props
12
+ * @param {string} props.theme The current theme name.
13
+ * @param {object} props.coordinationScopes The mapping from coordination types to coordination
14
+ * scopes.
15
+ * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,
16
+ * to call when the component has been removed from the grid.
17
+ * @param {string} props.title The component title.
18
+ * @param {string} props.variablesLabelOverride The singular form
19
+ * of the name of the variable.
20
+ * @param {string} props.variablesPluralLabelOverride The plural
21
+ * form of the name of the variable.
22
+ * @param {boolean} props.enableMultiSelect If true, allow
23
+ * shift-clicking to select multiple genes.
24
+ * @param {boolean} props.showTable If true, shows a table with the feature name and id.
25
+ * @param {'alphabetical'|'original'} props.sort The sort order of the genes. If sort is defined and
26
+ * it is not equal to `alphabetical`, the genes will be displayed in the feature list in
27
+ * the original order.
28
+ * @param {'featureIndex'|'featureLabels'|null} props.sortKey The information to use for sorting.
29
+ */
30
+ export function FeatureListSubscriber(props) {
31
+ const { coordinationScopes, removeGridComponent, variablesLabelOverride, theme, title: titleOverride, enableMultiSelect = false, showTable = false, sort = 'alphabetical', sortKey = null, } = props;
32
+ const loaders = useLoaders();
33
+ // Get "props" from the coordination space.
34
+ const [{ dataset, featureType, featureSelection: geneSelection, featureFilter: geneFilter, obsColorEncoding: cellColorEncoding, }, { setFeatureSelection: setGeneSelection, setFeatureFilter: setGeneFilter, setFeatureHighlight: setGeneHighlight, setObsColorEncoding: setCellColorEncoding, }] = useCoordination(COMPONENT_COORDINATION_TYPES[ViewType.FEATURE_LIST], coordinationScopes);
35
+ const variablesLabel = variablesLabelOverride || featureType;
36
+ const title = titleOverride || `${capitalize(variablesLabel)} List`;
37
+ // Get data from loaders using the data hooks.
38
+ // TODO: support multiple feature labels using featureLabelsType coordination values.
39
+ const [{ featureLabelsMap }, featureLabelsStatus, featureLabelsUrls] = useFeatureLabelsData(loaders, dataset, false, {}, {}, { featureType });
40
+ const [{ featureIndex }, matrixIndicesStatus, obsFeatureMatrixUrls] = useObsFeatureMatrixIndices(loaders, dataset, true, { featureType });
41
+ const isReady = useReady([
42
+ featureLabelsStatus,
43
+ matrixIndicesStatus,
44
+ ]);
45
+ const urls = useUrls([
46
+ featureLabelsUrls,
47
+ obsFeatureMatrixUrls,
48
+ ]);
49
+ const geneList = featureIndex || [];
50
+ const numGenes = geneList.length;
51
+ const hasFeatureLabels = Boolean(featureLabelsMap);
52
+ function setGeneSelectionAndColorEncoding(newSelection) {
53
+ setGeneSelection(newSelection);
54
+ setCellColorEncoding('geneSelection');
55
+ }
56
+ const [showFeatureTable, setShowFeatureTable] = useState(showTable);
57
+ const [featureListSort, setFeatureListSort] = useState(sort);
58
+ const [featureListSortKey, setFeatureListSortKey] = useState(null);
59
+ const initialSortKey = sortKey || (hasFeatureLabels ? 'featureLabels' : 'featureIndex');
60
+ const primaryColumnName = `${capitalize(featureType)} ID`;
61
+ return (_jsx(TitleInfo, { title: title, info: `${commaNumber(numGenes)} ${plur(variablesLabel, numGenes)}`, theme: theme,
62
+ // Virtual scroll is used but this allows for the same styling as a scroll component
63
+ // even though this no longer uses the TitleInfo component's
64
+ // scroll css (SelectableTable is virtual scroll).
65
+ isScroll: true, removeGridComponent: removeGridComponent, isReady: isReady, urls: urls, options: (_jsx(FeatureListOptions, { featureListSort: featureListSort, setFeatureListSort: setFeatureListSort, featureListSortKey: featureListSortKey || initialSortKey, setFeatureListSortKey: setFeatureListSortKey, showFeatureTable: showFeatureTable, setShowFeatureTable: setShowFeatureTable, hasFeatureLabels: Boolean(featureLabelsMap), primaryColumnName: primaryColumnName })), children: _jsx(FeatureList, { hasColorEncoding: cellColorEncoding === 'geneSelection', showFeatureTable: showFeatureTable, geneList: geneList, featureListSort: featureListSort, featureListSortKey: featureListSortKey || initialSortKey, featureLabelsMap: featureLabelsMap, featureType: featureType, geneSelection: geneSelection, geneFilter: geneFilter, setGeneSelection: setGeneSelectionAndColorEncoding, setGeneFilter: setGeneFilter, setGeneHighlight: setGeneHighlight, enableMultiSelect: enableMultiSelect, hasFeatureLabels: Boolean(featureLabelsMap), primaryColumnName: primaryColumnName }) }));
66
+ }
@@ -0,0 +1,3 @@
1
+ export const FEATURELIST_SORT_OPTIONS: string[];
2
+ export const ALT_COLNAME: "Alternate ID";
3
+ //# sourceMappingURL=constants.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.js"],"names":[],"mappings":"AAAA,gDAGE;AAEF,yCAA0C"}
@@ -0,0 +1,5 @@
1
+ export const FEATURELIST_SORT_OPTIONS = [
2
+ 'alphabetical',
3
+ 'original',
4
+ ];
5
+ export const ALT_COLNAME = 'Alternate ID';
@@ -0,0 +1,3 @@
1
+ export { FeatureListSubscriber } from "./FeatureListSubscriber.js";
2
+ export { default as FeatureList } from "./FeatureList.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":""}
package/dist-tsc/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export { FeatureListSubscriber, register } from './FeatureListSubscriber';
2
- export { default as FeatureList } from './FeatureList';
1
+ export { FeatureListSubscriber } from './FeatureListSubscriber.js';
2
+ export { default as FeatureList } from './FeatureList.js';
@@ -0,0 +1,21 @@
1
+ /**
2
+ * A table with "selectable" rows.
3
+ * @prop {string[]} columns An array of column names, corresponding to data object properties.
4
+ * @prop {string[]} columnLabels An array of labels to be used for the columns, corresponding to `columns`.
5
+ * columnLabels.length must be equal to columns.length.
6
+ * @prop {object[]} data An array of data objects used to populate table rows.
7
+ * @prop {function} onChange Callback function,
8
+ * passed a selection object when `allowMultiple` is false (and `null` if `allowUncheck` is true),
9
+ * or passed an array of selection objects when `allowMultiple` is true.
10
+ * @prop {string} idKey The key for a unique identifier property of `data` objects.
11
+ * @prop {string} valueKey If initially-selected rows are required,
12
+ * this key specifies a boolean property of the `data` objects
13
+ * indicating those rows that should be initially selected.
14
+ * @prop {boolean} allowMultiple Whether to allow multiple rows to be selected.
15
+ * @prop {boolean} allowUncheck Whether to allow selected rows to be un-checked. By default, false.
16
+ * @prop {boolean} showTableHead Whether to show the table header element. By default, true.
17
+ * @prop {boolean} showTableInputs Whether to show the table input elements for each row.
18
+ * By default, false.
19
+ */
20
+ export default function SelectableTable(props: any): JSX.Element;
21
+ //# sourceMappingURL=SelectableTable.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SelectableTable.d.ts","sourceRoot":"","sources":["../../src/selectable-table/SelectableTable.js"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;;;;;GAkBG;AACH,iEAyLC"}
@@ -0,0 +1,137 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /* eslint-disable jsx-a11y/no-noninteractive-element-to-interactive-role */
3
+ /* eslint-disable jsx-a11y/click-events-have-key-events */
4
+ /* eslint-disable max-len */
5
+ import React, { useEffect, useCallback, useState } from 'react';
6
+ // The CommonJS imports for react-virtualized are needed
7
+ // because the ESM version is broken.
8
+ // Reference: https://github.com/bvaughn/react-virtualized/issues/1632
9
+ import { AutoSizer } from 'react-virtualized/dist/commonjs/AutoSizer/index.js';
10
+ import { Table } from 'react-virtualized/dist/commonjs/Table/index.js';
11
+ import { v4 as uuidv4 } from 'uuid';
12
+ import { union, difference, isEqual } from 'lodash-es';
13
+ import clsx from 'clsx';
14
+ import { useStyles } from './styles.js';
15
+ const SHIFT_KEYCODE = 16;
16
+ /**
17
+ * A table with "selectable" rows.
18
+ * @prop {string[]} columns An array of column names, corresponding to data object properties.
19
+ * @prop {string[]} columnLabels An array of labels to be used for the columns, corresponding to `columns`.
20
+ * columnLabels.length must be equal to columns.length.
21
+ * @prop {object[]} data An array of data objects used to populate table rows.
22
+ * @prop {function} onChange Callback function,
23
+ * passed a selection object when `allowMultiple` is false (and `null` if `allowUncheck` is true),
24
+ * or passed an array of selection objects when `allowMultiple` is true.
25
+ * @prop {string} idKey The key for a unique identifier property of `data` objects.
26
+ * @prop {string} valueKey If initially-selected rows are required,
27
+ * this key specifies a boolean property of the `data` objects
28
+ * indicating those rows that should be initially selected.
29
+ * @prop {boolean} allowMultiple Whether to allow multiple rows to be selected.
30
+ * @prop {boolean} allowUncheck Whether to allow selected rows to be un-checked. By default, false.
31
+ * @prop {boolean} showTableHead Whether to show the table header element. By default, true.
32
+ * @prop {boolean} showTableInputs Whether to show the table input elements for each row.
33
+ * By default, false.
34
+ */
35
+ export default function SelectableTable(props) {
36
+ const { hasColorEncoding, columns, columnLabels, data, onChange, idKey = 'id', valueKey = 'value', allowMultiple = false, allowUncheck = false, showTableHead = true, showTableInputs = false, testHeight = undefined, testWidth = undefined, } = props;
37
+ const [selectedRows, setSelectedRows] = useState(null);
38
+ const [isCheckingMultiple, setIsCheckingMultiple] = useState(false);
39
+ // Enable selecting multiple rows while the shift key is down.
40
+ useEffect(() => {
41
+ function onKeyDown(event) {
42
+ if (allowMultiple && event.keyCode === SHIFT_KEYCODE) {
43
+ setIsCheckingMultiple(true);
44
+ }
45
+ }
46
+ function onKeyUp(event) {
47
+ if (allowMultiple && event.keyCode === SHIFT_KEYCODE) {
48
+ setIsCheckingMultiple(false);
49
+ }
50
+ }
51
+ window.addEventListener('keydown', onKeyDown);
52
+ window.addEventListener('keyup', onKeyUp);
53
+ return () => {
54
+ window.removeEventListener('keydown', onKeyDown);
55
+ window.removeEventListener('keyup', onKeyUp);
56
+ };
57
+ }, [allowMultiple]);
58
+ // Callback function to update the `selectedRows` state.
59
+ const onSelectRow = useCallback((value, checked) => {
60
+ if (checked || allowUncheck) {
61
+ if (!isCheckingMultiple
62
+ && (checked || (!checked && allowMultiple && selectedRows.length > 1))) {
63
+ setSelectedRows([value]);
64
+ }
65
+ else if (!allowMultiple && !checked) {
66
+ setSelectedRows([]);
67
+ }
68
+ else {
69
+ setSelectedRows(checked
70
+ ? union(selectedRows || [], [value])
71
+ : difference(selectedRows || [], [value]));
72
+ }
73
+ }
74
+ }, [allowMultiple, isCheckingMultiple, allowUncheck, selectedRows]);
75
+ // Handler for checkbox input elements.
76
+ const handleInputChange = useCallback((event) => {
77
+ const { target } = event;
78
+ const { checked } = target;
79
+ const { value } = target;
80
+ onSelectRow(value, checked);
81
+ }, [onSelectRow]);
82
+ // Function to map row IDs to corresponding objects
83
+ // to pass to the `onChange` callback.
84
+ const getDataFromIds = useCallback(ids => ids.map(id => ({
85
+ [idKey]: id,
86
+ data: data.find(item => item[idKey] === id),
87
+ })), [data, idKey]);
88
+ // Function to check if a row ID has been selected.
89
+ const isSelected = useCallback(id => (Array.isArray(selectedRows) && selectedRows.includes(id)), [selectedRows]);
90
+ /* eslint-disable react-hooks/exhaustive-deps */
91
+ useEffect(() => {
92
+ // Check whether an initial set of rows should be selected.
93
+ const initialSelectedRows = data
94
+ .map((d) => {
95
+ if (d[valueKey]) {
96
+ return d[idKey];
97
+ }
98
+ return null;
99
+ })
100
+ .filter(Boolean);
101
+ if (!isEqual(initialSelectedRows, selectedRows)) {
102
+ if (initialSelectedRows.length > 0) {
103
+ setSelectedRows(initialSelectedRows);
104
+ }
105
+ else {
106
+ setSelectedRows(null);
107
+ }
108
+ }
109
+ }, [data, idKey, valueKey]);
110
+ /* eslint-disable react-hooks/exhaustive-deps */
111
+ useEffect(() => {
112
+ // Call the `onChange` prop function with an updated row or set of rows.
113
+ if (!onChange || !selectedRows) {
114
+ return;
115
+ }
116
+ const selectedRowData = getDataFromIds(selectedRows);
117
+ if (allowMultiple) {
118
+ onChange(selectedRowData);
119
+ }
120
+ else if (selectedRows.length === 1) {
121
+ onChange(selectedRowData[0]);
122
+ }
123
+ else if (selectedRows.length === 0) {
124
+ onChange(null);
125
+ }
126
+ }, [selectedRows, allowMultiple]);
127
+ const classes = useStyles();
128
+ // Generate a unique ID to use in (for, id) label-input pairs.
129
+ const inputUuid = uuidv4();
130
+ const rowRenderer = ({ index, style }) => (
131
+ // eslint-disable-next-line jsx-a11y/interactive-supports-focus
132
+ _jsxs("div", { className: clsx(classes.tableItem, classes.tableRow, { 'row-checked': isSelected(data[index][idKey]) }), style: style, role: "button", onClick: () => onSelectRow(data[index][idKey], !isSelected(data[index][idKey]) || !hasColorEncoding), children: [_jsx("div", { className: clsx(classes.inputContainer, classes.tableCell, { [classes.hiddenInputColumn]: !showTableInputs }), children: _jsx("label", { htmlFor: `${inputUuid}_${data[index][idKey]}`, children: _jsx("input", { id: `${inputUuid}_${data[index][idKey]}`, type: "checkbox", className: clsx(classes.radioOrCheckbox, isCheckingMultiple ? classes.tableCheckbox : classes.tableRadio), name: inputUuid, value: data[index][idKey], onChange: handleInputChange, checked: isSelected(data[index][idKey]) }) }) }), columns.map(column => (_jsx("div", { className: classes.tableCell, children: data[index][column] }, column)))] }, data[index][idKey]));
133
+ const headerRowRenderer = ({ style }) => (_jsx("div", { className: classes.tableRow, style: style, children: columnLabels.map(columnLabel => (_jsx("div", { className: classes.tableCell, style: { fontWeight: 'bold' }, children: columnLabel }, columnLabel))) }));
134
+ return (_jsx("div", { className: classes.selectableTable, children: _jsx(AutoSizer, { children: ({ width, height }) => (_jsx(Table, { height: testHeight || height, gridStyle: { outline: 'none' }, rowCount: data.length,
135
+ // 24 is 1 em + padding in either direction (see _selectable_table.scss).
136
+ rowHeight: 24, headerHeight: showTableHead ? 24 : undefined, rowRenderer: rowRenderer, width: testWidth || width, headerRowRenderer: showTableHead ? headerRowRenderer : undefined, rowGetter: ({ index }) => data[index] })) }) }));
137
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=SelectableTable.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SelectableTable.test.d.ts","sourceRoot":"","sources":["../../src/selectable-table/SelectableTable.test.jsx"],"names":[],"mappings":""}
@@ -0,0 +1,94 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { describe, it, expect, afterEach } from 'vitest';
3
+ import '@testing-library/jest-dom';
4
+ import { cleanup, render, screen, } from '@testing-library/react';
5
+ import userEvent from '@testing-library/user-event';
6
+ import React from 'react';
7
+ import SelectableTable from './SelectableTable.js';
8
+ const user = userEvent.setup();
9
+ afterEach(() => {
10
+ cleanup();
11
+ });
12
+ const tableData = [
13
+ {
14
+ X: 'X1',
15
+ Y: 'Y1',
16
+ Name: 'Tile 1',
17
+ },
18
+ {
19
+ X: 'X1',
20
+ Y: 'Y2',
21
+ Name: 'Tile 2',
22
+ },
23
+ {
24
+ X: 'X3',
25
+ Y: 'Y3',
26
+ Name: 'Tile 3',
27
+ },
28
+ ];
29
+ const tableIdKey = 'Name';
30
+ const tableColumns = [
31
+ 'X',
32
+ 'Y',
33
+ 'Name',
34
+ ];
35
+ const columnLabels = ['Label 1', 'Label 2', 'Name'];
36
+ describe('SelectableTable.js', () => {
37
+ describe('<SelectableTable />', () => {
38
+ it('renders column values', async () => {
39
+ render(_jsx(SelectableTable, { data: tableData, columns: tableColumns, columnLabels: columnLabels, idKey: tableIdKey, testHeight: 500, testWidth: 500 }));
40
+ expect(await screen.findByText('Label 1'));
41
+ expect(await screen.findByText('Label 2'));
42
+ expect(await screen.findByText('Name'));
43
+ // Since the button (although hidden) is also a table-cell, it has a blank string.
44
+ expect(await screen.findAllByText('X1'));
45
+ expect(await screen.findByText('Y2'));
46
+ expect(await screen.findByText('Tile 3'));
47
+ });
48
+ it('emits single selected object when allowMultiple is false', async () => {
49
+ const p = new Promise((resolve) => {
50
+ render(_jsx(SelectableTable, { data: tableData, columns: tableColumns, columnLabels: columnLabels, idKey: tableIdKey, onChange: (selection) => {
51
+ expect(Array.isArray(selection)).toBe(false);
52
+ expect(selection.Name).toEqual('Tile 1');
53
+ resolve();
54
+ }, testHeight: 500, testWidth: 500 }));
55
+ screen.findByText('Tile 1').then((row) => {
56
+ user.click(row);
57
+ });
58
+ });
59
+ await p;
60
+ });
61
+ it('emits an array of selected objects when allowMultiple is true', async () => {
62
+ const p = new Promise((resolve) => {
63
+ render(_jsx(SelectableTable, { data: tableData, columns: tableColumns, columnLabels: columnLabels, idKey: tableIdKey, allowMultiple: true, onChange: (selection) => {
64
+ expect(Array.isArray(selection)).toBe(true);
65
+ expect(selection.length).toEqual(1);
66
+ expect(selection[0].Name).toEqual('Tile 2');
67
+ resolve();
68
+ }, testHeight: 500, testWidth: 500 }));
69
+ screen.findByText('Tile 2').then((row) => {
70
+ user.click(row);
71
+ });
72
+ });
73
+ await p;
74
+ });
75
+ it('renders single column values', async () => {
76
+ const customTableColumns = [
77
+ 'Name',
78
+ ];
79
+ const customColumnLabels = ['Name'];
80
+ render(_jsx(SelectableTable, { data: tableData, columns: customTableColumns, columnLabels: customColumnLabels, idKey: tableIdKey, testHeight: 500, testWidth: 500 }));
81
+ // write an expect statement to check that Label 1 is not rendered
82
+ const label1 = screen.queryByText('Label 1');
83
+ const label2 = screen.queryByText('Label 2');
84
+ const X1 = screen.queryByText('X1');
85
+ const Y2 = screen.queryByText('Y2');
86
+ expect(label1).toBeNull();
87
+ expect(label2).toBeNull();
88
+ expect(X1).toBeNull();
89
+ expect(Y2).toBeNull();
90
+ expect(await screen.findByText('Tile 3'));
91
+ expect(await screen.findByText('Name'));
92
+ });
93
+ });
94
+ });
@@ -0,0 +1,2 @@
1
+ export { default as SelectableTable } from "./SelectableTable.js";
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/selectable-table/index.js"],"names":[],"mappings":""}
@@ -0,0 +1 @@
1
+ export { default as SelectableTable } from './SelectableTable.js';
@@ -0,0 +1,2 @@
1
+ export const useStyles: (props?: any) => import("@material-ui/core/styles/withStyles").ClassNameMap<"selectableTable" | "tableRow" | "tableItem" | "tableCell" | "inputContainer" | "hiddenInputColumn" | "radioOrCheckbox" | "tableRadio" | "tableCheckbox">;
2
+ //# sourceMappingURL=styles.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"styles.d.ts","sourceRoot":"","sources":["../../src/selectable-table/styles.js"],"names":[],"mappings":"AAGA,8PAuEI"}
@@ -0,0 +1,73 @@
1
+ /* eslint-disable max-len */
2
+ import { makeStyles } from '@material-ui/core';
3
+ export const useStyles = makeStyles(theme => ({
4
+ selectableTable: {
5
+ flex: '1 1 auto',
6
+ outline: 'none',
7
+ },
8
+ tableRow: {
9
+ display: 'flex',
10
+ flexDirection: 'row',
11
+ borderBottom: `1px solid ${theme.palette.secondaryBackgroundDim}`, // map-get($theme-colors, "secondary-background-dim");
12
+ },
13
+ tableItem: {
14
+ cursor: 'pointer',
15
+ userSelect: 'none',
16
+ '&.row-checked': {
17
+ backgroundColor: theme.palette.secondaryBackgroundDim, // map-get($theme-colors, "secondary-background-dim");
18
+ },
19
+ '&:not(.row-checked):hover': {
20
+ /*
21
+ @if $theme-name == dark {
22
+ background-color: darken(map-get($theme-colors, "secondary-background-dim"), 10%);
23
+ } @else {
24
+ background-color: lighten(map-get($theme-colors, "secondary-background-dim"), 10%);
25
+ }
26
+ */
27
+ },
28
+ },
29
+ tableCell: {
30
+ textAlign: 'left',
31
+ flexBasis: 0,
32
+ flexGrow: 1,
33
+ textOverflow: 'ellipsis',
34
+ whiteSpace: 'nowrap',
35
+ },
36
+ inputContainer: {
37
+ width: '1em',
38
+ '& label': {
39
+ display: 'block',
40
+ margin: '0',
41
+ cursor: 'pointer',
42
+ },
43
+ '& input': {
44
+ cursor: 'pointer',
45
+ },
46
+ },
47
+ hiddenInputColumn: {
48
+ // Class for first column of inputs, to hide them if desired.
49
+ display: 'none',
50
+ },
51
+ radioOrCheckbox: {
52
+ appearance: 'none',
53
+ /* create custom radiobutton appearance */
54
+ display: 'inline-block',
55
+ width: '1em',
56
+ height: '1em',
57
+ margin: '0.3em 0.5em 0.0em 0.5em',
58
+ padding: '6px',
59
+ /* background-color only for content */
60
+ backgroundClip: 'content-box',
61
+ border: `2px solid ${theme.palette.grayLight}`,
62
+ backgroundColor: theme.palette.grayLight,
63
+ '&:checked': {
64
+ backgroundClip: 'unset',
65
+ },
66
+ },
67
+ tableRadio: {
68
+ borderRadius: '50%',
69
+ },
70
+ tableCheckbox: {
71
+ borderRadius: '2px',
72
+ },
73
+ }));