@vitessce/feature-list 2.0.3-beta.0 → 2.0.3

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.
@@ -1,52 +0,0 @@
1
- import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
- import React, { useEffect, useState } from 'react';
3
- import every from 'lodash/every';
4
- import { makeStyles } from '@material-ui/core/styles';
5
- import { SelectableTable } from './selectable-table/index';
6
- const useStyles = makeStyles(() => ({
7
- searchBar: {
8
- marginBottom: '4px',
9
- border: '0',
10
- padding: '2px',
11
- borderRadius: '2px',
12
- },
13
- }));
14
- export default function FeatureList(props) {
15
- const { hasColorEncoding, geneList = [], featureLabelsMap, geneSelection = [], geneFilter = null, setGeneSelection, enableMultiSelect, } = props;
16
- const classes = useStyles();
17
- const [searchTerm, setSearchTerm] = useState('');
18
- const [searchResults, setSearchResults] = useState(geneList);
19
- useEffect(() => {
20
- const results = geneList
21
- .filter(gene => (gene.toLowerCase().includes(searchTerm.toLowerCase())
22
- || featureLabelsMap?.get(gene)?.toLowerCase().includes(searchTerm.toLowerCase())));
23
- setSearchResults(results);
24
- }, [searchTerm, geneList, featureLabelsMap]);
25
- function onChange(selection) {
26
- if (setGeneSelection && selection) {
27
- if (Array.isArray(selection)) {
28
- if (selection.length > 0 && every(selection, s => s.key)) {
29
- setGeneSelection(selection.map(s => s.key));
30
- }
31
- else {
32
- setGeneSelection(null);
33
- }
34
- }
35
- else if (selection.key) {
36
- setGeneSelection([selection.key]);
37
- }
38
- }
39
- }
40
- const data = searchResults
41
- .filter(gene => (geneFilter ? geneFilter.includes(gene) : true))
42
- .map(gene => ({
43
- key: gene,
44
- name: featureLabelsMap?.get(gene) || gene,
45
- value: (geneSelection ? geneSelection.includes(gene) : false),
46
- }))
47
- .sort((a, b) => a.name.localeCompare(b.name));
48
- const handleChange = (event) => {
49
- setSearchTerm(event.target.value);
50
- };
51
- return (_jsxs(_Fragment, { children: [_jsx("input", { className: classes.searchBar, type: "text", placeholder: "Search", value: searchTerm, onChange: handleChange }), _jsx(SelectableTable, { columns: ['name'], data: data, hasColorEncoding: hasColorEncoding, idKey: "key", valueKey: "value", onChange: onChange, allowMultiple: enableMultiSelect, allowUncheck: enableMultiSelect, showTableHead: false })] }));
52
- }
@@ -1,54 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import React from 'react';
3
- import plur from 'plur';
4
- import { capitalize, commaNumber } from '@vitessce/utils';
5
- import { TitleInfo, useReady, useUrls, useFeatureLabelsData, useObsFeatureMatrixIndices, useCoordination, useLoaders, registerPluginViewType, } from '@vitessce/vit-s';
6
- import { ViewType, COMPONENT_COORDINATION_TYPES } from '@vitessce/constants-internal';
7
- import FeatureList from './FeatureList';
8
- /**
9
- * A subscriber component for a gene listing component.
10
- * @param {object} props
11
- * @param {string} props.theme The current theme name.
12
- * @param {object} props.coordinationScopes The mapping from coordination types to coordination
13
- * scopes.
14
- * @param {function} props.removeGridComponent The callback function to pass to TitleInfo,
15
- * to call when the component has been removed from the grid.
16
- * @param {string} props.title The component title.
17
- * @param {string} props.variablesLabelOverride The singular form
18
- * of the name of the variable.
19
- * @param {string} props.variablesPluralLabelOverride The plural
20
- * form of the name of the variable.
21
- * @param {boolean} props.enableMultiSelect If true, allow
22
- * shift-clicking to select multiple genes.
23
- */
24
- export function FeatureListSubscriber(props) {
25
- const { coordinationScopes, removeGridComponent, variablesLabelOverride, theme, title: titleOverride, enableMultiSelect = false, } = props;
26
- const loaders = useLoaders();
27
- // Get "props" from the coordination space.
28
- 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);
29
- const variablesLabel = variablesLabelOverride || featureType;
30
- const title = titleOverride || `${capitalize(variablesLabel)} List`;
31
- const [urls, addUrl] = useUrls(loaders, dataset);
32
- // Get data from loaders using the data hooks.
33
- // TODO: support multiple feature labels using featureLabelsType coordination values.
34
- const [{ featureLabelsMap }, featureLabelsStatus] = useFeatureLabelsData(loaders, dataset, addUrl, false, {}, {}, { featureType });
35
- const [{ featureIndex }, matrixIndicesStatus] = useObsFeatureMatrixIndices(loaders, dataset, addUrl, true, { featureType });
36
- const isReady = useReady([
37
- featureLabelsStatus,
38
- matrixIndicesStatus,
39
- ]);
40
- const geneList = featureIndex || [];
41
- const numGenes = geneList.length;
42
- function setGeneSelectionAndColorEncoding(newSelection) {
43
- setGeneSelection(newSelection);
44
- setCellColorEncoding('geneSelection');
45
- }
46
- return (_jsx(TitleInfo, { title: title, info: `${commaNumber(numGenes)} ${plur(variablesLabel, numGenes)}`, theme: theme,
47
- // Virtual scroll is used but this allows for the same styling as a scroll component
48
- // even though this no longer uses the TitleInfo component's
49
- // scroll css (SelectableTable is virtual scroll).
50
- isScroll: true, removeGridComponent: removeGridComponent, isReady: isReady, urls: urls, children: _jsx(FeatureList, { hasColorEncoding: cellColorEncoding === 'geneSelection', geneList: geneList, featureLabelsMap: featureLabelsMap, geneSelection: geneSelection, geneFilter: geneFilter, setGeneSelection: setGeneSelectionAndColorEncoding, setGeneFilter: setGeneFilter, setGeneHighlight: setGeneHighlight, enableMultiSelect: enableMultiSelect }) }));
51
- }
52
- export function register() {
53
- registerPluginViewType(ViewType.FEATURE_LIST, FeatureListSubscriber, COMPONENT_COORDINATION_TYPES[ViewType.FEATURE_LIST]);
54
- }
@@ -1,134 +0,0 @@
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
- import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
7
- import Table from 'react-virtualized/dist/commonjs/Table';
8
- import uuidv4 from 'uuid/v4';
9
- import union from 'lodash/union';
10
- import difference from 'lodash/difference';
11
- import isEqual from 'lodash/isEqual';
12
- import clsx from 'clsx';
13
- import { useStyles } from './styles';
14
- const SHIFT_KEYCODE = 16;
15
- /**
16
- * A table with "selectable" rows.
17
- * @prop {string[]} columns An array of column names, corresponding to data object properties.
18
- * @prop {object[]} data An array of data objects used to populate table rows.
19
- * @prop {function} onChange Callback function,
20
- * passed a selection object when `allowMultiple` is false (and `null` if `allowUncheck` is true),
21
- * or passed an array of selection objects when `allowMultiple` is true.
22
- * @prop {string} idKey The key for a unique identifier property of `data` objects.
23
- * @prop {string} valueKey If initially-selected rows are required,
24
- * this key specifies a boolean property of the `data` objects
25
- * indicating those rows that should be initially selected.
26
- * @prop {boolean} allowMultiple Whether to allow multiple rows to be selected.
27
- * @prop {boolean} allowUncheck Whether to allow selected rows to be un-checked. By default, false.
28
- * @prop {boolean} showTableHead Whether to show the table header element. By default, true.
29
- * @prop {boolean} showTableInputs Whether to show the table input elements for each row.
30
- * By default, false.
31
- */
32
- export default function SelectableTable(props) {
33
- const { hasColorEncoding, columns, data, onChange, idKey = 'id', valueKey = 'value', allowMultiple = false, allowUncheck = false, showTableHead = true, showTableInputs = false, testHeight = undefined, testWidth = undefined, } = props;
34
- const [selectedRows, setSelectedRows] = useState(null);
35
- const [isCheckingMultiple, setIsCheckingMultiple] = useState(false);
36
- // Enable selecting multiple rows while the shift key is down.
37
- useEffect(() => {
38
- function onKeyDown(event) {
39
- if (allowMultiple && event.keyCode === SHIFT_KEYCODE) {
40
- setIsCheckingMultiple(true);
41
- }
42
- }
43
- function onKeyUp(event) {
44
- if (allowMultiple && event.keyCode === SHIFT_KEYCODE) {
45
- setIsCheckingMultiple(false);
46
- }
47
- }
48
- window.addEventListener('keydown', onKeyDown);
49
- window.addEventListener('keyup', onKeyUp);
50
- return () => {
51
- window.removeEventListener('keydown', onKeyDown);
52
- window.removeEventListener('keyup', onKeyUp);
53
- };
54
- }, [allowMultiple]);
55
- // Callback function to update the `selectedRows` state.
56
- const onSelectRow = useCallback((value, checked) => {
57
- if (checked || allowUncheck) {
58
- if (!isCheckingMultiple
59
- && (checked || (!checked && allowMultiple && selectedRows.length > 1))) {
60
- setSelectedRows([value]);
61
- }
62
- else if (!allowMultiple && !checked) {
63
- setSelectedRows([]);
64
- }
65
- else {
66
- setSelectedRows(checked
67
- ? union(selectedRows || [], [value])
68
- : difference(selectedRows || [], [value]));
69
- }
70
- }
71
- }, [allowMultiple, isCheckingMultiple, allowUncheck, selectedRows]);
72
- // Handler for checkbox input elements.
73
- const handleInputChange = useCallback((event) => {
74
- const { target } = event;
75
- const { checked } = target;
76
- const { value } = target;
77
- onSelectRow(value, checked);
78
- }, [onSelectRow]);
79
- // Function to map row IDs to corresponding objects
80
- // to pass to the `onChange` callback.
81
- const getDataFromIds = useCallback(ids => ids.map(id => ({
82
- [idKey]: id,
83
- data: data.find(item => item[idKey] === id),
84
- })), [data, idKey]);
85
- // Function to check if a row ID has been selected.
86
- const isSelected = useCallback(id => (Array.isArray(selectedRows) && selectedRows.includes(id)), [selectedRows]);
87
- /* eslint-disable react-hooks/exhaustive-deps */
88
- useEffect(() => {
89
- // Check whether an initial set of rows should be selected.
90
- const initialSelectedRows = data
91
- .map((d) => {
92
- if (d[valueKey]) {
93
- return d[idKey];
94
- }
95
- return null;
96
- })
97
- .filter(Boolean);
98
- if (!isEqual(initialSelectedRows, selectedRows)) {
99
- if (initialSelectedRows.length > 0) {
100
- setSelectedRows(initialSelectedRows);
101
- }
102
- else {
103
- setSelectedRows(null);
104
- }
105
- }
106
- }, [data, idKey, valueKey]);
107
- /* eslint-disable react-hooks/exhaustive-deps */
108
- useEffect(() => {
109
- // Call the `onChange` prop function with an updated row or set of rows.
110
- if (!onChange || !selectedRows) {
111
- return;
112
- }
113
- const selectedRowData = getDataFromIds(selectedRows);
114
- if (allowMultiple) {
115
- onChange(selectedRowData);
116
- }
117
- else if (selectedRows.length === 1) {
118
- onChange(selectedRowData[0]);
119
- }
120
- else if (selectedRows.length === 0) {
121
- onChange(null);
122
- }
123
- }, [selectedRows, allowMultiple]);
124
- const classes = useStyles();
125
- // Generate a unique ID to use in (for, id) label-input pairs.
126
- const inputUuid = uuidv4();
127
- const rowRenderer = ({ index, style }) => (
128
- // eslint-disable-next-line jsx-a11y/interactive-supports-focus
129
- _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.checkbox : classes.radio), 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]));
130
- const headerRowRenderer = ({ style }) => (_jsx("div", { className: clsx({ [classes.hiddenInputColumn]: !showTableInputs }, classes.tableRow), style: style, children: columns.map(column => (_jsx("div", { children: column }, column))) }));
131
- return (_jsx("div", { className: classes.selectableTable, children: _jsx(AutoSizer, { children: ({ width, height }) => (_jsx(Table, { height: testHeight || height, gridStyle: { outline: 'none' }, rowCount: data.length,
132
- // 24 is 1 em + padding in either direction (see _selectable_table.scss).
133
- rowHeight: 24, headerHeight: showTableHead ? 24 : undefined, rowRenderer: rowRenderer, width: testWidth || width, headerRowRenderer: showTableHead ? headerRowRenderer : undefined, rowGetter: ({ index }) => data[index] })) }) }));
134
- }
@@ -1,72 +0,0 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import '@testing-library/jest-dom';
3
- import { cleanup, render, screen } from '@testing-library/react';
4
- import userEvent from '@testing-library/user-event';
5
- import { afterEach } from 'vitest';
6
- const user = userEvent.setup();
7
- import SelectableTable from './SelectableTable';
8
- afterEach(() => {
9
- cleanup();
10
- });
11
- const tableData = [
12
- {
13
- X: 'X1',
14
- Y: 'Y1',
15
- Name: 'Tile 1',
16
- },
17
- {
18
- X: 'X1',
19
- Y: 'Y2',
20
- Name: 'Tile 2',
21
- },
22
- {
23
- X: 'X3',
24
- Y: 'Y3',
25
- Name: 'Tile 3',
26
- },
27
- ];
28
- const tableIdKey = 'Name';
29
- const tableColumns = [
30
- 'X',
31
- 'Y',
32
- 'Name',
33
- ];
34
- describe('SelectableTable.js', () => {
35
- describe('<SelectableTable />', () => {
36
- it('renders column values', async () => {
37
- render(_jsx(SelectableTable, { data: tableData, columns: tableColumns, idKey: tableIdKey, testHeight: 500, testWidth: 500 }));
38
- expect(await screen.findByText('Name'));
39
- // Since the button (although hidden) is also a table-cell, it has a blank string.
40
- expect(await screen.findAllByText('X1'));
41
- expect(await screen.findByText('Y2'));
42
- expect(await screen.findByText('Tile 3'));
43
- });
44
- it('emits single selected object when allowMultiple is false', async () => {
45
- const p = new Promise((resolve, reject) => {
46
- render(_jsx(SelectableTable, { data: tableData, columns: tableColumns, idKey: tableIdKey, onChange: (selection) => {
47
- expect(Array.isArray(selection)).toBe(false);
48
- expect(selection.Name).toEqual('Tile 1');
49
- resolve();
50
- }, testHeight: 500, testWidth: 500 }));
51
- screen.findByText('Tile 1').then((row) => {
52
- user.click(row);
53
- });
54
- });
55
- await p;
56
- });
57
- it('emits an array of selected objects when allowMultiple is true', async () => {
58
- const p = new Promise((resolve, reject) => {
59
- render(_jsx(SelectableTable, { data: tableData, columns: tableColumns, idKey: tableIdKey, allowMultiple: true, onChange: (selection) => {
60
- expect(Array.isArray(selection)).toBe(true);
61
- expect(selection.length).toEqual(1);
62
- expect(selection[0].Name).toEqual('Tile 2');
63
- resolve();
64
- }, testHeight: 500, testWidth: 500 }));
65
- screen.findByText('Tile 2').then((row) => {
66
- user.click(row);
67
- });
68
- });
69
- await p;
70
- });
71
- });
72
- });
@@ -1 +0,0 @@
1
- "use strict";
@@ -1,69 +0,0 @@
1
- /* eslint-disable max-len */
2
- import { makeStyles } from '@material-ui/core/styles';
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
- padding: '0 4px',
31
- },
32
- inputContainer: {
33
- width: '1em',
34
- '& label': {
35
- display: 'block',
36
- margin: '0',
37
- cursor: 'pointer',
38
- },
39
- '& input': {
40
- cursor: 'pointer',
41
- },
42
- },
43
- hiddenInputColumn: {
44
- // Class for first column of inputs, to hide them if desired.
45
- display: 'none',
46
- },
47
- radioOrCheckbox: {
48
- appearance: 'none',
49
- /* create custom radiobutton appearance */
50
- display: 'inline-block',
51
- width: '1em',
52
- height: '1em',
53
- margin: '0.3em 0.5em 0.0em 0.5em',
54
- padding: '6px',
55
- /* background-color only for content */
56
- backgroundClip: 'content-box',
57
- border: `2px solid ${theme.palette.grayLight}`,
58
- backgroundColor: theme.palette.grayLight,
59
- '&:checked': {
60
- backgroundClip: 'unset',
61
- },
62
- },
63
- radio: {
64
- borderRadius: '50%',
65
- },
66
- checkbox: {
67
- borderRadius: '2px',
68
- },
69
- }));