Skip to main content

nibkeep_node/library/
listing.rs

1//! Listing the things of a space that meet conditions, in the order of a field.
2
3use std::cmp::Ordering;
4use std::collections::BTreeSet;
5
6use nibkeep_base::{EntityId, SpaceId};
7use nibkeep_model::storage::Statements;
8use nibkeep_model::{Decimal, FieldName, Languages, State, TypeName, Types, Value};
9use nibkeep_time::{Day, Start};
10
11use super::Library;
12use super::entities::{
13	Listed, PART, display_name, kept_apart, listed_from, name_on, things, with_type,
14};
15use super::links::may_link;
16use crate::NodeError;
17
18/// What [`Library::list`] lists: the things of a space, or of a type, that meet every
19/// condition, ordered by name or by a field.
20#[derive(Clone, Debug, Default, PartialEq, Eq)]
21pub struct Listing {
22	/// Only the entities of this type.
23	pub of_type: Option<TypeName>,
24	/// Only the entities whose field shows the value, for each of these: references by
25	/// the entity they refer to, or one merged with it, and names by their full text.
26	pub conditions: Vec<(FieldName, Value)>,
27	/// The field to order the entities by, by the first value it shows of each: numbers by
28	/// size, dates by when they start, text and names alphabetically without regard to
29	/// case, references by the names of what they refer to, no before yes. Entities without
30	/// such a value come last, and entities with the same value by name.
31	pub order_by: Option<FieldName>,
32	/// The day whose values the conditions and the order look at, and whose names the
33	/// entities go by, if not today.
34	pub on: Option<Day>,
35}
36
37impl Library {
38	/// The items of an ordered list of a space, in their order: the memberships that put
39	/// them in it, not deleted, by position key ([technical design: ordered lists]).
40	///
41	/// [technical design: ordered lists]: ../../../../docs/Technical-design.md#66-ordered-lists-and-long-text
42	///
43	/// # Errors
44	///
45	/// Returns an error if the library has no such space, or the space cannot be read.
46	pub fn list_members(
47		&self,
48		space: SpaceId,
49		list: EntityId,
50	) -> Result<Vec<nibkeep_log::list::Member>, NodeError> {
51		let open = self.space(space)?;
52		let state = open.stored.log().state();
53		Ok(nibkeep_log::list::members(state, state.canonical(list)?)?)
54	}
55
56	/// The things of a space, deleted ones and those that define types aside, that the
57	/// listing asks for, as they are on its day, or else `today`, ordered by name without
58	/// regard to case, unnamed ones last, unless the listing orders them by a field.
59	///
60	/// # Errors
61	///
62	/// Returns an error if the library has no such space, or the space cannot be read.
63	pub fn list(
64		&self,
65		space: SpaceId,
66		listing: &Listing,
67		today: Day,
68	) -> Result<Vec<Listed>, NodeError> {
69		let open = self.space(space)?;
70		let state = open.stored.log().state();
71		let known = (&open.types, &self.languages);
72		let day = listing.on.unwrap_or(today);
73		let mut listed = if listing.conditions.is_empty() {
74			self.entities(space, listing.of_type.as_ref())?
75		} else {
76			open.stored.reading(|stored| {
77				// Each condition's value, in the value index, narrows the candidates, except a
78				// name, compared by its full text, and a decimal or a quantity, compared by
79				// size, which the index does not hold apart.
80				let mut candidates: Option<BTreeSet<EntityId>> = None;
81				for (field, value) in &listing.conditions {
82					if matches!(
83						value,
84						Value::Name(_) | Value::Decimal(_) | Value::Quantity(_)
85					) {
86						continue;
87					}
88					let mut found = BTreeSet::new();
89					for target in targets(state, value)? {
90						found.extend(stored.find(field, &target)?);
91					}
92					candidates = Some(match candidates {
93						None => found,
94						Some(before) => before.intersection(&found).copied().collect(),
95					});
96				}
97				let candidates = match (candidates, &listing.of_type) {
98					(Some(candidates), _) => candidates,
99					(None, Some(of_type)) => with_type(stored, of_type)?,
100					(None, None) => things(state)?,
101				};
102				let mut kept = BTreeSet::new();
103				for entity in candidates {
104					let entity = state.canonical(entity)?;
105					if kept.contains(&entity)
106						|| state.is_deleted(entity)?
107						|| kept_apart(state, entity)?
108					{
109						continue;
110					}
111					if let Some(of_type) = &listing.of_type
112						&& !state.types(entity)?.contains(of_type)
113					{
114						continue;
115					}
116					let mut holds = true;
117					for (field, value) in &listing.conditions {
118						if !shows(state, known, (entity, day), field, value)? {
119							holds = false;
120							break;
121						}
122					}
123					if holds {
124						kept.insert(entity);
125					}
126				}
127				listed_from(state, known.0, known.1, (kept, PART))
128			})?
129		};
130		// On another day, entities go by the names they had then.
131		if listing.on.is_some() {
132			open.stored.reading(|_| {
133				for entity in &mut listed {
134					entity.name = name_on(state, known.0, known.1, entity.id, day)?;
135				}
136				Ok::<_, NodeError>(())
137			})?;
138			listed.sort_by_cached_key(|entity| {
139				let name = entity.name.as_deref().map(str::to_lowercase);
140				(name.is_none(), name, entity.id)
141			});
142		}
143		let Some(field) = &listing.order_by else {
144			return Ok(listed);
145		};
146		open.stored.reading(|_| {
147			let mut keyed = Vec::with_capacity(listed.len());
148			for entity in listed {
149				let key = sort_key(state, known, (entity.id, day), field)?;
150				keyed.push((key, entity));
151			}
152			// A stable sort keeps entities with the same value in the order of their names.
153			keyed.sort_by(|(left, _), (right, _)| match (left, right) {
154				(Some(left), Some(right)) => left.cmp(right),
155				(Some(_), None) => Ordering::Less,
156				(None, Some(_)) => Ordering::Greater,
157				(None, None) => Ordering::Equal,
158			});
159			Ok(keyed.into_iter().map(|(_, entity)| entity).collect())
160		})
161	}
162}
163
164impl Library {
165	/// The types that the entities of a type have, that type too, deleted entities aside:
166	/// what else they are, such as editions that are audiobooks.
167	///
168	/// # Errors
169	///
170	/// Returns an error if the library has no such space, or the space cannot be read.
171	pub fn types_with(
172		&self,
173		space: SpaceId,
174		of_type: &TypeName,
175	) -> Result<BTreeSet<TypeName>, NodeError> {
176		let open = self.space(space)?;
177		let state = open.stored.log().state();
178		open.stored.reading(|stored| {
179			let mut held = BTreeSet::from([of_type.clone()]);
180			for entity in with_type(stored, of_type)? {
181				held.extend(state.types(entity)?);
182			}
183			Ok(held)
184		})
185	}
186}
187
188/// The values whose statements can meet a condition of `value`: the value, and for a
189/// reference, a reference to each entity merged with the one it refers to.
190fn targets<S: Statements>(state: &State<S>, value: &Value) -> Result<Vec<Value>, NodeError>
191where
192	NodeError: From<S::Error>,
193{
194	let Some(entity) = value.as_reference() else {
195		return Ok(vec![value.clone()]);
196	};
197	let canonical = state.canonical(entity)?;
198	let mut targets = vec![Value::Reference(canonical)];
199	for member in state.merged(canonical)? {
200		if member != canonical {
201			targets.push(Value::Reference(member));
202		}
203	}
204	if !targets.contains(value) {
205		targets.push(value.clone());
206	}
207	Ok(targets)
208}
209
210/// The values a field of an entity shows on a day, as [`State::resolve_counted`] chooses
211/// them.
212fn shown<S: Statements>(
213	state: &State<S>,
214	(types, languages): (&Types, &Languages),
215	(entity, day): (EntityId, Day),
216	field: &FieldName,
217) -> Result<Vec<Value>, NodeError>
218where
219	NodeError: From<S::Error>,
220{
221	let definition = types.field(field);
222	let (shown, _) = state.resolve_counted(entity, field, definition.as_ref(), day, languages)?;
223	Ok(shown
224		.into_iter()
225		.map(|(statement, _)| statement.value.clone())
226		.collect())
227}
228
229/// Whether a field of an entity shows a value on a day: a reference to the entity, or to
230/// one merged with it, unless the entity is merged with it itself; a name with the same
231/// full text; and a number of the same size, a quantity in the same unit too.
232fn shows<S: Statements>(
233	state: &State<S>,
234	known: (&Types, &Languages),
235	at: (EntityId, Day),
236	field: &FieldName,
237	value: &Value,
238) -> Result<bool, NodeError>
239where
240	NodeError: From<S::Error>,
241{
242	let (entity, _) = at;
243	for shown in shown(state, known, at, field)? {
244		let same = match (&shown, value) {
245			(Value::Reference(shown), Value::Reference(wanted)) => {
246				// As links are counted: an entity merged into the one it refers to does not
247				// link to itself.
248				let wanted = state.canonical(*wanted)?;
249				state.canonical(*shown)? == wanted && may_link(state, entity, wanted)?
250			}
251			(Value::Name(shown), Value::Name(wanted)) => shown.full() == wanted.full(),
252			(Value::Quantity(shown), Value::Quantity(wanted)) => {
253				shown.unit() == wanted.unit() && size(shown.number()) == size(wanted.number())
254			}
255			(shown, wanted) => match (number(shown), number(wanted)) {
256				(Some(shown), Some(wanted)) => shown == wanted,
257				_ => shown == wanted,
258			},
259		};
260		if same {
261			return Ok(true);
262		}
263	}
264	Ok(false)
265}
266
267/// An integer or a decimal as its size: digits without trailing zeros, and a power of ten,
268/// so that 12.5 and 12.50 are one size.
269fn number(value: &Value) -> Option<(i128, i64)> {
270	match value {
271		Value::Integer(integer) => Some(size(
272			Decimal::new(i128::from(*integer), 0).expect("an integer is a decimal"),
273		)),
274		Value::Decimal(decimal) => Some(size(*decimal)),
275		_ => None,
276	}
277}
278
279/// A decimal's size, as [`number`] gives it.
280fn size(decimal: Decimal) -> (i128, i64) {
281	let (mut mantissa, mut exponent) = (decimal.mantissa(), decimal.exponent());
282	if mantissa == 0 {
283		return (0, 0);
284	}
285	while mantissa % 10 == 0 {
286		mantissa /= 10;
287		exponent += 1;
288	}
289	(mantissa, exponent)
290}
291
292/// What an entity is ordered by: the first value a field shows, if one can be ordered.
293#[derive(Clone, Debug, PartialEq)]
294enum SortKey {
295	/// No before yes.
296	Boolean(bool),
297	/// Integers and decimals, by size.
298	Number(f64),
299	/// Quantities: those in the field's unit by size, then those in other units, by unit
300	/// and size, since no unit is converted.
301	Measure(bool, String, f64),
302	/// Dates, by when they start, as a day and a second of it: an interval open at its
303	/// start, with none, before every other date.
304	Date(Option<(Day, u32)>),
305	/// Text, names and the names of what references refer to, without regard to case.
306	Text(String),
307}
308
309impl SortKey {
310	/// The place of the key's kind, so that keys of different kinds are ordered too.
311	fn rank(&self) -> u8 {
312		match self {
313			Self::Boolean(_) => 0,
314			Self::Number(_) => 1,
315			Self::Measure(..) => 2,
316			Self::Date(..) => 3,
317			Self::Text(_) => 4,
318		}
319	}
320
321	fn cmp(&self, other: &Self) -> Ordering {
322		match (self, other) {
323			(Self::Boolean(left), Self::Boolean(right)) => left.cmp(right),
324			(Self::Number(left), Self::Number(right)) => left.total_cmp(right),
325			(Self::Measure(other, unit, left), Self::Measure(other_right, unit_right, right)) => {
326				(other, unit)
327					.cmp(&(other_right, unit_right))
328					.then_with(|| left.total_cmp(right))
329			}
330			(Self::Date(left), Self::Date(right)) => left.cmp(right),
331			(Self::Text(left), Self::Text(right)) => left.cmp(right),
332			_ => self.rank().cmp(&other.rank()),
333		}
334	}
335}
336
337/// The key that orders an entity by a field: the first value it shows, if it can be
338/// ordered.
339fn sort_key<S: Statements>(
340	state: &State<S>,
341	known: (&Types, &Languages),
342	at: (EntityId, Day),
343	field: &FieldName,
344) -> Result<Option<SortKey>, NodeError>
345where
346	NodeError: From<S::Error>,
347{
348	let Some(value) = shown(state, known, at, field)?.into_iter().next() else {
349		return Ok(None);
350	};
351	let decimal = |mantissa: i128, exponent: i64| {
352		#[expect(clippy::cast_precision_loss, reason = "close enough to order by")]
353		let mantissa = mantissa as f64;
354		mantissa * 10_f64.powi(i32::try_from(exponent).unwrap_or(0))
355	};
356	Ok(match value {
357		Value::Boolean(boolean) => Some(SortKey::Boolean(boolean)),
358		#[expect(clippy::cast_precision_loss, reason = "close enough to order by")]
359		Value::Integer(integer) => Some(SortKey::Number(integer as f64)),
360		Value::Decimal(number) => Some(SortKey::Number(decimal(
361			number.mantissa(),
362			number.exponent(),
363		))),
364		Value::Quantity(quantity) => {
365			let number = quantity.number();
366			let (types, _) = known;
367			let unit = types
368				.field(field)
369				.and_then(|definition| definition.unit().map(str::to_owned));
370			Some(SortKey::Measure(
371				unit.as_deref() != Some(quantity.unit()),
372				quantity.unit().to_owned(),
373				decimal(number.mantissa(), number.exponent()),
374			))
375		}
376		Value::Date(date) => Some(match date.start() {
377			Start::BeginningOfTime => SortKey::Date(None),
378			Start::At { day, second } => SortKey::Date(Some((day, second.unwrap_or(0)))),
379		}),
380		Value::Text(text) => Some(SortKey::Text(text.to_lowercase())),
381		Value::Name(name) => Some(SortKey::Text(name.full().to_lowercase())),
382		Value::Reference(entity) => {
383			let (types, languages) = known;
384			display_name(state, types, languages, state.canonical(entity)?)?
385				.map(|name| SortKey::Text(name.to_lowercase()))
386		}
387		Value::Blob(_) | Value::Unknown(_) => None,
388	})
389}