1use std::cell::Cell;
4use std::rc::Rc;
5
6use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
7use ailloli_ui_core::event::{Event, Key, KeyState, NamedKey};
8use ailloli_ui_core::style::{
9 Border, FlexItemStyle, InteractionState, LayoutSizeHint, LayoutStyle, Radius, StateStyle,
10};
11use ailloli_ui_core::{Color, Constraints, FontId, Offset, Rect, Size, TextStyle, Theme};
12use ailloli_ui_runtime::app::ExternalUrl;
13use ailloli_ui_runtime::component::{Binding, IntoView, Memo, View, Widget};
14use ailloli_ui_runtime::input::{ActivationPolicy, EventCtx, FocusPolicy, HoverCursorRole};
15use ailloli_ui_runtime::layout::{
16 ChildLayout, LayoutArtifact, LayoutChild, LayoutCtx, LayoutResult,
17};
18use ailloli_ui_runtime::scene::PaintCtx;
19use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawText};
20use ailloli_ui_text::{TextLayoutParams, TextSystem, WrapMode};
21
22use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
23
24#[derive(Clone, Debug)]
40pub struct LinkStyle {
41 pub text: StateStyle<TextStyle>,
43 pub focus_ring: Border,
45 pub focus_ring_offset: f32,
47}
48
49impl Default for LinkStyle {
50 fn default() -> Self {
51 let theme = Theme::default();
52 let palette = theme.palette();
53 let normal = TextStyle::new(FontId::Ui, 14, palette.accent).underline();
54 Self {
55 text: StateStyle {
56 normal,
57 hovered: Some(TextStyle::new(FontId::Ui, 14, Color::WHITE).underline()),
58 pressed: Some(normal.without_decoration()),
59 focused: None,
60 disabled: Some(
61 TextStyle::new(FontId::Ui, 14, palette.text_muted.with_alpha(0.65)).underline(),
62 ),
63 },
64 focus_ring: Border::new(1.0, palette.focus),
65 focus_ring_offset: 2.0,
66 }
67 }
68}
69
70impl LinkStyle {
71 pub fn resolve_text(&self, state: InteractionState) -> TextStyle {
89 let resolved = self.text.resolve(state);
90 TextStyle {
91 font: self.text.normal.font,
92 px_size: self.text.normal.px_size,
93 ..resolved
94 }
95 }
96
97 fn visual_inflate(&self) -> f32 {
99 let widths = self.focus_ring.layout_widths();
100 self.focus_ring_offset
101 + widths
102 .left
103 .max(widths.top)
104 .max(widths.right)
105 .max(widths.bottom)
106 }
107}
108
109enum LinkContent<A> {
111 Empty,
113 Label(String),
115 Child(View<A>),
117}
118
119pub struct Link<A = ()> {
146 pub(crate) layout: LayoutStyle,
148 pub(crate) flex_item: FlexItemStyle,
150 content: LinkContent<A>,
152 href: Option<ExternalUrl>,
154 disabled: Binding<bool>,
156 style: LinkStyle,
158}
159
160crate::impl_layout_builders!(Link);
161
162impl<A: 'static> Default for Link<A> {
163 fn default() -> Self {
164 Self::new()
165 }
166}
167
168impl<A: 'static> Link<A> {
169 pub fn new() -> Self {
182 Self {
183 layout: LayoutStyle::default(),
184 flex_item: FlexItemStyle::default(),
185 content: LinkContent::Empty,
186 href: None,
187 disabled: Binding::Static(false),
188 style: LinkStyle::default(),
189 }
190 }
191
192 pub fn with_label(label: impl Into<String>) -> Self {
205 Self {
206 content: LinkContent::Label(label.into()),
207 ..Self::new()
208 }
209 }
210
211 pub fn child(mut self, child: impl IntoView<A>) -> Self {
225 self.content = LinkContent::Child(child.into_view());
226 self
227 }
228
229 pub fn href(mut self, href: impl AsRef<str>) -> Self {
244 self.href = ExternalUrl::parse(href).ok();
245 self
246 }
247
248 pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
261 self.disabled = disabled.into();
262 self
263 }
264
265 pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
276 self.disabled(disabled)
277 }
278
279 pub fn style(mut self, style: TextStyle) -> Self {
294 self.style.text.normal = style;
295 self
296 }
297
298 pub fn link_style(mut self, style: LinkStyle) -> Self {
308 self.style = style;
309 self
310 }
311}
312
313struct LinkWidget {
315 layout: LayoutStyle,
317 href: Option<ExternalUrl>,
319 disabled: Binding<bool>,
321 style: LinkStyle,
323 laid_out_content: Cell<bool>,
325 interaction: Rc<Cell<InteractionState>>,
327}
328
329impl<A: 'static> Widget<A> for LinkWidget {
330 fn debug_name(&self) -> &'static str {
331 "Link"
332 }
333
334 fn layout(
335 &self,
336 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
337 ctx: &mut LayoutCtx<'_>,
338 children: &mut [LayoutChild],
339 constraints: Constraints,
340 ) -> LayoutResult {
341 let mut child_layouts = Vec::new();
342 let mut intrinsic = Size::default();
343 if let Some(child) = children.first_mut() {
344 let result = child.layout(engine, ctx, constraints.loosen());
345 intrinsic = result.size;
346 child_layouts.push(ChildLayout {
347 offset: Offset::default(),
348 size: result.size,
349 paint_bounds: Rect::new(0.0, 0.0, result.size.w, result.size.h),
350 visual_bounds: result.visual_bounds,
351 });
352 }
353 let size = apply_layout_size(intrinsic, self.layout, constraints);
354 self.laid_out_content.set(size.w > 0.0 && size.h > 0.0);
355 let paint_bounds = Rect::new(0.0, 0.0, size.w, size.h);
356 let inflate = self.style.visual_inflate();
357 LayoutResult {
358 size,
359 children: child_layouts,
360 paint_bounds,
361 visual_bounds: paint_bounds.inflate(inflate, inflate),
362 overlay_hit_bounds: Vec::new(),
363 clip: None,
364 is_window_root_clip: false,
365 artifact: None,
366 }
367 }
368
369 fn paint(&self, ctx: &mut PaintCtx<'_>, _bounds: Rect, _layout: &LayoutResult) {
370 let input = ctx.interaction();
371 self.interaction.set(InteractionState {
372 hovered: input.hovered,
373 pressed: input.pressed,
374 focused: input.focused,
375 disabled: self.disabled.read() || self.href.is_none(),
376 });
377 }
378
379 fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
380 let state = self.interaction.get();
381 if state.focused && !state.disabled && self.style.focus_ring.is_visible() {
382 ctx.push(DrawCmd::Border(DrawBorder {
383 rect: bounds.inflate(self.style.focus_ring_offset, self.style.focus_ring_offset),
384 radius: Radius::uniform(self.style.focus_ring_offset),
385 border: self.style.focus_ring,
386 }));
387 }
388 }
389
390 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
391 if self.disabled.read() || !self.laid_out_content.get() {
392 return;
393 }
394 let Some(href) = self.href.as_ref() else {
395 return;
396 };
397 let activate = match event {
398 Event::Pointer(PointerEvent::Button {
399 pos,
400 button: MouseButton::Left,
401 pressed: false,
402 ..
403 }) => bounds.contains(pos.x, pos.y),
404 Event::Keyboard(key) => {
405 key.state == KeyState::Pressed
406 && !key.repeat
407 && matches!(&key.key, Key::Named(NamedKey::Enter))
408 }
409 _ => false,
410 };
411 if activate {
412 let _ = ctx.open_external_url(href);
413 ctx.stop_propagation();
414 }
415 }
416
417 fn focus_policy(&self) -> FocusPolicy {
418 if self.href.is_some() && !self.disabled.read() && self.laid_out_content.get() {
419 FocusPolicy::Focusable
420 } else {
421 FocusPolicy::NotFocusable
422 }
423 }
424
425 fn activation_policy(&self) -> ActivationPolicy {
426 ActivationPolicy::SuppressOnFocusOnly
427 }
428
429 fn hover_cursor_role(&self) -> HoverCursorRole {
430 if self.href.is_some() && !self.disabled.read() && self.laid_out_content.get() {
431 HoverCursorRole::Pointer
432 } else {
433 HoverCursorRole::Default
434 }
435 }
436}
437
438struct LinkLabelWidget {
440 label: String,
442 style: LinkStyle,
444 interaction: Rc<Cell<InteractionState>>,
446}
447
448fn layout_label(
450 text_system: &mut TextSystem,
451 label: &str,
452 style: TextStyle,
453) -> ailloli_ui_text::TextLayoutHandle {
454 text_system.layout_cached(TextLayoutParams {
455 text: label,
456 style,
457 max_width: None,
458 wrap_mode: WrapMode::NoWrap,
459 })
460}
461
462impl<A: 'static> Widget<A> for LinkLabelWidget {
463 fn debug_name(&self) -> &'static str {
464 "LinkLabel"
465 }
466
467 fn layout(
468 &self,
469 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
470 ctx: &mut LayoutCtx<'_>,
471 _children: &mut [LayoutChild],
472 constraints: Constraints,
473 ) -> LayoutResult {
474 let prepared = ctx
475 .text_system
476 .as_deref_mut()
477 .map(|text| layout_label(text, &self.label, self.style.text.normal));
478 let intrinsic = prepared
479 .as_ref()
480 .map(|layout| Size::new(layout.metrics.width, layout.metrics.height))
481 .unwrap_or_else(|| Size::new(0.0, self.style.text.normal.px_size as f32 * 1.2));
482 let size = constraints.constrain(intrinsic);
483 let bounds = Rect::new(0.0, 0.0, size.w, size.h);
484 LayoutResult {
485 size,
486 children: Vec::new(),
487 paint_bounds: bounds,
488 visual_bounds: bounds,
489 overlay_hit_bounds: Vec::new(),
490 clip: None,
491 is_window_root_clip: false,
492 artifact: prepared.map(LayoutArtifact::Text),
493 }
494 }
495
496 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, layout: &LayoutResult) {
497 let state = self.interaction.get();
498 let style = self.style.resolve_text(state);
499 let prepared = match layout.artifact.as_ref() {
500 Some(LayoutArtifact::Text(prepared)) => prepared.clone(),
501 None => {
502 let Some(text) = ctx.text_system.as_deref_mut() else {
503 return;
504 };
505 layout_label(text, &self.label, self.style.text.normal)
506 }
507 };
508 let baseline = prepared
509 .lines
510 .first()
511 .map(|line| line.baseline_y)
512 .unwrap_or(0.0);
513 ctx.push(DrawCmd::Text(DrawText {
514 pos: [bounds.x, bounds.y + baseline],
515 color: style.color,
516 decoration: style.decoration,
517 layout: prepared,
518 }));
519 }
520}
521
522impl<A: 'static> IntoView<A> for Link<A> {
523 fn into_view(self) -> View<A> {
524 let interaction = Rc::new(Cell::new(InteractionState::default()));
525 let child = match self.content {
526 LinkContent::Empty => View::empty(),
527 LinkContent::Label(label) => View::leaf(LinkLabelWidget {
528 label,
529 style: self.style.clone(),
530 interaction: interaction.clone(),
531 }),
532 LinkContent::Child(child) => child,
533 };
534 let widget = LinkWidget {
535 layout: self.layout,
536 href: self.href,
537 disabled: self.disabled,
538 style: self.style,
539 laid_out_content: Cell::new(false),
540 interaction,
541 };
542 finish_view_sized(
543 View::node(widget, vec![child]),
544 self.flex_item,
545 LayoutSizeHint::from_layout(self.layout),
546 )
547 }
548}