rqjs_ext/utils/
class.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3use rquickjs::{
4    atom::PredefinedAtom, class::JsClass, prelude::This, Array, Class, Ctx, Function, Object,
5    Result, Value,
6};
7
8// use crate::modules::console::CUSTOM_INSPECT_SYMBOL_DESCRIPTION;
9
10use super::{object::ObjectExt, result::OptionExt};
11
12pub trait IteratorDef<'js>
13where
14    Self: 'js + JsClass<'js> + Sized,
15{
16    fn js_entries(&self, ctx: Ctx<'js>) -> Result<Array<'js>>;
17
18    fn js_iterator(&self, ctx: Ctx<'js>) -> Result<Value<'js>> {
19        let value = self.js_entries(ctx)?;
20        let obj = value.as_object();
21        let values_fn: Function = obj.get(PredefinedAtom::Values)?;
22        values_fn.call((This(value),))
23    }
24}
25
26pub fn get_class_name(value: &Value) -> Result<Option<String>> {
27    value
28        .get_optional::<_, Object>(PredefinedAtom::Constructor)?
29        .and_then_ok(|ctor| ctor.get_optional::<_, String>(PredefinedAtom::Name))
30}
31
32#[inline(always)]
33pub fn get_class<'js, C>(provided: &Value<'js>) -> Result<Option<Class<'js, C>>>
34where
35    C: JsClass<'js>,
36{
37    if provided
38        .as_object()
39        .map(|p| p.instance_of::<C>())
40        .unwrap_or_default()
41    {
42        return Ok(Some(Class::<C>::from_value(&provided.clone())?));
43    }
44    Ok(None)
45}
46
47pub trait CustomInspectExtension<'js> {
48    fn define_with_custom_inspect(globals: &Object<'js>) -> Result<()>;
49}
50
51pub trait CustomInspect<'js>
52where
53    Self: JsClass<'js>,
54{
55    fn custom_inspect(&self, ctx: Ctx<'js>) -> Result<Object<'js>>;
56}
57
58// impl<'js, C> CustomInspectExtension<'js> for Class<'js, C>
59// where
60//     C: JsClass<'js> + CustomInspect<'js> + 'js,
61// {
62//     fn define_with_custom_inspect(globals: &Object<'js>) -> Result<()> {
63//         Self::define(globals)?;
64//         let custom_inspect_symbol =
65//             Symbol::for_description(globals, CUSTOM_INSPECT_SYMBOL_DESCRIPTION)?;
66//         if let Some(proto) = Class::<C>::prototype(globals.ctx().clone()) {
67//             proto.prop(
68//                 custom_inspect_symbol,
69//                 Accessor::from(|this: This<Class<'js, C>>, ctx| this.borrow().custom_inspect(ctx)),
70//             )?;
71//         }
72//         Ok(())
73//     }
74// }