Skip to main content

kernel/graph/
node_props.rs

1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Node-property setters and per-node query accessors.
5//!
6//! All of Graph's property mutators for individual nodes: title,
7//! thumbnail, favicon, mime hint, pinned, frame-layout hints, tags,
8//! classifications, tag-icon override, position (committed +
9//! projected), plus the per-node query accessors that sit alongside
10//! them (`node_tags`, `node_classifications`, `frame_layout_hints`,
11//! `node_projected_position`, `node_committed_position`,
12//! `projected_centroid`). Browser-runtime setters (session scroll,
13//! form draft, viewer override, compat mode, lifecycle) left with the
14//! `BrowserNodeState` sidecar (boundary pass slice C, 2026-07-09).
15//!
16//! Extracted from `graph/mod.rs` per the 2026-05-11 kernel
17//! decomposition pass. Lifecycle ops (`new`, `add_node`,
18//! `add_node_with_id`, `remove_node`, `update_node_url`,
19//! `recompute_cached_hosts`) stay in `mod.rs` since they own Graph's
20//! construction shape; everything property-setter-shaped lives here.
21
22use std::collections::HashSet;
23use std::time::{SystemTime, UNIX_EPOCH};
24
25use super::Graph;
26use super::identity::NodeKey;
27use super::node_facets::{
28    ARRANGEMENT_FRAME_LAYOUT, ARRANGEMENT_PIN, ARRANGEMENT_SPLIT_OFFER_SUPPRESSED,
29    PRESENTATION_TAGS, PROVENANCE_DERIVATIONS, PROVENANCE_IMPORT, SEMANTIC_CLASSIFICATIONS,
30    SEMANTIC_PROPERTIES, VISIT_HISTORY, VisitHistoryFacet,
31};
32use crate::types::{
33    ClassificationScheme, ClassificationStatus, FrameLayoutHint, ImageRef, ImageRole,
34    NodeClassification, NodeImportProvenance, NodeProperty, NodeTagPresentationState,
35};
36
37impl Graph {
38    pub(crate) fn set_node_title(&mut self, key: NodeKey, title: String) -> bool {
39        let Some(node) = self.inner.node_mut(key) else {
40            return false;
41        };
42        if node.title == title {
43            return false;
44        }
45        node.title = title;
46        true
47    }
48
49    /// Attach a stored image reference under `role`, reporting whether the
50    /// node changed.
51    ///
52    /// The caller stores the blob first (`pandect::image_store::
53    /// save_image`) and passes the handle; the kernel neither hashes nor
54    /// holds pixels. Because references are content-addressed, re-depositing
55    /// an unchanged image compares equal here and reports `false`, so an
56    /// identical re-capture is a no-op instead of a graph-dirtying rewrite.
57    pub(crate) fn set_node_image(
58        &mut self,
59        key: NodeKey,
60        role: ImageRole,
61        image: ImageRef,
62    ) -> bool {
63        let Some(node) = self.inner.node_mut(key) else {
64            return false;
65        };
66        if node.images.get(&role) == Some(&image) {
67            return false;
68        }
69        node.images.insert(role, image);
70        true
71    }
72
73    /// Directly bear (or clear) a nested graph on a node WITHOUT running the
74    /// delta spine — for copy/load paths building a graph that has no journal
75    /// yet (a fork re-bearing the worlds it carried as real file copies; the
76    /// component copy itself deliberately drops `nested` so two LIVE nodes
77    /// never share one world). Journaled edits go through
78    /// `GraphDelta::SetNodeNested` instead.
79    pub fn bear_nested(&mut self, key: NodeKey, nested: Option<codicil::LogId>) -> bool {
80        self.set_node_nested(key, nested)
81    }
82
83    /// Set or clear the node's borne graph (`Node.nested`). Structural
84    /// containment per the one-node ruling; journals as
85    /// `ReplaySetNodeNestedById` so installs replay attributed.
86    pub(crate) fn set_node_nested(&mut self, key: NodeKey, nested: Option<codicil::LogId>) -> bool {
87        let Some(node) = self.inner.node_mut(key) else {
88            return false;
89        };
90        if node.nested == nested {
91            return false;
92        }
93        node.nested = nested;
94        true
95    }
96
97    pub(crate) fn set_node_mime_hint(&mut self, key: NodeKey, mime_hint: Option<String>) -> bool {
98        let Some(node) = self.inner.node_mut(key) else {
99            return false;
100        };
101        if node.media_type == mime_hint {
102            return false;
103        }
104        node.media_type = mime_hint;
105        true
106    }
107
108    /// Attach or clear an out-of-line, content-addressed representation.
109    ///
110    /// The host must deposit the bytes in a muniment `BlobStore` first. The
111    /// kernel carries only the stable hash and never performs storage I/O.
112    pub(crate) fn set_node_content(
113        &mut self,
114        key: NodeKey,
115        content: Option<super::ContentHash>,
116    ) -> bool {
117        let Some(node) = self.inner.node_mut(key) else {
118            return false;
119        };
120        if node.content == content {
121            return false;
122        }
123        node.content = content;
124        if node.content.is_some() {
125            node.body = None;
126        }
127        true
128    }
129
130    pub(crate) fn set_node_pinned(&mut self, key: NodeKey, is_pinned: bool) -> bool {
131        if self.inner.node(key).is_none() {
132            return false;
133        }
134        if self.node_is_pinned(key) == Some(is_pinned) {
135            return false;
136        }
137        self.set_node_facet(key, ARRANGEMENT_PIN, &is_pinned)
138    }
139
140    pub(crate) fn append_frame_layout_hint(&mut self, key: NodeKey, hint: FrameLayoutHint) -> bool {
141        if self.inner.node(key).is_none() {
142            return false;
143        }
144        let mut hints =
145            self.node_facet_or_default::<Vec<FrameLayoutHint>>(key, ARRANGEMENT_FRAME_LAYOUT);
146        hints.push(hint);
147        self.set_node_facet(key, ARRANGEMENT_FRAME_LAYOUT, &hints)
148    }
149
150    pub(crate) fn remove_frame_layout_hint_at(&mut self, key: NodeKey, hint_index: usize) -> bool {
151        if self.inner.node(key).is_none() {
152            return false;
153        }
154        let mut hints =
155            self.node_facet_or_default::<Vec<FrameLayoutHint>>(key, ARRANGEMENT_FRAME_LAYOUT);
156        if hint_index >= hints.len() {
157            return false;
158        }
159        hints.remove(hint_index);
160        self.set_node_facet(key, ARRANGEMENT_FRAME_LAYOUT, &hints)
161    }
162
163    pub(crate) fn move_frame_layout_hint(
164        &mut self,
165        key: NodeKey,
166        from_index: usize,
167        to_index: usize,
168    ) -> bool {
169        if self.inner.node(key).is_none() {
170            return false;
171        }
172        let mut hints =
173            self.node_facet_or_default::<Vec<FrameLayoutHint>>(key, ARRANGEMENT_FRAME_LAYOUT);
174        if from_index >= hints.len() || to_index >= hints.len() || from_index == to_index {
175            return false;
176        }
177        let hint = hints.remove(from_index);
178        hints.insert(to_index, hint);
179        self.set_node_facet(key, ARRANGEMENT_FRAME_LAYOUT, &hints)
180    }
181
182    pub(crate) fn set_frame_split_offer_suppressed(
183        &mut self,
184        key: NodeKey,
185        suppressed: bool,
186    ) -> bool {
187        if self.inner.node(key).is_none() {
188            return false;
189        }
190        if self.frame_split_offer_suppressed(key) == Some(suppressed) {
191            return false;
192        }
193        self.set_node_facet(key, ARRANGEMENT_SPLIT_OFFER_SUPPRESSED, &suppressed)
194    }
195
196    pub fn frame_layout_hints(&self, key: NodeKey) -> Option<Vec<FrameLayoutHint>> {
197        self.get_node(key)?;
198        Some(self.node_facet_or_default(key, ARRANGEMENT_FRAME_LAYOUT))
199    }
200
201    pub fn frame_split_offer_suppressed(&self, key: NodeKey) -> Option<bool> {
202        self.get_node(key)?;
203        Some(self.node_facet_or_default(key, ARRANGEMENT_SPLIT_OFFER_SUPPRESSED))
204    }
205
206    pub fn node_is_pinned(&self, key: NodeKey) -> Option<bool> {
207        self.get_node(key)?;
208        Some(self.node_facet_or_default(key, ARRANGEMENT_PIN))
209    }
210
211    pub(crate) fn insert_node_tag(&mut self, key: NodeKey, tag: String) -> bool {
212        let inserted = {
213            let Some(node) = self.inner.node_mut(key) else {
214                return false;
215            };
216            node.tags.insert(tag.clone())
217        };
218        if inserted {
219            let mut presentation =
220                self.node_facet_or_default::<NodeTagPresentationState>(key, PRESENTATION_TAGS);
221            if !presentation.ordered_tags.contains(&tag) {
222                presentation.ordered_tags.push(tag);
223                self.set_node_facet(key, PRESENTATION_TAGS, &presentation);
224            }
225        }
226        inserted
227    }
228
229    pub(crate) fn remove_node_tag(&mut self, key: NodeKey, tag: &str) -> bool {
230        let removed = {
231            let Some(node) = self.inner.node_mut(key) else {
232                return false;
233            };
234            node.tags.remove(tag)
235        };
236        if removed {
237            let mut presentation =
238                self.node_facet_or_default::<NodeTagPresentationState>(key, PRESENTATION_TAGS);
239            presentation.ordered_tags.retain(|entry| entry != tag);
240            presentation.icon_overrides.remove(tag);
241            self.set_node_facet(key, PRESENTATION_TAGS, &presentation);
242        }
243        removed
244    }
245
246    /// Set a node's inline authored content body (a knot note's djot source).
247    /// Returns whether the body actually changed. The sanctioned write path for
248    /// `Node::body` — the note editor and web-clip previously reached it through
249    /// `get_node_mut` (write-path migration, 2026-07-01).
250    pub(crate) fn set_node_body(&mut self, key: NodeKey, body: Option<String>) -> bool {
251        let Some(node) = self.inner.node_mut(key) else {
252            return false;
253        };
254        let clears_content = body.is_some() && node.content.is_some();
255        if node.body == body && !clears_content {
256            return false;
257        }
258        node.body = body;
259        if node.body.is_some() {
260            node.content = None;
261        }
262        true
263    }
264
265    /// Append an open literal property, deduplicating the full literal record
266    /// `(predicate, value, datatype, lang)`. Returns whether the property was
267    /// newly added. The sanctioned write path for `Node::properties` — the
268    /// linked-data ingest previously pushed through `get_node_mut` (write-path
269    /// migration, 2026-07-01).
270    pub(crate) fn append_node_property(&mut self, key: NodeKey, property: NodeProperty) -> bool {
271        if self.inner.node(key).is_none() {
272            return false;
273        }
274        let mut properties =
275            self.node_facet_or_default::<Vec<NodeProperty>>(key, SEMANTIC_PROPERTIES);
276        if let Some(existing) = properties
277            .iter_mut()
278            .find(|existing| existing.content_eq(&property))
279        {
280            if existing.provenance_iri != property.provenance_iri
281                || existing.asserted_at_ms != property.asserted_at_ms
282            {
283                existing.provenance_iri = property.provenance_iri;
284                existing.asserted_at_ms = property.asserted_at_ms;
285                return self.set_node_facet(key, SEMANTIC_PROPERTIES, &properties);
286            }
287            return false;
288        }
289        properties.push(property);
290        self.set_node_facet(key, SEMANTIC_PROPERTIES, &properties)
291    }
292
293    pub fn node_tags(&self, key: NodeKey) -> Option<&HashSet<String>> {
294        self.get_node(key).map(|node| &node.tags)
295    }
296
297    pub fn node_tag_presentation(&self, key: NodeKey) -> Option<NodeTagPresentationState> {
298        self.get_node(key)?;
299        Some(self.node_facet_or_default(key, PRESENTATION_TAGS))
300    }
301
302    pub fn node_import_provenance(&self, key: NodeKey) -> Option<Vec<NodeImportProvenance>> {
303        self.get_node(key)?;
304        Some(self.node_facet_or_default(key, PROVENANCE_IMPORT))
305    }
306
307    // --- Classification accessors (Stage A) ---
308
309    pub fn node_classifications(&self, key: NodeKey) -> Option<Vec<NodeClassification>> {
310        self.get_node(key)?;
311        Some(self.node_facet_or_default(key, SEMANTIC_CLASSIFICATIONS))
312    }
313
314    pub fn node_properties(&self, key: NodeKey) -> Option<Vec<NodeProperty>> {
315        self.get_node(key)?;
316        Some(self.node_facet_or_default(key, SEMANTIC_PROPERTIES))
317    }
318
319    pub fn node_derivations(&self, key: NodeKey) -> Option<Vec<crate::types::NodeDerivation>> {
320        self.get_node(key)?;
321        Some(self.node_facet_or_default(key, PROVENANCE_DERIVATIONS))
322    }
323
324    /// Add a classification record to a node.
325    ///
326    /// Deduplicates by `(scheme, value)`. Returns `true` if the record was inserted.
327    pub(crate) fn add_node_classification(
328        &mut self,
329        key: NodeKey,
330        classification: NodeClassification,
331    ) -> bool {
332        if self.inner.node(key).is_none() {
333            return false;
334        }
335        let mut classifications =
336            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
337        let already_exists = classifications
338            .iter()
339            .any(|c| c.scheme == classification.scheme && c.value == classification.value);
340        if already_exists {
341            return false;
342        }
343        classifications.push(classification);
344        self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
345    }
346
347    /// Append a [`NodeDerivation`](crate::types::NodeDerivation) to `key`'s
348    /// provenance record — e.g. a harvested link node that was `ExtractedFrom`
349    /// its source page (capture plan C3). Idempotent: a duplicate (same sub-kind
350    /// + source) is not re-added. Returns whether it was added. Same-graph
351    /// derivations are recorded after the fact here; cross-graph ones ride node
352    /// creation via `copy_node_from`.
353    pub(crate) fn record_derivation(
354        &mut self,
355        key: NodeKey,
356        derivation: crate::types::NodeDerivation,
357    ) -> bool {
358        if self.inner.node(key).is_none() {
359            return false;
360        }
361        let mut derivations = self.node_facet_or_default::<Vec<crate::types::NodeDerivation>>(
362            key,
363            PROVENANCE_DERIVATIONS,
364        );
365        if derivations.contains(&derivation) {
366            return false;
367        }
368        derivations.push(derivation);
369        self.set_node_facet(key, PROVENANCE_DERIVATIONS, &derivations)
370    }
371
372    /// Remove all classification records matching `(scheme, value)`.
373    ///
374    /// Returns `true` if at least one record was removed.
375    pub(crate) fn remove_node_classification(
376        &mut self,
377        key: NodeKey,
378        scheme: &ClassificationScheme,
379        value: &str,
380    ) -> bool {
381        if self.inner.node(key).is_none() {
382            return false;
383        }
384        let mut classifications =
385            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
386        let before = classifications.len();
387        classifications.retain(|c| !(c.scheme == *scheme && c.value == value));
388        if classifications.len() == before {
389            return false;
390        }
391        self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
392    }
393
394    /// Update the `status` of a classification record identified by `(scheme, value)`.
395    ///
396    /// Returns `true` if a matching record was found and updated.
397    pub(crate) fn set_node_classification_status(
398        &mut self,
399        key: NodeKey,
400        scheme: &ClassificationScheme,
401        value: &str,
402        status: ClassificationStatus,
403    ) -> bool {
404        if self.inner.node(key).is_none() {
405            return false;
406        }
407        let mut classifications =
408            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
409        let mut found = false;
410        for c in &mut classifications {
411            if c.scheme == *scheme && c.value == value {
412                c.status = status.clone();
413                found = true;
414            }
415        }
416        found && self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
417    }
418
419    /// Promote a classification record to primary for its scheme; demotes all others.
420    ///
421    /// Returns `true` if a matching record was found.
422    pub(crate) fn set_node_primary_classification(
423        &mut self,
424        key: NodeKey,
425        scheme: &ClassificationScheme,
426        value: &str,
427    ) -> bool {
428        if self.inner.node(key).is_none() {
429            return false;
430        }
431        let mut classifications =
432            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
433        let mut found = false;
434        for c in &mut classifications {
435            if c.scheme == *scheme {
436                c.primary = c.value == value;
437                if c.value == value {
438                    found = true;
439                }
440            }
441        }
442        found && self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
443    }
444
445    pub(crate) fn set_node_tag_icon_override(
446        &mut self,
447        key: NodeKey,
448        tag: &str,
449        icon: Option<crate::types::BadgeIcon>,
450    ) -> bool {
451        let Some(node) = self.inner.node(key) else {
452            return false;
453        };
454        if !node.tags.contains(tag) || tag.starts_with('#') || tag.starts_with("udc:") {
455            return false;
456        }
457        let mut presentation =
458            self.node_facet_or_default::<NodeTagPresentationState>(key, PRESENTATION_TAGS);
459        match icon {
460            Some(icon) => {
461                if presentation.icon_overrides.get(tag) == Some(&icon) {
462                    return false;
463                }
464                presentation.icon_overrides.insert(tag.to_string(), icon);
465                self.set_node_facet(key, PRESENTATION_TAGS, &presentation)
466            }
467            None => {
468                if presentation.icon_overrides.remove(tag).is_none() {
469                    return false;
470                }
471                self.set_node_facet(key, PRESENTATION_TAGS, &presentation)
472            }
473        }
474    }
475
476    // `set_node_position` / `set_node_projected_position` / `node_projected_position`
477    // left with `Node.position` (S2): a node's position is no longer graph truth.
478    // The live position is seiche's; the durable position is the cartography
479    // sidecar's; the host reads and writes those, not the graph.
480
481    // `projected_centroid` (the mean of node positions) left with S2's position
482    // dissolution: a centroid over positions is a view concern computed from
483    // seiche's live layout host-side, not a kernel method over the transient
484    // `Node.position`. It had no production caller.
485
486    pub(crate) fn touch_node_last_visited_now(&mut self, key: NodeKey) -> bool {
487        self.set_node_last_visited_at_ms(key, Graph::epoch_ms())
488    }
489
490    pub(crate) fn set_node_last_visited_at_ms(&mut self, key: NodeKey, timestamp_ms: u64) -> bool {
491        if self.inner.node(key).is_none() {
492            return false;
493        }
494        let mut history = self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY);
495        history.last_visited_ms = Some(timestamp_ms);
496        self.set_node_facet(key, VISIT_HISTORY, &history)
497    }
498
499    pub(crate) fn set_node_last_session_visited(
500        &mut self,
501        key: NodeKey,
502        last_session_visited: u64,
503    ) -> bool {
504        if self.inner.node(key).is_none() {
505            return false;
506        }
507        let mut history = self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY);
508        if history.last_session_visited == last_session_visited {
509            return false;
510        }
511        history.last_session_visited = last_session_visited;
512        self.set_node_facet(key, VISIT_HISTORY, &history)
513    }
514
515    pub fn node_last_visited(&self, key: NodeKey) -> Option<SystemTime> {
516        self.get_node(key)?;
517        self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY)
518            .last_visited_ms
519            .map(|milliseconds| UNIX_EPOCH + std::time::Duration::from_millis(milliseconds))
520    }
521
522    pub fn node_last_session_visited(&self, key: NodeKey) -> Option<u64> {
523        self.get_node(key)?;
524        Some(
525            self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY)
526                .last_session_visited,
527        )
528    }
529
530    /// Internal setter for `Node::history`. Tightened to `pub(crate)` so the
531    /// only reachable write surface from outside `kernel` is
532    /// `GraphDelta::UpdateNodeHistory`, dispatched via the
533    /// `app::history::GraphBrowserApp::apply_node_history_change` helper.
534    pub(crate) fn set_node_history_state(
535        &mut self,
536        key: NodeKey,
537        history_entries: Vec<String>,
538        history_index: usize,
539    ) -> bool {
540        let Some(id) = self.inner.node(key).map(|n| n.id) else {
541            return false;
542        };
543        let clamped_index = if history_entries.is_empty() {
544            0
545        } else {
546            history_index.min(history_entries.len() - 1)
547        };
548        let current = self.nav.projection(id);
549        if current.entries == history_entries && current.current_index == clamped_index {
550            return false;
551        }
552        // Reset this node's history to the given linear path (the shared visit
553        // space owns it now; a linear reset replaces any prior tree for the node).
554        self.nav.remove(id);
555        self.nav.seed_linear(id, history_entries, clamped_index);
556        true
557    }
558}