Skip to content

Commit 47eebe0

Browse files
authored
Clean up cond vars (#536)
1 parent adf5b7f commit 47eebe0

File tree

13 files changed

+51
-132
lines changed

13 files changed

+51
-132
lines changed

pynecone/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from .components.graphing.victory import data
1111
from .config import Config
1212
from .constants import Env, Transports
13-
from .event import EventChain, console_log, redirect, window_alert
13+
from .event import EVENT_ARG, EventChain, console_log, redirect, window_alert
1414
from .middleware import Middleware
1515
from .model import Model, session
1616
from .route import route

pynecone/components/__init__.py

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,12 @@ def cond(condition: Any, c1: Any, c2: Any = None):
106106
107107
Returns:
108108
The conditional component.
109+
110+
Raises:
111+
ValueError: If the arguments are invalid.
109112
"""
110113
# Import here to avoid circular imports.
111-
from pynecone.var import Var
112-
113-
from .tags.tag import PropCond
114+
from pynecone.var import BaseVar, Var
114115

115116
# Convert the condition to a Var.
116117
cond_var = Var.create(condition)
@@ -123,6 +124,20 @@ def cond(condition: Any, c1: Any, c2: Any = None):
123124
), "Both arguments must be components."
124125
return Cond.create(cond_var, c1, c2)
125126

126-
# Otherwise, create a PropCond.
127-
assert not isinstance(c2, Component), "Both arguments must be props."
128-
return PropCond.create(cond_var, c1, c2)
127+
# Otherwise, create a conditionl Var.
128+
# Check that the second argument is valid.
129+
if isinstance(c2, Component):
130+
raise ValueError("Both arguments must be props.")
131+
if c2 is None:
132+
raise ValueError("For conditional vars, the second argument must be set.")
133+
134+
# Create the conditional var.
135+
return BaseVar(
136+
name=utils.format_cond(
137+
cond=cond_var.full_name,
138+
true_value=c1,
139+
false_value=c2,
140+
is_prop=True,
141+
),
142+
type_=c1.type_ if isinstance(c1, BaseVar) else type(c1),
143+
)

pynecone/components/forms/input.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ def get_controlled_triggers(cls) -> Dict[str, Var]:
6060
"on_focus": EVENT_ARG.target.value,
6161
"on_blur": EVENT_ARG.target.value,
6262
"on_key_down": EVENT_ARG.key,
63-
"on_key_press": EVENT_ARG.key,
6463
"on_key_up": EVENT_ARG.key,
6564
}
6665

pynecone/components/forms/slider.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ class Slider(ChakraComponent):
1616
# State var to bind the the input.
1717
value: Var[int]
1818

19+
# The color scheme.
20+
color_scheme: Var[str]
21+
1922
# The placeholder text.
2023
default_value: Var[int]
2124

pynecone/components/forms/textarea.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,5 @@ def get_controlled_triggers(cls) -> Dict[str, Var]:
5454
"on_focus": EVENT_ARG.target.value,
5555
"on_blur": EVENT_ARG.target.value,
5656
"on_key_down": EVENT_ARG.key,
57-
"on_key_press": EVENT_ARG.key,
5857
"on_key_up": EVENT_ARG.key,
5958
}

pynecone/components/tags/tag.py

Lines changed: 2 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def __init__(self, *args, **kwargs):
4747

4848
@staticmethod
4949
def format_prop(
50-
prop: Union[Var, EventChain, ComponentStyle, PropCond, str],
50+
prop: Union[Var, EventChain, ComponentStyle, str],
5151
) -> Union[int, float, str]:
5252
"""Format a prop.
5353
@@ -71,10 +71,6 @@ def format_prop(
7171
events = ",".join([utils.format_event(event) for event in prop.events])
7272
prop = f"({local_args}) => Event([{events}])"
7373

74-
# Handle conditional props.
75-
elif isinstance(prop, PropCond):
76-
return str(prop)
77-
7874
# Handle other types.
7975
elif isinstance(prop, str):
8076
if utils.is_wrapped(prop, "{"):
@@ -89,7 +85,7 @@ def format_prop(
8985
if isinstance(prop, dict):
9086
# Convert any var keys to strings.
9187
prop = {
92-
key: str(val) if isinstance(val, (Var, PropCond)) else val
88+
key: str(val) if isinstance(val, Var) else val
9389
for key, val in prop.items()
9490
}
9591

@@ -188,54 +184,3 @@ def is_valid_prop(prop: Optional[Var]) -> bool:
188184
Whether the prop is valid.
189185
"""
190186
return prop is not None and not (isinstance(prop, dict) and len(prop) == 0)
191-
192-
193-
class PropCond(Base):
194-
"""A conditional prop."""
195-
196-
# The condition to determine which prop to render.
197-
cond: Var[Any]
198-
199-
# The prop to render if the condition is true.
200-
prop1: Any
201-
202-
# The prop to render if the condition is false.
203-
prop2: Any
204-
205-
@classmethod
206-
def create(cls, cond: Var, prop1: Any, prop2: Any):
207-
"""Create a conditional Prop.
208-
209-
Args:
210-
cond: The cond to determine which prop to render.
211-
prop1: The prop value to render if the cond is true.
212-
prop2: The prop value to render if the cond is false.
213-
214-
Returns:
215-
The conditional Prop.
216-
217-
Raises:
218-
ValueError: If the condition or prop values are not set.
219-
"""
220-
if cond is None:
221-
raise ValueError("The condition must be set.")
222-
if prop1 is None or prop2 is None:
223-
raise ValueError("Both prop values must be set.")
224-
return cls(
225-
cond=cond,
226-
prop1=prop1,
227-
prop2=prop2,
228-
)
229-
230-
def __str__(self) -> str:
231-
"""Render the prop as a React string.
232-
233-
Returns:
234-
The React code to render the prop.
235-
"""
236-
return utils.format_cond(
237-
cond=self.cond.full_name,
238-
true_value=self.prop1,
239-
false_value=self.prop2,
240-
is_prop=True,
241-
)

pynecone/route.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,11 +24,11 @@ def route(
2424
Note: the decorated functions still need to be imported.
2525
2626
Args:
27-
route: The route to reach the page. Defaults to None.
28-
title: The title of the page. Defaults to None.
29-
image: The favicon of the page. Defaults to None.
30-
description: The description of the page. Defaults to None.
31-
on_load: The event handler called when the page load. Defaults to None.
27+
route: The route to reach the page.
28+
title: The title of the page.
29+
image: The favicon of the page.
30+
description: The description of the page
31+
on_load: The event handler called when the page load.
3232
3333
Returns:
3434
The decorated function.

pynecone/utils.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1060,14 +1060,14 @@ def format_cond(
10601060
Returns:
10611061
The formatted conditional expression.
10621062
"""
1063+
# Import here to avoid circular imports.
1064+
from pynecone.var import Var
1065+
10631066
if is_prop:
1064-
if isinstance(true_value, str):
1065-
true_value = wrap(true_value, "'")
1066-
if isinstance(false_value, str):
1067-
false_value = wrap(false_value, "'")
1068-
expr = f"{cond} ? {true_value} : {false_value}".replace("{", "").replace(
1069-
"}", ""
1070-
)
1067+
prop1 = Var.create(true_value, is_string=type(true_value) == str)
1068+
prop2 = Var.create(false_value, is_string=type(false_value) == str)
1069+
assert prop1 is not None and prop2 is not None, "Invalid prop values"
1070+
expr = f"{cond} ? {prop1} : {prop2}".replace("{", "").replace("}", "")
10711071
else:
10721072
expr = f"{cond} ? {true_value} : {false_value}"
10731073

pynecone/var.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -876,7 +876,7 @@ def clear(self):
876876
self._reassign_field()
877877

878878
def setdefault(self, *args, **kwargs):
879-
"""set default.
879+
"""Return value of key if or set default.
880880
881881
Args:
882882
args: The args passed.
@@ -901,7 +901,7 @@ def pop(self, k, d=None):
901901
self._reassign_field()
902902

903903
def update(self, *args, **kwargs):
904-
"""update dict.
904+
"""Update the dict with another dict.
905905
906906
Args:
907907
args: The args passed.
@@ -911,7 +911,7 @@ def update(self, *args, **kwargs):
911911
self._reassign_field()
912912

913913
def __setitem__(self, *args, **kwargs):
914-
"""set item.
914+
"""Set an item in the dict.
915915
916916
Args:
917917
args: The args passed.
@@ -921,7 +921,7 @@ def __setitem__(self, *args, **kwargs):
921921
self._reassign_field() if hasattr(self, "_reassign_field") else None
922922

923923
def __delitem__(self, *args, **kwargs):
924-
"""delete item.
924+
"""Delete an item in the dict.
925925
926926
Args:
927927
args: The args passed.

tests/components/layout/test_cond.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import json
12
from typing import Any
23

34
import pytest
@@ -6,8 +7,8 @@
67
from pynecone.components import cond
78
from pynecone.components.layout.cond import Cond
89
from pynecone.components.layout.fragment import Fragment
9-
from pynecone.components.tags.tag import PropCond
1010
from pynecone.components.typography.text import Text
11+
from pynecone.var import Var
1112

1213

1314
@pytest.fixture
@@ -68,10 +69,10 @@ def test_prop_cond(c1: Any, c2: Any):
6869
c2,
6970
)
7071

71-
assert isinstance(prop_cond, PropCond)
72-
assert prop_cond.prop1 == c1
73-
assert prop_cond.prop2 == c2
74-
assert prop_cond.cond == True # noqa
72+
assert isinstance(prop_cond, Var)
73+
c1 = json.dumps(c1).replace('"', "`")
74+
c2 = json.dumps(c2).replace('"', "`")
75+
assert str(prop_cond) == f"{{true ? {c1} : {c2}}}"
7576

7677

7778
def test_cond_no_else():

0 commit comments

Comments
 (0)