コード例 #1
0
def main():
    ex_name = _example_name_input()

    mount, component = hotswap(update_on_change=True)

    def update_component():
        print(f"Loading example: {ex_name!r}")
        mount(load_one_example(ex_name))

    for file in get_example_files_by_name(ex_name):
        on_file_change(file, update_component)

    idom.run(component)
コード例 #2
0
ファイル: victory_chart.py プロジェクト: Beanstalk-Farms/idom
import idom

victory = idom.install("victory", fallback="loading...")
bar_style = {"parent": {"width": "500px"}, "data": {"fill": "royalblue"}}
idom.run(idom.component(lambda: victory.VictoryBar({"style": bar_style})))
コード例 #3
0
        {"style": {
            "margin-top": "5px"
        }},
        idom.html.label(
            "C",
            idom.html.sub(index),
            " × X",
            idom.html.sup(index),
        ),
        idom.html.input({
            "type": "number",
            "onChange": callback,
        }, ),
    )


def polynomial(x, coefficients):
    return sum(c * (x**(i + 1)) for i, c in enumerate(coefficients))


def linspace(start, stop, n):
    if n == 1:
        yield stop
        return
    h = (stop - start) / (n - 1)
    for i in range(n):
        yield start + h * i


idom.run(PolynomialPlot)
コード例 #4
0
def Todo():
    items, set_items = idom.hooks.use_state([])

    async def add_new_task(event):
        if event["key"] == "Enter":
            set_items(items + [event["target"]["value"]])

    tasks = []

    for index, text in enumerate(items):

        async def remove_task(event, index=index):
            set_items(items[:index] + items[index + 1:])

        task_text = idom.html.td(idom.html.p(text))
        delete_button = idom.html.td({"onClick": remove_task},
                                     idom.html.button(["x"]))
        tasks.append(idom.html.tr(task_text, delete_button))

    task_input = idom.html.input({"onKeyDown": add_new_task})
    task_table = idom.html.table(tasks)

    return idom.html.div(
        idom.html.p("press enter to add a task:"),
        task_input,
        task_table,
    )


idom.run(Todo)
コード例 #5
0
from idom import component, html, run, use_state


@component
def CounterList():
    counters, set_counters = use_state([0, 0, 0])

    def make_increment_click_handler(index):
        def handle_click(event):
            new_value = counters[index] + 1
            set_counters(counters[:index] + [new_value] + counters[index + 1 :])

        return handle_click

    return html.ul(
        [
            html.li(
                count,
                html.button({"onClick": make_increment_click_handler(index)}, "+1"),
                key=index,
            )
            for index, count in enumerate(counters)
        ]
    )


run(CounterList)
コード例 #6
0
ファイル: wrap_in_div.py プロジェクト: idom-team/idom
from idom import component, html, run


@component
def MyTodoList():
    return html.div(
        html.h1("My Todo List"),
        html.img({"src": "https://picsum.photos/id/0/500/300"}),
        html.ul(html.li("The first thing I need to do is...")),
    )


run(MyTodoList)
コード例 #7
0
import idom

material_ui = idom.install("@material-ui/core", fallback="loading...")

idom.run(
    idom.component(
        lambda: material_ui.Button(
            {"color": "primary", "variant": "contained"}, "Hello World!"
        )
    )
)
コード例 #8
0
import idom

victory = idom.install("victory", fallback="loading...")

idom.run(
    idom.component(
        lambda: victory.VictoryBar({"style": {
            "parent": {
                "width": "500px"
            }
        }}), ))
コード例 #9
0
import idom


def increment(last_count):
    return last_count + 1


def decrement(last_count):
    return last_count - 1


@idom.component
def Counter():
    initial_count = 0
    count, set_count = idom.hooks.use_state(initial_count)
    return idom.html.div(
        f"Count: {count}",
        idom.html.button({"onClick": lambda event: set_count(initial_count)},
                         "Reset"),
        idom.html.button({"onClick": lambda event: set_count(increment)}, "+"),
        idom.html.button({"onClick": lambda event: set_count(decrement)}, "-"),
    )


idom.run(Counter)
コード例 #10
0
ファイル: run_flask.py プロジェクト: idom-team/idom
# :lines: 11-

from idom import run
from idom.backend import flask as flask_server

# the run() function is the entry point for examples
flask_server.configure = lambda _, cmpt: run(cmpt)

from flask import Flask

from idom import component, html
from idom.backend.flask import configure


@component
def HelloWorld():
    return html.h1("Hello, world!")


app = Flask(__name__)
configure(app, HelloWorld)
コード例 #11
0
import idom


@idom.component
def Slideshow():
    index, set_index = idom.hooks.use_state(0)

    def next_image(event):
        set_index(index + 1)

    return idom.html.img({
        "src": f"https://picsum.photos/800/300?image={index}",
        "style": {
            "cursor": "pointer"
        },
        "onClick": next_image,
    })


