Skip to content

Commit

Permalink
clean up API
Browse files Browse the repository at this point in the history
  • Loading branch information
wwwillchen committed Jun 14, 2024
1 parent de562d6 commit 324f4cb
Show file tree
Hide file tree
Showing 13 changed files with 145 additions and 85 deletions.
13 changes: 0 additions & 13 deletions mesop/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,9 @@
from mesop.component_helpers.helper import (
content_component as content_component,
)
from mesop.component_helpers.helper import (
insert_web_component as insert_web_component,
)
from mesop.component_helpers.helper import (
register_event_handler as register_event_handler,
)
from mesop.component_helpers.helper import (
register_event_mapper as register_event_mapper,
)
from mesop.component_helpers.helper import (
slot as slot,
)
from mesop.component_helpers.web_component import (
web_component as web_component,
)
from mesop.components.audio.audio import audio as audio
from mesop.components.badge.badge import badge as badge

Expand Down Expand Up @@ -149,7 +137,6 @@
from mesop.events import (
LoadEvent as LoadEvent,
)
from mesop.events import MesopEvent as UserEvent # noqa: F401
from mesop.exceptions import (
MesopDeveloperException as MesopDeveloperException,
)
Expand Down
34 changes: 28 additions & 6 deletions mesop/component_helpers/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,22 @@
import inspect
import json
from functools import wraps
from typing import Any, Callable, Generator, Type, TypeVar, cast, overload
from typing import (
Any,
Callable,
Generator,
Type,
TypeVar,
cast,
overload,
)

from google.protobuf import json_format
from google.protobuf.message import Message

import mesop.protos.ui_pb2 as pb
from mesop.component_helpers.style import Style, to_style_proto
from mesop.events import ClickEvent, InputEvent, MesopEvent
from mesop.events import ClickEvent, CustomEvent, InputEvent, MesopEvent
from mesop.exceptions import MesopDeveloperException
from mesop.key import Key, key_from_proto
from mesop.runtime import runtime
Expand Down Expand Up @@ -230,17 +238,23 @@ def insert_composite_component(

def insert_web_component(
name: str,
events: dict[str, Callable[[CustomEvent], Any]],
properties: dict[str, Any],
key: str | None = None,
style: Style | None = None,
):
type = pb.WebComponentType(properties_json=json.dumps(properties))
event_to_ids: dict[str, str] = {}
for event in events:
event_handler = events[event]
event_to_ids[event] = register_event_handler(event_handler, CustomEvent)
type_proto = pb.WebComponentType(
properties_json=json.dumps(properties),
events_json=json.dumps(event_to_ids),
)
return insert_component(
# Prefix with <web> to ensure there's never any overlap.
type_name="<web>" + name,
proto=type,
proto=type_proto,
key=key,
style=style,
)


Expand Down Expand Up @@ -360,6 +374,14 @@ def register_event_mapper(
),
)

runtime().register_event_mapper(
CustomEvent,
lambda userEvent, key: CustomEvent(
key=key.key,
value=json.loads(userEvent.string_value),
),
)


