1use std::collections::{BTreeMap, BTreeSet};
6
7use nibkeep_base::{EntityId, SpaceId};
8use nibkeep_model::schema::{FIELD_DEFINITION, TYPE_DEFINITION};
9use nibkeep_model::storage::Statements;
10use nibkeep_model::{FieldDef, FieldName, Languages, Resolution, State, TypeName, Types, Value};
11use nibkeep_time::Day;
12
13use super::Library;
14use super::entities::{Listed, More, Searched, defines_types, display_name, resolve};
15use crate::NodeError;
16
17#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Links {
20 pub field: FieldName,
22 pub reverse: Option<FieldName>,
25 pub role: bool,
27 pub count: usize,
29 pub entities: Vec<Linking>,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct Linking {
37 pub id: EntityId,
39 pub name: Option<String>,
41 pub types: Vec<TypeName>,
43 pub participants: Vec<(FieldName, Vec<EntityId>)>,
46}
47
48impl Library {
49 pub fn links_to(
58 &self,
59 space: SpaceId,
60 entity: EntityId,
61 day: Day,
62 limit: usize,
63 ) -> Result<Vec<Links>, NodeError> {
64 let open = self.space(space)?;
65 open.stored.reading(|_| {
66 links_to(
67 open.stored.log().state(),
68 &open.types,
69 &self.languages,
70 (entity, Some(day)),
71 (day, limit),
72 )
73 })
74 }
75
76 pub fn links_to_on_any_day(
85 &self,
86 space: SpaceId,
87 entity: EntityId,
88 day: Day,
89 limit: usize,
90 ) -> Result<Vec<Links>, NodeError> {
91 let open = self.space(space)?;
92 open.stored.reading(|_| {
93 links_to(
94 open.stored.log().state(),
95 &open.types,
96 &self.languages,
97 (entity, None),
98 (day, limit),
99 )
100 })
101 }
102
103 pub fn same_relationship(
113 &self,
114 space: SpaceId,
115 kinds: &[TypeName],
116 values: &[(FieldName, Value)],
117 ) -> Result<Vec<EntityId>, NodeError> {
118 let open = self.space(space)?;
119 let state = open.stored.log().state();
120 let types = &open.types;
121 let mut roles: BTreeMap<&FieldName, BTreeSet<EntityId>> = BTreeMap::new();
122 for (field, value) in values {
123 if let Some(participant) = value.as_reference()
124 && types.field(field).is_some_and(|field| field.is_role())
125 {
126 roles
127 .entry(field)
128 .or_default()
129 .insert(state.canonical(participant)?);
130 }
131 }
132 let Some((first_role, first_participants)) = roles.first_key_value() else {
133 return Ok(Vec::new());
134 };
135 let Some(&first) = first_participants.first() else {
136 return Ok(Vec::new());
137 };
138 let mut same = BTreeSet::new();
139 for statement in state.referrers(first)? {
140 if statement.field != **first_role {
141 continue;
142 }
143 let candidate = state.canonical(statement.entity)?;
144 if same.contains(&candidate) || !may_link(state, candidate, first)? {
145 continue;
146 }
147 let held = state.types(candidate)?;
148 if !kinds.iter().all(|kind| held.contains(kind)) {
149 continue;
150 }
151 let mut holds_all = true;
152 for (field, participants) in &roles {
153 let mut current = BTreeSet::new();
154 for statement in state.current(candidate, field)? {
155 if let Some(reference) = statement.value.as_reference() {
156 current.insert(state.canonical(reference)?);
157 }
158 }
159 if !participants.is_subset(¤t) {
160 holds_all = false;
161 break;
162 }
163 }
164 if holds_all {
165 same.insert(candidate);
166 }
167 }
168 Ok(same.into_iter().collect())
169 }
170}
171
172pub(crate) fn may_link<S: Statements>(
175 state: &State<S>,
176 holder: EntityId,
177 entity: EntityId,
178) -> Result<bool, NodeError>
179where
180 NodeError: From<S::Error>,
181{
182 Ok(holder != entity && !state.is_deleted(holder)? && !defines_types(state, holder)?)
183}
184
185fn refers_to<S: Statements>(
187 state: &State<S>,
188 shown: &[std::borrow::Cow<'_, nibkeep_model::Statement>],
189 entity: EntityId,
190) -> Result<bool, NodeError>
191where
192 NodeError: From<S::Error>,
193{
194 for statement in shown {
195 if let Some(reference) = statement.value.as_reference()
196 && state.canonical(reference)? == entity
197 {
198 return Ok(true);
199 }
200 }
201 Ok(false)
202}
203
204fn participants<S: Statements>(
207 state: &State<S>,
208 types: &Types,
209 languages: &Languages,
210 relationship: EntityId,
211 through: &FieldName,
212 day: Day,
213) -> Result<Vec<(FieldName, Vec<EntityId>)>, NodeError>
214where
215 NodeError: From<S::Error>,
216{
217 let mut participants = Vec::new();
218 for field in state.fields(relationship)? {
219 if field == *through || !types.field(&field).is_some_and(|field| field.is_role()) {
220 continue;
221 }
222 let (shown, _) = resolve(state, types, languages, relationship, &field, day)?;
223 let mut entities = Vec::new();
224 for statement in &shown {
225 if let Some(reference) = statement.value.as_reference() {
226 let reference = state.canonical(reference)?;
227 if !entities.contains(&reference) {
228 entities.push(reference);
229 }
230 }
231 }
232 if !entities.is_empty() {
233 participants.push((field, entities));
234 }
235 }
236 Ok(participants)
237}
238
239pub(crate) fn searched_through<S: Statements>(
253 state: &State<S>,
254 (types, languages): (&Types, &Languages),
255 (hits, first): (&[EntityId], usize),
256 keep: &mut Keep<'_>,
257) -> Result<Searched, NodeError>
258where
259 NodeError: From<S::Error>,
260{
261 let listed = |id: EntityId,
262 kinds: BTreeSet<TypeName>,
263 via: Option<EntityId>|
264 -> Result<Listed, NodeError> {
265 Ok(Listed {
266 id,
267 name: display_name(state, types, languages, id)?,
268 types: kinds.into_iter().collect(),
269 via,
270 })
271 };
272 let mut seen: BTreeSet<EntityId> = hits.iter().copied().collect();
275 let by_words = found_by_words(state, hits, &mut seen)?;
276 let mut found = Vec::new();
278 let mut kept = 0_usize;
279 for (entity, kinds) in &by_words {
280 if keep(*entity, kinds)? {
281 kept += 1;
282 if found.len() < first {
283 found.push(listed(*entity, kinds.clone(), None)?);
284 }
285 }
286 }
287 if kept > first {
288 return Ok(Searched {
289 listed: found,
290 more: More::AtLeast(kept - first),
291 });
292 }
293 let searched = types.searched_fields();
297 let mut add = |entities: Vec<EntityId>,
298 via: EntityId,
299 (found, kept): (&mut Vec<Listed>, &mut usize)|
300 -> Result<Vec<EntityId>, NodeError> {
301 let mut new = Vec::new();
302 let mut listing = Vec::new();
303 for entity in entities {
304 if !seen.insert(entity) {
305 continue;
306 }
307 new.push(entity);
308 let kinds = state.types(entity)?;
309 if keep(entity, &kinds)? {
310 *kept += 1;
311 if found.len() < first {
312 listing.push(listed(entity, kinds, Some(via))?);
313 }
314 }
315 }
316 listing.sort_by_cached_key(|entity| by_name(entity.name.as_deref(), entity.id));
317 found.extend(listing);
318 Ok(new)
319 };
320 for (hit, _) in by_words {
321 let (stand_ins, linked) = linking_for_search(state, (types, &searched), hit)?;
322 let both: Vec<EntityId> = stand_ins.iter().chain(&linked).copied().collect();
323 let listed_before = found.len();
324 let added = add(both, hit, (&mut found, &mut kept))?;
325 let mut through: Vec<EntityId> = added
329 .into_iter()
330 .filter(|entity| stand_ins.contains(entity))
331 .collect();
332 if found.len() < first && through.len() > 1 {
333 let mut ordered = Vec::with_capacity(through.len());
334 for entity in through {
335 let name = match found[listed_before..]
336 .iter()
337 .find(|listed| listed.id == entity)
338 {
339 Some(listed) => listed.name.clone(),
340 None => display_name(state, types, languages, entity)?,
341 };
342 ordered.push((by_name(name.as_deref(), entity), entity));
343 }
344 ordered.sort();
345 through = ordered.into_iter().map(|(_, entity)| entity).collect();
346 }
347 for stand_in in through {
348 let (_, linked) = linking_for_search(state, (types, &searched), stand_in)?;
349 add(
350 linked.into_iter().collect(),
351 stand_in,
352 (&mut found, &mut kept),
353 )?;
354 }
355 }
356 found.truncate(first);
357 Ok(Searched {
358 more: More::Exactly(kept - found.len()),
359 listed: found,
360 })
361}
362
363fn by_name(name: Option<&str>, id: EntityId) -> (bool, Option<String>, EntityId) {
366 let name = name.map(str::to_lowercase);
367 (name.is_none(), name, id)
368}
369
370pub(crate) type Keep<'a> = dyn FnMut(EntityId, &BTreeSet<TypeName>) -> Result<bool, NodeError> + 'a;
372
373fn found_by_words<S: Statements>(
378 state: &State<S>,
379 hits: &[EntityId],
380 seen: &mut BTreeSet<EntityId>,
381) -> Result<Vec<(EntityId, BTreeSet<TypeName>)>, NodeError>
382where
383 NodeError: From<S::Error>,
384{
385 let mut found = Vec::with_capacity(hits.len());
386 for &hit in hits {
387 let kinds = state.types(hit)?;
390 if kinds.contains(&TYPE_DEFINITION)
394 || kinds.contains(&FIELD_DEFINITION)
395 || kinds.contains(&nibkeep_std::THUMBNAIL)
396 || kinds.contains(&nibkeep_governance::SPACE_NAMES)
397 {
398 continue;
399 }
400 let of = if kinds.contains(&nibkeep_std::ORIGIN) {
401 nibkeep_std::ORIGIN_OF
402 } else if kinds.contains(&nibkeep_std::CHECKOUT) {
403 nibkeep_std::CHECKOUT_OF
404 } else {
405 found.push((hit, kinds));
406 continue;
407 };
408 for file in super::files::found_at(state, (hit, &of))? {
409 if !seen.insert(file) || state.is_deleted(file)? {
410 continue;
411 }
412 let kinds = state.types(file)?;
413 if kinds.contains(&nibkeep_std::FILE) {
414 found.push((file, kinds));
415 }
416 }
417 }
418 Ok(found)
419}
420
421fn linking_for_search<S: Statements>(
426 state: &State<S>,
427 (types, searched): (&Types, &BTreeSet<FieldName>),
428 entity: EntityId,
429) -> Result<(BTreeSet<EntityId>, BTreeSet<EntityId>), NodeError>
430where
431 NodeError: From<S::Error>,
432{
433 let mut stand_ins = BTreeSet::new();
434 let mut linked = BTreeSet::new();
435 for field in searched {
436 let stands_for = types
437 .field(field)
438 .is_some_and(|definition| definition.is_stands_for());
439 for statement in state.referrers_in(entity, field)? {
440 let holder = state.canonical(statement.entity)?;
441 if !may_link(state, holder, entity)? {
442 continue;
443 }
444 if stands_for {
445 stand_ins.insert(holder);
446 } else {
447 linked.insert(holder);
448 }
449 }
450 }
451 linked.retain(|holder| !stand_ins.contains(holder));
452 Ok((stand_ins, linked))
453}
454
455pub(crate) fn links_to<S: Statements>(
459 state: &State<S>,
460 types: &Types,
461 languages: &Languages,
462 (entity, shown): (EntityId, Option<Day>),
463 (day, limit): (Day, usize),
464) -> Result<Vec<Links>, NodeError>
465where
466 NodeError: From<S::Error>,
467{
468 let entity = state.canonical(entity)?;
469 let mut linking: BTreeMap<FieldName, BTreeSet<EntityId>> = BTreeMap::new();
470 let mut checked: BTreeSet<(EntityId, FieldName)> = BTreeSet::new();
471 for statement in state.referrers(entity)? {
472 let holder = state.canonical(statement.entity)?;
473 if !checked.insert((holder, statement.field.clone())) || !may_link(state, holder, entity)? {
474 continue;
475 }
476 let counts = if let Some(day) = shown {
480 let (shown, _) = resolve(state, types, languages, holder, &statement.field, day)?;
481 refers_to(state, &shown, entity)?
482 } else {
483 let definition = types.field(&statement.field);
484 let (Resolution::Values(shown) | Resolution::Competing(shown)) =
485 state.resolve(holder, &statement.field, definition.as_ref())?;
486 refers_to(state, &shown, entity)?
487 };
488 if counts {
489 linking
490 .entry(statement.field.clone())
491 .or_default()
492 .insert(holder);
493 }
494 }
495 let mut links = Vec::new();
496 for (field, holders) in linking {
497 let definition = types.field(&field);
498 let role = definition.as_ref().is_some_and(FieldDef::is_role);
499 let mut entities = Vec::new();
500 for id in &holders {
502 entities.push(Linking {
503 id: *id,
504 name: display_name(state, types, languages, *id)?,
505 types: Vec::new(),
506 participants: Vec::new(),
507 });
508 }
509 entities.sort_by_cached_key(|linking| by_name(linking.name.as_deref(), linking.id));
510 entities.truncate(limit);
511 for linking in &mut entities {
512 linking.types = state.types(linking.id)?.into_iter().collect();
513 if role {
514 linking.participants =
515 participants(state, types, languages, linking.id, &field, day)?;
516 }
517 }
518 links.push(Links {
519 reverse: definition.and_then(|field| field.reverse().cloned()),
520 field,
521 role,
522 count: holders.len(),
523 entities,
524 });
525 }
526 Ok(links)
527}