Skip to content

Commit

Permalink
Rename variant to type (for button component) to simplify API and ali…
Browse files Browse the repository at this point in the history
…gn with Material Design specs: https://m3.material.io/components/all-buttons
  • Loading branch information
wwwillchen committed Dec 27, 2023
1 parent 63fce42 commit 9dc5d89
Show file tree
Hide file tree
Showing 14 changed files with 46 additions and 46 deletions.
2 changes: 1 addition & 1 deletion generator/fixtures/component_name.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,4 @@ def component_name(
),
)

# INSERT_VARIANT_INDEX_FN
# INSERT_TYPE_INDEX_FN
6 changes: 3 additions & 3 deletions generator/generate_ng_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ def template(directive: str = "") -> str:
return template()
# You cannot dynamically set the directive (e.g. for button class)
# see: https://github.com/angular/components/issues/26350
# As a workaround, we print the template N times where N = # of variants
# As a workaround, we print the template N times where N = # of types
open_brace = "{"
closed_brace = "}"
outs: list[str] = []
for index, directive in enumerate(spec.input.directive_names):
outs.append(
f"""
@if(config().getVariantIndex() === {index}) {open_brace}
@if(config().getTypeIndex() === {index}) {open_brace}
{template(directive=directive)}
{closed_brace}
"""
Expand All @@ -79,7 +79,7 @@ def format_directives(spec: pb.ComponentSpec) -> str:
+ " "
+ "\n".join(
[
f"""[attr.{directive}]=\"config().getVariant() === '{directive}'\""""
f"""[attr.{directive}]=\"config().getType() === '{directive}'\""""
for directive in spec.input.directive_names
]
)
Expand Down
2 changes: 1 addition & 1 deletion generator/generate_proto_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def generate_proto_schema(spec: pb.ComponentSpec) -> str:

if len(spec.input.directive_names):
index += 1
fields.append(f"int32 variant_index = {index};")
fields.append(f"int32 type_index = {index};")

message_contents = (
"{\n" + "\n".join([" " + field for field in fields]) + "\n}"
Expand Down
18 changes: 9 additions & 9 deletions generator/generate_py_component.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def generate_py_component(spec: pb.ComponentSpec) -> str:
.replace("# INSERT_COMPONENT_PARAMS", generate_py_component_params(spec))
.replace("# INSERT_PROTO_CALLSITE", generate_py_proto_callsite(spec))
.replace("# INSERT_COMPONENT_CALL", generate_py_callsite(spec))
.replace("# INSERT_VARIANT_INDEX_FN", generate_index_variant_fn(spec))
.replace("# INSERT_TYPE_INDEX_FN", generate_index_type_fn(spec))
.replace("INSERT_DOC_STRING", generate_doc_string(spec))
)

Expand Down Expand Up @@ -52,7 +52,7 @@ def generate_doc_string(spec: pb.ComponentSpec):
f"on_{native_event}: [{native_event}](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/{native_event}_event) is a native browser event."
)
if len(spec.input.directive_names):
out.append("variant: component variations")
out.append("type: component variations")
return f"""Creates a {component_name} component.
{composite_comment}
Args:
Expand Down Expand Up @@ -117,7 +117,7 @@ def generate_py_component_params(spec: pb.ComponentSpec) -> str:
)
if len(spec.input.directive_names):
out.append(
f"variant: {format_string_literals(list(spec.input.directive_names))} = {wrap_quote(spec.input.directive_names[0])}"
f"type: {format_string_literals(list(spec.input.directive_names))} = {wrap_quote(spec.input.directive_names[0])}"
)
return ", ".join(out)

Expand All @@ -138,24 +138,24 @@ def generate_py_proto_callsite(spec: pb.ComponentSpec) -> str:
f"on_{native_event}_handler_id=register_event_handler({event_param_name}, event={format_native_event_name(native_event)}) if {event_param_name} else ''"
)
if len(spec.input.directive_names):
out.append("variant_index=_get_variant_index(variant)")
out.append("type_index=_get_type_index(type)")
return ", ".join(out)


def generate_index_variant_fn(spec: pb.ComponentSpec) -> str:
def generate_index_type_fn(spec: pb.ComponentSpec) -> str:
if not len(spec.input.directive_names):
return ""

exprs: list[str] = []
for index, variant in enumerate(spec.input.directive_names):
for index, type in enumerate(spec.input.directive_names):
s = f"""
if variant == '{variant}':
if type == '{type}':
return {index}"""
exprs.append(s)
return f"""
def _get_variant_index(variant: str) -> int:
def _get_type_index(type: str) -> int:
{''.join(exprs)}
raise Exception("Unexpected variant: " + variant)
raise Exception("Unexpected type: " + type)
"""


Expand Down
10 changes: 5 additions & 5 deletions mesop/component_helpers/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,15 @@ def wrapper(*args: Any, **kwargs: Any):
def create_component(
type_name: str, proto: Message, key: str | None = None
) -> pb.Component:
variant_index = 0
type_index = 0
# This is not exactly type-safe, but it's a convenient way of grabbing the
# variant index value.
if hasattr(proto, "variant_index"):
variant_index = proto.variant_index # type: ignore
# type index value.
if hasattr(proto, "type_index"):
type_index = proto.type_index # type: ignore
type = pb.Type(
name=type_name,
value=proto.SerializeToString(),
variant_index=variant_index, # type: ignore
type_index=type_index, # type: ignore
)
if runtime().debug_mode:
type.debug_json = json_format.MessageToJson(
Expand Down
10 changes: 5 additions & 5 deletions mesop/components/button/button.ng.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
@if(config().getVariantIndex() === 0) {
@if(config().getTypeIndex() === 0) {
<button
mat-button
[color]="config().getColor()"
Expand All @@ -9,7 +9,7 @@
<ng-content></ng-content>
</button>

} @if(config().getVariantIndex() === 1) {
} @if(config().getTypeIndex() === 1) {
<button
mat-raised-button
[color]="config().getColor()"
Expand All @@ -20,7 +20,7 @@
<ng-content></ng-content>
</button>

} @if(config().getVariantIndex() === 2) {
} @if(config().getTypeIndex() === 2) {
<button
mat-flat-button
[color]="config().getColor()"
Expand All @@ -31,7 +31,7 @@
<ng-content></ng-content>
</button>

} @if(config().getVariantIndex() === 3) {
} @if(config().getTypeIndex() === 3) {
<button
mat-stroked-button
[color]="config().getColor()"
Expand All @@ -42,7 +42,7 @@
<ng-content></ng-content>
</button>

} @if(config().getVariantIndex() === 4) {
} @if(config().getTypeIndex() === 4) {
<button
mat-icon-button
[color]="config().getColor()"
Expand Down
2 changes: 1 addition & 1 deletion mesop/components/button/button.proto
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ message ButtonType {
bool disable_ripple = 2;
bool disabled = 3;
string on_click_handler_id = 4;
int32 variant_index = 5;
int32 type_index = 5;
}
22 changes: 11 additions & 11 deletions mesop/components/button/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
def button(
*,
on_click: Callable[[ClickEvent], Any] | None = None,
variant: Literal["raised", "flat", "stroked", "icon"] | None = None,
type: Literal["raised", "flat", "stroked", "icon"] | None = None,
color: str = "",
disable_ripple: bool = False,
disabled: bool = False,
Expand All @@ -24,7 +24,7 @@ def button(
Args:
on_click: [click](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click_event) is a native browser event.
variant: Type of button style to use
type: Type of button style to use
color: Theme color palette of the button
disable_ripple: Whether the ripple effect is disabled or not.
disabled: Whether the button is disabled.
Expand All @@ -40,22 +40,22 @@ def button(
on_click_handler_id=register_event_handler(on_click, event=ClickEvent)
if on_click
else "",
variant_index=_get_variant_index(variant),
type_index=_get_type_index(type),
),
)


def _get_variant_index(
variant: Literal["raised", "flat", "stroked", "icon"] | None,
def _get_type_index(
type: Literal["raised", "flat", "stroked", "icon"] | None,
) -> int:
if variant is None:
if type is None:
return 0
if variant == "raised":
if type == "raised":
return 1
if variant == "flat":
if type == "flat":
return 2
if variant == "stroked":
if type == "stroked":
return 3
if variant == "icon":
if type == "icon":
return 4
raise Exception("Unexpected variant: " + variant)
raise Exception("Unexpected type: " + type)
8 changes: 4 additions & 4 deletions mesop/examples/buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class State:
count_clicks: int = 0


def button_click(action: me.ClickEvent):
def button_click():
state = me.state(State)
state.count_clicks += 1

Expand All @@ -19,13 +19,13 @@ def main():
with me.button(on_click=button_click):
me.text(text="default button")

with me.button(on_click=button_click, variant="flat"):
with me.button(on_click=button_click, type="flat"):
me.text(text="flat button")

with me.button(on_click=button_click, variant="raised"):
with me.button(on_click=button_click, type="raised"):
me.text(text="raised button")

with me.button(on_click=button_click, variant="stroked"):
with me.button(on_click=button_click, type="stroked"):
me.text(text="stroked button")

me.text(text=f"{state.count_clicks} clicks")
2 changes: 1 addition & 1 deletion mesop/examples/playground.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def left_panel():
on_input=on_input,
)

with me.button(variant="stroked", on_click=on_submit):
with me.button(type="stroked", on_click=on_submit):
me.text("Submit")


Expand Down
2 changes: 1 addition & 1 deletion mesop/examples/playground_critic.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def left_panel():
on_input=on_input,
)

with me.button(variant="stroked", on_click=on_submit):
with me.button(type="stroked", on_click=on_submit):
me.text("Submit")

with me.box(style="margin: 16px 0"):
Expand Down
2 changes: 1 addition & 1 deletion mesop/examples/shared/navmenu.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def on_click(event: me.ClickEvent):
"""
):
with me.box(style="margin-bottom: 8px;"):
with me.button(variant="icon", on_click=on_click, key=url):
with me.button(type="icon", on_click=on_click, key=url):
with me.box(
style="""
display: flex;
Expand Down
4 changes: 2 additions & 2 deletions mesop/protos/ui.proto
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,6 @@ message Type {
bytes value = 5;
string debug_json = 6;
// Needed outside of |value| because ComponentRenderer (TS) needs to know
// the variant index in order to do content projection correctly.
int32 variant_index = 7;
// the type index in order to do content projection correctly.
int32 type_index = 7;
}
2 changes: 1 addition & 1 deletion mesop/web/src/component_renderer/component_renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export class ComponentRenderer {
// Need to attach view or it doesn't render.
// View automatically detaches when it is destroyed.
// Template will destroy each ViewRef when it is destroyed.
const index = this.component.getType()?.getVariantIndex() ?? 0;
const index = this.component.getType()?.getTypeIndex() ?? 0;
this.applicationRef.attachView(projectedViewRef);
const projectableNodes = [];
projectableNodes[index] = projectedViewRef.rootNodes;
Expand Down

0 comments on commit 9dc5d89

Please sign in to comment.