tern-sdk 0.1.0

Talk to Tern over the Tern Surface Protocol: typed node builders, diffing with derived ids, flow control, event routing, print/ask helpers and a plain-text fallback.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Typed prop values: styled text, enumerations (each with an escape hatch
//! for values newer than the SDK), sizes and actions.

use serde::{Serialize, Serializer};

/// Defines a string enumeration with an `Other` escape hatch.
macro_rules! string_enum {
	($(#[$m:meta])* $name:ident { $($(#[$vm:meta])* $var:ident = $s:literal),* $(,)? }) => {
		$(#[$m])*
		#[derive(Clone, Debug, PartialEq, Eq, Hash)]
		pub enum $name {
			$($(#[$vm])* $var,)*
			/// A value this SDK doesn't name.
			Other(String),
		}

		impl $name {
			/// The value on the wire.
			pub fn as_str(&self) -> &str {
				match self {
					$(Self::$var => $s,)*
					Self::Other(s) => s,
				}
			}
		}

		impl From<&str> for $name {
			fn from(s: &str) -> Self {
				match s {
					$($s => Self::$var,)*
					_ => Self::Other(s.to_owned()),
				}
			}
		}

		impl From<String> for $name {
			fn from(s: String) -> Self {
				Self::from(s.as_str())
			}
		}

		impl ::std::fmt::Display for $name {
			fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
				f.write_str(self.as_str())
			}
		}

		impl ::serde::Serialize for $name {
			fn serialize<S: ::serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
				s.serialize_str(self.as_str())
			}
		}
	};
}

pub(crate) use string_enum;

string_enum!(
	/// The semantic color of a node's chrome.
	Tone {
		/// Gray.
		Neutral = "neutral",
		/// The accent.
		Accent = "accent",
		/// Informational.
		Info = "info",
		/// Success.
		Success = "success",
		/// Warning.
		Warning = "warning",
		/// Error.
		Error = "error",
		/// Pending.
		Pending = "pending",
		/// Quiet.
		Muted = "muted",
		/// The user's own.
		User = "user",
	}
);

string_enum!(
	/// The state of a card or tool.
	Status {
		/// Not started.
		Pending = "pending",
		/// In progress.
		Running = "running",
		/// Finished.
		Done = "done",
		/// Failed.
		Error = "error",
		/// Stopped.
		Cancelled = "cancelled",
	}
);

string_enum!(
	/// The state of an agent.
	AgentStatus {
		/// Not started.
		Pending = "pending",
		/// In progress.
		Running = "running",
		/// Finished.
		Done = "done",
		/// Failed.
		Failed = "failed",
		/// Stopped.
		Aborted = "aborted",
		/// Waiting for work.
		Idle = "idle",
		/// Parked.
		Parked = "parked",
	}
);

string_enum!(
	/// A transient selection mark drawn over a node.
	Mark {
		/// An accent bar at the node's left.
		Pick = "pick",
		/// Dims the node.
		Drop = "drop",
	}
);

string_enum!(
	/// Space between children, or a spacer's height.
	Gap {
		/// None.
		None = "none",
		/// 2px.
		Xs = "xs",
		/// 6px.
		Sm = "sm",
		/// 10px (12px for a spacer).
		Md = "md",
		/// 16px (20px for a spacer).
		Lg = "lg",
	}
);

string_enum!(
	/// Cross-axis alignment of a row's or column's children.
	Align {
		/// Start.
		Start = "start",
		/// Center.
		Center = "center",
		/// End.
		End = "end",
		/// Text baselines.
		Baseline = "baseline",
		/// Stretch.
		Stretch = "stretch",
	}
);

string_enum!(
	/// Main-axis distribution of a row's or column's children.
	Justify {
		/// Space between.
		Between = "between",
		/// Packed at the end.
		End = "end",
	}
);

string_enum!(
	/// How text wraps.
	Wrap {
		/// Between words.
		Word = "word",
		/// Anywhere.
		Char = "char",
		/// Never.
		None = "none",
	}
);

string_enum!(
	/// Where overflowing text is cut.
	Truncate {
		/// Keep the start.
		End = "end",
		/// Keep the end.
		Start = "start",
		/// Keep both ends.
		Middle = "middle",
	}
);

string_enum!(
	/// Text alignment in a table column.
	TextAlign {
		/// Start.
		Start = "start",
		/// Center.
		Center = "center",
		/// End (numbers).
		End = "end",
	}
);

string_enum!(
	/// A span effect.
	Fx {
		/// A highlight sweeping across.
		Shimmer = "shimmer",
		/// Fades in and out.
		Pulse = "pulse",
		/// None.
		None = "none",
	}
);

string_enum!(
	/// A span style token (several join with spaces; palette tokens through
	/// `Other`).
	Token {
		/// Quiet text.
		Muted = "muted",
		/// Quieter text.
		Dim = "dim",
		/// Weight 600.
		Strong = "strong",
		/// Italic.
		Em = "em",
		/// The accent color.
		Accent = "accent",
		/// Success color.
		Success = "success",
		/// Warning color.
		Warning = "warning",
		/// Error color.
		Error = "error",
		/// Info color.
		Info = "info",
		/// An inline code chip.
		Code = "code",
		/// Tabular figures.
		Mono = "mono",
		/// A file path.
		Path = "path",
		/// A keycap.
		Key = "key",
		/// Link color.
		Link = "link",
		/// A number.
		Num = "num",
		/// Inserted text.
		Ins = "ins",
		/// Deleted text.
		Del = "del",
		/// A highlight.
		Mark = "mark",
		/// A misspelled word.
		Typo = "typo",
		/// A Nerd Font glyph.
		Icon = "icon",
		/// Not drawn.
		Hide = "hide",
	}
);

string_enum!(
	/// A spinner's indicator.
	SpinnerStyle {
		/// Braille dots.
		Braille = "braille",
		/// Three pulsing dots.
		Dots = "dots",
		/// omp's thinking glyph.
		Starburst = "starburst",
		/// A dot circling a ring.
		Orbit = "orbit",
	}
);

string_enum!(
	/// How a shimmer sweeps.
	ShimmerMode {
		/// Left to right, restarting.
		Classic = "classic",
		/// Back and forth.
		Kitt = "kitt",
	}
);

string_enum!(
	/// How an elapsed timer reads.
	ElapsedFormat {
		/// `1m 5s`.
		Short = "short",
		/// `1:05`.
		Clock = "clock",
	}
);

string_enum!(
	/// A meter's shape.
	MeterStyle {
		/// A rounded track.
		Bar = "bar",
		/// A ring.
		Ring = "ring",
		/// A grid of squares.
		Blocks = "blocks",
	}
);

string_enum!(
	/// Small, medium or large.
	Size {
		/// Small.
		Sm = "sm",
		/// Medium.
		Md = "md",
		/// Large.
		Lg = "lg",
	}
);

string_enum!(
	/// Which chart.
	ChartKind {
		/// A heatmap of cells.
		Heatmap = "heatmap",
		/// Bars.
		Bars = "bars",
		/// A sparkline.
		Spark = "spark",
	}
);

string_enum!(
	/// A thinking-effort rung.
	EffortLevel {
		/// 0/6.
		Off = "off",
		/// 1/6.
		Minimal = "minimal",
		/// 2/6.
		Low = "low",
		/// 3/6.
		Medium = "medium",
		/// 4/6.
		High = "high",
		/// 5/6.
		Xhigh = "xhigh",
		/// Full, on fire.
		Max = "max",
	}
);

string_enum!(
	/// How a diff lays out.
	DiffMode {
		/// One column.
		Unified = "unified",
		/// Side by side.
		Split = "split",
		/// The user's setting.
		Auto = "auto",
	}
);

string_enum!(
	/// How a `kv` lays out.
	KvLayout {
		/// Aligned rows.
		Grid = "grid",
		/// One wrapping line.
		Inline = "inline",
	}
);

string_enum!(
	/// A text's line-length cap.
	Measure {
		/// 80 cells.
		Prose = "prose",
	}
);

string_enum!(
	/// A card variant.
	CardVariant {
		/// No ring, fill or rounding.
		Bare = "bare",
	}
);

string_enum!(
	/// A picker sheet's size.
	PickerSize {
		/// Medium.
		Md = "md",
		/// Large.
		Lg = "lg",
		/// The whole pane.
		Screen = "screen",
	}
);

string_enum!(
	/// A picker's row template.
	PickerLayout {
		/// Rows.
		Rows = "rows",
		/// Cards (detail on its own line).
		Cards = "cards",
		/// A node per row.
		Timeline = "timeline",
		/// Depth guides and chevrons.
		Tree = "tree",
	}
);

string_enum!(
	/// Where a picker's preview sits.
	PickerPreview {
		/// Beside the list.
		Side = "side",
		/// Under the list.
		Below = "below",
		/// No preview.
		None = "none",
	}
);

string_enum!(
	/// Which part of a picker the keys drive.
	PickerFocus {
		/// The list.
		List = "list",
		/// The scope column.
		Scopes = "scopes",
		/// The tab row.
		Tabs = "tabs",
		/// The chip strip.
		Strip = "strip",
		/// The preview.
		Preview = "preview",
	}
);

string_enum!(
	/// A picker's state.
	PickerState {
		/// Rows shown.
		Ready = "ready",
		/// Skeleton rows.
		Loading = "loading",
		/// An error card.
		Error = "error",
	}
);

string_enum!(
	/// How a tool's string target is drawn.
	TargetKind {
		/// A shell line.
		Command = "command",
		/// A file path.
		Path = "path",
		/// A pattern in quotes.
		Pattern = "pattern",
		/// A query in quotes.
		Query = "query",
		/// Text.
		Text = "text",
	}
);

string_enum!(
	/// A tool's frame.
	ToolFrame {
		/// A ring.
		Card = "card",
		/// No ring.
		Inline = "inline",
	}
);

string_enum!(
	/// A checklist's presentation.
	ChecklistMode {
		/// The whole list.
		Full = "full",
		/// A pill.
		Hud = "hud",
		/// A reminder line.
		Reminder = "reminder",
	}
);

string_enum!(
	/// A checklist item's state.
	ItemStatus {
		/// Not started.
		Pending = "pending",
		/// In progress.
		Active = "active",
		/// Finished.
		Done = "done",
		/// Dropped.
		Dropped = "dropped",
		/// Blocked.
		Blocked = "blocked",
	}
);

string_enum!(
	/// An overlay's size.
	OverlaySize {
		/// Small.
		Sm = "sm",
		/// Medium.
		Md = "md",
		/// Large.
		Lg = "lg",
		/// A full sheet.
		Full = "full",
	}
);

string_enum!(
	/// Which group of a status strip a segment sits in.
	Side {
		/// The right group.
		Right = "right",
	}
);

string_enum!(
	/// A picker column's format.
	ColumnFormat {
		/// Text.
		Text = "text",
		/// A number.
		Num = "num",
		/// A price.
		Price = "price",
		/// A meter.
		Bar = "bar",
		/// A time.
		Time = "time",
		/// A duration.
		Elapsed = "elapsed",
		/// Dim text.
		Dim = "dim",
	}
);

string_enum!(
	/// How a `prefs` choice draws.
	ChoiceStyle {
		/// Segments when few and short, else a menu.
		Auto = "auto",
		/// Segments.
		Segmented = "segmented",
		/// A popup menu.
		Menu = "menu",
	}
);

string_enum!(
	/// The type of an `el` `input`.
	InputType {
		/// A checkbox.
		Checkbox = "checkbox",
		/// A radio.
		Radio = "radio",
	}
);

/// One styled run of text: `{t, s?, fx?, href?}`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct Span {
	/// The text.
	pub t:    String,
	/// Space-separated style tokens.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub s:    Option<String>,
	/// An effect.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub fx:   Option<Fx>,
	/// A link.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub href: Option<String>,
}

impl Span {
	/// A plain span.
	pub fn new(t: impl Into<String>) -> Self {
		Self { t: t.into(), ..Self::default() }
	}

	/// Adds a style token (or several, space-separated).
	pub fn style(mut self, token: impl Into<Token>) -> Self {
		let token = token.into();
		self.s = Some(match self.s.take() {
			Some(s) if !s.is_empty() => format!("{s} {token}"),
			_ => token.to_string(),
		});
		self
	}

	/// Sets the effect.
	pub fn fx(mut self, fx: impl Into<Fx>) -> Self {
		self.fx = Some(fx.into());
		self
	}

	/// Makes the span a link.
	pub fn href(mut self, href: impl Into<String>) -> Self {
		self.href = Some(href.into());
		self
	}
}

impl From<&str> for Span {
	fn from(t: &str) -> Self {
		Self::new(t)
	}
}

impl From<String> for Span {
	fn from(t: String) -> Self {
		Self::new(t)
	}
}

/// Text given as a plain string or as styled spans.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Text {
	/// A plain string.
	Plain(String),
	/// Styled spans.
	Spans(Vec<Span>),
}

impl Text {
	/// The text without styles.
	pub fn plain(&self) -> String {
		match self {
			Self::Plain(s) => s.clone(),
			Self::Spans(spans) => spans.iter().map(|s| s.t.as_str()).collect(),
		}
	}
}

impl Default for Text {
	fn default() -> Self {
		Self::Plain(String::new())
	}
}

impl Serialize for Text {
	fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
		match self {
			Self::Plain(t) => s.serialize_str(t),
			Self::Spans(spans) => spans.serialize(s),
		}
	}
}

