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
use super::{Position, PositionState, RenderHtml};
use crate::{
    hydration::Cursor,
    ssr::StreamBuilder,
    view::{Mountable, Render, Renderer},
};
use throw_error::Error as AnyError;

impl<R, T, E> Render<R> for Result<T, E>
where
    T: Render<R>,
    R: Renderer,
    E: Into<AnyError> + 'static,
{
    type State = ResultState<T::State, R>;

    fn build(self) -> Self::State {
        let placeholder = R::create_placeholder();
        let state = match self {
            Ok(view) => Ok(view.build()),
            Err(e) => Err(throw_error::throw(e.into())),
        };
        ResultState { placeholder, state }
    }

    fn rebuild(self, state: &mut Self::State) {
        match (&mut state.state, self) {
            // both errors: throw the new error and replace
            (Err(prev), Err(new)) => {
                *prev = throw_error::throw(new.into());
            }
            // both Ok: need to rebuild child
            (Ok(old), Ok(new)) => {
                T::rebuild(new, old);
            }
            // Ok => Err: unmount, replace with marker, and throw
            (Ok(old), Err(err)) => {
                old.unmount();
                state.state = Err(throw_error::throw(err));
            }
            // Err => Ok: clear error and build
            (Err(err), Ok(new)) => {
                throw_error::clear(err);
                let mut new_state = new.build();
                R::try_mount_before(&mut new_state, state.placeholder.as_ref());
                state.state = Ok(new_state);
            }
        }
    }
}

/// View state for a `Result<_, _>` view.
pub struct ResultState<T, R>
where
    T: Mountable<R>,
    R: Renderer,
{
    /// Marks the location of this view.
    placeholder: R::Placeholder,
    /// The view state.
    state: Result<T, throw_error::ErrorId>,
}

impl<T, R> Drop for ResultState<T, R>
where
    T: Mountable<R>,
    R: Renderer,
{
    fn drop(&mut self) {
        // when the state is cleared, unregister this error; this item is being dropped and its
        // error should no longer be shown
        if let Err(e) = &self.state {
            throw_error::clear(e);
        }
    }
}

impl<T, R> Mountable<R> for ResultState<T, R>
where
    T: Mountable<R>,
    R: Renderer,
{
    fn unmount(&mut self) {
        if let Ok(ref mut state) = self.state {
            state.unmount();
        }
        self.placeholder.unmount();
    }

    fn mount(&mut self, parent: &R::Element, marker: Option<&R::Node>) {
        self.placeholder.mount(parent, marker);
        if let Ok(ref mut state) = self.state {
            state.mount(parent, Some(self.placeholder.as_ref()));
        }
    }

    fn insert_before_this(
        &self,
        parent: &R::Element,
        child: &mut dyn Mountable<R>,
    ) -> bool {
        if self
            .state
            .as_ref()
            .map(|n| n.insert_before_this(parent, child))
            == Ok(true)
        {
            true
        } else {
            self.placeholder.insert_before_this(parent, child)
        }
    }
}

impl<R, T, E> RenderHtml<R> for Result<T, E>
where
    T: RenderHtml<R>,
    R: Renderer,
    E: Into<AnyError> + Send + 'static,
{
    type AsyncOutput = Result<T::AsyncOutput, E>;

    const MIN_LENGTH: usize = T::MIN_LENGTH;

    async fn resolve(self) -> Self::AsyncOutput {
        match self {
            Ok(view) => Ok(view.resolve().await),
            Err(e) => Err(e),
        }
    }

    fn html_len(&self) -> usize {
        match self {
            Ok(i) => i.html_len(),
            Err(_) => 0,
        }
    }

    fn to_html_with_buf(
        self,
        buf: &mut String,
        position: &mut super::Position,
    ) {
        match self {
            Ok(inner) => inner.to_html_with_buf(buf, position),
            Err(e) => {
                throw_error::throw(e);
            }
        }
    }

    fn to_html_async_with_buf<const OUT_OF_ORDER: bool>(
        self,
        buf: &mut StreamBuilder,
        position: &mut Position,
    ) where
        Self: Sized,
    {
        match self {
            Ok(inner) => {
                inner.to_html_async_with_buf::<OUT_OF_ORDER>(buf, position)
            }
            Err(e) => {
                throw_error::throw(e);
            }
        }
    }

    fn hydrate<const FROM_SERVER: bool>(
        self,
        cursor: &Cursor<R>,
        position: &PositionState,
    ) -> Self::State {
        // hydrate the state, if it exists
        let state = self
            .map(|s| s.hydrate::<FROM_SERVER>(cursor, position))
            .map_err(|e| throw_error::throw(e.into()));

        let placeholder = cursor.next_placeholder(position);

        ResultState { placeholder, state }
    }
}