Skip to main content

kernel/graph/
node_props.rs

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