Fixed double-click handling for column width reset
This commit is contained in:
@@ -33,7 +33,7 @@ from myfasthtml.core.formatting.dsl.parser import DSLParser
|
||||
from myfasthtml.core.formatting.engine import FormattingEngine
|
||||
from myfasthtml.core.instances import MultipleInstance
|
||||
from myfasthtml.core.optimized_ft import OptimizedDiv
|
||||
from myfasthtml.core.utils import make_safe_id, merge_classes, make_unique_safe_id
|
||||
from myfasthtml.core.utils import make_safe_id, merge_classes, make_unique_safe_id, is_null
|
||||
from myfasthtml.icons.carbon import row, column, grid
|
||||
from myfasthtml.icons.fluent import checkbox_unchecked16_regular
|
||||
from myfasthtml.icons.fluent_p2 import checkbox_checked16_regular, column_edit20_regular
|
||||
@@ -102,6 +102,9 @@ class DatagridSettings(DbObject):
|
||||
|
||||
|
||||
class DatagridStore(DbObject):
|
||||
"""
|
||||
Store Dataframes
|
||||
"""
|
||||
def __init__(self, owner, save_state):
|
||||
with self.initializing():
|
||||
super().__init__(owner, name=f"{owner.get_id()}#df", save_state=save_state)
|
||||
@@ -128,7 +131,7 @@ class Commands(BaseCommands):
|
||||
return Command("SetColumnWidth",
|
||||
"Set column width after resize",
|
||||
self._owner,
|
||||
self._owner.set_column_width
|
||||
self._owner.handle_set_column_width
|
||||
).htmx(target=None)
|
||||
|
||||
def move_column(self):
|
||||
@@ -137,7 +140,14 @@ class Commands(BaseCommands):
|
||||
self._owner,
|
||||
self._owner.move_column
|
||||
).htmx(target=None)
|
||||
|
||||
|
||||
def reset_column_width(self):
|
||||
return Command("ResetColumnWidth",
|
||||
"Auto-size column to fit content",
|
||||
self._owner,
|
||||
self._owner.reset_column_width
|
||||
).htmx(target=f"#th_{self._id}")
|
||||
|
||||
def filter(self):
|
||||
return Command("Filter",
|
||||
"Filter Grid",
|
||||
@@ -522,7 +532,7 @@ class DataGrid(MultipleInstance):
|
||||
row_dict[col_def.col_id] = default_value
|
||||
self._df_store.save()
|
||||
|
||||
def set_column_width(self, col_id: str, width: str):
|
||||
def handle_set_column_width(self, col_id: str, width: str):
|
||||
"""Update column width after resize. Called via Command from JS."""
|
||||
logger.debug(f"set_column_width: {col_id=} {width=}")
|
||||
for col in self._state.columns:
|
||||
@@ -561,7 +571,69 @@ class DataGrid(MultipleInstance):
|
||||
self._state.columns.insert(target_idx, col)
|
||||
|
||||
self._state.save()
|
||||
|
||||
|
||||
def calculate_optimal_column_width(self, col_id: str) -> int:
|
||||
"""
|
||||
Calculate optimal width for a column based on content.
|
||||
|
||||
Considers both the title length and the maximum data length in the column,
|
||||
then applies a formula to estimate pixel width.
|
||||
|
||||
Args:
|
||||
col_id: Column identifier
|
||||
|
||||
Returns:
|
||||
Optimal width in pixels (between 50 and 500)
|
||||
"""
|
||||
col_def = next((c for c in self._state.columns if c.col_id == col_id), None)
|
||||
if not col_def:
|
||||
logger.warning(f"calculate_optimal_column_width: column not found {col_id=}")
|
||||
return 150 # default width
|
||||
|
||||
# Title length
|
||||
title_length = len(col_def.title)
|
||||
|
||||
# Max data length
|
||||
max_data_length = 0
|
||||
if col_id in self._df_store.ns_fast_access:
|
||||
col_array = self._df_store.ns_fast_access[col_id]
|
||||
if col_array is not None and len(col_array) > 0:
|
||||
max_data_length = max(len(str(v)) for v in col_array)
|
||||
|
||||
# Calculate width (8px per char + 30px padding)
|
||||
max_length = max(title_length, max_data_length)
|
||||
optimal_width = max_length * 8 + 30
|
||||
|
||||
# Apply limits (50px min, 500px max)
|
||||
return max(50, min(optimal_width, 500))
|
||||
|
||||
def reset_column_width(self, col_id: str):
|
||||
"""
|
||||
Auto-size column to fit content. Called via Command from JS double-click.
|
||||
|
||||
Calculates the optimal width based on the longest content in the column
|
||||
and applies it to all cells. Updates both the state and the visual display.
|
||||
|
||||
Args:
|
||||
col_id: Column identifier to reset
|
||||
|
||||
Returns:
|
||||
Updated header with script to update body cells
|
||||
"""
|
||||
logger.debug(f"reset_column_width: {col_id=}")
|
||||
optimal_width = self.calculate_optimal_column_width(col_id)
|
||||
|
||||
# Update and persist
|
||||
for col in self._state.columns:
|
||||
if col.col_id == col_id:
|
||||
col.width = optimal_width
|
||||
break
|
||||
|
||||
self._state.save()
|
||||
|
||||
# Return updated header with script to update body cells via after-settle
|
||||
return self.render_partial("header", col_id=col_id, optimal_width=optimal_width)
|
||||
|
||||
def filter(self):
|
||||
logger.debug("filter")
|
||||
self._state.filtered[FILTER_INPUT_CID] = self._datagrid_filter.get_query()
|
||||
@@ -648,7 +720,8 @@ class DataGrid(MultipleInstance):
|
||||
def mk_headers(self):
|
||||
resize_cmd = self.commands.set_column_width()
|
||||
move_cmd = self.commands.move_column()
|
||||
|
||||
reset_cmd = self.commands.reset_column_width()
|
||||
|
||||
def _mk_header_name(col_def: DataGridColumnState):
|
||||
return Div(
|
||||
mk.label(col_def.title, icon=IconsHelper.get(col_def.type)),
|
||||
@@ -656,14 +729,14 @@ class DataGrid(MultipleInstance):
|
||||
cls="flex truncate cursor-default",
|
||||
data_tooltip=col_def.title,
|
||||
)
|
||||
|
||||
|
||||
def _mk_header(col_def: DataGridColumnState):
|
||||
if not col_def.visible:
|
||||
return None
|
||||
|
||||
|
||||
return Div(
|
||||
_mk_header_name(col_def),
|
||||
Div(cls="dt2-resize-handle", data_command_id=resize_cmd.id),
|
||||
Div(cls="dt2-resize-handle", data_command_id=resize_cmd.id, data_reset_command_id=reset_cmd.id),
|
||||
style=f"width:{col_def.width}px;",
|
||||
data_col=col_def.col_id,
|
||||
data_tooltip=col_def.title,
|
||||
@@ -749,7 +822,7 @@ class DataGrid(MultipleInstance):
|
||||
style, formatted_value = self._formatting_engine.apply_format(rules, value, row_data)
|
||||
|
||||
# Use formatted value or convert to string
|
||||
value_str = formatted_value if formatted_value is not None else str(value)
|
||||
value_str = formatted_value if formatted_value is not None else str(value) if not is_null(value) else ""
|
||||
|
||||
# OPTIMIZATION: Only escape if necessary (check for HTML special chars with pre-compiled regex)
|
||||
if _HTML_SPECIAL_CHARS_REGEX.search(value_str):
|
||||
@@ -993,31 +1066,43 @@ class DataGrid(MultipleInstance):
|
||||
style="height: 100%; grid-template-rows: auto 1fr;"
|
||||
)
|
||||
|
||||
def render_partial(self, fragment="cell"):
|
||||
def render_partial(self, fragment="cell", **kwargs):
|
||||
"""
|
||||
|
||||
:param fragment: cell | body
|
||||
:param redraw_scrollbars:
|
||||
|
||||
:param fragment: cell | body | table | header
|
||||
:param kwargs: Additional parameters for specific fragments (col_id, optimal_width for header)
|
||||
:return:
|
||||
"""
|
||||
res = []
|
||||
|
||||
|
||||
extra_attr = {
|
||||
"hx-on::after-settle": f"initDataGrid('{self._id}');",
|
||||
}
|
||||
|
||||
|
||||
if fragment == "body":
|
||||
body_container = self.mk_body_wrapper()
|
||||
body_container.attrs.update(extra_attr)
|
||||
res.append(body_container)
|
||||
|
||||
|
||||
elif fragment == "table":
|
||||
table = self.mk_table()
|
||||
table.attrs.update(extra_attr)
|
||||
res.append(table)
|
||||
|
||||
|
||||
elif fragment == "header":
|
||||
col_id = kwargs.get("col_id")
|
||||
optimal_width = kwargs.get("optimal_width")
|
||||
|
||||
header_extra_attr = {
|
||||
"hx-on::after-settle": f"setColumnWidth('{self._id}', '{col_id}', '{optimal_width}');",
|
||||
}
|
||||
|
||||
header = self.mk_headers()
|
||||
header.attrs.update(header_extra_attr)
|
||||
return header
|
||||
|
||||
res.append(self.mk_selection_manager())
|
||||
|
||||
|
||||
return tuple(res)
|
||||
|
||||
def dispose(self):
|
||||
|
||||
Reference in New Issue
Block a user