idom.run(Slideshow)
コード例 #12
0
ファイル: main.py プロジェクト: idom-team/idom
            {
                "style": {
                    "width": "200px",
                    "height": "200px",
                    "backgroundColor": "slategray",
                }
            },
            image(
                "png",
                CHARACTER_IMAGE,
                {
                    "style": {
                        "position": "relative",
                        "left": f"{position.x}px",
                        "top": f"{position.y}.px",
                        "transform": f"rotate({position.angle}deg) scale(2, 2)",
                    }
                },
            ),
        ),
        html.button({"onClick": lambda e: set_position(translate(x=-10))}, "Move Left"),
        html.button({"onClick": lambda e: set_position(translate(x=10))}, "Move Right"),
        html.button({"onClick": lambda e: set_position(translate(y=-10))}, "Move Up"),
        html.button({"onClick": lambda e: set_position(translate(y=10))}, "Move Down"),
        html.button({"onClick": lambda e: set_position(rotate(-30))}, "Rotate Left"),
        html.button({"onClick": lambda e: set_position(rotate(30))}, "Rotate Right"),
    )


run(Scene)
コード例 #13
0
ファイル: sample_app.py プロジェクト: idom-team/idom
import idom

idom.run(idom.sample.SampleApp)
コード例 #14
0
import json

import idom

mui = idom.web.module_from_template(
    "react@^17.0.0",
    "@material-ui/[email protected]",
    fallback="⌛",
)
Button = idom.web.export(mui, "Button")


@idom.component
def ViewButtonEvents():
    event, set_event = idom.hooks.use_state(None)

    return idom.html.div(
        Button(
            {
                "color": "primary",
                "variant": "contained",
                "onClick": lambda event: set_event(event),
            },
            "Click Me!",
        ),
        idom.html.pre(json.dumps(event, indent=2)),
    )


idom.run(ViewButtonEvents)
コード例 #15
0
from idom import component, event, html, run


@component
def DoNotChangePages():
    return html.div(
        html.p("Normally clicking this link would take you to a new page"),
        html.a(
            {
                "onClick": event(lambda event: None, prevent_default=True),
                "href": "https://google.com",
            },
            "https://google.com",
        ),
    )


run(DoNotChangePages)
コード例 #16
0
                    create_grid_block("black", block_scale, key=i)
                    for i in range(grid_size)
                ],
                key=i,
            ) for i in range(grid_size)
        ],
    )


def create_grid_block(color, block_scale, key):
    return idom.html.div(
        {
            "style": {
                "height": f"{block_scale}px",
                "width": f"{block_scale}px",
                "backgroundColor": color,
                "outline": "1px solid grey",
            }
        },
        key=key,
    )


def assign_grid_block_color(grid, point, color):
    x, y = point
    block = grid["children"][x]["children"][y]
    block["attributes"]["style"]["backgroundColor"] = color


idom.run(GameView)
コード例 #17
0
ファイル: set_color_3_times.py プロジェクト: idom-team/idom
def ColorButton():
    color, set_color = use_state("gray")

    def handle_click(event):
        set_color("orange")
        set_color("pink")
        set_color("blue")

    def handle_reset(event):
        set_color("gray")

    return html.div(
        html.button(
            {
                "onClick": handle_click,
                "style": {
                    "backgroundColor": color
                }
            }, "Set Color"),
        html.button(
            {
                "onClick": handle_reset,
                "style": {
                    "backgroundColor": color
                }
            }, "Reset"),
    )


run(ColorButton)
コード例 #18
0
ファイル: main.py プロジェクト: idom-team/idom
from idom import component, hooks, html, run


@component
def SyncedInputs():
    value, set_value = hooks.use_state("")
    return html.p(
        Input("First input", value, set_value),
        Input("Second input", value, set_value),
    )


@component
def Input(label, value, set_value):
    def handle_change(event):
        set_value(event["target"]["value"])

    return html.label(label + " ",
                      html.input({
                          "value": value,
                          "onChange": handle_change
                      }))


run(SyncedInputs)
コード例 #19
0
            "alt": alt,
            "style": {
                "height": "200px"
            }
        }),
        html.div(
            html.button(
                {"onClick": handle_more_click},
                f"{'Show' if show_more else 'Hide'} details",
            ),
            (html.p(description) if show_more else ""),
        ),
    )


@component
def App():
    return html.div(
        html.section({"style": {
            "width": "50%",
            "float": "left"
        }}, Gallery()),
        html.section({"style": {
            "width": "50%",
            "float": "left"
        }}, Gallery()),
    )


run(App)
コード例 #20
0
ファイル: click_count.py プロジェクト: idom-team/idom
import idom


@idom.component
def ClickCount():
    count, set_count = idom.hooks.use_state(0)

    return idom.html.button(
        {"onClick": lambda event: set_count(count + 1)},
        [f"Click count: {count}"],
    )


idom.run(ClickCount)
コード例 #21
0
HERE = Path(__file__)
DATA_PATH = HERE.parent / "data.json"
sculpture_data = json.loads(DATA_PATH.read_text())


