from __future__ import annotations
import contextlib
import json
from collections.abc import Callable
from typing import Any
from ..base import Widget
from ..metrics import (
BUTTON_BORDER,
BUTTON_FONT_SIZE,
BUTTON_HEIGHT,
BUTTON_LETTER_SPACING,
BUTTON_LG_FONT_SIZE,
BUTTON_LG_HEIGHT,
BUTTON_LG_LETTER_SPACING,
BUTTON_LG_PAD_X,
BUTTON_PAD_X,
BUTTON_SM_FONT_SIZE,
BUTTON_SM_HEIGHT,
BUTTON_SM_LETTER_SPACING,
BUTTON_SM_PAD_X,
BUTTON_TINY_FONT_SIZE,
BUTTON_TINY_HEIGHT,
BUTTON_TINY_LETTER_SPACING,
BUTTON_TINY_PAD_X,
CHECK_BOX,
CHECK_FONT_SIZE,
CHECK_GAP,
CHECK_HEIGHT,
CHECK_PAD_X,
ENTRY_HEIGHT,
ENTRY_WIDTH,
estimate_text_width,
)
[docs]
class Entry(Widget):
"""A single-line text input field.
Config options: ``text``, ``placeholder``, ``justify``, ``width``,
``password`` (bool), ``maxlength``, plus all CSS properties from
``_CONFIG_TO_CSS``.
"""
_ARIA_ROLE = "textbox"
_FIRST_POSITIONAL_AS_TEXT = True
def __init__(
self,
*args: Any,
parent: Widget | None = None,
text: str = "",
justify: str = "",
maxlength: int | None = None,
**kwargs: Any,
) -> None:
args, kwargs = self._swap_first_positional_str(args, kwargs)
if args:
parent = args[0]
if "text" in kwargs and text == "":
text = kwargs.pop("text")
super().__init__(parent, **kwargs)
self._config_dict["text"] = (
self._textvariable.get() if self._textvariable is not None else str(text)
)
if justify:
self._config_dict["justify"] = justify
if maxlength is not None:
self._config_dict["maxlength"] = maxlength
@property
def text(self) -> str:
return self._config_dict.get("text", "")
@text.setter
def text(self, value: str) -> None:
self._config_dict["text"] = str(value)
self._sync()
@property
def justify(self) -> str:
return self._config_dict.get("justify", "")
@justify.setter
def justify(self, value: str) -> None:
self._config_dict["justify"] = value
self._sync()
@property
def maxlength(self) -> int | None:
return self._config_dict.get("maxlength")
@maxlength.setter
def maxlength(self, value: int | None) -> None:
if value is not None:
self._config_dict["maxlength"] = value
else:
self._config_dict.pop("maxlength", None)
self._sync()
@property
def placeholder(self) -> str:
return self._config_dict.get("placeholder", "")
@placeholder.setter
def placeholder(self, value: str) -> None:
self._config_dict["placeholder"] = str(value)
self._sync()
@property
def password(self) -> bool:
return self._config_dict.get("password", False)
@password.setter
def password(self, value: bool) -> None:
self._config_dict["password"] = bool(value)
self._sync()
@property
def readonly(self) -> bool:
return self._config_dict.get("state") == "readonly"
@readonly.setter
def readonly(self, value: bool) -> None:
self._set_state("readonly" if value else "normal")
@property
def enabled(self) -> bool:
return not self._config_dict.get("disabled", False)
@enabled.setter
def enabled(self, value: bool) -> None:
self._set_state("normal" if value else "disabled")
def _own_min_size(self) -> tuple[int, int]:
return (ENTRY_WIDTH, ENTRY_HEIGHT)
def _render(self) -> str:
val = self._config_dict.get("text", "")
escaped = val.replace("&", "&").replace('"', """)
placeholder = self._config_dict.get("placeholder", "")
placeholder_attr = f' placeholder="{placeholder}"' if placeholder else ""
width = self._config_dict.get("width", 150)
style = self._render_style() + f"width:{width}px;"
j = self._config_dict.get("justify", "")
if j == "center":
style += "text-align:center;"
elif j in ("right", "e"):
style += "text-align:right;"
input_type = "password" if self._config_dict.get("password") else "text"
ml = self._config_dict.get("maxlength")
ml_attr = f' maxlength="{ml}"' if ml is not None else ""
attrs = self._render_attrs()
return f'<input id="{self._id}" class="iskg-entry" type="{input_type}" value="{escaped}"{placeholder_attr}{ml_attr} style="{style}" {attrs}/>'
def _var_updated(self, var: Any) -> None:
if var is self._textvariable:
self._config_dict["text"] = var.get()
self._sync()
def _handle_bridge_event(self, event_name: str, event_data: Any) -> None:
if event_name in ("change", "input"):
self._config_dict["text"] = str(event_data)
super()._handle_bridge_event(event_name, event_data)
def _render_js(self) -> str:
return f'''document.getElementById("{self._id}").onchange=function(){{
iskg_bridge_event("{self._id}","change",this.value);
}};
document.getElementById("{self._id}").oninput=function(){{
iskg_bridge_event("{self._id}","input",this.value);
}};'''
def _default_takefocus(self) -> bool:
return True
def _render_update_js(self) -> str:
parts = []
val = self._config_dict.get("text", "")
escaped = val.replace("\\", "\\\\").replace("'", "\\'")
parts.append(f'iskg_set_value("{self._id}","{escaped}");')
pw = "password" if self._config_dict.get("password") else "text"
parts.append(f'iskg_set_attr("{self._id}","type","{pw}");')
ml = self._config_dict.get("maxlength")
if ml is not None:
parts.append(f'iskg_set_attr("{self._id}","maxlength","{ml}");')
j = self._config_dict.get("justify", "")
if j:
ta = {"center": "center", "right": "right", "e": "right"}.get(j, "left")
parts.append(f'iskg_set_style("{self._id}",{json.dumps("text-align:" + ta)});')
return ";".join(parts)
[docs]
class CheckBox(Widget):
"""A toggleable check box with label."""
_ARIA_ROLE = "checkbox"
_FIRST_POSITIONAL_AS_TEXT = True
def _render_aria_attrs(self) -> str:
checked = self._config_dict.get("checked", False)
result = f' role="checkbox" aria-checked="{str(checked).lower()}"'
if self._config_dict.get("disabled"):
result += ' aria-disabled="true"'
return result
def __init__(
self,
*args: Any,
parent: Widget | None = None,
text: str = "",
checked: bool = False,
command: Callable | None = None,
**kwargs: Any,
) -> None:
args, kwargs = self._swap_first_positional_str(args, kwargs)
if args:
parent = args[0]
if command:
kwargs["command"] = command
if "text" in kwargs and text == "":
text = kwargs.pop("text")
super().__init__(parent, **kwargs)
self._config_dict["text"] = text
self._config_dict["checked"] = checked
if command is not None:
self._config_dict["command"] = command
@property
def checked(self) -> bool:
return self._config_dict.get("checked", False)
@checked.setter
def checked(self, value: bool) -> None:
self._config_dict["checked"] = bool(value)
self._sync()
@property
def text(self) -> str:
return self._config_dict.get("text", "")
@text.setter
def text(self, value: str) -> None:
self._config_dict["text"] = str(value)
self._sync()
@property
def enabled(self) -> bool:
return not self._config_dict.get("disabled", False)
@enabled.setter
def enabled(self, value: bool) -> None:
self._set_state("normal" if value else "disabled")
def _var_updated(self, var: Any) -> None:
if var is self._variable:
self._config_dict["checked"] = var.get()
self._sync()
def _handle_bridge_event(self, event_name: str, event_data: Any) -> None:
if event_name == "change":
self._config_dict["checked"] = event_data == "true"
cmd = self._config_dict.get("command")
if cmd is not None:
with contextlib.suppress(Exception):
cmd(self.checked)
super()._handle_bridge_event(event_name, event_data)
def _own_min_size(self) -> tuple[int, int]:
text = self._config_dict.get("text", "")
w = estimate_text_width(
text, CHECK_FONT_SIZE, pad_x=CHECK_PAD_X, extra=CHECK_BOX + CHECK_GAP
)
return (w, CHECK_HEIGHT)
def _render(self) -> str:
text = self._config_dict.get("text", "")
checked = self._config_dict.get("checked", False)
cls = "iskg-check-wrap"
if self._config_dict.get("disabled"):
cls += " disabled"
check_cls = "iskg-check" + (" checked" if checked else "")
style = self._render_style()
attrs = self._render_attrs()
return f'''<label id="{self._id}" class="{cls}" style="{style}" {attrs}>
<span class="{check_cls}"></span>
<span>{text}</span>
</label>'''
def _render_js(self) -> str:
return f'''document.getElementById("{self._id}").onclick=function(){{
var c=this.querySelector(".iskg-check");
c.classList.toggle("checked");
iskg_bridge_event("{self._id}","change",c.classList.contains("checked")?"true":"false");
}};'''
def _default_takefocus(self) -> bool:
return True
def _render_update_js(self) -> str:
checked = self._config_dict.get("checked", False)
return f'var el=document.getElementById("{self._id}");if(el)el.querySelector(".iskg-check").classList.toggle("checked",{json.dumps(checked)});'
[docs]
class ComboBox(Widget):
"""A dropdown select menu."""
_ARIA_ROLE = "combobox"
def __init__(
self,
parent: Widget | None = None,
values: list[str] | None = None,
current: int = 0,
command: Callable | None = None,
editable: bool = False,
**kwargs: Any,
) -> None:
if command:
kwargs["command"] = command
super().__init__(parent, **kwargs)
self._config_dict["values"] = values or []
self._config_dict["current"] = current
self._config_dict["editable"] = editable
@property
def current(self) -> int:
return self._config_dict.get("current", 0)
@current.setter
def current(self, idx: int) -> None:
self._config_dict["current"] = int(idx)
self._sync()
@property
def value(self) -> str:
vals = self._config_dict.get("values", [])
idx = self._config_dict.get("current", 0)
return vals[idx] if 0 <= idx < len(vals) else ""
@value.setter
def value(self, v: str) -> None:
vals = self._config_dict.get("values", [])
if v in vals:
self.current = vals.index(v)
else:
# Try to match by string equality; fall back to -1.
self._config_dict["_pending_value"] = v
@property
def values(self) -> list[str]:
"""The list of selectable options (read-only snapshot)."""
return list(self._config_dict.get("values", []))
@values.setter
def values(self, vals: list[str]) -> None:
self._config_dict["values"] = list(vals or [])
# Re-apply pending value if any
pending = self._config_dict.pop("_pending_value", None)
if pending is not None and pending in self._config_dict["values"]:
self._config_dict["current"] = self._config_dict["values"].index(pending)
self._sync()
@property
def editable(self) -> bool:
return self._config_dict.get("editable", False)
@editable.setter
def editable(self, value: bool) -> None:
self._config_dict["editable"] = bool(value)
self._sync()
@property
def enabled(self) -> bool:
return not self._config_dict.get("disabled", False)
@enabled.setter
def enabled(self, value: bool) -> None:
self._set_state("normal" if value else "disabled")
def _var_updated(self, var: Any) -> None:
if var is self._textvariable:
vals = self._config_dict.get("values", [])
target = var.get()
for i, v in enumerate(vals):
if v == target:
self._config_dict["current"] = i
break
self._sync()
def _handle_bridge_event(self, event_name: str, event_data: Any) -> None:
if event_name == "change":
self._variable_handled = True
try:
idx = int(event_data)
vals = self._config_dict.get("values", [])
if 0 <= idx < len(vals):
self._config_dict["current"] = idx
if self._textvariable is not None:
self._textvariable.set(vals[idx], _from_widget=self)
except (ValueError, TypeError):
pass
super()._handle_bridge_event(event_name, event_data)
self._variable_handled = False
def _render(self) -> str:
vals = self._config_dict.get("values", [])
cur = self._config_dict.get("current", 0)
cur_text = vals[cur] if vals and 0 <= cur < len(vals) else ""
style = self._render_style()
width = self._config_dict.get("width", 140)
items_html = "".join(
f'<div class="iskg-cb-item" data-idx="{i}">{v}</div>' for i, v in enumerate(vals)
)
cls = "iskg-cb-wrap"
if self._config_dict.get("disabled"):
cls += " iskg-disabled"
attrs = self._render_attrs()
if self._config_dict.get("editable"):
sel_esc = cur_text.replace("&", "&").replace('"', """)
return f'''<div id="{self._id}" class="{cls}" style="{style}width:{width}px;" {attrs}>
<input id="{self._id}-input" class="iskg-cb-input" value="{sel_esc}" style="width:{width - 22}px;">
<div class="iskg-cb-display" id="{self._id}-disp">
<span class="iskg-cb-arrow">▾</span>
</div>
<div class="iskg-cb-drop" id="{self._id}-drop" style="display:none;">
{items_html}
</div>
</div>'''
return f'''<div id="{self._id}" class="{cls}" style="{style}width:{width}px;" {attrs}>
<div class="iskg-cb-display" id="{self._id}-disp">
<span id="{self._id}-text">{cur_text}</span>
<span class="iskg-cb-arrow">▾</span>
</div>
<div class="iskg-cb-drop" id="{self._id}-drop" style="display:none;">
{items_html}
</div>
</div>'''
def _render_js(self) -> str:
editable = self._config_dict.get("editable")
if editable:
refs = (
'var inp=document.getElementById("%(id)s-input");\n'
'var disp=document.getElementById("%(id)s-disp");'
)
setter = "inp.value=item.innerText;"
else:
refs = (
'var disp=document.getElementById("%(id)s-disp");\n'
'var text=document.getElementById("%(id)s-text");'
)
setter = "text.innerText=item.innerText;"
refs = refs.replace("%(id)s", self._id)
return f'''(function(){{
var wrap=document.getElementById("{self._id}");
var drop=document.getElementById("{self._id}-drop");
function anchorRect(){{
/* El wrap puede estar estirado por el flex del padre (align-items:stretch),
asi que anclamos al control visible y no a la caja del wrap. */
var r=null;
for(var i=0;i<wrap.children.length;i++){{
var c=wrap.children[i];
if(c===drop)continue;
var cr=c.getBoundingClientRect();
if(cr.width<=0||cr.height<=0)continue;
if(!r)r={{top:cr.top,bottom:cr.bottom,left:cr.left,right:cr.right}};
else{{
r.top=Math.min(r.top,cr.top);r.bottom=Math.max(r.bottom,cr.bottom);
r.left=Math.min(r.left,cr.left);r.right=Math.max(r.right,cr.right);
}}
}}
if(!r){{
var wr=wrap.getBoundingClientRect();
r={{top:wr.top,bottom:wr.top+Math.min(wr.height,26),left:wr.left,right:wr.left+wr.width}};
}}
return r;
}}
function fixedOrigin(){{
/* Un ancestro con transform/filter/contain:paint convierte position:fixed
en relativo a ese ancestro: compensamos su origen. */
var e=wrap.parentElement;
while(e&&e!==document.documentElement){{
var s=getComputedStyle(e);
var t=s.transform, f=s.filter, p=s.perspective, c=s.contain||"", w=s.willChange||"";
if((t&&t!=="none")||(f&&f!=="none")||(p&&p!=="none")||
c.indexOf("paint")>=0||w.indexOf("transform")>=0){{
var er=e.getBoundingClientRect();
return {{x:er.left,y:er.top}};
}}
e=e.parentElement;
}}
return {{x:0,y:0}};
}}
function placeDrop(){{
var r=anchorRect(), o=fixedOrigin();
var vw=window.innerWidth, vh=window.innerHeight;
var width=Math.max(r.right-r.left,120);
var left=Math.max(4,Math.min(r.left-o.x,vw-width-4));
var gap=2;
var above=(r.top-o.y)-gap, below=vh-(r.bottom-o.y)-gap;
var full=drop.scrollHeight||180;
var up=(full>below&&above>below);
var cap=Math.max(60,Math.min(180,up?above:below));
/* fixed escapa overflow/stacking del resto de la UI */
drop.style.position="fixed";
drop.style.left=left+"px";
drop.style.width=width+"px";
drop.style.maxHeight=cap+"px";
var h=Math.min(full,cap);
drop.style.top=(up?(r.top-o.y)-h-gap:(r.bottom-o.y))+"px";
}}
function closeDrop(){{
drop.style.display="none";wrap.classList.remove("iskg-cb-open");
drop.style.position="";drop.style.top="";drop.style.left="";
drop.style.width="";drop.style.maxHeight="";
}}
function openDrop(){{
drop.style.display="block";wrap.classList.add("iskg-cb-open");
placeDrop();
}}
{refs}
disp.onclick=function(e){{e.stopPropagation();
if(drop.style.display=="block"){{closeDrop();return;}}
document.querySelectorAll(".iskg-cb-drop").forEach(function(d){{d.style.display="none";}});
document.querySelectorAll(".iskg-cb-wrap").forEach(function(w){{w.classList.remove("iskg-cb-open");}});
openDrop();
}};
drop.onclick=function(e){{var item=e.target.closest(".iskg-cb-item");
if(item){{var idx=item.dataset.idx;
{setter}
closeDrop();
iskg_bridge_event("{self._id}","change",idx);
}}
}};
{
(
"""if(inp){{
inp.addEventListener("input",function(){{
var q=inp.value.toLowerCase();
var all=drop.querySelectorAll(".iskg-cb-item");
var visible=0;
all.forEach(function(it){{
var m=it.innerText.toLowerCase().indexOf(q)>=0;
it.style.display=m?"":"none";
if(m)visible++;
}});
if(visible>0)openDrop();else closeDrop();
}});
inp.addEventListener("keydown",function(e){{
if(e.key==="Enter"&&drop.style.display==="block"){{
var first=drop.querySelector(".iskg-cb-item:not([style*='display: none'])");
if(first){{first.click();e.preventDefault();}}
}}
}});
}}"""
)
if editable
else ""
}
window.addEventListener("resize",function(){{if(drop.style.display=="block")placeDrop();}});
document.addEventListener("scroll",function(){{if(drop.style.display=="block")placeDrop();}},true);
document.addEventListener("click",function(e){{
if(!wrap.contains(e.target))closeDrop();
}});
}}());'''
def _default_takefocus(self) -> bool:
return True
def _render_update_js(self) -> str:
cur = self._config_dict.get("current", 0)
vals = self._config_dict.get("values", [])
cur_text = vals[cur] if vals and 0 <= cur < len(vals) else ""
# Rebuild the option list so changes to `values` are reflected live.
items_html = "".join(
f'<div class="iskg-cb-item" data-idx="{i}">{v}</div>' for i, v in enumerate(vals)
)
return f'''var t=document.getElementById("{self._id}-text");
if(t)t.innerText={json.dumps(cur_text)};
var inp=document.getElementById("{self._id}-input");
if(inp)inp.value={json.dumps(cur_text)};
var drop=document.getElementById("{self._id}-drop");
if(drop){{drop.innerHTML={json.dumps(items_html)};}}
var items=document.querySelectorAll("#{self._id}-drop .iskg-cb-item");
items.forEach(function(x,i){{x.classList.toggle("iskg-cb-sel",i=={cur});}});'''
[docs]
class Slider(Widget):
"""A horizontal range slider.
Config options: ``from``, ``to``, ``value``, ``step``, ``orient``
(``"horizontal"`` / ``"vertical"``), ``show_value`` (bool),
plus all CSS properties.
"""
_ARIA_ROLE = "slider"
def _render_aria_attrs(self) -> str:
from_ = self._config_dict.get("from", 0)
to = self._config_dict.get("to", 100)
val = self._config_dict.get("value", 0)
result = (
f' role="slider" aria-valuemin="{from_}" aria-valuemax="{to}" aria-valuenow="{val}"'
)
if self._config_dict.get("disabled"):
result += ' aria-disabled="true"'
return result
def __init__(
self,
parent: Widget | None = None,
value: float = 50,
min_value: float | None = None,
max_value: float | None = None,
command: Callable | None = None,
from_: float = 0,
to: float = 100,
orient: str = "horizontal",
**kwargs: Any,
) -> None:
if command:
kwargs["command"] = command
super().__init__(parent, **kwargs)
self._config_dict["from"] = from_
self._config_dict["to"] = to
if min_value is not None:
self._config_dict["from"] = min_value
if max_value is not None:
self._config_dict["to"] = max_value
self._config_dict["value"] = self._variable.get() if self._variable is not None else value
self._config_dict["orient"] = orient
@property
def value(self) -> float:
return self._config_dict.get("value", 0)
@value.setter
def value(self, v: float) -> None:
self._config_dict["value"] = float(v)
self._sync()
@property
def from_(self) -> float:
return self._config_dict.get("from", 0)
@from_.setter
def from_(self, v: float) -> None:
self._config_dict["from"] = float(v)
self._sync()
@property
def to(self) -> float:
return self._config_dict.get("to", 100)
@to.setter
def to(self, v: float) -> None:
self._config_dict["to"] = float(v)
self._sync()
@property
def step(self) -> float | None:
return self._config_dict.get("step")
@step.setter
def step(self, v: float | None) -> None:
if v is not None:
self._config_dict["step"] = float(v)
else:
self._config_dict.pop("step", None)
self._sync()
@property
def orient(self) -> str:
return self._config_dict.get("orient", "horizontal")
@orient.setter
def orient(self, v: str) -> None:
self._config_dict["orient"] = str(v)
self._sync()
@property
def show_value(self) -> bool:
return self._get_cfg("show-value", True)
@show_value.setter
def show_value(self, v: bool) -> None:
self._config_dict["show-value"] = bool(v)
self._sync()
@property
def enabled(self) -> bool:
return not self._config_dict.get("disabled", False)
@enabled.setter
def enabled(self, value: bool) -> None:
self._set_state("normal" if value else "disabled")
def _render(self) -> str:
lo = self._config_dict.get("from", 0)
hi = self._config_dict.get("to", 100)
val = self._config_dict.get("value", 0)
orient = self._config_dict.get("orient", "horizontal")
show_val = self._get_cfg("show-value", True)
step = self._get_cfg("step")
step_attr = f' step="{step}"' if step is not None else ""
style = self._render_style()
width = self._config_dict.get("width", 150)
attrs = self._render_attrs()
if orient == "vertical":
vlen = self._config_dict.get("height", 100)
slider_cls = "iskg-slider-vert"
track_cls = "iskg-slider-vert-track"
wrap_style = f"{style}flex-direction:column;align-items:center;gap:4px;"
slider_style = f"width:{vlen}px;height:4px;"
track_style = f"width:30px;height:{vlen}px;"
val_html = f'<span class="iskg-slider-val-center">{val}</span>' if show_val else ""
return f'''<div class="iskg-slider-wrap" style="{wrap_style}">
<div class="{track_cls}" style="{track_style}">
<input id="{self._id}" class="{slider_cls}" type="range" min="{lo}" max="{hi}" value="{val}"{step_attr} style="{slider_style}" {attrs}/>
</div>
{val_html}
</div>'''
else:
slider_cls = "iskg-slider"
wrap_style = f"{style}width:{width}px;"
slider_style = f"width:{width}px;"
val_html = f'<span class="iskg-slider-val">{val}</span>' if show_val else ""
return f'''<div class="iskg-slider-wrap" style="{wrap_style}">
<input id="{self._id}" class="{slider_cls}" type="range" min="{lo}" max="{hi}" value="{val}"{step_attr} style="{slider_style}" {attrs}/>
{val_html}
</div>'''
def _var_updated(self, var: Any) -> None:
if var is self._variable:
self._config_dict["value"] = float(var.get())
self._sync()
def _handle_bridge_event(self, event_name: str, event_data: Any) -> None:
if event_name == "change":
with contextlib.suppress(ValueError, TypeError):
self._config_dict["value"] = float(event_data)
super()._handle_bridge_event(event_name, event_data)
def _render_js(self) -> str:
return f'''var el=document.getElementById("{self._id}");
el.oninput=function(){{
var v=parseFloat(this.value);
var wrap=this.closest(".iskg-slider-wrap");
if(wrap){{
var sib=wrap.querySelector(".iskg-slider-val,.iskg-slider-val-center");
if(sib)sib.innerText=v;
}}
iskg_bridge_event("{self._id}","change",v.toString());
}};
el.onwheel=function(e){{
e.preventDefault();
var step=(parseFloat(this.max)-parseFloat(this.min))/100||1;
this.value=parseFloat(this.value)+(e.deltaY>0?-step:step);
var evt=new Event("input",{{bubbles:true}});
this.dispatchEvent(evt);
}};'''
def _default_takefocus(self) -> bool:
return True
def _render_update_js(self) -> str:
val = self._config_dict.get("value", 0)
return f'''var el=document.getElementById("{self._id}");
if(el){{el.value={val};
var wrap=el.closest(".iskg-slider-wrap");
if(wrap){{
var sib=wrap.querySelector(".iskg-slider-val,.iskg-slider-val-center");
if(sib)sib.innerText={val};
}}}}'''
[docs]
class SpinBox(Widget):
"""A numeric stepper with up/down buttons."""
_ARIA_ROLE = "spinbutton"
def _render_aria_attrs(self) -> str:
from_ = self._config_dict.get("from", 0)
to = self._config_dict.get("to", 100)
val = self._config_dict.get("value", 0)
result = f' role="spinbutton" aria-valuemin="{from_}" aria-valuemax="{to}" aria-valuenow="{val}"'
if self._config_dict.get("disabled"):
result += ' aria-disabled="true"'
return result
def __init__(
self,
parent: Widget | None = None,
value: int = 0,
min_value: int | None = None,
max_value: int | None = None,
step: int = 1,
command: Callable | None = None,
from_: int = 0,
to: int = 100,
**kwargs: Any,
) -> None:
if command:
kwargs["command"] = command
super().__init__(parent, **kwargs)
self._config_dict["from"] = from_
self._config_dict["to"] = to
if min_value is not None:
self._config_dict["from"] = min_value
if max_value is not None:
self._config_dict["to"] = max_value
self._config_dict["step"] = step
self._config_dict["value"] = self._variable.get() if self._variable is not None else value
@property
def value(self) -> int:
return self._config_dict.get("value", 0)
@value.setter
def value(self, v: int) -> None:
self._config_dict["value"] = int(v)
self._sync()
@property
def from_(self) -> int:
return self._config_dict.get("from", 0)
@from_.setter
def from_(self, v: int) -> None:
self._config_dict["from"] = int(v)
self._sync()
@property
def to(self) -> int:
return self._config_dict.get("to", 100)
@to.setter
def to(self, v: int) -> None:
self._config_dict["to"] = int(v)
self._sync()
@property
def min_value(self) -> int:
return self._config_dict.get("from", 0)
@min_value.setter
def min_value(self, v: int) -> None:
self._config_dict["from"] = int(v)
self._sync()
@property
def max_value(self) -> int:
return self._config_dict.get("to", 100)
@max_value.setter
def max_value(self, v: int) -> None:
self._config_dict["to"] = int(v)
self._sync()
@property
def step(self) -> int:
return self._config_dict.get("step", 1)
@step.setter
def step(self, v: int) -> None:
self._config_dict["step"] = max(1, int(v))
self._sync()
@property
def enabled(self) -> bool:
return not self._config_dict.get("disabled", False)
@enabled.setter
def enabled(self, value: bool) -> None:
self._set_state("normal" if value else "disabled")
def _render(self) -> str:
val = self._config_dict.get("value", 0)
style = self._render_style()
attrs = self._render_attrs()
return f'''<div class="iskg-spinbox-wrap" style="{style}">
<input id="{self._id}" class="iskg-spinbox" type="text" value="{val}" readonly {attrs}/>
<div class="iskg-spinbox-btns">
<button class="iskg-spinup" id="{self._id}-up">▲</button>
<button class="iskg-spindown" id="{self._id}-dn">▼</button>
</div>
</div>'''
def _render_js(self) -> str:
step = self._config_dict.get("step", 1)
return f'''document.getElementById("{self._id}-up").onclick=function(){{
var inp=document.getElementById("{self._id}");
var v=parseInt(inp.value)||0;
if(v<{self._config_dict["to"]}){{v+={step};inp.value=v;iskg_bridge_event("{self._id}","change",v.toString());}}
}};
document.getElementById("{self._id}-dn").onclick=function(){{
var inp=document.getElementById("{self._id}");
var v=parseInt(inp.value)||0;
if(v>{self._config_dict["from"]}){{v-={step};inp.value=v;iskg_bridge_event("{self._id}","change",v.toString());}}
}};'''
def _var_updated(self, var: Any) -> None:
if var is self._variable:
self._config_dict["value"] = int(var.get())
self._sync()
def _handle_bridge_event(self, event_name: str, event_data: Any) -> None:
if event_name == "change":
with contextlib.suppress(ValueError, TypeError):
self._config_dict["value"] = int(event_data)
super()._handle_bridge_event(event_name, event_data)
def _default_takefocus(self) -> bool:
return True
def _render_update_js(self) -> str:
val = self._config_dict.get("value", 0)
return f'document.getElementById("{self._id}").value={val};'
[docs]
class Scale(Slider):
"""A range slider with min/max labels."""
@property
def from_(self) -> float:
return self._config_dict.get("from", 0)
@from_.setter
def from_(self, v: float) -> None:
self._config_dict["from"] = float(v)
self._sync()
@property
def to(self) -> float:
return self._config_dict.get("to", 1)
@to.setter
def to(self, v: float) -> None:
self._config_dict["to"] = float(v)
self._sync()
@property
def orient(self) -> str:
return self._config_dict.get("orient", "horizontal")
@orient.setter
def orient(self, v: str) -> None:
self._config_dict["orient"] = str(v)
self._sync()
def __init__(
self,
parent: Widget | None = None,
value: float = 0.5,
command: Callable | None = None,
from_: float = 0.0,
to: float = 1.0,
orient: str = "horizontal",
**kwargs: Any,
) -> None:
super().__init__(
parent, value=value, command=command, from_=from_, to=to, orient=orient, **kwargs
)
def _render(self) -> str:
lo = self._config_dict.get("from", 0)
hi = self._config_dict.get("to", 1)
val = self._config_dict.get("value", 0.5)
orient = self._config_dict.get("orient", "horizontal")
style = self._render_style()
width = self._config_dict.get("width", 200)
attrs = self._render_attrs()
if orient == "horizontal":
return f'''<div class="iskg-scale-wrap" style="{style}width:{width}px;">
<div class="iskg-scale-labels"><span>{lo}</span><span>{hi}</span></div>
<input id="{self._id}" class="iskg-slider" type="range" min="{lo}" max="{hi}" value="{val}" style="width:100%;" {attrs}/>
</div>'''
else:
height = self._config_dict.get("height", 200)
return f'''<div class="iskg-scale-wrap" style="{style}height:{height}px;align-items:center;">
<span>{hi}</span>
<div class="iskg-slider-vert-track" style="flex:1;width:30px;">
<input id="{self._id}" class="iskg-slider-vert" type="range" min="{lo}" max="{hi}" value="{val}" style="width:{height}px;height:4px;" {attrs}/>
</div>
<span>{lo}</span>
</div>'''
def _render_update_js(self) -> str:
"""Update the slider value AND the min/max labels so they stay in sync."""
val = self._config_dict.get("value", 0)
lo = self._config_dict.get("from", 0)
hi = self._config_dict.get("to", 1)
return f'''var el=document.getElementById("{self._id}");
if(el){{el.value={val};
var wrap=el.closest(".iskg-scale-wrap");
if(wrap){{
var labels=wrap.querySelectorAll(".iskg-scale-labels span");
if(labels.length>=2){{labels[0].innerText={lo};labels[1].innerText={hi};}}
}}}}'''
[docs]
class ToggleSwitch(Widget):
"""A toggle switch akin to a checkbox with slider appearance."""
_ARIA_ROLE = "switch"
_FIRST_POSITIONAL_AS_TEXT = True
def _render_aria_attrs(self) -> str:
checked = self._config_dict.get("checked", False)
result = f' role="switch" aria-checked="{str(checked).lower()}"'
if self._config_dict.get("disabled"):
result += ' aria-disabled="true"'
return result
def __init__(
self,
*args: Any,
parent: Widget | None = None,
text: str = "",
active: bool | None = None,
command: Callable | None = None,
checked: bool = False,
**kwargs: Any,
) -> None:
args, kwargs = self._swap_first_positional_str(args, kwargs)
if args:
parent = args[0]
if command:
kwargs["command"] = command
if "text" in kwargs and text == "":
text = kwargs.pop("text")
super().__init__(parent, **kwargs)
self._config_dict["text"] = text
self._config_dict["checked"] = checked if active is None else active
if command is not None:
self._config_dict["command"] = command
@property
def checked(self) -> bool:
return self._config_dict.get("checked", False)
@checked.setter
def checked(self, v: bool) -> None:
self._config_dict["checked"] = bool(v)
self._sync()
@property
def text(self) -> str:
return self._config_dict.get("text", "")
@text.setter
def text(self, value: str) -> None:
self._config_dict["text"] = str(value)
self._sync()
@property
def enabled(self) -> bool:
return not self._config_dict.get("disabled", False)
@enabled.setter
def enabled(self, value: bool) -> None:
self._set_state("normal" if value else "disabled")
def _var_updated(self, var: Any) -> None:
if var is self._variable:
self._config_dict["checked"] = var.get()
self._sync()
def _handle_bridge_event(self, event_name: str, event_data: Any) -> None:
if event_name == "change":
self._config_dict["checked"] = event_data == "true"
cmd = self._config_dict.get("command")
if cmd is not None:
with contextlib.suppress(Exception):
cmd(self.checked)
super()._handle_bridge_event(event_name, event_data)
def _render(self) -> str:
text = self._config_dict.get("text", "")
checked = self._config_dict.get("checked", False)
style = self._render_style()
track_cls = "iskg-toggle-track" + (" checked" if checked else "")
wrap_cls = "iskg-toggle-wrap"
if self._config_dict.get("disabled"):
wrap_cls += " disabled"
attrs = self._render_attrs()
return f'''<label id="{self._id}" class="{wrap_cls}" style="{style}" {attrs}>
<span class="{track_cls}"><span class="iskg-toggle-knob"></span></span>
<span class="iskg-toggle-text">{text}</span>
</label>'''
def _render_js(self) -> str:
return f'''document.getElementById("{self._id}").onclick=function(){{
var t=this.querySelector(".iskg-toggle-track");
t.classList.toggle("checked");
iskg_bridge_event("{self._id}","change",t.classList.contains("checked")?"true":"false");
}};'''
def _default_takefocus(self) -> bool:
return True
def _render_update_js(self) -> str:
checked = self._config_dict.get("checked", False)
return f'''var el=document.getElementById("{self._id}");
if(el){{var t=el.querySelector(".iskg-toggle-track");
t.classList.toggle("checked",{json.dumps(checked)});}}'''