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    pub(crate) fn set_node_pinned(&mut self, key: NodeKey, is_pinned: bool) -> bool {
109        if self.inner.node(key).is_none() {
110            return false;
111        }
112        if self.node_is_pinned(key) == Some(is_pinned) {
113            return false;
114        }
115        self.set_node_facet(key, ARRANGEMENT_PIN, &is_pinned)
116    }
117
118    pub(crate) fn append_frame_layout_hint(&mut self, key: NodeKey, hint: FrameLayoutHint) -> bool {
119        if self.inner.node(key).is_none() {
120            return false;
121        }
122        let mut hints =
123            self.node_facet_or_default::<Vec<FrameLayoutHint>>(key, ARRANGEMENT_FRAME_LAYOUT);
124        hints.push(hint);
125        self.set_node_facet(key, ARRANGEMENT_FRAME_LAYOUT, &hints)
126    }
127
128    pub(crate) fn remove_frame_layout_hint_at(&mut self, key: NodeKey, hint_index: usize) -> bool {
129        if self.inner.node(key).is_none() {
130            return false;
131        }
132        let mut hints =
133            self.node_facet_or_default::<Vec<FrameLayoutHint>>(key, ARRANGEMENT_FRAME_LAYOUT);
134        if hint_index >= hints.len() {
135            return false;
136        }
137        hints.remove(hint_index);
138        self.set_node_facet(key, ARRANGEMENT_FRAME_LAYOUT, &hints)
139    }
140
141    pub(crate) fn move_frame_layout_hint(
142        &mut self,
143        key: NodeKey,
144        from_index: usize,
145        to_index: usize,
146    ) -> bool {
147        if self.inner.node(key).is_none() {
148            return false;
149        }
150        let mut hints =
151            self.node_facet_or_default::<Vec<FrameLayoutHint>>(key, ARRANGEMENT_FRAME_LAYOUT);
152        if from_index >= hints.len() || to_index >= hints.len() || from_index == to_index {
153            return false;
154        }
155        let hint = hints.remove(from_index);
156        hints.insert(to_index, hint);
157        self.set_node_facet(key, ARRANGEMENT_FRAME_LAYOUT, &hints)
158    }
159
160    pub(crate) fn set_frame_split_offer_suppressed(
161        &mut self,
162        key: NodeKey,
163        suppressed: bool,
164    ) -> bool {
165        if self.inner.node(key).is_none() {
166            return false;
167        }
168        if self.frame_split_offer_suppressed(key) == Some(suppressed) {
169            return false;
170        }
171        self.set_node_facet(key, ARRANGEMENT_SPLIT_OFFER_SUPPRESSED, &suppressed)
172    }
173
174    pub fn frame_layout_hints(&self, key: NodeKey) -> Option<Vec<FrameLayoutHint>> {
175        self.get_node(key)?;
176        Some(self.node_facet_or_default(key, ARRANGEMENT_FRAME_LAYOUT))
177    }
178
179    pub fn frame_split_offer_suppressed(&self, key: NodeKey) -> Option<bool> {
180        self.get_node(key)?;
181        Some(self.node_facet_or_default(key, ARRANGEMENT_SPLIT_OFFER_SUPPRESSED))
182    }
183
184    pub fn node_is_pinned(&self, key: NodeKey) -> Option<bool> {
185        self.get_node(key)?;
186        Some(self.node_facet_or_default(key, ARRANGEMENT_PIN))
187    }
188
189    pub(crate) fn insert_node_tag(&mut self, key: NodeKey, tag: String) -> bool {
190        let inserted = {
191            let Some(node) = self.inner.node_mut(key) else {
192                return false;
193            };
194            node.tags.insert(tag.clone())
195        };
196        if inserted {
197            let mut presentation =
198                self.node_facet_or_default::<NodeTagPresentationState>(key, PRESENTATION_TAGS);
199            if !presentation.ordered_tags.contains(&tag) {
200                presentation.ordered_tags.push(tag);
201                self.set_node_facet(key, PRESENTATION_TAGS, &presentation);
202            }
203        }
204        inserted
205    }
206
207    pub(crate) fn remove_node_tag(&mut self, key: NodeKey, tag: &str) -> bool {
208        let removed = {
209            let Some(node) = self.inner.node_mut(key) else {
210                return false;
211            };
212            node.tags.remove(tag)
213        };
214        if removed {
215            let mut presentation =
216                self.node_facet_or_default::<NodeTagPresentationState>(key, PRESENTATION_TAGS);
217            presentation.ordered_tags.retain(|entry| entry != tag);
218            presentation.icon_overrides.remove(tag);
219            self.set_node_facet(key, PRESENTATION_TAGS, &presentation);
220        }
221        removed
222    }
223
224    /// Set a node's inline authored content body (a knot note's djot source).
225    /// Returns whether the body actually changed. The sanctioned write path for
226    /// `Node::body` — the note editor and web-clip previously reached it through
227    /// `get_node_mut` (write-path migration, 2026-07-01).
228    pub(crate) fn set_node_body(&mut self, key: NodeKey, body: Option<String>) -> bool {
229        let Some(node) = self.inner.node_mut(key) else {
230            return false;
231        };
232        if node.body == body {
233            return false;
234        }
235        node.body = body;
236        true
237    }
238
239    /// Append an open literal property, deduplicating the full literal record
240    /// `(predicate, value, datatype, lang)`. Returns whether the property was
241    /// newly added. The sanctioned write path for `Node::properties` — the
242    /// linked-data ingest previously pushed through `get_node_mut` (write-path
243    /// migration, 2026-07-01).
244    pub(crate) fn append_node_property(&mut self, key: NodeKey, property: NodeProperty) -> bool {
245        if self.inner.node(key).is_none() {
246            return false;
247        }
248        let mut properties =
249            self.node_facet_or_default::<Vec<NodeProperty>>(key, SEMANTIC_PROPERTIES);
250        if let Some(existing) = properties
251            .iter_mut()
252            .find(|existing| existing.content_eq(&property))
253        {
254            if existing.provenance_iri != property.provenance_iri
255                || existing.asserted_at_ms != property.asserted_at_ms
256            {
257                existing.provenance_iri = property.provenance_iri;
258                existing.asserted_at_ms = property.asserted_at_ms;
259                return self.set_node_facet(key, SEMANTIC_PROPERTIES, &properties);
260            }
261            return false;
262        }
263        properties.push(property);
264        self.set_node_facet(key, SEMANTIC_PROPERTIES, &properties)
265    }
266
267    pub fn node_tags(&self, key: NodeKey) -> Option<&HashSet<String>> {
268        self.get_node(key).map(|node| &node.tags)
269    }
270
271    pub fn node_tag_presentation(&self, key: NodeKey) -> Option<NodeTagPresentationState> {
272        self.get_node(key)?;
273        Some(self.node_facet_or_default(key, PRESENTATION_TAGS))
274    }
275
276    pub fn node_import_provenance(&self, key: NodeKey) -> Option<Vec<NodeImportProvenance>> {
277        self.get_node(key)?;
278        Some(self.node_facet_or_default(key, PROVENANCE_IMPORT))
279    }
280
281    // --- Classification accessors (Stage A) ---
282
283    pub fn node_classifications(&self, key: NodeKey) -> Option<Vec<NodeClassification>> {
284        self.get_node(key)?;
285        Some(self.node_facet_or_default(key, SEMANTIC_CLASSIFICATIONS))
286    }
287
288    pub fn node_properties(&self, key: NodeKey) -> Option<Vec<NodeProperty>> {
289        self.get_node(key)?;
290        Some(self.node_facet_or_default(key, SEMANTIC_PROPERTIES))
291    }
292
293    pub fn node_derivations(&self, key: NodeKey) -> Option<Vec<crate::types::NodeDerivation>> {
294        self.get_node(key)?;
295        Some(self.node_facet_or_default(key, PROVENANCE_DERIVATIONS))
296    }
297
298    /// Add a classification record to a node.
299    ///
300    /// Deduplicates by `(scheme, value)`. Returns `true` if the record was inserted.
301    pub(crate) fn add_node_classification(
302        &mut self,
303        key: NodeKey,
304        classification: NodeClassification,
305    ) -> bool {
306        if self.inner.node(key).is_none() {
307            return false;
308        }
309        let mut classifications =
310            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
311        let already_exists = classifications
312            .iter()
313            .any(|c| c.scheme == classification.scheme && c.value == classification.value);
314        if already_exists {
315            return false;
316        }
317        classifications.push(classification);
318        self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
319    }
320
321    /// Append a [`NodeDerivation`](crate::types::NodeDerivation) to `key`'s
322    /// provenance record — e.g. a harvested link node that was `ExtractedFrom`
323    /// its source page (capture plan C3). Idempotent: a duplicate (same sub-kind
324    /// + source) is not re-added. Returns whether it was added. Same-graph
325    /// derivations are recorded after the fact here; cross-graph ones ride node
326    /// creation via `copy_node_from`.
327    pub(crate) fn record_derivation(
328        &mut self,
329        key: NodeKey,
330        derivation: crate::types::NodeDerivation,
331    ) -> bool {
332        if self.inner.node(key).is_none() {
333            return false;
334        }
335        let mut derivations = self.node_facet_or_default::<Vec<crate::types::NodeDerivation>>(
336            key,
337            PROVENANCE_DERIVATIONS,
338        );
339        if derivations.contains(&derivation) {
340            return false;
341        }
342        derivations.push(derivation);
343        self.set_node_facet(key, PROVENANCE_DERIVATIONS, &derivations)
344    }
345
346    /// Remove all classification records matching `(scheme, value)`.
347    ///
348    /// Returns `true` if at least one record was removed.
349    pub(crate) fn remove_node_classification(
350        &mut self,
351        key: NodeKey,
352        scheme: &ClassificationScheme,
353        value: &str,
354    ) -> bool {
355        if self.inner.node(key).is_none() {
356            return false;
357        }
358        let mut classifications =
359            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
360        let before = classifications.len();
361        classifications.retain(|c| !(c.scheme == *scheme && c.value == value));
362        if classifications.len() == before {
363            return false;
364        }
365        self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
366    }
367
368    /// Update the `status` of a classification record identified by `(scheme, value)`.
369    ///
370    /// Returns `true` if a matching record was found and updated.
371    pub(crate) fn set_node_classification_status(
372        &mut self,
373        key: NodeKey,
374        scheme: &ClassificationScheme,
375        value: &str,
376        status: ClassificationStatus,
377    ) -> bool {
378        if self.inner.node(key).is_none() {
379            return false;
380        }
381        let mut classifications =
382            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
383        let mut found = false;
384        for c in &mut classifications {
385            if c.scheme == *scheme && c.value == value {
386                c.status = status.clone();
387                found = true;
388            }
389        }
390        found && self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
391    }
392
393    /// Promote a classification record to primary for its scheme; demotes all others.
394    ///
395    /// Returns `true` if a matching record was found.
396    pub(crate) fn set_node_primary_classification(
397        &mut self,
398        key: NodeKey,
399        scheme: &ClassificationScheme,
400        value: &str,
401    ) -> bool {
402        if self.inner.node(key).is_none() {
403            return false;
404        }
405        let mut classifications =
406            self.node_facet_or_default::<Vec<NodeClassification>>(key, SEMANTIC_CLASSIFICATIONS);
407        let mut found = false;
408        for c in &mut classifications {
409            if c.scheme == *scheme {
410                c.primary = c.value == value;
411                if c.value == value {
412                    found = true;
413                }
414            }
415        }
416        found && self.set_node_facet(key, SEMANTIC_CLASSIFICATIONS, &classifications)
417    }
418
419    pub(crate) fn set_node_tag_icon_override(
420        &mut self,
421        key: NodeKey,
422        tag: &str,
423        icon: Option<crate::types::BadgeIcon>,
424    ) -> bool {
425        let Some(node) = self.inner.node(key) else {
426            return false;
427        };
428        if !node.tags.contains(tag) || tag.starts_with('#') || tag.starts_with("udc:") {
429            return false;
430        }
431        let mut presentation =
432            self.node_facet_or_default::<NodeTagPresentationState>(key, PRESENTATION_TAGS);
433        match icon {
434            Some(icon) => {
435                if presentation.icon_overrides.get(tag) == Some(&icon) {
436                    return false;
437                }
438                presentation.icon_overrides.insert(tag.to_string(), icon);
439                self.set_node_facet(key, PRESENTATION_TAGS, &presentation)
440            }
441            None => {
442                if presentation.icon_overrides.remove(tag).is_none() {
443                    return false;
444                }
445                self.set_node_facet(key, PRESENTATION_TAGS, &presentation)
446            }
447        }
448    }
449
450    // `set_node_position` / `set_node_projected_position` / `node_projected_position`
451    // left with `Node.position` (S2): a node's position is no longer graph truth.
452    // The live position is seiche's; the durable position is the cartography
453    // sidecar's; the host reads and writes those, not the graph.
454
455    // `projected_centroid` (the mean of node positions) left with S2's position
456    // dissolution: a centroid over positions is a view concern computed from
457    // seiche's live layout host-side, not a kernel method over the transient
458    // `Node.position`. It had no production caller.
459
460    pub(crate) fn touch_node_last_visited_now(&mut self, key: NodeKey) -> bool {
461        self.set_node_last_visited_at_ms(key, Graph::epoch_ms())
462    }
463
464    pub(crate) fn set_node_last_visited_at_ms(&mut self, key: NodeKey, timestamp_ms: u64) -> bool {
465        if self.inner.node(key).is_none() {
466            return false;
467        }
468        let mut history = self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY);
469        history.last_visited_ms = Some(timestamp_ms);
470        self.set_node_facet(key, VISIT_HISTORY, &history)
471    }
472
473    pub(crate) fn set_node_last_session_visited(
474        &mut self,
475        key: NodeKey,
476        last_session_visited: u64,
477    ) -> bool {
478        if self.inner.node(key).is_none() {
479            return false;
480        }
481        let mut history = self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY);
482        if history.last_session_visited == last_session_visited {
483            return false;
484        }
485        history.last_session_visited = last_session_visited;
486        self.set_node_facet(key, VISIT_HISTORY, &history)
487    }
488
489    pub fn node_last_visited(&self, key: NodeKey) -> Option<SystemTime> {
490        self.get_node(key)?;
491        self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY)
492            .last_visited_ms
493            .map(|milliseconds| UNIX_EPOCH + std::time::Duration::from_millis(milliseconds))
494    }
495
496    pub fn node_last_session_visited(&self, key: NodeKey) -> Option<u64> {
497        self.get_node(key)?;
498        Some(
499            self.node_facet_or_default::<VisitHistoryFacet>(key, VISIT_HISTORY)
500                .last_session_visited,
501        )
502    }
503
504    /// Internal setter for `Node::history`. Tightened to `pub(crate)` so the
505    /// only reachable write surface from outside `kernel` is
506    /// `GraphDelta::UpdateNodeHistory`, dispatched via the
507    /// `app::history::GraphBrowserApp::apply_node_history_change` helper.
508    pub(crate) fn set_node_history_state(
509        &mut self,
510        key: NodeKey,
511        history_entries: Vec<String>,
512        history_index: usize,
513    ) -> bool {
514        let Some(id) = self.inner.node(key).map(|n| n.id) else {
515            return false;
516        };
517        let clamped_index = if history_entries.is_empty() {
518            0
519        } else {
520            history_index.min(history_entries.len() - 1)
521        };
522        let current = self.nav.projection(id);
523        if current.entries == history_entries && current.current_index == clamped_index {
524            return false;
525        }
526        // Reset this node's history to the given linear path (the shared visit
527        // space owns it now; a linear reset replaces any prior tree for the node).
528        self.nav.remove(id);
529        self.nav.seed_linear(id, history_entries, clamped_index);
530        true
531    }
532}