1use std::{borrow::Borrow, fmt, ops::Deref, sync::Arc};
6
7use super::js::{JsHost, JsIn, JsKind, JsOwned};
8use crate::{JsonValue, style::Color};
9
10#[derive(Clone)]
12pub struct SharedString(Repr);
13
14#[derive(Clone)]
15enum Repr {
16 Static(&'static str),
17 Shared(Arc<str>),
18}
19
20impl SharedString {
21 pub const fn new_static(s: &'static str) -> Self {
23 Self(Repr::Static(s))
24 }
25
26 pub fn as_str(&self) -> &str {
28 match &self.0 {
29 Repr::Static(s) => s,
30 Repr::Shared(s) => s,
31 }
32 }
33
34 pub(crate) fn to_arc(&self) -> Arc<str> {
35 match &self.0 {
36 Repr::Static(s) => Arc::from(*s),
37 Repr::Shared(s) => s.clone(),
38 }
39 }
40}
41
42impl Default for SharedString {
43 fn default() -> Self {
44 Self::new_static("")
45 }
46}
47
48impl Deref for SharedString {
49 type Target = str;
50
51 fn deref(&self) -> &str {
52 self.as_str()
53 }
54}
55
56impl AsRef<str> for SharedString {
57 fn as_ref(&self) -> &str {
58 self.as_str()
59 }
60}
61
62impl Borrow<str> for SharedString {
63 fn borrow(&self) -> &str {
64 self.as_str()
65 }
66}
67
68impl PartialEq for SharedString {
69 fn eq(&self, other: &Self) -> bool {
70 let (a, b) = (self.as_str(), other.as_str());
71 std::ptr::eq(a, b) || a == b
72 }
73}
74
75impl Eq for SharedString {}
76
77impl std::hash::Hash for SharedString {
78 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
79 self.as_str().hash(state)
80 }
81}
82
83impl PartialEq<str> for SharedString {
84 fn eq(&self, other: &str) -> bool {
85 self.as_str() == other
86 }
87}
88
89impl PartialEq<&str> for SharedString {
90 fn eq(&self, other: &&str) -> bool {
91 self.as_str() == *other
92 }
93}
94
95impl fmt::Debug for SharedString {
96 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
97 fmt::Debug::fmt(self.as_str(), f)
98 }
99}
100
101impl fmt::Display for SharedString {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 f.write_str(self.as_str())
104 }
105}
106
107impl From<&'static str> for SharedString {
108 fn from(s: &'static str) -> Self {
109 Self::new_static(s)
110 }
111}
112
113impl From<String> for SharedString {
114 fn from(s: String) -> Self {
115 Self(Repr::Shared(s.into()))
116 }
117}
118
119impl From<Arc<str>> for SharedString {
120 fn from(s: Arc<str>) -> Self {
121 Self(Repr::Shared(s))
122 }
123}
124
125impl From<&SharedString> for SharedString {
126 fn from(s: &SharedString) -> Self {
127 s.clone()
128 }
129}
130
131#[derive(Debug, Clone, PartialEq)]
133pub struct PropError(pub String);
134
135impl PropError {
136 pub fn expected(ty: &str, value: &JsonValue) -> Self {
138 let mut got = value.to_string();
139 if got.len() > 40 {
140 got.truncate(40);
141 got.push('…');
142 }
143 Self(format!("expected {ty}, got {got}"))
144 }
145}
146
147impl fmt::Display for PropError {
148 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149 f.write_str(&self.0)
150 }
151}
152
153impl std::error::Error for PropError {}
154
155#[derive(Debug, Clone, Default)]
158pub struct TsTypes {
159 types: std::collections::BTreeMap<&'static str, String>,
160}
161
162impl TsTypes {
163 pub fn declare(
166 &mut self,
167 name: &'static str,
168 declaration: impl FnOnce(&mut TsTypes) -> String,
169 ) -> String {
170 if !self.types.contains_key(name) {
171 self.types.insert(name, String::new());
173 let text = declaration(self);
174 self.types.insert(name, text);
175 }
176 name.to_owned()
177 }
178
179 pub fn class(&mut self, def: &'static super::ClassDef) -> String {
183 def.name.to_owned()
184 }
185
186 pub(crate) fn merge(&mut self, other: &TsTypes) {
188 for (name, text) in &other.types {
189 self.types.entry(name).or_insert_with(|| text.clone());
190 }
191 }
192
193 pub(crate) fn declarations(&self) -> impl Iterator<Item = &str> {
194 self.types.values().map(String::as_str)
195 }
196}
197
198pub type TsType = fn(&mut TsTypes) -> String;
200
201#[doc(hidden)]
205pub const fn ts_of<T: JsValue>() -> TsType {
206 if super::DECLARATIONS {
207 T::ts_type
208 } else {
209 |_| String::new()
210 }
211}
212
213pub trait PropEnum: JsValue {
216 fn js_name(&self) -> &'static str;
218}
219
220pub trait JsValue: Sized {
226 fn ts_type(types: &mut TsTypes) -> String;
229
230 fn from_js(value: JsIn<'_>) -> Result<Self, PropError>;
232
233 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
235}
236
237impl JsValue for bool {
238 fn ts_type(_types: &mut TsTypes) -> String {
239 "boolean".into()
240 }
241
242 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
243 value.as_bool().ok_or_else(|| value.expected("a boolean"))
244 }
245
246 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
247 Ok(JsOwned::new(host, host.new_bool(*self)))
248 }
249}
250
251pub(crate) fn fits(n: f64, signed: bool, bits: u32) -> bool {
256 if !n.is_finite() || n.fract() != 0.0 {
257 return false;
258 }
259 let (lo, hi) = if signed {
260 let half = 2f64.powi(bits as i32 - 1);
261 (-half, half)
262 } else {
263 (0.0, 2f64.powi(bits as i32))
264 };
265 n >= lo && n < hi
266}
267
268macro_rules! number {
269 ($check:ident: $($ty:ty),*) => {$(
270 impl JsValue for $ty {
271 fn ts_type(_types: &mut TsTypes) -> String {
272 "number".into()
273 }
274
275 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
276 let n = value.as_number().ok_or_else(|| value.expected("a number"))?;
277 number!(@$check $ty, n, value);
278 Ok(n as $ty)
279 }
280
281 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
283 Ok(JsOwned::new(host, host.new_number(*self as f64)))
284 }
285 }
286 )*};
287 (@any $ty:ty, $n:ident, $value:ident) => {};
289 (@whole $ty:ty, $n:ident, $value:ident) => {
290 if !fits($n, <$ty>::MIN != 0, <$ty>::BITS) {
291 return Err($value.expected(concat!("an integer that fits ", stringify!($ty))));
292 }
293 };
294}
295
296number!(any: f32, f64);
297
298impl JsValue for crate::geometry::Points {
300 fn ts_type(_types: &mut TsTypes) -> String {
301 "number".into()
302 }
303
304 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
305 f32::from_js(value).map(Self)
306 }
307
308 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
309 self.0.to_js(host)
310 }
311}
312number!(whole: i16, i32, i64, u16, u32, u64, usize);
313
314impl JsValue for crate::geometry::DevicePixels {
316 fn ts_type(types: &mut TsTypes) -> String {
317 i32::ts_type(types)
318 }
319
320 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
321 i32::from_js(value).map(Self)
322 }
323
324 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
325 self.0.to_js(host)
326 }
327}
328
329impl JsValue for crate::geometry::Size<crate::geometry::DevicePixels> {
331 fn ts_type(_types: &mut TsTypes) -> String {
332 "Size".into()
333 }
334
335 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
336 if value.kind() != JsKind::Object {
337 return Err(value.expected("an object with width and height"));
338 }
339 let side = |key: &str| -> Result<crate::geometry::DevicePixels, PropError> {
340 let v = value.field(key)?;
341 crate::geometry::DevicePixels::from_js(v.get())
342 .map_err(|e| PropError(format!("`{key}`: {e}")))
343 };
344 Ok(Self::new(side("width")?, side("height")?))
345 }
346
347 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
348 let owned = JsOwned::new(host, host.new_object()?);
349 let object = owned.get().raw();
350 host.set_field(object, "width", self.width.to_js(host)?.into_raw())?;
351 host.set_field(object, "height", self.height.to_js(host)?.into_raw())?;
352 Ok(owned)
353 }
354}
355
356impl JsValue for SharedString {
357 fn ts_type(_types: &mut TsTypes) -> String {
358 "string".into()
359 }
360
361 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
362 value
363 .as_string()
364 .map(Into::into)
365 .ok_or_else(|| value.expected("a string"))
366 }
367
368 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
369 Ok(JsOwned::new(host, host.new_string(self.as_str())?))
370 }
371}
372
373impl JsValue for String {
374 fn ts_type(_types: &mut TsTypes) -> String {
375 "string".into()
376 }
377
378 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
379 value.as_string().ok_or_else(|| value.expected("a string"))
380 }
381
382 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
383 Ok(JsOwned::new(host, host.new_string(self)?))
384 }
385}
386
387impl JsValue for crate::Hsla {
390 fn ts_type(types: &mut TsTypes) -> String {
391 Color::ts_type(types)
392 }
393
394 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
395 Color::from_js(value).map(Into::into)
396 }
397
398 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
399 Color::from(*self).to_js(host)
400 }
401}
402
403impl JsValue for Color {
405 fn ts_type(_types: &mut TsTypes) -> String {
406 "string".into()
407 }
408
409 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
410 value
411 .as_string()
412 .as_deref()
413 .and_then(Color::parse)
414 .ok_or_else(|| value.expected("a color"))
415 }
416
417 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
418 Ok(JsOwned::new(
419 host,
420 host.new_string(&format!("#{:08x}", self.0))?,
421 ))
422 }
423}
424
425#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
427pub struct NodeRef(pub crate::NodeId);
428
429impl JsValue for NodeRef {
430 fn ts_type(_types: &mut TsTypes) -> String {
431 "YNode".into()
432 }
433
434 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
435 value
436 .host()
437 .node(value.raw())
438 .map(NodeRef)
439 .ok_or_else(|| value.expected("a node"))
440 }
441
442 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
444 Ok(JsOwned::new(host, host.node_value(self.0)))
445 }
446}
447
448impl JsValue for JsonValue {
451 fn ts_type(_types: &mut TsTypes) -> String {
452 "unknown".into()
453 }
454
455 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
456 match value.kind() {
457 JsKind::Undefined => Ok(JsonValue::Null),
458 _ => value.to_json(),
459 }
460 }
461
462 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
463 Ok(JsOwned::new(host, host.json(self)?))
464 }
465}
466
467impl<T: JsValue> JsValue for Option<T> {
469 fn ts_type(types: &mut TsTypes) -> String {
470 format!("{} | null", T::ts_type(types))
471 }
472
473 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
474 if value.is_nullish() {
475 Ok(None)
476 } else {
477 T::from_js(value).map(Some)
478 }
479 }
480
481 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
482 match self {
483 Some(v) => v.to_js(host),
484 None => Ok(JsOwned::new(host, host.null())),
485 }
486 }
487}
488
489impl JsValue for Vec<u8> {
493 fn ts_type(_types: &mut TsTypes) -> String {
494 "Uint8Array".into()
495 }
496
497 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
498 value
499 .as_bytes()
500 .ok_or_else(|| value.expected("a Uint8Array"))
501 }
502
503 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
504 Ok(JsOwned::new(host, host.new_bytes(self)?))
505 }
506}
507
508impl JsValue for std::collections::BTreeMap<String, String> {
510 fn ts_type(_types: &mut TsTypes) -> String {
511 "Record<string, string>".into()
512 }
513
514 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
515 if value.kind() != JsKind::Object {
516 return Err(value.expected("an object of strings"));
517 }
518 let JsonValue::Object(fields) = value.to_json()? else {
519 return Err(value.expected("an object of strings"));
520 };
521 fields
522 .into_iter()
523 .map(|(key, v)| match v {
524 JsonValue::String(s) => Ok((key, s)),
525 other => Err(PropError::expected("a string", &other)),
526 })
527 .collect()
528 }
529
530 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
531 let object = JsOwned::new(host, host.new_object()?);
532 for (key, value) in self {
533 host.set_field(object.get().raw(), key, host.new_string(value)?)?;
534 }
535 Ok(object)
536 }
537}
538
539impl JsValue for std::time::SystemTime {
541 fn ts_type(_types: &mut TsTypes) -> String {
542 "Date".into()
543 }
544
545 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
546 let millis = value
547 .as_date()
548 .filter(|m| m.is_finite())
549 .ok_or_else(|| value.expected("a valid Date"))?;
550 let since = std::time::Duration::from_secs_f64(millis.abs() / 1000.0);
551 let time = if millis < 0.0 {
552 std::time::UNIX_EPOCH.checked_sub(since)
553 } else {
554 std::time::UNIX_EPOCH.checked_add(since)
555 };
556 time.ok_or_else(|| value.expected("a Date in range"))
557 }
558
559 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
560 let millis = match self.duration_since(std::time::UNIX_EPOCH) {
561 Ok(since) => since.as_secs_f64() * 1000.0,
562 Err(before) => -before.duration().as_secs_f64() * 1000.0,
563 };
564 Ok(JsOwned::new(host, host.new_date(millis)?))
565 }
566}
567
568impl<T: JsValue> JsValue for Vec<T> {
569 fn ts_type(types: &mut TsTypes) -> String {
570 format!("({})[]", T::ts_type(types))
571 }
572
573 fn from_js(value: JsIn<'_>) -> Result<Self, PropError> {
574 let len = value
575 .array_len()?
576 .ok_or_else(|| value.expected("an array"))?;
577 let mut out = Vec::with_capacity(len.min(1024));
580 for i in 0..len {
581 let item = value.index(i)?;
582 out.push(T::from_js(item.get()).map_err(|e| PropError(format!("[{i}]: {e}")))?);
583 }
584 Ok(out)
585 }
586
587 fn to_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
588 let mut items = Vec::with_capacity(self.len());
591 for item in self {
592 items.push(item.to_js(host)?);
593 }
594 let raws = items.into_iter().map(JsOwned::into_raw).collect();
595 Ok(JsOwned::new(host, host.new_array(raws)?))
596 }
597}