Skip to content

Commit

Permalink
Support for JavaScript function properties (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
CrystalWindSnake authored May 10, 2024
1 parent 459a732 commit 375f37a
Show file tree
Hide file tree
Showing 4 changed files with 221 additions and 4 deletions.
14 changes: 13 additions & 1 deletion nicegui_tabulator/core/tabulator.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { loadResource } from "../../static/utils/resources.js";
import { convertDynamicProperties } from "../../static/utils/dynamic_properties.js";


const eventArgsExtractor = new Map([
Expand Down Expand Up @@ -57,7 +58,7 @@ export default {
loadResource(window.path_prefix + `${this.resource_path}/tabulator.min.css`),
]);


convertDynamicProperties(this.options, true);
this.table = new Tabulator(this.$el, this.options);

},
Expand All @@ -77,5 +78,16 @@ export default {
}
return runMethod(this.table, name, args);
},

setColumns(columns) {
convertDynamicProperties(columns, true);
this.table.setColumns(columns);
},

updateColumnDefinition(field, definition) {
convertDynamicProperties(definition, true);
this.table.updateColumnDefinition(field, definition);
},

},
};
96 changes: 93 additions & 3 deletions nicegui_tabulator/core/tabulator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pathlib import Path
from typing import Callable, Dict
from typing import Callable, Dict, List, Optional
from nicegui.element import Element
from nicegui.events import handle_event
from nicegui import ui, Client as ng_client
Expand Down Expand Up @@ -36,7 +36,14 @@ def on_event(
event: str,
callback: Callable[..., None],
):
""" """
"""
Register an event listener for the tabulator table.
Args:
event (str): The name of the event to listen for.
callback (Callable[..., None]): The function to call when the event is triggered.
"""

@self.__deferred_task.register
def _():
Expand All @@ -48,7 +55,16 @@ def _():
def run_table_method(
self, name: str, *args, timeout: float = 1, check_interval: float = 0.01
) -> AwaitableResponse:
""" """
"""
Run a method on the tabulator table.
Args:
name (str): The name of the method to run.
*args: The arguments to pass to the method.
timeout (float, optional): The maximum time to wait for the method to complete. Defaults to 1.
check_interval (float, optional): The interval at which to check if the method has completed. Defaults to 0.01.
"""
return self.run_method(
"run_table_method",
name,
Expand All @@ -57,6 +73,80 @@ def run_table_method(
check_interval=check_interval,
)

def set_columns(self, columns: List[Dict]) -> None:
"""
To replace the current column definitions for all columns in a table.
@see https://tabulator.info/docs/6.2/columns#replace
Args:
columns (List[Dict]): The list of column definition objects for the table.
## Example Usage
```python
table = Tabulator({...})
new_columns = [
{'title':"Name", 'field':"name"},
{'title':"Age", 'field':"age"},
]
table.set_columns(new_columns)
```
"""
self.run_method("setColumns", columns)

def update_column_definition(self, field: str, definition: Dict) -> None:
"""
Update an existing column definition.
@see https://tabulator.info/docs/6.2/columns#update
Args:
field (str): The field name of the column you want to update.
definition (Dict): The new column definition object for the column.
## Example Usage
```python
table = Tabulator({...})
table.update_column_definition("name", {'title':"Updated Title"})
```
"""
self.run_method("updateColumnDefinition", field, definition)

def add_column(
self,
definition: Dict,
before: Optional[bool] = None,
position: Optional[str] = None,
) -> None:
"""
Add a column to the table.
@see https://tabulator.info/docs/6.2/columns#add
Args:
definition (Dict): The column definition object for the column you want to add.
before (Optional[bool], optional): Determines how to position the new column. A value of true will insert the column to the left of existing columns, a value of false will insert it to the right. If a Position argument is supplied then this will determine whether the new colum is inserted before or after this column.
position (Optional[str], optional): The field to insert the new column next to, this can be any of the standard column component look up options.
## Example Usage
```python
table = Tabulator({...})
table.add_column({'title':"Age", 'field':"age"}, True, "name")
```
"""
self.run_table_method("addColumn", definition, before, position)

def update(self) -> None:
super().update()
self.run_method("update_table")


class DeferredTask:
def __init__(self):
Expand Down
2 changes: 2 additions & 0 deletions tests/screen.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ def open(self, path: str):
timeout=5000,
wait_until="domcontentloaded",
)

self._page.wait_for_timeout(600)
return self._page

def close(self):
Expand Down
113 changes: 113 additions & 0 deletions tests/test_tabulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,3 +113,116 @@ def on_sort():
# click row
table.locator(".tabulator-row").first.click()
expect(lbl_row_click).to_contain_text("Mary May")


def test_manipulate_columns(browser: BrowserManager, page_path: str):
@ui.page(page_path)
def _():
tabledata = [
{"id": 1, "name": "Oli Bob", "age": "12", "color": "red", "dob": ""},
{
"id": 2,
"name": "Mary May",
"age": "1",
"color": "blue",
"dob": "14/05/1982",
},
]

table_config = {
"height": 205,
"data": tabledata,
"columns": [
{"title": "Name", "field": "name", "width": 150},
{"title": "Age", "field": "age", "hozAlign": "left"},
],
}

table = tabulator(table_config).classes("target")

def update_columns():
table.update_column_definition(
"name",
{
"title": "new name",
},
)

ui.button("update_columns", on_click=update_columns)

def set_columns():
table.set_columns(
[
{"title": "color", "field": "color"},
{"title": "dob", "field": "dob"},
]
)

ui.button("set_columns", on_click=set_columns)

def add_column():
table.add_column({"title": "Age", "field": "age"}, False, "color")

ui.button("add_column", on_click=add_column)

page = browser.open(page_path)

table = page.locator(".target")

# update column
page.get_by_role("button", name="update_columns").click()
expect(table.locator(".tabulator-headers .tabulator-col").first).to_contain_text(
"new name"
)

# set columns
page.get_by_role("button", name="set_columns").click()
expect(table.locator(".tabulator-headers .tabulator-col").first).to_contain_text(
"color"
)
expect(table.locator(".tabulator-headers .tabulator-col").last).to_contain_text(
"dob"
)

# add column
page.get_by_role("button", name="add_column").click()
expect(table.locator(".tabulator-headers .tabulator-col").nth(1)).to_contain_text(
"Age"
)


def test_dynamic_configs(browser: BrowserManager, page_path: str):
@ui.page(page_path)
def _():
tabledata = [
{"id": 1, "name": "Oli Bob", "age": "12", "color": "red", "dob": ""}
]

table_config = {
"height": 205,
"data": tabledata,
"columns": [
{
"title": "Name",
"field": "name",
"width": 150,
":cellClick": 'function(e, cell){emitEvent("cellClick","name")}',
},
{"title": "Age", "field": "age", "hozAlign": "left"},
],
}

ui.on("cellClick", lambda e: lbl_cell_click.set_text(e.args))

tabulator(table_config).classes("target")

lbl_cell_click = ui.label().classes("cell-click-label")

page = browser.open(page_path)

table = page.locator(".target")
lbl_cell_click = page.locator(".cell-click-label")

table.locator(".tabulator-row .tabulator-cell").first.click()

expect(lbl_cell_click).to_contain_text("name")

0 comments on commit 375f37a

Please sign in to comment.