1use std::fmt;
8use std::fmt::{Display, Formatter, Write as _};
9
10use colored::Colorize as _;
11use mozjs::jsapi::PromiseState;
12
13use crate::format::{Config, format_value, indent_str};
14use crate::{Context, Promise};
15
16pub fn format_promise<'cx>(cx: &'cx Context, cfg: Config, promise: &'cx Promise) -> PromiseDisplay<'cx> {
22 PromiseDisplay { cx, promise, cfg }
23}
24
25#[must_use]
26pub struct PromiseDisplay<'cx> {
27 cx: &'cx Context,
28 promise: &'cx Promise<'cx>,
29 cfg: Config,
30}
31
32impl Display for PromiseDisplay<'_> {
33 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
34 let colour = self.cfg.colours.promise;
35 let state = self.promise.state();
36
37 let state = match state {
38 PromiseState::Pending => return "Promise { <pending> }".color(colour).fmt(f),
39 PromiseState::Fulfilled => "<fulfilled>".color(colour),
40 PromiseState::Rejected => "<rejected>".color(colour),
41 };
42
43 "Promise {".color(colour).fmt(f)?;
44 let result = self.promise.result(self.cx);
45
46 if self.cfg.multiline {
47 let result = format_value(self.cx, self.cfg.depth(self.cfg.depth + 1), &result);
48
49 f.write_char('\n')?;
50 indent_str((self.cfg.indentation + self.cfg.depth + 1) as usize).fmt(f)?;
51 state.fmt(f)?;
52 f.write_char(' ')?;
53 result.fmt(f)?;
54 "\n}".color(colour).fmt(f)
55 } else {
56 let result = format_value(self.cx, self.cfg, &result);
57
58 f.write_char(' ')?;
59 state.fmt(f)?;
60 f.write_char(' ')?;
61 result.fmt(f)?;
62 " }".color(colour).fmt(f)
63 }
64 }
65}