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