instaui 0.1.9__py3-none-any.whl → 0.1.10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import typing
2
2
  from instaui.vars.mixin_types.observable import ObservableMixin
3
- from instaui.vars.mixin_types.py_binding import CanInputMixin
3
+ from instaui.vars.mixin_types.py_binding import CanInputMixin, CanOutputMixin
4
4
  from instaui.ui_functions.input_slient_data import InputSilentData
5
5
 
6
6
  from instaui.vars.mixin_types.common_type import TObservableInput
@@ -33,3 +33,13 @@ def analyze_observable_inputs(inputs: typing.List[TObservableInput]):
33
33
  result_inputs.append(input)
34
34
 
35
35
  return result_inputs, slients, datas
36
+
37
+
38
+ def auto_made_inputs_to_slient(
39
+ inputs: typing.Optional[typing.Sequence[TObservableInput]],
40
+ outputs: typing.Optional[typing.Sequence[CanOutputMixin]],
41
+ ):
42
+ if inputs is None or outputs is None:
43
+ return inputs
44
+
45
+ return [InputSilentData(input) if input in outputs else input for input in inputs]
@@ -10,6 +10,9 @@ from instaui.arco import component_types
10
10
  from instaui.event.event_mixin import EventMixin
11
11
  from ._utils import handle_props, try_setup_vmodel
12
12
 
