use std::{
hash::Hasher,
sync::{Arc, Mutex},
};
use super::{
Button, ButtonSize, ButtonVariant, icons, names,
part_style::{FontFamily, Length, PartStyle},
recipe::{Case, Interaction, Name, Recipe, ResolvedPart, ResolvedRecipe},
shared::{fading, one_line},
sparkline::{color_of, paint_key, width_of},
theme::{Themed, current_theme},
};
use crate::{
app::{
component::Component,
ctx::Ctx,
events::{DragEvent, EditEvent, KeyboardEvent, MouseButtonMask, TouchEvent},
theme::{BorderSize, OpacityLevel, PaletteColor, RadiusSize, Theme},
},
canvas::{ArcDirection, CanvasHandle, Context2D, LineCap, LineJoin},
components::{Canvas, Column, Row, Stack},
core::{ElementRef, Signal},
images::ImageData,
layout::{Alignment, layout_kind::Justify, stack_alignment::StackAlignment},
node::{CursorIcon, Element, border::Border, color::Color, dimension::Dimension},
time::Instant,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SignaturePadPart {
Root,
Surface,
Ink,
Guide,
Baseline,
Placeholder,
Actions,
}
names!(SignaturePadPart {
Root => "root",
Surface => "surface",
Ink => "ink",
Guide => "guide",
Baseline => "baseline",
Placeholder => "placeholder",
Actions => "actions",
});
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SignaturePadState {
Empty,
Signed,
Drawing,
Interactive,
ReadOnly,
Invalid,
Disabled,
}
names!(SignaturePadState {
Empty => "empty",
Signed => "signed",
Drawing => "drawing",
Interactive => "interactive",
ReadOnly => "read_only",
Invalid => "invalid",
Disabled => "disabled",
});
#[derive(Clone, Copy, Debug, PartialEq, crate::DevtoolsInspectable)]
pub struct SignaturePoint {
pub x: f32,
pub y: f32,
pub pressure: Option<f32>,
pub time: u32,
}
impl SignaturePoint {
pub fn new(x: f32, y: f32) -> Self {
Self {
x,
y,
pressure: None,
time: 0,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, crate::DevtoolsInspectable)]
pub struct SignatureStroke {
pub points: Vec<SignaturePoint>,
}
impl SignatureStroke {
pub fn new(points: impl IntoIterator<Item = SignaturePoint>) -> Self {
Self {
points: points.into_iter().collect(),
}
}
}
#[derive(Clone, Debug, Default, PartialEq, crate::DevtoolsInspectable)]
pub struct Signature {
pub width: f32,
pub height: f32,
pub strokes: Vec<SignatureStroke>,
}
impl Signature {
pub fn new(width: f32, height: f32) -> Self {
Self {
width,
height,
strokes: Vec::new(),
}
}
pub fn is_empty(&self) -> bool {
self.strokes.iter().all(|stroke| stroke.points.is_empty())
}
pub fn scale_to(&self, width: f32, height: f32) -> f32 {
if self.width <= 0.0 || self.height <= 0.0 || width <= 0.0 || height <= 0.0 {
return 1.0;
}
(width / self.width).min(height / self.height)
}
pub fn paint(&self, draw: &Context2D, width: f32, height: f32, ink: Color, line_width: f32) {
let scale = self.scale_to(width, height);
for stroke in &self.strokes {
let points: Vec<(f32, f32)> = stroke.points.iter().map(|p| (p.x * scale, p.y * scale)).collect();
trace(draw, &points, ink, line_width);
}
}
pub fn to_image(&self, scale_factor: f32, ink: Color, line_width: f32) -> Option<ImageData> {
let canvas = CanvasHandle::offscreen(self.width, self.height, scale_factor)?;
self.paint(&canvas.context_2d(), self.width, self.height, ink, line_width);
canvas.to_image_data()
}
pub fn to_png(&self, scale_factor: f32, ink: Color, line_width: f32) -> Option<Vec<u8>> {
let image = self.to_image(scale_factor, ink, line_width)?;
let mut out = Vec::new();
{
let mut encoder = png::Encoder::new(&mut out, image.width(), image.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().ok()?;
writer.write_image_data(image.data()).ok()?;
}
Some(out)
}
}
fn trace(draw: &Context2D, points: &[(f32, f32)], ink: Color, line_width: f32) {
let Some(&(first_x, first_y)) = points.first() else {
return;
};
let still = points
.iter()
.all(|(x, y)| (x - first_x).abs() < 0.5 && (y - first_y).abs() < 0.5);
if still {
draw.set_fill_style(ink);
draw.begin_path();
let _ = draw.arc(
first_x,
first_y,
line_width / 2.0,
0.0,
std::f32::consts::TAU,
ArcDirection::Clockwise,
);
draw.fill();
return;
}
draw.set_stroke_style(ink);
draw.set_line_width(line_width);
draw.set_line_cap(LineCap::Round);
draw.set_line_join(LineJoin::Round);
draw.begin_path();
draw.move_to(first_x, first_y);
if points.len() == 2 {
draw.line_to(points[1].0, points[1].1);
} else {
for pair in points[1..].windows(2) {
let ((x, y), (next_x, next_y)) = (pair[0], pair[1]);
draw.quadratic_curve_to(x, y, (x + next_x) / 2.0, (y + next_y) / 2.0);
}
let (last_x, last_y) = points[points.len() - 1];
draw.line_to(last_x, last_y);
}
draw.stroke();
}
const LEAST_STEP: f32 = 0.75;
pub type SignaturePadRenderer = Arc<dyn Fn(SignaturePadView) -> Element + Send + Sync>;
type Told = Arc<dyn Fn(&Signature) + Send + Sync>;
pub struct SignaturePad {
value: Signature,
bound: Option<Signal<Signature>>,
on_change: Vec<Told>,
label: Option<Arc<str>>,
placeholder: Option<Arc<str>>,
undo_label: Option<Arc<str>>,
clear_label: Option<Arc<str>>,
signed_text: Option<Arc<str>>,
empty_text: Option<Arc<str>>,
locale: Option<crate::core::InputWords>,
read_only: bool,
disabled: bool,
invalid: bool,
full_width: bool,
width: Option<Length>,
height: Option<Length>,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
key: Option<Arc<str>>,
}
impl SignaturePad {
fn of(value: Signature, bound: Option<Signal<Signature>>) -> Self {
Self {
value,
bound,
on_change: Vec::new(),
label: None,
placeholder: None,
undo_label: None,
clear_label: None,
signed_text: None,
empty_text: None,
locale: None,
read_only: false,
disabled: false,
invalid: false,
full_width: false,
width: None,
height: None,
states: Vec::new(),
rules: Recipe::new(),
forced: None,
id: None,
key: None,
}
}
pub fn new(signature: Signal<Signature>) -> Self {
Self::of(signature.get(), Some(signature))
}
pub fn controlled(signature: Signature, on_change: impl Fn(&Signature) + Send + Sync + 'static) -> Self {
Self::of(signature, None).on_change(on_change)
}
pub fn on_change(mut self, handler: impl Fn(&Signature) + Send + Sync + 'static) -> Self {
self.on_change.push(Arc::new(handler));
self
}
pub fn label(mut self, label: &str) -> Self {
self.label = Some(Arc::from(label));
self
}
pub fn placeholder(mut self, placeholder: &str) -> Self {
self.placeholder = Some(Arc::from(placeholder));
self
}
pub fn undo_label(mut self, label: &str) -> Self {
self.undo_label = Some(Arc::from(label));
self
}
pub fn clear_label(mut self, label: &str) -> Self {
self.clear_label = Some(Arc::from(label));
self
}
pub fn signed_text(mut self, text: &str) -> Self {
self.signed_text = Some(Arc::from(text));
self
}
pub fn empty_text(mut self, text: &str) -> Self {
self.empty_text = Some(Arc::from(text));
self
}
pub fn locale(mut self, locale: &crate::core::Locale) -> Self {
self.locale = Some(locale.input.clone());
self
}
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
pub fn disabled(mut self, disabled: bool) -> Self {
self.disabled = disabled;
self
}
pub fn invalid(mut self, invalid: bool) -> Self {
self.invalid = invalid;
self
}
pub fn full_width(mut self, full_width: bool) -> Self {
self.full_width = full_width;
self
}
pub fn width(mut self, width: impl Into<Length>) -> Self {
self.width = Some(width.into());
self
}
pub fn height(mut self, height: impl Into<Length>) -> Self {
self.height = Some(height.into());
self
}
pub fn state(mut self, state: impl Into<Name>, on: bool) -> Self {
let state = state.into();
self.states.retain(|held| *held != state);
if on {
self.states.push(state);
}
self
}
pub fn style(mut self, part: impl Into<Name>, style: impl FnOnce(PartStyle) -> PartStyle) -> Self {
self.rules = self.rules.base(part, style);
self
}
pub fn rules(mut self, rules: &Recipe) -> Self {
self.rules = self.rules.extend(rules);
self
}
pub fn force(mut self, interaction: Option<Interaction>) -> Self {
self.forced = interaction;
self
}
pub fn id(mut self, id: impl Into<Arc<str>>) -> Self {
self.id = Some(id.into());
self
}
pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
self.key = Some(key.into());
self
}
pub fn build(self, theme: &Theme) -> Element {
self.core().build(theme, None)
}
pub fn mount(self, ctx: &mut Ctx) -> Element {
let key = self.key.clone();
let props = SignaturePadProps(self.core());
match key {
Some(key) => ctx.mount_keyed::<SignaturePadHost>(&key, props),
None => ctx.mount::<SignaturePadHost>(props),
}
}
fn core(self) -> Core {
let (bound, handlers) = (self.bound, self.on_change);
let current: Arc<dyn Fn() -> Signature + Send + Sync> = match &bound {
Some(signal) => {
let signal = signal.clone();
Arc::new(move || signal.get_untracked())
}
None => {
let value = self.value.clone();
Arc::new(move || value.clone())
}
};
let change: Told = Arc::new(move |signature: &Signature| {
if let Some(signal) = &bound {
signal.set(signature.clone());
}
for handler in &handlers {
handler(signature);
}
});
let mut rules = self.rules;
if let Some(width) = self.width {
rules = rules.base(SignaturePadPart::Root, move |s| s.width(width));
}
if self.full_width {
rules = rules.base(SignaturePadPart::Root, |s| s.width(Length::Fill));
}
if let Some(height) = self.height {
rules = rules.base(SignaturePadPart::Root, move |s| s.height(height));
}
let words = self.locale.unwrap_or_else(|| super::current_locale().input.clone());
Core {
value: self.value,
current,
change,
label: self.label.unwrap_or(words.signature),
placeholder: self.placeholder.unwrap_or(words.sign_above_the_line),
undo_label: self.undo_label.unwrap_or(words.undo),
clear_label: self.clear_label.unwrap_or(words.clear),
signed_text: self.signed_text.unwrap_or(words.signed),
empty_text: self.empty_text.unwrap_or(words.not_signed),
read_only: self.read_only,
disabled: self.disabled,
invalid: self.invalid,
states: self.states,
rules,
forced: self.forced,
id: self.id,
}
}
}
impl From<SignaturePad> for Element {
fn from(pad: SignaturePad) -> Self {
let key = pad.key.clone();
let props = SignaturePadProps(pad.core());
match key {
Some(key) => Element::component_keyed::<SignaturePadHost>(key, props),
None => Element::component::<SignaturePadHost>(props),
}
}
}
#[derive(Clone)]
struct Core {
value: Signature,
current: Arc<dyn Fn() -> Signature + Send + Sync>,
change: Told,
label: Arc<str>,
placeholder: Arc<str>,
undo_label: Arc<str>,
clear_label: Arc<str>,
signed_text: Arc<str>,
empty_text: Arc<str>,
read_only: bool,
disabled: bool,
invalid: bool,
states: Vec<Name>,
rules: Recipe,
forced: Option<Interaction>,
id: Option<Arc<str>>,
}
#[derive(Clone)]
struct Live {
draft: Arc<Mutex<Option<Draft>>>,
drawn: Signal<u64>,
surface: ElementRef,
root: ElementRef,
history: Arc<Mutex<History>>,
}
#[derive(Default)]
struct History {
past: Vec<Signature>,
future: Vec<Signature>,
told: Option<Signature>,
}
impl History {
fn follow(&mut self, now: &Signature) {
if self.told.as_ref() != Some(now) {
self.past.clear();
self.future.clear();
}
}
fn change(&mut self, before: Signature, after: &Signature) {
self.follow(&before);
self.past.push(before);
self.future.clear();
self.told = Some(after.clone());
}
}
struct Draft {
points: Vec<SignaturePoint>,
began: Instant,
finger: Option<u64>,
}
impl Live {
fn redraw(&self) {
self.drawn.set(self.drawn.get_untracked().wrapping_add(1));
}
fn local(&self, x: f32, y: f32) -> (f32, f32) {
let bounds = self.surface.bounds();
(
(x - bounds.x).clamp(0.0, bounds.width.max(0.0)),
(y - bounds.y).clamp(0.0, bounds.height.max(0.0)),
)
}
fn begin(&self, x: f32, y: f32, pressure: Option<f32>, finger: Option<u64>) -> bool {
let mut draft = self.draft.lock().unwrap();
if draft.is_some() {
return false;
}
let (x, y) = self.local(x, y);
*draft = Some(Draft {
points: vec![SignaturePoint {
x,
y,
pressure,
time: 0,
}],
began: Instant::now(),
finger,
});
drop(draft);
self.redraw();
true
}
fn extend(&self, x: f32, y: f32, pressure: Option<f32>, finger: Option<u64>) {
let (x, y) = self.local(x, y);
let mut held = self.draft.lock().unwrap();
let Some(draft) = held.as_mut().filter(|draft| draft.finger == finger) else {
return;
};
if let Some(last) = draft.points.last()
&& (last.x - x).hypot(last.y - y) < LEAST_STEP
{
return;
}
let time = u32::try_from(draft.began.elapsed().as_millis()).unwrap_or(u32::MAX);
draft.points.push(SignaturePoint { x, y, pressure, time });
drop(held);
self.redraw();
}
fn end(&self, finger: Option<u64>) -> Option<Vec<SignaturePoint>> {
let mut held = self.draft.lock().unwrap();
if held.as_ref().is_none_or(|draft| draft.finger != finger) {
return None;
}
let draft = held.take()?;
drop(held);
self.redraw();
Some(draft.points)
}
fn cancel(&self, finger: Option<u64>) {
let mut held = self.draft.lock().unwrap();
if held.as_ref().is_some_and(|draft| draft.finger == finger) {
*held = None;
drop(held);
self.redraw();
}
}
}
impl Core {
fn build(self, theme: &Theme, live: Option<Live>) -> Element {
let interactive = !self.read_only && !self.disabled;
let draft: Vec<SignaturePoint> = live
.as_ref()
.and_then(|live| {
let _ = live.drawn.get();
live.draft.lock().unwrap().as_ref().map(|draft| draft.points.clone())
})
.unwrap_or_default();
let signed = !self.value.is_empty();
let case = Case {
variant: None,
size: None,
density: None,
breakpoint: super::current_breakpoint(),
states: self.states.clone(),
}
.state(SignaturePadState::Empty, !signed)
.state(SignaturePadState::Signed, signed)
.state(SignaturePadState::Drawing, !draft.is_empty())
.state(SignaturePadState::Interactive, interactive)
.state(SignaturePadState::ReadOnly, self.read_only)
.state(SignaturePadState::Invalid, self.invalid)
.state(SignaturePadState::Disabled, self.disabled);
let recipe = theme
.resolve::<SignaturePad>(&case, Some(&self.rules))
.owned_by(self.id.as_ref());
let view = SignaturePadView {
signature: self.value.clone(),
draft,
label: self.label.clone(),
placeholder: self.placeholder.clone(),
undo_label: self.undo_label.clone(),
clear_label: self.clear_label.clone(),
read_only: self.read_only,
disabled: self.disabled,
invalid: self.invalid,
recipe,
live: live.filter(|_| interactive),
core: self,
};
match theme.renderer::<SignaturePad>() {
Some(renderer) => renderer(view),
None => view.render(),
}
}
}
pub struct SignaturePadView {
pub signature: Signature,
pub draft: Vec<SignaturePoint>,
pub label: Arc<str>,
pub placeholder: Arc<str>,
pub undo_label: Arc<str>,
pub clear_label: Arc<str>,
pub read_only: bool,
pub disabled: bool,
pub invalid: bool,
pub recipe: ResolvedRecipe,
live: Option<Live>,
core: Core,
}
impl SignaturePadView {
pub fn part(&self, part: impl Into<Name>) -> ResolvedPart {
self.recipe.part(part).forced(self.core.forced)
}
pub fn theme(&self) -> &Theme {
self.recipe.theme()
}
pub fn signed(&self) -> bool {
!self.signature.is_empty()
}
pub fn interactive(&self) -> bool {
self.live.is_some()
}
fn sub_id(&self, suffix: &str) -> Option<String> {
self.core.id.as_ref().map(|id| format!("{id}-{suffix}"))
}
fn tell(&self) -> impl Fn(Signature) + Send + Sync + Clone + 'static {
let change = self.core.change.clone();
move |next: Signature| change(&next)
}
fn takers(
&self,
live: &Live,
) -> (
impl Fn() -> bool + Send + Sync + Clone + 'static,
impl Fn() -> bool + Send + Sync + Clone + 'static,
impl Fn() + Send + Sync + Clone + 'static,
) {
let (current, tell) = (self.core.current.clone(), self.tell());
let undo = {
let (current, tell, history) = (current.clone(), tell.clone(), live.history.clone());
move || {
let now = current();
let mut history = history.lock().unwrap();
history.follow(&now);
let back = history.past.pop().or_else(|| {
let mut next = now.clone();
while next.strokes.last().is_some_and(|stroke| stroke.points.is_empty()) {
next.strokes.pop();
}
next.strokes.pop().map(|_| next)
});
let Some(back) = back else {
return false;
};
history.future.push(now);
history.told = Some(back.clone());
drop(history);
tell(back);
true
}
};
let redo = {
let (current, tell, history) = (current.clone(), tell.clone(), live.history.clone());
move || {
let now = current();
let mut history = history.lock().unwrap();
history.follow(&now);
let Some(next) = history.future.pop() else {
return false;
};
history.past.push(now);
history.told = Some(next.clone());
drop(history);
tell(next);
true
}
};
let history = live.history.clone();
let clear = move || {
let now = current();
if !now.is_empty() {
let mut next = now.clone();
next.strokes.clear();
history.lock().unwrap().change(now, &next);
tell(next);
}
};
(undo, redo, clear)
}
pub fn root(&self) -> Stack {
let said = if self.signed() {
self.core.signed_text.clone()
} else {
self.core.empty_text.clone()
};
let mut root = Stack::new()
.stack_align(StackAlignment::TopStart)
.part(&self.part(SignaturePadPart::Root))
.describe("a11y_role", "img")
.describe("a11y_name", self.label.clone())
.describe("a11y_description", said);
if self.read_only {
root = root.describe("a11y_readonly", "true");
}
if self.disabled {
root = root.describe("a11y_disabled", "true");
}
if self.invalid {
root = root.describe("a11y_invalid", "true");
}
if let Some(live) = &self.live {
let (undo, redo, clear) = self.takers(live);
let back = undo.clone();
root = root
.ref_element(live.root.clone())
.tab_index(0)
.on_undo(move |event: EditEvent| {
if !undo() {
event.pass_on();
}
})
.on_redo(move |event: EditEvent| {
if !redo() {
event.pass_on();
}
})
.on_key_down(move |event: KeyboardEvent| {
if !event.focus_within || event.alt || event.ctrl || event.meta || event.composing {
return;
}
match event.key.as_str() {
"Backspace" => {
back();
}
"Delete" => clear(),
_ => return,
}
event.prevent_default();
});
}
if let Some(id) = &self.core.id {
root = root.id(id.clone());
}
root
}
pub fn surface(&self) -> Element {
let theme = self.theme();
let ink_part = self.part(SignaturePadPart::Ink);
let (ink, line_width) = (color_of(&ink_part, theme), width_of(&ink_part, theme, 2.0));
let (signature, draft) = (self.signature.clone(), self.draft.clone());
let key = paint_key(|hash| {
for stroke in signature
.strokes
.iter()
.chain(std::iter::once(&SignatureStroke::new(draft.iter().copied())))
{
hash.write_usize(stroke.points.len());
for point in &stroke.points {
hash.write_u32(point.x.to_bits());
hash.write_u32(point.y.to_bits());
}
}
hash.write_u32(signature.width.to_bits());
hash.write_u32(signature.height.to_bits());
hash.write(&[ink.r(), ink.g(), ink.b(), ink.a()]);
hash.write_u32(line_width.to_bits());
});
let mut canvas = Canvas::new()
.part(&self.part(SignaturePadPart::Surface))
.width(Dimension::Pct(100.0))
.height(Dimension::Pct(100.0))
.paint(key, move |canvas| {
let (draw, metrics) = (canvas.context_2d(), canvas.metrics());
draw.reset();
let (width, height) = (metrics.size.width, metrics.size.height);
signature.paint(&draw, width, height, ink, line_width);
let points: Vec<(f32, f32)> = draft.iter().map(|point| (point.x, point.y)).collect();
trace(&draw, &points, ink, line_width);
});
if let Some(live) = self.live.clone() {
let (current, tell) = (self.core.current.clone(), self.tell());
let finish = move |live: &Live, points: Vec<SignaturePoint>| {
let bounds = live.surface.bounds();
let mut next = current();
if next.is_empty() {
next.width = bounds.width;
next.height = bounds.height;
}
let scale = next.scale_to(bounds.width, bounds.height);
let points = points.into_iter().map(|point| SignaturePoint {
x: point.x / scale,
y: point.y / scale,
..point
});
let before = next.clone();
next.strokes.push(SignatureStroke::new(points));
live.history.lock().unwrap().change(before, &next);
tell(next);
};
let finish_touch = finish.clone();
let (on_start, on_move, on_end) = (live.clone(), live.clone(), live.clone());
let (touch_start, touch_move, touch_end, touch_cancel) = (live.clone(), live.clone(), live.clone(), live.clone());
canvas = canvas
.ref_element(live.surface.clone())
.focuses(&live.root)
.start_drag_buttons(MouseButtonMask::LEFT)
.on_drag_start(move |event: DragEvent| {
on_start.begin(event.x, event.y, None, None);
})
.on_drag_move(move |event: DragEvent| on_move.extend(event.x, event.y, None, None))
.on_drag_end(move |_: DragEvent| {
if let Some(points) = on_end.end(None) {
finish(&on_end, points);
}
})
.on_touch_start(move |event: TouchEvent| {
if touch_start.begin(event.x, event.y, event.force, Some(event.id)) {
event.prevent_default();
}
})
.on_touch_move(move |event: TouchEvent| touch_move.extend(event.x, event.y, event.force, Some(event.id)))
.on_touch_end(move |event: TouchEvent| {
if let Some(points) = touch_end.end(Some(event.id)) {
finish_touch(&touch_end, points);
}
})
.on_touch_cancel(move |event: TouchEvent| touch_cancel.cancel(Some(event.id)));
}
if let Some(id) = self.sub_id("surface") {
canvas = canvas.id(id);
}
canvas.into()
}
pub fn guide(&self) -> Element {
let placeholder = self.part(SignaturePadPart::Placeholder);
let mut guide = Column::new()
.part(&self.part(SignaturePadPart::Guide))
.width(Dimension::Pct(100.0))
.height(Dimension::Pct(100.0))
.justify(Justify::End)
.child(
Row::new()
.part(&self.part(SignaturePadPart::Baseline))
.width(Dimension::Pct(100.0)),
);
if !self.placeholder.is_empty() {
guide = guide.child(
Row::new()
.width(Dimension::Pct(100.0))
.min_width(0.0)
.child(one_line(&placeholder, &self.placeholder)),
);
}
guide.into()
}
pub fn actions(&self) -> Option<Element> {
let live = self.live.as_ref().filter(|_| self.signed())?;
let (undo, _, clear) = self.takers(live);
let strokes = self
.signature
.strokes
.iter()
.filter(|stroke| !stroke.points.is_empty())
.count();
let mut undo = Button::new(&self.undo_label)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon(icons::UNDO)
.icon_only(true)
.on_click(move |_| {
undo();
});
if strokes <= 1 {
undo = undo.focuses(&live.root);
}
let mut clear = Button::new(&self.clear_label)
.variant(ButtonVariant::Ghost)
.size(ButtonSize::Xs)
.icon(icons::TRASH)
.icon_only(true)
.focuses(&live.root)
.on_click(move |_| clear());
if let Some(id) = self.sub_id("undo") {
undo = undo.id(id);
}
if let Some(id) = self.sub_id("clear") {
clear = clear.id(id);
}
let theme = self.theme();
Some(
Row::new()
.part(&self.part(SignaturePadPart::Actions))
.width(Dimension::Pct(100.0))
.justify(Justify::End)
.align_items(Alignment::Center)
.hit_test(crate::node::HitTestBehavior::ContentOnly)
.child(undo.build(theme))
.child(clear.build(theme))
.into(),
)
}
pub fn render(self) -> Element {
let mut root = self.root().child(self.guide()).child(self.surface());
if let Some(actions) = self.actions() {
root = root.child(actions);
}
root.into()
}
}
#[derive(Clone)]
struct SignaturePadProps(Core);
impl PartialEq for SignaturePadProps {
fn eq(&self, _: &Self) -> bool {
false
}
}
impl crate::app::component::DevtoolsInspectable for SignaturePadProps {}
struct SignaturePadHost {
live: Live,
}
impl Component for SignaturePadHost {
type Props = SignaturePadProps;
fn create(ctx: &mut Ctx) -> Self {
Self {
live: Live {
draft: Arc::default(),
drawn: ctx.signal(0),
surface: ElementRef::new(),
root: ElementRef::new(),
history: Arc::default(),
},
}
}
fn render(&self, ctx: &mut Ctx) -> impl Into<Element> {
let core = ctx.props::<SignaturePadProps>().0.clone();
core.build(¤t_theme(), Some(self.live.clone()))
}
}
impl crate::ui::Styled for SignaturePad {
type Component = Self;
fn rules(self, rules: &crate::ui::Recipe) -> Self {
Self::rules(self, rules)
}
fn state(self, state: impl Into<crate::ui::Name>, on: bool) -> Self {
Self::state(self, state, on)
}
}
impl Themed for SignaturePad {
const NAME: &'static str = "signature_pad";
type Renderer = SignaturePadRenderer;
fn parts() -> crate::ui::Declared {
SignaturePadPart::declared()
}
fn states() -> crate::ui::Declared {
SignaturePadState::declared()
}
fn recipe() -> Recipe {
use PaletteColor::{Background, Destructive, Foreground, Input, MutedForeground};
use SignaturePadPart::{Actions, Baseline, Guide, Ink, Placeholder, Root, Surface};
use SignaturePadState::{Disabled, Interactive, Invalid};
Recipe::new()
.base(Root, |s| {
fading(
s.width(280.0)
.max_width(Length::Fill)
.height(124.0)
.background(Background)
.radius(RadiusSize::Lg)
.border(Border::inside(BorderSize::Sm, Input)),
)
})
.base(Guide, |s| s.padding_y(12.0).padding_x(16.0).gap(6.0))
.base(Baseline, |s| s.height(1.0).background(Input))
.base(Placeholder, |s| {
s.font_family(FontFamily::Mono)
.font_size(11.0)
.foreground(MutedForeground)
})
.base(Ink, |s| s.width(2.0).background(Foreground))
.base(Actions, |s| s.padding_x(6.0).padding_y(6.0).gap(2.0))
.focus_visible(Root, |s| s.focus_ring())
.state(Interactive, Surface, |s| s.cursor(CursorIcon::Crosshair))
.state(Invalid, Root, |s| s.border(Border::inside(BorderSize::Sm, Destructive)))
.state(Disabled, Root, |s| s.opacity(OpacityLevel::Disabled))
}
}
impl super::FieldControl for SignaturePad {
fn in_field(mut self, field: &super::InField) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.into()
}
fn mount_in_field(mut self, field: &super::InField, ctx: &mut Ctx) -> Element {
if self.label.is_none() && !field.label.is_empty() {
self.label = Some(field.label.clone());
}
self.invalid |= field.judgment == Some(super::Judgment::Invalid);
self.disabled |= field.disabled;
self.mount(ctx)
}
}