@component
def Gallery():
    index = 0

    def handle_click(event):
        index = index + 1

    bounded_index = index % len(sculpture_data)
    sculpture = sculpture_data[bounded_index]
    alt = sculpture["alt"]
    artist = sculpture["artist"]
    description = sculpture["description"]
    name = sculpture["name"]
    url = sculpture["url"]

    return html.div(
        html.button({"onClick": handle_click}, "Next"),
        html.h2(name, " by ", artist),
        html.p(f"({bounded_index + 1} or {len(sculpture_data)})"),
        html.img({"src": url, "alt": alt, "style": {"height": "200px"}}),
        html.p(description),
    )


run(Gallery)
コード例 #22
0
import json

import idom

material_ui = idom.install("@material-ui/core", fallback="loading...")


@idom.component
def ViewSliderEvents():
    event, set_event = idom.hooks.use_state(None)

    return idom.html.div(
        material_ui.Slider({
            "color": "primary",
            "step": 10,
            "min": 0,
            "max": 100,
            "defaultValue": 50,
            "valueLabelDisplay": "auto",
            "onChange": lambda *event: set_event(event),
        }),
        idom.html.pre(json.dumps(event, indent=2)),
    )


idom.run(ViewSliderEvents)
コード例 #23
0
ファイル: todo_from_list.py プロジェクト: idom-team/idom
from idom import component, html, run


@component
def DataList(items):
    list_item_elements = [html.li(text) for text in items]
    return html.ul(list_item_elements)


@component
def TodoList():
    tasks = [
        "Make breakfast (important)",
        "Feed the dog (important)",
        "Do laundry",
        "Go on a run (important)",
        "Clean the house",
        "Go to the grocery store",
        "Do some coding",
        "Read a book (important)",
    ]
    return html.section(
        html.h1("My Todo List"),
        DataList(tasks),
    )


run(TodoList)
コード例 #24
0
ファイル: moving_dot.py プロジェクト: idom-team/idom
            "y": event["clientY"] - outer_div_bounds["y"],
        })

    return html.div(
        {
            "onPointerMove": handle_pointer_move,
            "style": {
                "position": "relative",
                "height": "200px",
                "width": "100%",
                "backgroundColor": "white",
            },
        },
        html.div({
            "style": {
                "position": "absolute",
                "backgroundColor": "red",
                "borderRadius": "50%",
                "width": "20px",
                "height": "20px",
                "left": "-10px",
                "top": "-10px",
                "transform":
                f"translate({position['x']}px, {position['y']}px)",
            },
        }),
    )


run(MovingDot)
コード例 #25
0
ファイル: audio_player.py プロジェクト: idom-team/idom
import json

import idom


@idom.component
def PlayDinosaurSound():
    event, set_event = idom.hooks.use_state(None)
    return idom.html.div(
        idom.html.audio({
            "controls":
            True,
            "onTimeUpdate":
            lambda e: set_event(e),
            "src":
            "https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3",
        }),
        idom.html.pre(json.dumps(event, indent=2)),
    )


idom.run(PlayDinosaurSound)
コード例 #26
0
from idom import component, html, run, use_state


@component
def Counter():
    number, set_number = use_state(0)

    def handle_click(event):
        set_number(number + 5)
        print(number)

    return html.div(
        html.h1(number),
        html.button({"onClick": handle_click}, "Increment"),
    )


run(Counter)
コード例 #27
0
                set_selected_indices(selected_indices - {index})
            else:
                set_selected_indices(selected_indices | {index})

        return handle_click

    return html.div(
        {"style": {"display": "flex", "flex-direction": "row"}},
        [
            html.div(
                {
                    "onClick": make_handle_click(index),
                    "style": {
                        "height": "30px",
                        "width": "30px",
                        "backgroundColor": (
                            "black" if index in selected_indices else "white"
                        ),
                        "outline": "1px solid grey",
                        "cursor": "pointer",
                    },
                },
                key=index,
            )
            for index in range(line_size)
        ],
    )


run(Grid)
コード例 #28
0
ファイル: dict_remove.py プロジェクト: idom-team/idom
        html.button({"onClick": handle_add_click}, "add term"),
        html.label(
            "Term: ",
            html.input({"value": term_to_add, "onChange": handle_term_to_add_change}),
        ),
        html.label(
            "Definition: ",
            html.input(
                {
                    "value": definition_to_add,
                    "onChange": handle_definition_to_add_change,
                }
            ),
        ),
        html.hr(),
        [
            html.div(
                html.button(
                    {"onClick": make_delete_click_handler(term)}, "delete term"
                ),
                html.dt(term),
                html.dd(definition),
                key=term,
            )
            for term, definition in all_terms.items()
        ],
    )


run(Definitions)
コード例 #29
0
from idom import component, run, web


mui = web.module_from_template(
    "react@^17.0.0",
    "@material-ui/[email protected]",
    fallback="⌛",
)
Button = web.export(mui, "Button")


@component
def HelloWorld():
    return Button({"color": "primary", "variant": "contained"}, "Hello World!")


run(HelloWorld)
コード例 #30
0
from idom import component, html, run


@component
def Button():
    return html.button("I don't do anything yet")


run(Button)