Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to make only certain Tabulator rows selectable #2433

Merged
merged 2 commits into from
Jun 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion examples/reference/widgets/Tabulator.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@
"* **``page_size``** (``int``): Number of rows on each page.\n",
"* **``pagination``** (`str`, `default=None`): Set to 'local' or 'remote' to enable pagination; by default pagination is disabled with the value set to `None`.\n",
"* **``selection``** (``list``): The currently selected rows.\n",
"* **``selectable``** (`boolean` or `str`): Whether to allow selection of rows. Can be `True`, `False`, `'checkbox'` or `'toggle'`. \n",
"* **``selectable``** (`boolean` or `str`): Whether to allow selection of rows. Can be `True`, `False`, `'checkbox'`, `'checkbox-single'` or `'toggle'`. \n",
"* **``selectable_rows``** (`callable`): A function that should return a list of integer indexes given a DataFrame indicating which rows may be selected.\n",
"* **``show_index``** (``boolean``): Whether to show the index column.\n",
"* **``text_align``** (``dict`` or ``str``): A mapping from column name to alignment or a fixed column alignment, which should be one of 'left', 'center', 'right'.\n",
"* **`theme`** (``str``): The CSS theme to apply (note that changing the theme will restyle all tables on the page).\n",
Expand Down Expand Up @@ -441,6 +442,7 @@
"- `True`: Selects rows on click. To select multiple use Ctrl-select, to select a range use Shift-select\n",
"- `False`: Disables selection\n",
"- `'checkbox'`: Adds a column of checkboxes to toggle selections\n",
"- `'checkbox-single'`: Same as `'checkbox'` but disables (de)select-all in the header\n",
"- `'toggle'`: Selection toggles when clicked"
]
},
Expand All @@ -453,6 +455,22 @@
"pn.widgets.Tabulator(sel_df, selection=[0, 3, 7], selectable='checkbox')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Additionally we can also disable selection for specific rows by providing a `selectable_rows` function. The function must accept a DataFrame and return a list of integer indexes indicating which rows are selectable, e.g. here we disable selection for every second row:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pn.widgets.Tabulator(sel_df, selectable_rows=lambda df: list(range(0, len(df), 2)))"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down
2 changes: 2 additions & 0 deletions panel/models/tabulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ class DataTabulator(HTMLBox):

select_mode = Any(default=True)

selectable_rows = Nullable(List(Int))

theme = Enum(*TABULATOR_THEMES, default="simple")