impl From<&str> for Text {
	fn from(t: &str) -> Self {
		Self::Plain(t.to_owned())
	}
}

impl From<String> for Text {
	fn from(t: String) -> Self {
		Self::Plain(t)
	}
}

impl From<&String> for Text {
	fn from(t: &String) -> Self {
		Self::Plain(t.clone())
	}
}

impl From<Span> for Text {
	fn from(span: Span) -> Self {
		Self::Spans(vec![span])
	}
}

impl From<Vec<Span>> for Text {
	fn from(spans: Vec<Span>) -> Self {
		Self::Spans(spans)
	}
}

impl<const N: usize> From<[Span; N]> for Text {
	fn from(spans: [Span; N]) -> Self {
		Self::Spans(spans.into())
	}
}

/// A size bound: `"<n>ch"`, `"<n>lines"` or a fraction of the parent.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Extent {
	/// Character cells.
	Ch(f64),
	/// Text lines.
	Lines(f64),
	/// A fraction of the parent (`0.5` is half).
	Fraction(f64),
}

impl Serialize for Extent {
	fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
		match *self {
			Self::Ch(n) => s.collect_str(&format_args!("{n}ch")),
			Self::Lines(n) => s.collect_str(&format_args!("{n}lines")),
			Self::Fraction(f) => s.serialize_f64(f),
		}
	}
}

