1#![allow(unused_imports)]
2
3use crate::*;
4use pax_engine::api::LocalProperty;
5use pax_engine::api::{
6 cursor::CursorStyle, Click, Duration, EasingCurve, Event, MouseDown, MouseMove, MouseOut,
7 MouseOver, MouseUp,
8};
9use pax_engine::*;
10use pax_runtime::api::NodeContext;
11
12const DESKTOP_DRAWER_WIDTH_PX: f64 = 430.0;
13const MIN_PREVIEW_WIDTH_PX: f64 = 320.0;
14const MIN_DRAWER_WIDTH_PX: f64 = 280.0;
15const RESIZE_MIN_DELTA_PX: f64 = 2.0;
16const DRAWER_EASE_MS: u64 = 250;
17
18#[pax]
23#[engine_import_path("pax_engine")]
24#[file("reference/example_host.pax")]
25#[custom(Default)]
26pub struct ExampleHost {
27 pub title: Property<String>,
29 pub sources: Property<Vec<ExampleSource>>,
31 pub selected_source: Property<usize>,
33 pub drawer_open: Property<bool>,
35
36 pub _active_source: Property<ExampleSource>,
38 pub _source_markups: Property<Vec<String>>,
40 pub _active_source_markup: Property<String>,
42 pub _drawer_width_px: Property<f64>,
44 pub _drawer_progress: Property<f64>,
46 pub _drawer_target_open: Property<bool>,
48 pub _is_resizing_drawer: Property<bool>,
50 pub _compact_drawer: Property<bool>,
52}
53
54impl Default for ExampleHost {
55 fn default() -> Self {
56 Self {
57 title: Property::new("Example".to_string()),
58 sources: Property::new(vec![]),
59 selected_source: Property::new(0),
60 drawer_open: Property::new(false),
61 _active_source: Property::new(fallback_source()),
62 _source_markups: Property::new(vec![highlighted_code_markup(&fallback_source())]),
63 _active_source_markup: Property::new(highlighted_code_markup(&fallback_source())),
64 _drawer_width_px: Property::new(DESKTOP_DRAWER_WIDTH_PX),
65 _drawer_progress: Property::new(0.0),
66 _drawer_target_open: Property::new(false),
67 _is_resizing_drawer: Property::new(false),
68 _compact_drawer: Property::new(false),
69 }
70 }
71}
72
73impl ExampleHost {
74 pub fn on_mount(&mut self, ctx: &NodeContext) {
76 let drawer_open = self.drawer_open.get();
77 self._drawer_target_open.set(drawer_open);
78 self._drawer_progress
79 .set(if drawer_open { 1.0 } else { 0.0 });
80 self.clamp_drawer_to_host(ctx.bounds_self.get().0);
81
82 let sources = self.sources.local();
83 let selected_source = self.selected_source.local();
84 let deps = [sources.untyped(), selected_source.untyped()];
85 self._active_source.replace_with(LocalProperty::computed(
86 move || active_source(&sources.get(), selected_source.get()),
87 &deps,
88 ));
89
90 let sources_for_markup = self.sources.local();
91 let deps = [sources_for_markup.untyped()];
92 self._source_markups.replace_with(LocalProperty::computed(
93 move || source_markups(&sources_for_markup.get()),
94 &deps,
95 ));
96
97 let source_markups = self._source_markups.local();
98 let selected_source = self.selected_source.local();
99 let deps = [source_markups.untyped(), selected_source.untyped()];
100 self._active_source_markup
101 .replace_with(LocalProperty::computed(
102 move || {
103 let source_markups = source_markups.get();
104 if source_markups.is_empty() {
105 return highlighted_code_markup(&fallback_source());
106 }
107 source_markups
108 .get(selected_source.get().min(source_markups.len() - 1))
109 .cloned()
110 .unwrap_or_else(|| highlighted_code_markup(&fallback_source()))
111 },
112 &deps,
113 ));
114 }
115
116 pub fn on_pre_render(&mut self, ctx: &NodeContext) {
118 self.clamp_drawer_to_host(ctx.bounds_self.get().0);
119 let drawer_open = self.drawer_open.get();
120 if drawer_open != self._drawer_target_open.get() {
121 self._drawer_target_open.set(drawer_open);
122 self.animate_drawer_progress(drawer_open);
123 }
124 }
125
126 pub fn toggle_drawer(&mut self, _ctx: &NodeContext, _event: Event<Click>) {
128 let next_open = !self.drawer_open.get();
129 self.drawer_open.set(next_open);
130 self._drawer_target_open.set(next_open);
131 self.animate_drawer_progress(next_open);
132 }
133
134 pub fn on_resize_mouse_down(&mut self, ctx: &NodeContext, event: Event<MouseDown>) {
136 if !self.drawer_open.get() {
137 return;
138 }
139
140 let bounds = ctx.bounds_self.get();
141 let divider_px = bounds.0 - self._drawer_width_px.get();
142 if (event.mouse.x - divider_px).abs() < 12.0 {
143 self._is_resizing_drawer.set(true);
144 ctx.set_cursor(CursorStyle::EwResize);
145 }
146 }
147
148 pub fn on_split_mouse_down(&mut self, ctx: &NodeContext, _event: Event<MouseDown>) {
150 if !self.drawer_open.get() {
151 return;
152 }
153 self._is_resizing_drawer.set(true);
154 ctx.set_cursor(CursorStyle::EwResize);
155 }
156
157 pub fn on_resize_mouse_over(&mut self, ctx: &NodeContext, _event: Event<MouseOver>) {
159 ctx.set_cursor(CursorStyle::EwResize);
160 }
161
162 pub fn on_resize_mouse_out(&mut self, ctx: &NodeContext, _event: Event<MouseOut>) {
164 if !self._is_resizing_drawer.get() {
165 ctx.set_cursor(CursorStyle::Auto);
166 }
167 }
168
169 pub fn on_resize_mouse_move(&mut self, ctx: &NodeContext, event: Event<MouseMove>) {
171 if !self._is_resizing_drawer.get() {
172 return;
173 }
174
175 let bounds = ctx.bounds_self.get();
176 if bounds.0 < MIN_PREVIEW_WIDTH_PX + MIN_DRAWER_WIDTH_PX {
177 self._drawer_width_px.set_if_neq(bounds.0.max(0.0));
178 return;
179 }
180 let max_drawer_width = (bounds.0 - MIN_PREVIEW_WIDTH_PX).max(MIN_DRAWER_WIDTH_PX);
181 let drawer_width = (bounds.0 - event.mouse.x).clamp(MIN_DRAWER_WIDTH_PX, max_drawer_width);
182 if (drawer_width - self._drawer_width_px.get()).abs() >= RESIZE_MIN_DELTA_PX {
183 self._drawer_width_px.set(drawer_width);
184 }
185 }
186
187 pub fn on_resize_mouse_up(&mut self, ctx: &NodeContext, _event: Event<MouseUp>) {
189 self._is_resizing_drawer.set(false);
190 ctx.set_cursor(CursorStyle::Auto);
191 }
192
193 fn animate_drawer_progress(&self, open: bool) {
194 let target = if open { 1.0 } else { 0.0 };
195 self._drawer_progress.local().ease_to(
196 target,
197 Duration::Milliseconds(DRAWER_EASE_MS.into()),
198 EasingCurve::InQuad,
199 );
200 }
201
202 fn clamp_drawer_to_host(&self, host_width: f64) {
203 let Some((compact_drawer, next_width)) =
204 clamped_drawer_layout(host_width, self._drawer_width_px.get())
205 else {
206 return;
207 };
208 self._compact_drawer.set_if_neq(compact_drawer);
209 self._drawer_width_px.set_if_neq(next_width);
210 }
211}
212
213fn clamped_drawer_layout(host_width: f64, current_width: f64) -> Option<(bool, f64)> {
214 if host_width <= 0.0 {
215 return None;
216 }
217 let compact_drawer = host_width < MIN_PREVIEW_WIDTH_PX + MIN_DRAWER_WIDTH_PX;
218 let width = if compact_drawer {
219 host_width
220 } else {
221 current_width.clamp(MIN_DRAWER_WIDTH_PX, host_width - MIN_PREVIEW_WIDTH_PX)
222 };
223 Some((compact_drawer, width))
224}
225
226#[pax]
228#[engine_import_path("pax_engine")]
229pub struct ExampleSource {
230 pub label: String,
232 pub language: String,
234 pub code: String,
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 #[test]
243 fn compact_drawer_replaces_preview_at_narrow_widths() {
244 assert_eq!(clamped_drawer_layout(390.0, 430.0), Some((true, 390.0)));
245 }
246
247 #[test]
248 fn wide_drawer_preserves_preview_and_clamps_to_available_space() {
249 assert_eq!(clamped_drawer_layout(1_280.0, 430.0), Some((false, 430.0)));
250 assert_eq!(
251 clamped_drawer_layout(1_280.0, 1_100.0),
252 Some((false, 960.0))
253 );
254 }
255}
256
257#[pax]
259#[engine_import_path("pax_engine")]
260#[inlined(
261 <Group width=100% height=100% @click=self.select_source>
262 <Text class="example_host_tab_label" x=50% y=50% width={100% - 16px} height=18px text={source.label} selectable=false clip=true />
263 if self.index == self.selected {
264 <Path class="example_host_tab_active" width=100% height=100% />
265 }
266 if self.index != self.selected {
267 <Path class="example_host_tab_idle" width=100% height=100% />
268 }
269 </Group>
270
271 @settings {
272 .example_host_tab_label {
273 style: TextStyle {
274 font: Font::Web("Space Grotesk", "https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600&display=swap", FontStyle::Normal, FontWeight::Medium)
275 font_size: 11px
276 fill: WHITE
277 align_vertical: TextAlignVertical::Center
278 align_horizontal: TextAlignHorizontal::Center
279 align_multiline: TextAlignHorizontal::Center
280 underline: false
281 }
282 }
283
284 .example_host_tab_active {
285 fill: rgba(61, 103, 180, 255)
286 elements: [
287 PathElement::Point(0%, 100%),
288 PathElement::Line,
289 PathElement::Point(2.5%, 17%),
290 PathElement::Quadratic(2.5%, 0%),
291 PathElement::Point(5%, 0%),
292 PathElement::Line,
293 PathElement::Point(95%, 0%),
294 PathElement::Quadratic(97.5%, 0%),
295 PathElement::Point(97.5%, 17%),
296 PathElement::Line,
297 PathElement::Point(100%, 100%),
298 PathElement::Close
299 ]
300 }
301
302 .example_host_tab_idle {
303 fill: rgba(20, 24, 32, 255)
304 elements: [
305 PathElement::Point(0%, 100%),
306 PathElement::Line,
307 PathElement::Point(2.5%, 17%),
308 PathElement::Quadratic(2.5%, 0%),
309 PathElement::Point(5%, 0%),
310 PathElement::Line,
311 PathElement::Point(95%, 0%),
312 PathElement::Quadratic(97.5%, 0%),
313 PathElement::Point(97.5%, 17%),
314 PathElement::Line,
315 PathElement::Point(100%, 100%),
316 PathElement::Close
317 ]
318 }
319 }
320)]
321pub struct ExampleHostSourceTab {
322 pub source: Property<ExampleSource>,
324 pub index: Property<usize>,
326 pub selected: Property<usize>,
328}
329
330impl ExampleHostSourceTab {
331 pub fn select_source(&mut self, _ctx: &NodeContext, _event: Event<Click>) {
333 self.selected.set(self.index.get());
334 }
335}
336
337fn active_source(sources: &[ExampleSource], selected: usize) -> ExampleSource {
338 if sources.is_empty() {
339 return fallback_source();
340 }
341 sources
342 .get(selected.min(sources.len() - 1))
343 .cloned()
344 .unwrap_or_else(fallback_source)
345}
346
347fn fallback_source() -> ExampleSource {
348 ExampleSource {
349 label: "No source".to_string(),
350 language: "text".to_string(),
351 code: "No source files were provided.".to_string(),
352 }
353}
354
355fn source_markups(sources: &[ExampleSource]) -> Vec<String> {
356 if sources.is_empty() {
357 return vec![highlighted_code_markup(&fallback_source())];
358 }
359 sources.iter().map(highlighted_code_markup).collect()
360}
361
362fn highlighted_code_markup(source: &ExampleSource) -> String {
363 let mut out = String::from(
364 "<pre data-pax-code-markup=\"example-host\" style=\"margin:0; white-space:pre; line-height:18px; color:#e0eafa;\">",
365 );
366 for line in source.code.lines() {
367 highlight_line(line, source.language.as_str(), &mut out);
368 out.push('\n');
369 }
370 out.push_str("</pre>");
371 out
372}
373
374fn highlight_line(line: &str, language: &str, out: &mut String) {
375 let bytes = line.as_bytes();
376 let mut index = 0;
377 while index < bytes.len() {
378 let rest = &line[index..];
379 if rest.starts_with("//") {
380 push_span(out, "#7f8da8", rest);
381 return;
382 }
383
384 let ch = rest.chars().next().unwrap_or_default();
385 if ch == '"' {
386 let end = string_end(rest, '"');
387 push_span(out, "#ffd166", &rest[..end]);
388 index += end;
389 continue;
390 }
391 if ch == '\'' {
392 let end = string_end(rest, '\'');
393 push_span(out, "#ffd166", &rest[..end]);
394 index += end;
395 continue;
396 }
397 if ch.is_ascii_digit() {
398 let len = token_len(rest, |c| c.is_ascii_digit() || c == '.');
399 push_span(out, "#c792ea", &rest[..len]);
400 index += len;
401 continue;
402 }
403 if is_ident_start(ch) {
404 let len = token_len(rest, is_ident_continue);
405 let token = &rest[..len];
406 if is_keyword(token, language) {
407 push_span(out, "#82aaff", token);
408 } else if token.chars().next().is_some_and(|c| c.is_ascii_uppercase()) {
409 push_span(out, "#7ee787", token);
410 } else {
411 escape_html_into(out, token);
412 }
413 index += len;
414 continue;
415 }
416 if "{}[]()<>=+-*/.,:;!&|?%@".contains(ch) {
417 push_span(out, "#89ddff", &rest[..ch.len_utf8()]);
418 index += ch.len_utf8();
419 continue;
420 }
421
422 escape_html_into(out, &rest[..ch.len_utf8()]);
423 index += ch.len_utf8();
424 }
425}
426
427fn string_end(input: &str, quote: char) -> usize {
428 let mut escaped = false;
429 for (offset, ch) in input.char_indices().skip(1) {
430 if escaped {
431 escaped = false;
432 continue;
433 }
434 if ch == '\\' {
435 escaped = true;
436 continue;
437 }
438 if ch == quote {
439 return offset + ch.len_utf8();
440 }
441 }
442 input.len()
443}
444
445fn token_len(input: &str, predicate: impl Fn(char) -> bool) -> usize {
446 input
447 .char_indices()
448 .find_map(|(offset, ch)| (!predicate(ch)).then_some(offset))
449 .unwrap_or(input.len())
450}
451
452fn is_ident_start(ch: char) -> bool {
453 ch == '_' || ch.is_ascii_alphabetic()
454}
455
456fn is_ident_continue(ch: char) -> bool {
457 is_ident_start(ch) || ch.is_ascii_digit()
458}
459
460fn is_keyword(token: &str, language: &str) -> bool {
461 matches!(
462 token,
463 "as" | "bind"
464 | "break"
465 | "const"
466 | "continue"
467 | "else"
468 | "enum"
469 | "false"
470 | "fn"
471 | "for"
472 | "if"
473 | "impl"
474 | "in"
475 | "let"
476 | "match"
477 | "mod"
478 | "move"
479 | "mut"
480 | "pub"
481 | "return"
482 | "self"
483 | "Self"
484 | "slot"
485 | "struct"
486 | "true"
487 | "type"
488 | "use"
489 | "where"
490 | "while"
491 ) || (language == "pax" && matches!(token, "import" | "settings"))
492}
493
494fn push_span(out: &mut String, color: &str, text: &str) {
495 out.push_str("<span style=\"color:");
496 out.push_str(color);
497 out.push_str("\">");
498 escape_html_into(out, text);
499 out.push_str("</span>");
500}
501
502fn escape_html_into(out: &mut String, text: &str) {
503 for ch in text.chars() {
504 match ch {
505 '&' => out.push_str("&"),
506 '<' => out.push_str("<"),
507 '>' => out.push_str(">"),
508 '"' => out.push_str("""),
509 '\'' => out.push_str("'"),
510 _ => out.push(ch),
511 }
512 }
513}