theme_url = String(default=THEME_URL)
Expand Down
28 changes: 23 additions & 5 deletions panel/models/tabulator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@ export class DataTabulatorView extends PanelHTMLBoxView {
pagination: pagination,
paginationSize: this.model.page_size,
paginationInitialPage: 1,
selectableCheck: (row: any) => {
const selectable = this.model.selectable_rows
return (selectable == null) || (selectable.indexOf(row._row.data._index) >= 0)
}
}
if (pagination) {
configuration['ajaxURL'] = "http://panel.pyviz.org"
Expand Down Expand Up @@ -492,19 +496,31 @@ export class DataTabulatorView extends PanelHTMLBoxView {
indices.push(index)
else
indices.splice(indices.indexOf(index), 1)
const filtered = this._filter_selected(indices)
this.tabulator.deselectRow()
this.tabulator.selectRow(indices)
this.tabulator.selectRow(filtered)
this._selection_updating = true
selected.indices = indices
selected.indices = filtered
this._selection_updating = false
}

_filter_selected(indices: number[]): number[] {
const filtered = []
for (const ind of indices) {
if (this.model.selectable_rows == null ||
this.model.selectable_rows.indexOf(ind) >= 0)
filtered.push(ind)
}
return filtered
}

rowSelectionChanged(data: any, _: any): void {
if (this._selection_updating || this._initializing || (typeof this.model.select_mode) === 'boolean')
return
this._selection_updating = true
const indices: any = data.map((row: any) => row._index)
this.model.source.selected.indices = indices;
const indices: number[] = data.map((row: any) => row._index)
const filtered = this._filter_selected(indices)
this._selection_updating = indices.length === filtered.length
this.model.source.selected.indices = filtered;
this._selection_updating = false
}

Expand Down Expand Up @@ -538,6 +554,7 @@ export namespace DataTabulator {
page_size: p.Property<number>
pagination: p.Property<string | null>
select_mode: p.Property<any>
selectable_rows: p.Property<number[] | null>
source: p.Property<ColumnDataSource>
sorters: p.Property<any[]>
styles: p.Property<any>
Expand Down Expand Up @@ -577,6 +594,7 @@ export class DataTabulator extends HTMLBox {
page: [ Number, 0 ],
page_size: [ Number, 0 ],
select_mode: [ Any, true ],
selectable_rows: [ Nullable(Array(Number)), null ],
source: [ Ref(ColumnDataSource) ],
sorters: [ Array(Any), [] ],
styles: [ Any, {} ],
Expand Down
1 change: 1 addition & 0 deletions panel/reactive.py
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,7 @@ def _update_selected(self, *events, indices=None):

@updating
def _stream(self, stream, rollover=None):
self._processed, _ = self._get_data()
for ref, (m, _) in self._models.items():
if ref not in state._views or ref in state._fake_roots:
continue
Expand Down
48 changes: 48 additions & 0 deletions panel/tests/widgets/test_tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,15 @@ def test_tabulator_frozen_rows(document, comm):
assert model.frozen_rows == [1, 3]


def test_tabulator_selectable_rows(document, comm):
df = makeMixedDataFrame()
table = Tabulator(df, selectable_rows=lambda df: list(df[df.A>2].index.values))

model = table.get_root(document, comm)

assert model.selectable_rows == [3, 4]


def test_tabulator_pagination(document, comm):
df = makeMixedDataFrame()
table = Tabulator(df, pagination='remote', page_size=2)
Expand Down Expand Up @@ -376,6 +385,23 @@ def test_tabulator_pagination_selection(document, comm):
assert model.source.selected.indices == [0, 1]


def test_tabulator_pagination_selectable_rows(document, comm):
df = makeMixedDataFrame()
table = Tabulator(
df, pagination='remote', page_size=3,
selectable_rows=lambda df: list(df.index.values[::2])
)

model = table.get_root(document, comm)

print(table._processed)
assert model.selectable_rows == [0, 2]

table.page = 2

assert model.selectable_rows == [3]


def test_tabulator_styling(document, comm):
df = makeMixedDataFrame()
table = Tabulator(df)
Expand Down Expand Up @@ -856,6 +882,28 @@ def test_tabulator_stream_dataframe_with_filter(document, comm):
np.testing.assert_array_equal(values, expected[col])


def test_tabulator_stream_dataframe_selectable_rows(document, comm):
df = makeMixedDataFrame()
table = Tabulator(df, selectable_rows=lambda df: list(range(0, len(df), 2)))

model = table.get_root(document, comm)

assert model.selectable_rows == [0, 2, 4]

stream_value = pd.DataFrame({
'A': [5, 6],
'B': [1, 0],
'C': ['foo6', 'foo7'],
'D': [dt.datetime(2009, 1, 8), dt.datetime(2009, 1, 9)]
})

table.stream(stream_value)

print(len(table._processed))

assert model.selectable_rows == [0, 2, 4, 6]


def test_tabulator_dataframe_replace_data(document, comm):
df = makeMixedDataFrame()
table = Tabulator(df)
Expand Down
90 changes: 65 additions & 25 deletions panel/widgets/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -726,16 +726,26 @@ class Tabulator(BaseTable):
The height of each table row.""")

selectable = param.ObjectSelector(
default=True, objects=[True, False, 'checkbox', 'toggle'], doc="""
default=True, objects=[True, False, 'checkbox', 'checkbox-single', 'toggle'], doc="""
Defines the selection mode of the Tabulator.

- True: Selects rows on click. To select multiple use
Ctrl-select, to select a range use Shift-select
- checkbox: Adds a column of checkboxes to toggle selections
- toggle: Selection toggles when clicked
- False: Disables selection
- True
Selects rows on click. To select multiple use Ctrl-select,
to select a range use Shift-select
- False
Disables selection
- 'checkbox'
Adds a column of checkboxes to toggle selections
- 'checkbox-single'
Same as 'checkbox' but header does not alllow select/deselect all
- 'toggle'
Selection toggles when clicked
""")

selectable_rows = param.Callable(default=None, doc="""
A function which given a DataFrame should return a list of
rows by integer index, which are selectable.""")

sorters = param.List(default=[], doc="""
A list of sorters to apply during pagination.""")

Expand Down Expand Up @@ -789,6 +799,8 @@ def _process_param_change(self, msg):
msg['theme_url'] = THEME_URL
theme = 'tabulator' if self.theme == 'default' else 'tabulator_'+self.theme
self._widget_type.__css__ = [msg['theme_url'] + theme + '.min.css']
if msg.get('select_mode') == 'checkbox-single':
msg['select_mode'] = 'checkbox'
return msg

def _update_columns(self, event, model):
Expand Down Expand Up @@ -827,17 +839,15 @@ def _length(self):
def _get_style_data(self):
if self.value is None:
return {}
df = self._processed
if self.pagination == 'remote':
nrows = self.page_size
start = (self.page-1)*nrows
df = self.value.iloc[start: start+nrows]
else:
df = self.value

df = df.iloc[start:(start+nrows)]
styler = df.style
styler._todo = self.style._todo
styler._compute()
offset = len(self.indexes) + int(self.selectable == 'checkbox')
offset = len(self.indexes) + int(self.selectable in ('checkbox', 'checkbox-single'))

styles = {}
for (r, c), s in styler.ctx.items():
Expand All @@ -846,6 +856,16 @@ def _get_style_data(self):
styles[int(r)][offset+int(c)] = s
return styles

def _get_selectable(self):
if self.value is None or self.selectable_rows is None:
return None
df = self._processed
if self.pagination == 'remote':
nrows = self.page_size
start = (self.page-1)*nrows
df = df.iloc[start:(start+nrows)]
return self.selectable_rows(df)

def _update_style(self):
styles = self._get_style_data()
msg = {'styles': styles}
Expand All @@ -862,6 +882,7 @@ def _stream(self, stream, rollover=None, follow=True):
return
super()._stream(stream, rollover)
self._update_style()
self._update_selectable()

def stream(self, stream_value, rollover=None, reset_index=True, follow=True):
for ref, (model, _) in self._models.items():
Expand All @@ -888,6 +909,7 @@ def _patch(self, patch):
if not patch:
return
super()._patch(patch)
self._update_selectable()
if self.pagination == 'remote':
self._update_style()

Expand All @@ -899,6 +921,12 @@ def _update_cds(self, *events):
self._update_max_page()
self._update_selected()
self._update_style()
self._update_selectable()

def _update_selectable(self):
selectable = self._get_selectable()
for ref, (model, _) in self._models.items():
self._apply_update([], {'selectable_rows': selectable}, model, ref)

def _update_max_page(self):
length = self._length
Expand Down Expand Up @@ -962,18 +990,26 @@ def _get_properties(self, source):
length = self._length
if props.get('height', None) is None:
props['height'] = length * self.row_height + 30
props['source'] = source
props['styles'] = self._get_style_data()
props['columns'] = columns = self._get_columns()
props['configuration'] = self._get_configuration(columns)
props['page'] = self.page
props['pagination'] = self.pagination
props['page_size'] = self.page_size
props['layout'] = self.layout
props['groupby'] = self.groupby
props['hidden_columns'] = self.hidden_columns
props['editable'] = not self.disabled
props['select_mode'] = self.selectable
columns = self._get_columns()
if self.selectable == 'checkbox-single':
selectable = 'checkbox'
else:
selectable = self.selectable
props.update({
'source': source,
'styles': self._get_style_data(),
'columns': columns,
'configuration': self._get_configuration(columns),
'page': self.page,
'pagination': self.pagination,
'page_size': self.page_size,
'layout': self.layout,
'groupby': self.groupby,
'hidden_columns': self.hidden_columns,
'editable': not self.disabled,
'select_mode': selectable,
'selectable_rows': self._get_selectable()
})
process = {'theme': self.theme, 'frozen_rows': self.frozen_rows}
props.update(self._process_param_change(process))
if self.pagination:
Expand All @@ -996,10 +1032,12 @@ def _config_columns(self, column_objs):
column_objs = list(column_objs)
groups = {}
columns = []
if self.selectable == 'checkbox':
selectable = self.selectable
if isinstance(selectable, str) and selectable.startswith('checkbox'):
title = "" if selectable.endswith('-single') else "rowSelection"
columns.append({
"formatter": "rowSelection",
"titleFormatter": "rowSelection",
"titleFormatter": title,
"hozAlign": "center",
"headerSort": False,
"frozen": True
Expand Down Expand Up @@ -1035,6 +1073,8 @@ def _config_columns(self, column_objs):
col_dict['formatter'] = formatter.pop('type')
col_dict['formatterParams'] = formatter
editor = self.editors.get(column.field)
if column.field in self.editors and editor is None:
col_dict['editable'] = False
if isinstance(editor, str):
col_dict['editor'] = editor
elif isinstance(editor, dict):
Expand Down