Skip to content

Commit

Permalink
fix: to_camel_case fails on leading or trailing underscores (#979)
Browse files Browse the repository at this point in the history
Changed a prop to `if_` and noticed the `to_camel_case` method throws
with index out of bounds because it ends up trying to access characters
of an empty string. Figured we should preserve leading and trailing
underscores, but convert anything in the middle to camelCase.
  • Loading branch information
mattrunyon authored Oct 31, 2024
1 parent f7ee1a6 commit 08ff89c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
10 changes: 8 additions & 2 deletions plugins/ui/src/deephaven/ui/_internal/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,15 +71,21 @@ def get_component_qualname(component: Any) -> str:
def to_camel_case(snake_case_text: str) -> str:
"""
Convert a snake_case string to camelCase.
Preserves any leading or trailing underscores.
Args:
snake_case_text: The snake_case string to convert.
Returns:
The camelCase string.
"""
components = snake_case_text.split("_")
return components[0] + "".join((x[0].upper() + x[1:]) for x in components[1:])
leading_underscores = len(snake_case_text) - len(snake_case_text.lstrip("_"))
trailing_underscores = len(snake_case_text) - len(snake_case_text.rstrip("_"))
components = snake_case_text.strip("_").split("_")
camel_case_text = components[0] + "".join(
(x[0].upper() + x[1:]) for x in components[1:]
)
return "_" * leading_underscores + camel_case_text + "_" * trailing_underscores


def to_react_prop_case(snake_case_text: str) -> str:
Expand Down
14 changes: 14 additions & 0 deletions plugins/ui/test/deephaven/ui/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ def test_dict_to_camel_case(self):
dict_to_camel_case({"bar": "biz", "UNSAFE_class_name": "harry"}),
{"bar": "biz", "UNSAFEClassName": "harry"},
)
# Test leading/trailing underscore
self.assertDictEqual(
dict_to_camel_case(
{"foo_": "bar", "_baz": "biz", "__youre_a_wizard__": "Harry"}
),
{"foo_": "bar", "_baz": "biz", "__youreAWizard__": "Harry"},
)

def test_dict_to_react_props(self):
from deephaven.ui._internal.utils import dict_to_react_props
Expand All @@ -100,6 +107,13 @@ def test_dict_to_react_props(self):
),
{"bar": "biz", "UNSAFE_className": "harry", "aria-label": "ron"},
)
# Test trailing underscore
self.assertDictEqual(
dict_to_react_props(
{"foo_": "bar", "_baz": "biz", "__youre_a_wizard__": "Harry"}
),
{"foo_": "bar", "_baz": "biz", "__youreAWizard__": "Harry"},
)

def test_remove_empty_keys(self):
from deephaven.ui._internal.utils import remove_empty_keys
Expand Down

0 comments on commit 08ff89c

Please sign in to comment.