13
+
14
+ _TSelectValue = typing.Union[str, int, typing.Sequence[str], typing.Sequence[int]]
15
+
13
16
  _OPTIONS_TRANSLATE_JS: typing.Final = r"""(options)=>{
14
17
  if (Array.isArray(options)){
15
18
  const obj = {};
@@ -27,7 +30,7 @@ class Select(Element):
27
30
  def __init__(
28
31
  self,
29
32
  options: TMaybeRef[typing.Union[typing.Sequence, typing.Dict]],
30
- value: typing.Optional[TMaybeRef[typing.Union[str, int]]] = None,
33
+ value: typing.Optional[TMaybeRef[_TSelectValue]] = None,
31
34
  **kwargs: Unpack[component_types.TSelect],
32
35
  ):
33
36
  super().__init__("a-select")
@@ -74,8 +74,8 @@ function autoResize(root, chartIns, props) {
74
74
  if (!isInitialResize) {
75
75
  isInitialResize = true;
76
76
  if (
77
- root.offsetWidth === offsetWidth &&
78
- root.offsetHeight === offsetHeight
77
+ root.value.offsetWidth === offsetWidth &&
78
+ root.value.offsetHeight === offsetHeight
79
79
  ) {
80
80
  return;
81
81
  }
@@ -105,9 +105,11 @@ function setChartEvents(root, chartIns, emit, props) {
105
105
  if (chartEvents) {
106
106
  chartEvents.forEach(event => {
107
107
  chartIns.value.on(event, (...args) => {
108
- const eventArgs = args[0]
109
- delete eventArgs['event']
110
- delete eventArgs['$vars']
108
+ if (args.length > 0) {
109
+ const eventArgs = args[0]
110
+ delete eventArgs['event']
111
+ delete eventArgs['$vars']
112
+ }
111
113
 
112
114
  emit(`chart:${event}`, ...args)
113
115
  });
@@ -153,7 +153,7 @@ class ECharts(
153
153
  self._zr_events: Set[str] = set()
154
154
  self.props({"option": option})
155
155
 
156
- if init_options:
156
+ if init_options is not None:
157
157
  self.props({"initOptions": init_options})
158
158
 
159
159
  if update_options:
@@ -96,8 +96,11 @@ class Element(Component):
96
96
  self._props.update(self._default_props)
97
97
  self._proxy_props: List[ElementBindingMixin] = []
98
98
 
99
- self._js_events: defaultdict[str, List[EventMixin]] = defaultdict(list)
100
- self._web_events: defaultdict[str, List[EventMixin]] = defaultdict(list)
99
+ self._events: defaultdict[str, List[EventMixin]] = defaultdict(list)
100
+
101
+ # self._js_events: defaultdict[str, List[EventMixin]] = defaultdict(list)
102
+ # self._web_events: defaultdict[str, List[EventMixin]] = defaultdict(list)
103
+ # self._vue_events: defaultdict[str, List[EventMixin]] = defaultdict(list)
101
104
  self._directives: Dict[Directive, None] = {}
102
105
 
103
106
  self._slot_manager = SlotManager()
@@ -328,11 +331,7 @@ class Element(Component):
328
331
  if extends:
329
332
  handler = handler.copy_with_extends(extends)
330
333
 
331
- if handler.event_type() == "js":
332
- self._js_events[event_name].append(handler)
333
-
334
- if handler.event_type() == "web":
335
- self._web_events[event_name].append(handler)
334
+ self._events[event_name].append(handler)
336
335
 
337
336
  return self
338
337
 
@@ -452,8 +451,8 @@ class Element(Component):
452
451
  v._to_element_binding_config() for v in self._proxy_props
453
452
  ]
454
453
 
455
- if self._js_events or self._web_events:
456
- data["events"] = _normalize_events(self._js_events, self._web_events)
454
+ if self._events:
455
+ data["events"] = _normalize_events(self._events)
457
456
 
458
457
  if self._slot_manager.has_slot():
459
458
  data["slots"] = self._slot_manager
@@ -477,20 +476,11 @@ class Element(Component):
477
476
 
478
477
 
479
478
  def _normalize_events(
480
- js_events: defaultdict[str, List[EventMixin]],
481
- web_events: defaultdict[str, List[EventMixin]],
479
+ events: defaultdict[str, List[EventMixin]],
482
480
  ):
483
- merged: defaultdict[str, List[EventMixin]] = defaultdict(list)
484
-
485
- for name, events in js_events.items():
486
- name = _normalize_event_name(name)
487
- merged[name].extend(events)
488
-
489
- for name, events in web_events.items():
490
- name = _normalize_event_name(name)
491
- merged[name].extend(events)
492
-
493
- return dict(merged)
481
+ return {
482
+ _normalize_event_name(name): event_list for name, event_list in events.items()
483
+ }
494
484
 
495
485
 
496
486
  def _normalize_event_name(event_name: str):
@@ -121,23 +121,75 @@ class Grid(Element):
121
121
  area = f"{real_row} / {real_column} / {real_row_span} / {real_column_span}"
122
122
  return self.mark_area(area)
123
123
 
124
- @classmethod
124
+ @staticmethod
125
125
  def auto_columns(
126
- cls,
127
126
  *,
128
127
  min_width: TMaybeRef[str],
129
128
  mode: TMaybeRef[Literal["auto-fill", "auto-fit"]] = "auto-fit",
130
- ) -> Grid:
131
- if isinstance(min_width, ObservableMixin) or isinstance(mode, ObservableMixin):
132
- template = JsComputed(
133
- inputs=[min_width, mode],
134
- code=r"(min_width, mode)=> `repeat(${mode}, minmax(min(${min_width},100%), 1fr))`",
135
- )
129
+ ):
130
+ """
131
+ Generate a dynamic grid column configuration for responsive layout systems.
132
+
133
+ Creates a computed layout specification that calculates column dimensions
134
+ based on minimum width requirements and auto-sizing behavior. Retu
135
+
136
+ Args:
137
+ min_width (TMaybeRef[str]):
138
+ Minimum width constraint for columns as a CSS length string (e.g., "300px").
139
+ Accepts reactive references for dynamic updates.
140
+ mode (TMaybeRef[Literal["auto, optional):
141
+ Auto-sizing behavior strategy:
142
+ - "auto-fill": Preserves container space by creating additional columns
143
+ - "auto-fit": Adjusts columns to fit available space.
144
+ Defaults to "auto-fit".
145
+
146
+ Example:
147
+ .. code-block:: python
148
+
149
+ with ui.grid(columns=ui.grid.auto_columns(min_width="300px")):
150
+ ...
151
+ """
152
+ template = JsComputed(
153
+ inputs=[min_width, mode],
154
+ code=r"(min_width, mode)=> `repeat(${mode}, minmax(min(${min_width},100%), 1fr))`",
155
+ )
156
+
157
+ return template
158
+
159
+ @staticmethod
160
+ def auto_rows(
161
+ *,
162
+ min_height: TMaybeRef[str],
163
+ mode: TMaybeRef[Literal["auto-fill", "auto-fit"]] = "auto-fit",
164
+ ):
165
+ """
166
+ Generate a dynamic grid row configuration for responsive layout systems.
167
+
168
+ Creates a computed layout specification that calculates row dimensions
169
+ based on minimum height requirements and auto-sizing behavior.
170
+
171
+ Args:
172
+ min_height (TMaybeRef[str]):
173
+ Minimum height constraint for rows as a CSS length string (e.g., "300px").
174
+ mode (TMaybeRef[Literal["auto, optional):
175
+ Auto-sizing behavior strategy:
176
+ - "auto-fill": Preserves container space by creating additional rows
177
+ - "auto-fit": Adjusts rows to fit available space.
178
+ Defaults to "auto-fit".
179
+
180
+ Example:
181
+ .. code-block:: python
182
+
183
+ with ui.grid(rows=ui.grid.auto_rows(min_height="300px")):
184
+ ...
185
+ """
136
186
 
137
- else:
138
- template = f"repeat({mode}, minmax(min({min_width},100%), 1fr))"
187
+ template = JsComputed(
188
+ inputs=[min_height, mode],
189
+ code=r"(min_height, mode)=> `repeat(${mode}, minmax(min(${min_height},100%), 1fr))`",
190
+ )
139
191
 
140
- return cls(columns=template)
192
+ return template
141
193
 
142
194
  def row_gap(self, gap: TMaybeRef[str]) -> Grid:
143
195
  return self.style({"row-gap": gap})
@@ -7,6 +7,16 @@ if TYPE_CHECKING:
7
7
 
8
8
 
9
9
  class Paragraph(Element):
10
+ """
11
+ A component class representing an HTML `<p>` (paragraph) element.
12
+
13
+ Args:
14
+ text (Union[str, TMaybeRef[Any]]):The text content of the paragraph.
15
+ - If a string is provided, the content is static.
16
+ - If a `TMaybeRef` object is provided, the content
17
+ will reactively update when the referenced value changes.
18
+ """
19
+
10
20
  def __init__(
11
21
  self,
12
22
  text: Union[str, TMaybeRef[Any]],
@@ -0,0 +1,5 @@
1
+ from instaui.components.html.span import Span
2
+
3
+
4
+ label = Span
5
+ """ A label element. Equivalent to `html.span`. """
instaui/event/js_event.py CHANGED
@@ -55,4 +55,28 @@ def js_event(
55
55
  outputs: typing.Optional[typing.Sequence] = None,
56
56
  code: str,
57
57
  ):
58
+ """
59
+ Creates a client-side event handler decorator for binding JavaScript logic to UI component events.
60
+
61
+ Args:
62
+ inputs (typing.Optional[typing.Sequence], optional):Reactive sources (state variables, computed values)
63
+ that should be passed to the event handler. These values
64
+ will be available in the JavaScript context through the `args` array.
65
+ outputs (typing.Optional[typing.Sequence], optional): Targets (state variables, UI elements) that should
66
+ update when this handler executes. Used for coordinating
67
+ interface updates after the event is processed.
68
+ code (str): JavaScript code to execute when the event is triggered.
69
+
70
+ # Example:
71
+ .. code-block:: python
72
+ from instaui import ui, html
73
+
74
+ a = ui.state(0)
75
+
76
+ plus_one = ui.js_event(inputs=[a], outputs=[a], code="a =>a + 1")
77
+
78
+ html.button("click me").on_click(plus_one)
79
+ html.paragraph(a)
80
+
81
+ """
58
82
  return JsEvent(inputs=inputs, outputs=outputs, code=code)
@@ -0,0 +1,66 @@
1
+ import typing
2
+ from instaui.common.jsonable import Jsonable
3
+ from instaui.vars.mixin_types.observable import ObservableMixin
4
+ from .event_mixin import EventMixin
5
+
6
+
7
+ class VueEvent(Jsonable, EventMixin):
8
+ """
9
+ Create an event object that can be bound to a UI component's event listener.
10
+
11
+ This function generates a callable event handler with optional contextual bindings.
12
+ The event logic is defined via a code string, which can reference bound variables.
13
+
14
+ Args:
15
+ code (str): A string containing the executable logic for the event handler.
16
+ Typically contains a function body or expression that utilizes bound variables.
17
+ bindings (typing.Optional[typing.Dict[str, typing.Any]], optional): A dictionary mapping variable names to values that should be available in the
18
+ event handler's context. If None, no additional bindings are created.. Defaults to None.
19
+
20
+ Example:
21
+ .. code-block:: python
22
+ a = ui.state(1)
23
+
24
+ event = ui.vue_event(bindings={"a": a}, code=r'''()=> { a.value +=1}''')
25
+
26
+ html.span(a)
27
+ html.button("plus").on("click", event)
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ *,
33
+ code: str,
34
+ bindings: typing.Optional[typing.Dict[str, typing.Any]] = None,
35
+ ):
36
+ self.code = code
37
+ self._bindings = bindings
38
+
39
+ if bindings:
40
+ bindData = [
41
+ int(not isinstance(v, ObservableMixin)) for v in bindings.values()
42
+ ]
43
+
44
+ if sum(bindData) > 0:
45
+ self.bindData = bindData
46
+
47
+ self.bind = {
48
+ k: typing.cast(ObservableMixin, v)._to_observable_config()
49
+ if isinstance(v, ObservableMixin)
50
+ else v
51
+ for k, v in bindings.items()
52
+ }
53
+
54
+ def copy_with_extends(self, extends: typing.Dict):
55
+ raise NotImplementedError("VueEvent does not support extends")
56
+
57
+ def event_type(self):
58
+ return "vue"
59
+
60
+ def _to_json_dict(self):
61
+ data = super()._to_json_dict()
62
+ data["type"] = self.event_type()
63
+ return data
64
+
65
+
66
+ vue_event = VueEvent
@@ -20,8 +20,8 @@ class WebEvent(Jsonable, EventMixin, typing.Generic[P, R]):
20
20
  def __init__(
21
21
  self,
22
22
  fn: typing.Callable[P, R],
23
- inputs: typing.List[CanInputMixin],
24
- outputs: typing.List[CanOutputMixin],
23
+ inputs: typing.Sequence[CanInputMixin],
24
+ outputs: typing.Sequence[CanOutputMixin],
25
25
  ):
26
26
  self._inputs = inputs
27
27
  self._outputs = outputs
@@ -36,7 +36,7 @@ class WebEvent(Jsonable, EventMixin, typing.Generic[P, R]):
36
36
  def copy_with_extends(self, extends: typing.Sequence[CanInputMixin]):
37
37
  return WebEvent(
38
38
  fn=self._fn,
39
- inputs=self._inputs + list(extends),
39
+ inputs=list(self._inputs) + list(extends),
40
40
  outputs=self._outputs,
41
41
  )
42
42
 
@@ -76,32 +76,43 @@ class WebEvent(Jsonable, EventMixin, typing.Generic[P, R]):
76
76
  return data
77
77
 
78
78
 
79
- @typing.overload
80
- def ui_event(fn: typing.Callable[P, R]) -> WebEvent[P, R]: ...
79
+ def event(
80
+ *,
81
+ inputs: typing.Optional[typing.Sequence] = None,
82
+ outputs: typing.Optional[typing.Sequence] = None,
83
+ ):
84
+ """
85
+ Creates an event handler decorator for binding reactive logic to component events.
81
86
 
87
+ Args:
88
+ inputs (typing.Optional[typing.Sequence], optional): Reactive sources (state objects, computed properties)
89
+ that should be accessible during event handling.
90
+ These values will be passed to the decorated function
91
+ when the event fires.
92
+ outputs (typing.Optional[typing.Sequence], optional): Targets (state variables, UI elements) that should
93
+ update when this handler executes. Used for coordinating
94
+ interface updates after the event is processed.
82
95
 
83
- @typing.overload
84
- def ui_event(
85
- *,
86
- inputs: typing.Optional[typing.Union[_T_input, typing.Sequence[_T_input]]] = None,
87
- outputs: typing.Optional[
88
- typing.Union[_T_output, typing.Sequence[_T_output]]
89
- ] = None,
90
- ) -> typing.Callable[[typing.Callable[P, R]], WebEvent[P, R]]: ...
96
+ # Example:
97
+ .. code-block:: python
98
+ from instaui import ui, html
99
+
100
+ a = ui.state(0)
91
101
 
102
+ @ui.event(inputs=[a], outputs=[a])
103
+ def plus_one(a):
104
+ return a + 1
92
105
 
93
- def ui_event(
94
- fn: typing.Optional[typing.Callable[P, R]] = None, *, inputs=None, outputs=None
95
- ) -> typing.Union[
96
- WebEvent[P, R], typing.Callable[[typing.Callable[P, R]], WebEvent[P, R]]
97
- ]:
98
- inputs = [inputs] if isinstance(inputs, CanInputMixin) else inputs
99
- outputs = [outputs] if isinstance(outputs, CanOutputMixin) else outputs
100
- if fn is None:
106
+ html.button("click me").on_click(plus_one)
107
+ html.paragraph(a)
101
108
 
102
- def wrapper(fn: typing.Callable[P, R]):
103
- return WebEvent(fn, inputs=inputs or [], outputs=outputs or [])
109
+ """
104
110
 
105
- return wrapper
111
+ def wrapper(func: typing.Callable[P, R]):
112
+ return WebEvent(
113
+ func,
114
+ inputs or [],
115
+ outputs=outputs or [],
116
+ )
106
117
 
107
- return WebEvent(fn, inputs=inputs or [], outputs=outputs or [])
118
+ return wrapper
@@ -23,17 +23,20 @@ class HandlerInfo:
23
23
  fn: Callable
24
24
  fn_location_info: str
25
25
  outputs_binding_count: int = 0
26
- hanlder_param_converters: List[pydantic_system.TypeAdapterProtocol] = field(
26
+ handler_param_converters: List[pydantic_system.TypeAdapterProtocol] = field(
27
27
  default_factory=list
28
28
  )
29
+ is_last_param_args: bool = False
29
30
 
30
31
  def get_handler_args(self, input_values: List):
32
+ real_param_converters = _try_expand_params_converters(
33
+ self.handler_param_converters, input_values, self.is_last_param_args
34
+ )
35
+
31
36
  try:
32
37
  return [
33
38
  param_converter.to_python_value(value)
34
- for param_converter, value in zip(
35
- self.hanlder_param_converters, input_values
36
- )
39
+ for param_converter, value in zip(real_param_converters, input_values)
37
40
  ]
38
41
  except pydantic_core._pydantic_core.ValidationError as e:
39
42
  raise ValueError(f"invalid input[{self.fn_location_info}]: {e}") from None
@@ -49,6 +52,7 @@ class HandlerInfo:
49
52
  ):
50
53
  custom_type_adapter_map = custom_type_adapter_map or {}
51
54
  params_infos = func_system.get_fn_params_infos(handler)
55
+ is_last_param_args = func_system.is_last_param_args(handler)
52
56
  param_converters = [
53
57
  custom_type_adapter_map.get(
54
58
  idx, pydantic_system.create_type_adapter(param_type)
@@ -62,5 +66,23 @@ class HandlerInfo:
62
66
  handler,
63
67
  f'File "{file}", line {lineno}',
64
68
  outputs_binding_count,
65
- hanlder_param_converters=param_converters,
69
+ handler_param_converters=param_converters,
70
+ is_last_param_args=is_last_param_args,
66
71
  )
72
+
73
+
74
+ def _try_expand_params_converters(
75
+ old_param_converters: List[pydantic_system.TypeAdapterProtocol],
76
+ input_values: List,
77
+ is_last_param_args: bool,
78
+ ):
79
+ if not is_last_param_args:
80
+ return old_param_converters
81
+
82
+ diff = len(input_values) - len(old_param_converters)
83
+ if diff == 0:
84
+ return old_param_converters
85
+
86
+ arg_param_converters = [old_param_converters[-1]] * diff
87
+
88
+ return [*old_param_converters[:], *arg_param_converters]
@@ -1 +1 @@
1
- :root{color-scheme:light dark}:where(body){--insta-column-gap: 1rem;height:100vh}:where(*){box-sizing:border-box}:where(#app){height:100%}:where(.app-box,.insta-main){height:100%;overflow-y:auto}:where(.insta-main){--insta-padding: 16px;padding:var(--insta-padding, 16px)}
1
+ :root{color-scheme:light dark}:where(body){--insta-column-gap: 1rem;height:100vh}:where(*){box-sizing:border-box;margin:0;padding:0}:where(#app){height:100%}:where(.app-box,.insta-main){height:100%;overflow-y:auto}:where(.insta-main){--insta-padding: 16px;padding:var(--insta-padding, 16px)}