_COMPONENT_DIFF_FIELDS = (
"key",
Expand Down
20 changes: 0 additions & 20 deletions mesop/component_helpers/web_component.py

This file was deleted.

3 changes: 3 additions & 0 deletions mesop/events/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from .events import (
ClickEvent as ClickEvent,
)
from .events import (
CustomEvent as CustomEvent,
)
from .events import (
InputEvent as InputEvent,
)
Expand Down
7 changes: 7 additions & 0 deletions mesop/events/events.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from dataclasses import dataclass
from typing import Any


@dataclass(kw_only=True)
Expand Down Expand Up @@ -43,3 +44,9 @@ class LoadEvent:
"""

path: str


@dataclass(kw_only=True)
class CustomEvent:
value: Any
key: str
13 changes: 8 additions & 5 deletions mesop/examples/custom_component/custom_component.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,20 @@ import {
css,
} from 'https://cdn.jsdelivr.net/gh/lit/dist@3/core/lit-core.min.js';

const INCREMENT_EVENT = 'increment-event';

class FooComponent extends LitElement {
static properties = {
value: {type: Number},
style: {type: String},
handlerId: {type: String},
incrementEventHandlerId: {attribute: INCREMENT_EVENT, type: String},
};

constructor() {
super();
this.value = 0;
this.style = '';
this.handlerId = '';
this.incrementEventHandlerId = '';
}

static styles = css`
Expand All @@ -29,18 +31,19 @@ class FooComponent extends LitElement {
<div class="container" style="${this.style}">
<span>Value: ${this.value}</span>
<button id="increment-btn" @click="${this._onIncrement}">
Increment
Increment2
</button>
</div>
`;
}

_onIncrement() {
debugger;
this.dispatchEvent(
new CustomEvent('mesop-event', {
new CustomEvent(INCREMENT_EVENT, {
detail: {
payload: {value: this.value + 2},
handlerId: this.handlerId,
handlerId: this.incrementEventHandlerId,
},
bubbles: true,
}),
Expand Down
41 changes: 17 additions & 24 deletions mesop/examples/custom_component/custom_component.py
Original file line number Diff line number Diff line change
@@ -1,43 +1,36 @@
import json
import os
from dataclasses import dataclass
from typing import Any, Callable

import mesop as me
import mesop.labs as mel

current_module_dir = os.path.dirname(os.path.abspath(__file__))
js_file_path = os.path.join(current_module_dir, "custom_component.js")
print(f"JS file path: {js_file_path}")
# current_module_dir = os.path.dirname(os.path.abspath(__file__))
# js_file_path = os.path.join(current_module_dir, "custom_component.js")
# print(f"JS file path: {js_file_path}")


@dataclass(kw_only=True)
class CustomEvent(me.UserEvent):
value: int
# mel.register_event_mapper(
# IncrementEvent,
# lambda event: IncrementEvent(key=event.key, value=event.json["value"]),
# )

# Instead of explicit event mapper.
# We will log the target event class when sending the event...
# Then, we will map the values to the class - key=key, othre attrs, based on key

me.register_event_mapper(
CustomEvent,
lambda event, key: CustomEvent(
key=key.key, value=json.loads(event.string_value)["value"]
),
)


@me.web_component(js_path=js_file_path)
@mel.web_component(path="./custom_component.js")
def foo_custom_component(
*,
value: int,
on_event: Callable[..., Any],
on_increment: Callable[[mel.CustomEvent], Any],
key: str | None = None,
style: me.Style | None = None,
):
me.insert_web_component(
mel.insert_web_component(
name="foo-component",
key=key,
style=style,
events={
"increment-event": on_increment,
},
properties={
"value": value,
"handlerId": me.register_event_handler(on_event, CustomEvent),
},
)
pass
16 changes: 12 additions & 4 deletions mesop/examples/custom_component/custom_component_app.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
from pydantic import BaseModel

import mesop as me
import mesop.labs as mel

from .custom_component import CustomEvent, foo_custom_component
from .custom_component import foo_custom_component


@me.page(path="/custom_component")
def page():
me.text("custom_component12")
foo_custom_component(value=me.state(State).value, on_event=on_foo_event)
foo_custom_component(value=me.state(State).value, on_increment=on_increment)


@me.stateclass
class State:
value: int = 3


def on_foo_event(e: CustomEvent):
me.state(State).value = e.value
class Increment(BaseModel):
value: int


def on_increment(e: mel.CustomEvent):
increment = Increment(**e.value)
me.state(State).value = increment.value
7 changes: 7 additions & 0 deletions mesop/labs/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
from mesop.component_helpers.helper import (
insert_web_component as insert_web_component,
)
from mesop.events import CustomEvent as CustomEvent
from mesop.labs.chat import ChatMessage as ChatMessage
from mesop.labs.chat import chat as chat
from mesop.labs.text_to_image import text_to_image as text_to_image
from mesop.labs.text_to_text import text_io as text_io
from mesop.labs.text_to_text import text_to_text as text_to_text
from mesop.labs.web_component import (
web_component as web_component,
)
49 changes: 49 additions & 0 deletions mesop/labs/web_component.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import inspect
import os
from functools import wraps
from typing import Any, Callable, TypeVar, cast

from mesop.runtime import runtime

C = TypeVar("C", bound=Callable[..., Any])


def web_component(path: str):
current_frame = inspect.currentframe()
assert current_frame
previous_frame = current_frame.f_back
assert previous_frame
caller_module_file = inspect.getfile(previous_frame)
caller_module_dir = os.path.dirname(os.path.abspath(caller_module_file))
full_path = os.path.join(caller_module_dir, path)

with open(full_path) as js_file:
js_content = js_file.read()
runtime().register_js_script(js_content)

def component_wrapper(fn: C) -> C:
@wraps(fn)
def wrapper(*args: Any, **kw_args: Any):
fn(*args, **kw_args)

return cast(C, wrapper)

return component_wrapper


# @dataclass(kw_only=True)
# class EventOutput:
# json: dict[str, Any]
# key: str


# def register_event_mapper(event: type[_T], map_fn: Callable[[EventOutput], _T]):
# runtime().register_event_mapper(
# event=event,
# map_fn=lambda event, key: map_fn(
# EventOutput(
# json=json.loads(event.string_value),
# key=key.key,
# )
# ),
# )
1 change: 1 addition & 0 deletions mesop/protos/ui.proto
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@ message Type {

message WebComponentType {
optional string properties_json = 1;
optional string events_json = 2;
}

// Represents user-defined components.
Expand Down
4 changes: 2 additions & 2 deletions mesop/runtime/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from flask import g

import mesop.protos.ui_pb2 as pb
from mesop.events import LoadEvent, MesopEvent
from mesop.events import LoadEvent
from mesop.exceptions import MesopDeveloperException, MesopUserException
from mesop.key import Key
from mesop.security.security_policy import SecurityPolicy
Expand Down Expand Up @@ -33,7 +33,7 @@ class PageConfig:
on_load: OnLoadHandler | None


E = TypeVar("E", bound=MesopEvent)
E = TypeVar("E")
T = TypeVar("T")


Expand Down
Loading

0 comments on commit 324f4cb

Please sign in to comment.