/// Size bounds `{w?, h?}` for `min` and `max`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct Bound {
	/// The width bound.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub w: Option<Extent>,
	/// The height bound.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub h: Option<Extent>,
}

impl Bound {
	/// A width bound.
	pub const fn w(w: Extent) -> Self {
		Self { w: Some(w), h: None }
	}

	/// A height bound.
	pub const fn h(h: Extent) -> Self {
		Self { w: None, h: Some(h) }
	}

	/// Both bounds.
	pub const fn wh(w: Extent, h: Extent) -> Self {
		Self { w: Some(w), h: Some(h) }
	}
}

/// A flex basis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Basis {
	/// A fraction of the parent.
	Fraction(f64),
	/// The node's own size, without shrinking.
	Content,
}

impl Serialize for Basis {
	fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
		match *self {
			Self::Fraction(f) => s.serialize_f64(f),
			Self::Content => s.serialize_str("content"),
		}
	}
}

impl From<f64> for Basis {
	fn from(f: f64) -> Self {
		Self::Fraction(f)
	}
}

/// A node key: a string, or an integer named in decimal.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum NodeKey {
	/// A string key.
	Str(String),
	/// An integer key.
	Int(i64),
}

impl Serialize for NodeKey {
	fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
		match self {
			Self::Str(k) => s.serialize_str(k),
			Self::Int(n) => s.serialize_i64(*n),
		}
	}
}

