Skip to main content

navree_orm/attributes/
visibility.rs

1//! What a serialized record shows, per record and per collection: hidden
2//! and visible names, and appended accessors.
3//!
4//! A record starts with its model's lists (`#[model(hidden(..),
5//! visible(..), appends(..))]`) and can change them for itself:
6//!
7//! ```
8//! # use navree_orm::__doc_models::*;
9//! let mut tag = Record::new(Tag { id: 1, name: "vip".into(), color: "gold".into() });
10//! tag.make_hidden(["color"]);
11//! assert_eq!(tag.to_value()?, serde_json::json!({"id": 1, "name": "vip"}));
12//! tag.make_visible(["color"]).set_visible(["name"]);
13//! assert_eq!(tag.to_value()?, serde_json::json!({"name": "vip"}));
14//! # Ok::<(), navree_orm::OrmError>(())
15//! ```
16
17use std::borrow::Cow;
18
19use crate::attributes::state::Names;
20use crate::collection::Collection;
21use crate::error::{OrmError, Result};
22use crate::model::Model;
23use crate::record::Record;
24
25/// A condition for [`Record::make_visible_if`] and
26/// [`Record::make_hidden_if`]: a `bool`, or a function of the record.
27pub trait Condition<T> {
28    /// Whether the condition holds for `subject`.
29    fn holds(self, subject: &T) -> bool;
30}
31
32impl<T> Condition<T> for bool {
33    fn holds(self, _subject: &T) -> bool {
34        self
35    }
36}
37
38impl<T, F: FnOnce(&T) -> bool> Condition<T> for F {
39    fn holds(self, subject: &T) -> bool {
40        self(subject)
41    }
42}
43
44/// Names from anything that turns into them.
45fn names<N: Into<Cow<'static, str>>>(names: impl IntoIterator<Item = N>) -> Names {
46    names.into_iter().map(Into::into).collect()
47}
48
49/// `list` followed by the names of `more` it does not have yet.
50fn merged(mut list: Names, more: Names) -> Names {
51    for name in more {
52        if !list.contains(&name) {
53            list.push(name);
54        }
55    }
56    list
57}
58
59fn defaults(names: &'static [&'static str]) -> Names {
60    names.iter().map(|name| Cow::Borrowed(*name)).collect()
61}
62
63impl<M: Model> Record<M> {
64    /// The names serialized records of this record leave out.
65    pub fn hidden(&self) -> Vec<&str> {
66        match &self.attributes.hidden {
67            Some(list) => list.iter().map(AsRef::as_ref).collect(),
68            None => M::meta().hidden_names().to_vec(),
69        }
70    }
71
72    /// The only names serialized records of this record keep; empty keeps
73    /// every name.
74    pub fn visible(&self) -> Vec<&str> {
75        match &self.attributes.visible {
76            Some(list) => list.iter().map(AsRef::as_ref).collect(),
77            None => M::meta().visible_names().to_vec(),
78        }
79    }
80
81    /// The accessors serialized records of this record append.
82    pub fn appends(&self) -> Vec<&str> {
83        self.appended_names()
84    }
85
86    pub(crate) fn hidden_names(&self) -> Names {
87        self.attributes
88            .hidden
89            .clone()
90            .unwrap_or_else(|| defaults(M::meta().hidden_names()))
91    }
92
93    pub(crate) fn visible_names(&self) -> Names {
94        self.attributes
95            .visible
96            .clone()
97            .unwrap_or_else(|| defaults(M::meta().visible_names()))
98    }
99
100    pub(crate) fn appended_names(&self) -> Vec<&str> {
101        match &self.attributes.appends {
102            Some(list) => list.iter().map(AsRef::as_ref).collect(),
103            None => M::meta().appended_names().to_vec(),
104        }
105    }
106
107    /// Shows `names` again: they leave the hidden list, and join the visible
108    /// list when there is one.
109    pub fn make_visible<N: Into<Cow<'static, str>>>(
110        &mut self,
111        names: impl IntoIterator<Item = N>,
112    ) -> &mut Self {
113        let shown = self::names(names);
114        let hidden: Names = self
115            .hidden_names()
116            .into_iter()
117            .filter(|name| !shown.contains(name))
118            .collect();
119        self.attributes.hidden = Some(hidden);
120        let visible = self.visible_names();
121        if !visible.is_empty() {
122            self.attributes.visible = Some(merged(visible, shown));
123        }
124        self
125    }
126
127    /// [`make_visible`](Record::make_visible) when `condition` holds (a
128    /// `bool`, or a function of the record).
129    pub fn make_visible_if<N: Into<Cow<'static, str>>>(
130        &mut self,
131        condition: impl Condition<Self>,
132        names: impl IntoIterator<Item = N>,
133    ) -> &mut Self {
134        if condition.holds(self) {
135            self.make_visible(names);
136        }
137        self
138    }
139
140    /// Hides `names` too.
141    pub fn make_hidden<N: Into<Cow<'static, str>>>(
142        &mut self,
143        names: impl IntoIterator<Item = N>,
144    ) -> &mut Self {
145        let hidden = merged(self.hidden_names(), self::names(names));
146        self.attributes.hidden = Some(hidden);
147        self
148    }
149
150    /// [`make_hidden`](Record::make_hidden) when `condition` holds.
151    pub fn make_hidden_if<N: Into<Cow<'static, str>>>(
152        &mut self,
153        condition: impl Condition<Self>,
154        names: impl IntoIterator<Item = N>,
155    ) -> &mut Self {
156        if condition.holds(self) {
157            self.make_hidden(names);
158        }
159        self
160    }
161
162    /// Replaces the hidden names.
163    pub fn set_hidden<N: Into<Cow<'static, str>>>(
164        &mut self,
165        names: impl IntoIterator<Item = N>,
166    ) -> &mut Self {
167        self.attributes.hidden = Some(self::names(names));
168        self
169    }
170
171    /// Adds to the hidden names.
172    pub fn merge_hidden<N: Into<Cow<'static, str>>>(
173        &mut self,
174        names: impl IntoIterator<Item = N>,
175    ) -> &mut Self {
176        self.make_hidden(names)
177    }
178
179    /// Replaces the visible names (empty keeps every name).
180    pub fn set_visible<N: Into<Cow<'static, str>>>(
181        &mut self,
182        names: impl IntoIterator<Item = N>,
183    ) -> &mut Self {
184        self.attributes.visible = Some(self::names(names));
185        self
186    }
187
188    /// Adds to the visible names.
189    pub fn merge_visible<N: Into<Cow<'static, str>>>(
190        &mut self,
191        names: impl IntoIterator<Item = N>,
192    ) -> &mut Self {
193        let visible = merged(self.visible_names(), self::names(names));
194        self.attributes.visible = Some(visible);
195        self
196    }
197
198    /// Appends the accessors `names` to serialized records of this record;
199    /// a name that is not an accessor of the model is an error.
200    pub fn append<N: Into<Cow<'static, str>>>(
201        &mut self,
202        names: impl IntoIterator<Item = N>,
203    ) -> Result<&mut Self> {
204        let appends = merged(
205            self.current_appends(),
206            checked_accessors::<M>(self::names(names))?,
207        );
208        self.attributes.appends = Some(appends);
209        Ok(self)
210    }
211
212    /// Replaces the appended accessors.
213    pub fn set_appends<N: Into<Cow<'static, str>>>(
214        &mut self,
215        names: impl IntoIterator<Item = N>,
216    ) -> Result<&mut Self> {
217        self.attributes.appends = Some(checked_accessors::<M>(self::names(names))?);
218        Ok(self)
219    }
220
221    /// Adds to the appended accessors (like [`append`](Record::append)).
222    pub fn merge_appends<N: Into<Cow<'static, str>>>(
223        &mut self,
224        names: impl IntoIterator<Item = N>,
225    ) -> Result<&mut Self> {
226        self.append(names)
227    }
228
229    /// Appends no accessor.
230    pub fn without_appends(&mut self) -> &mut Self {
231        self.attributes.appends = Some(Vec::new());
232        self
233    }
234
235    /// Whether serialized records of this record append accessor `name`.
236    pub fn has_appended(&self, name: &str) -> bool {
237        self.appended_names().contains(&name)
238    }
239
240    fn current_appends(&self) -> Names {
241        self.attributes
242            .appends
243            .clone()
244            .unwrap_or_else(|| defaults(M::meta().appended_names()))
245    }
246}
247
248/// `names`, each an accessor of `M`.
249fn checked_accessors<M: Model>(names: Names) -> Result<Names> {
250    let accessors = M::accessors();
251    for name in &names {
252        if !accessors
253            .iter()
254            .any(|accessor| accessor.name() == name.as_ref())
255        {
256            let known: Vec<&str> = accessors.iter().map(|accessor| accessor.name()).collect();
257            return Err(OrmError::InvalidQuery(format!(
258                "{} has no accessor named `{name}` to append ({})",
259                M::meta().name(),
260                if known.is_empty() {
261                    "it has no #[accessors] block".to_owned()
262                } else {
263                    format!("its accessors: {}", known.join(", "))
264                }
265            )));
266        }
267    }
268    Ok(names)
269}
270
271impl<M: Model> Collection<M> {
272    /// Hides `names` in every record.
273    pub fn make_hidden<N: Into<Cow<'static, str>>>(
274        &mut self,
275        names: impl IntoIterator<Item = N>,
276    ) -> &mut Self {
277        let names = self::names(names);
278        for record in self.iter_mut() {
279            record.make_hidden(names.iter().cloned());
280        }
281        self
282    }
283
284    /// Adds to the hidden names of every record.
285    pub fn merge_hidden<N: Into<Cow<'static, str>>>(
286        &mut self,
287        names: impl IntoIterator<Item = N>,
288    ) -> &mut Self {
289        self.make_hidden(names)
290    }
291
292    /// Replaces the hidden names of every record.
293    pub fn set_hidden<N: Into<Cow<'static, str>>>(
294        &mut self,
295        names: impl IntoIterator<Item = N>,
296    ) -> &mut Self {
297        let names = self::names(names);
298        for record in self.iter_mut() {
299            record.set_hidden(names.iter().cloned());
300        }
301        self
302    }
303
304    /// Shows `names` again in every record.
305    pub fn make_visible<N: Into<Cow<'static, str>>>(
306        &mut self,
307        names: impl IntoIterator<Item = N>,
308    ) -> &mut Self {
309        let names = self::names(names);
310        for record in self.iter_mut() {
311            record.make_visible(names.iter().cloned());
312        }
313        self
314    }
315
316    /// Adds to the visible names of every record.
317    pub fn merge_visible<N: Into<Cow<'static, str>>>(
318        &mut self,
319        names: impl IntoIterator<Item = N>,
320    ) -> &mut Self {
321        let names = self::names(names);
322        for record in self.iter_mut() {
323            record.merge_visible(names.iter().cloned());
324        }
325        self
326    }
327
328    /// Replaces the visible names of every record.
329    pub fn set_visible<N: Into<Cow<'static, str>>>(
330        &mut self,
331        names: impl IntoIterator<Item = N>,
332    ) -> &mut Self {
333        let names = self::names(names);
334        for record in self.iter_mut() {
335            record.set_visible(names.iter().cloned());
336        }
337        self
338    }
339
340    /// Appends the accessors `names` to every record.
341    pub fn append<N: Into<Cow<'static, str>>>(
342        &mut self,
343        names: impl IntoIterator<Item = N>,
344    ) -> Result<&mut Self> {
345        let names = checked_accessors::<M>(self::names(names))?;
346        for record in self.iter_mut() {
347            record.append(names.iter().cloned())?;
348        }
349        Ok(self)
350    }
351
352    /// Replaces the appended accessors of every record.
353    pub fn set_appends<N: Into<Cow<'static, str>>>(
354        &mut self,
355        names: impl IntoIterator<Item = N>,
356    ) -> Result<&mut Self> {
357        let names = checked_accessors::<M>(self::names(names))?;
358        for record in self.iter_mut() {
359            record.set_appends(names.iter().cloned())?;
360        }
361        Ok(self)
362    }
363
364    /// Appends no accessor in any record.
365    pub fn without_appends(&mut self) -> &mut Self {
366        for record in self.iter_mut() {
367            record.without_appends();
368        }
369        self
370    }
371}