impl From<&str> for NodeKey {
	fn from(k: &str) -> Self {
		Self::Str(k.to_owned())
	}
}

impl From<String> for NodeKey {
	fn from(k: String) -> Self {
		Self::Str(k)
	}
}

impl From<&String> for NodeKey {
	fn from(k: &String) -> Self {
		Self::Str(k.clone())
	}
}

/// Implements `From<integer>` for [`NodeKey`].
macro_rules! int_key {
	($($t:ty),*) => {
		$(impl From<$t> for NodeKey {
			fn from(n: $t) -> Self {
				Self::Int(n as i64)
			}
		})*
	};
}

int_key!(i32, i64, u32, u64, usize);

/// What a pointer does on a node: `{click?, dblclick?, menu?}`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize)]
pub struct Actions {
	/// The click action.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub click:    Option<String>,
	/// The double-click action.
	#[serde(skip_serializing_if = "Option::is_none")]
	pub dblclick: Option<String>,
	/// Context-menu actions.
	#[serde(skip_serializing_if = "Vec::is_empty")]
	pub menu:     Vec<String>,
}

impl Actions {
	/// No actions.
	pub fn new() -> Self {
		Self::default()
	}

	/// Sets the click action.
	pub fn click(mut self, act: impl Into<String>) -> Self {
		self.click = Some(act.into());
		self
	}

	/// Sets the double-click action.
	pub fn dblclick(mut self, act: impl Into<String>) -> Self {
		self.dblclick = Some(act.into());
		self
	}

	/// Adds a context-menu action.
	pub fn menu(mut self, act: impl Into<String>) -> Self {
		self.menu.push(act.into());
		self
	}
}