diaryx_core 1.4.4

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
//! Frontmatter operation command handlers.

use std::path::Path;

use crate::yaml_value::YamlValue;

use crate::command::Response;
use crate::diaryx::Diaryx;
use crate::error::DiaryxError;
use crate::error::Result;
use crate::fs::AsyncFileSystem;

impl<FS: AsyncFileSystem + Clone> Diaryx<FS> {
    fn extract_markdown_link_destinations(content: &str) -> Vec<String> {
        let bytes = content.as_bytes();
        let mut links = Vec::new();
        let mut i = 0;

        while i < bytes.len() {
            if bytes[i] != b'[' {
                i += 1;
                continue;
            }
            if i > 0 && bytes[i - 1] == b'!' {
                i += 1;
                continue;
            }

            let mut label_end = i + 1;
            while label_end < bytes.len() {
                match bytes[label_end] {
                    b'\\' => label_end += 2,
                    b']' => break,
                    _ => label_end += 1,
                }
            }

            if label_end >= bytes.len()
                || bytes[label_end] != b']'
                || label_end + 1 >= bytes.len()
                || bytes[label_end + 1] != b'('
            {
                i += 1;
                continue;
            }

            let href_start = label_end + 2;
            let mut cursor = href_start;
            let mut depth = 1usize;
            while cursor < bytes.len() {
                match bytes[cursor] {
                    b'\\' => cursor += 2,
                    b'(' => {
                        depth += 1;
                        cursor += 1;
                    }
                    b')' => {
                        depth -= 1;
                        if depth == 0 {
                            let href = content[href_start..cursor].trim();
                            let href = href
                                .strip_prefix('<')
                                .and_then(|s| s.strip_suffix('>'))
                                .unwrap_or(href);
                            if !href.is_empty() {
                                links.push(href.to_string());
                            }
                            cursor += 1;
                            break;
                        }
                        cursor += 1;
                    }
                    _ => cursor += 1,
                }
            }

            i = cursor.max(i + 1);
        }

        links
    }

    fn is_local_body_link(href: &str) -> bool {
        let lowered = href.trim().to_ascii_lowercase();
        !(lowered.contains("://")
            || lowered.starts_with("mailto:")
            || lowered.starts_with("tel:")
            || lowered.starts_with('#')
            || lowered.starts_with("javascript:"))
    }

    async fn content_uses_target(
        &self,
        source_path: &str,
        target_canonical: &str,
        content: Option<&str>,
    ) -> bool {
        let source_canonical = self.get_canonical_path(source_path);
        let body = match content {
            Some(content) => content.to_string(),
            None => self
                .entry()
                .get_content(source_path)
                .await
                .unwrap_or_default(),
        };

        Self::extract_markdown_link_destinations(&body)
            .into_iter()
            .filter(|href| Self::is_local_body_link(href))
            .any(|href| {
                self.resolve_frontmatter_link_target(&href, &source_canonical) == target_canonical
            })
    }

    async fn upsert_frontmatter_link_array_item(
        &self,
        file_path: &str,
        key: &str,
        target_canonical: &str,
    ) -> Result<bool> {
        let file_canonical = self.get_canonical_path(file_path);
        let existing = self
            .entry()
            .get_frontmatter_property(file_path, key)
            .await?;
        let mut items = match existing {
            Some(YamlValue::Sequence(items)) => items,
            Some(_) => Vec::new(),
            None => Vec::new(),
        };

        let already_present = items.iter().any(|item| {
            item.as_str().is_some_and(|s| {
                self.resolve_frontmatter_link_target(s, &file_canonical) == target_canonical
            })
        });
        if already_present {
            return Ok(false);
        }

        let formatted = self.format_link_for_file(target_canonical, &file_canonical);
        items.push(YamlValue::String(formatted));
        self.entry()
            .set_frontmatter_property(file_path, key, YamlValue::Sequence(items))
            .await?;
        Ok(true)
    }

    async fn remove_frontmatter_link_array_item(
        &self,
        file_path: &str,
        key: &str,
        target_canonical: &str,
    ) -> Result<bool> {
        let file_canonical = self.get_canonical_path(file_path);
        let existing = self
            .entry()
            .get_frontmatter_property(file_path, key)
            .await?;
        let Some(YamlValue::Sequence(items)) = existing else {
            return Ok(false);
        };
        let original_len = items.len();

        let filtered: Vec<YamlValue> = items
            .into_iter()
            .filter(|item| {
                !item.as_str().is_some_and(|s| {
                    self.resolve_frontmatter_link_target(s, &file_canonical) == target_canonical
                })
            })
            .collect();

        let changed = filtered.len() != original_len;
        if !changed {
            return Ok(false);
        }

        if filtered.is_empty() {
            self.entry()
                .remove_frontmatter_property(file_path, key)
                .await?;
        } else {
            self.entry()
                .set_frontmatter_property(file_path, key, YamlValue::Sequence(filtered))
                .await?;
        }
        Ok(true)
    }

    async fn ensure_self_link_property(&self, file_path: &str) -> Result<bool> {
        let canonical_path = self.get_canonical_path(file_path);
        match self
            .entry()
            .get_frontmatter_property(file_path, "link")
            .await?
        {
            Some(YamlValue::String(existing))
                if self.resolve_frontmatter_link_target(&existing, &canonical_path)
                    == canonical_path =>
            {
                Ok(false)
            }
            Some(_) => Ok(false),
            None => {
                let formatted = self.format_link_for_file(&canonical_path, &canonical_path);
                self.entry()
                    .set_frontmatter_property(file_path, "link", YamlValue::String(formatted))
                    .await?;
                Ok(true)
            }
        }
    }

    async fn track_link_metadata_change(&self, path: &str) {
        let canonical_path = self.get_canonical_path(path);
        self.plugin_registry()
            .track_file_for_sync(&canonical_path)
            .await;
    }

    pub(crate) async fn cmd_get_frontmatter(&self, path: String) -> Result<Response> {
        let fm = self.entry().get_frontmatter(&path).await?;
        Ok(Response::Frontmatter(fm))
    }

    pub(crate) async fn cmd_set_frontmatter_property(
        &self,
        path: String,
        key: String,
        value: YamlValue,
        root_index_path: Option<String>,
    ) -> Result<Response> {
        // Handle link/part_of/contents/attachments specially - normalize and
        // format links according to workspace settings.
        // CrdtFs.write_file extracts metadata from frontmatter automatically
        {
            let canonical_path = self.get_canonical_path(&path);

            if key == "link" {
                if let YamlValue::String(ref s) = value {
                    let canonical_target = self.resolve_frontmatter_link_target(s, &canonical_path);
                    let formatted = self.format_link_for_file(&canonical_target, &canonical_path);
                    let yaml_value = YamlValue::String(formatted);
                    self.entry()
                        .set_frontmatter_property(&path, &key, yaml_value)
                        .await?;

                    self.plugin_registry()
                        .track_file_for_sync(&canonical_path)
                        .await;

                    self.emit_workspace_sync().await;
                    return Ok(Response::Ok);
                }
            } else if key == "attachment" {
                if let YamlValue::String(ref s) = value {
                    let canonical_target = self.resolve_attachment_link_target_with_hint(
                        s,
                        &canonical_path,
                        Some(crate::link_parser::LinkFormat::PlainCanonical),
                    );
                    let formatted =
                        self.format_attachment_link_for_file(&canonical_target, &canonical_path);
                    let yaml_value = YamlValue::String(formatted);
                    self.entry()
                        .set_frontmatter_property(&path, &key, yaml_value)
                        .await?;

                    self.plugin_registry()
                        .track_file_for_sync(&canonical_path)
                        .await;

                    self.emit_workspace_sync().await;
                    return Ok(Response::Ok);
                }
            } else if key == "part_of" {
                // Parse the value, convert to canonical, format as markdown link
                if let YamlValue::String(ref s) = value {
                    let canonical_target = self.resolve_frontmatter_link_target(s, &canonical_path);

                    // Format as markdown link for file
                    let formatted = self.format_link_for_file(&canonical_target, &canonical_path);

                    // Write formatted link to file - CrdtFs extracts metadata automatically
                    let yaml_value = YamlValue::String(formatted);
                    self.entry()
                        .set_frontmatter_property(&path, &key, yaml_value)
                        .await?;

                    // Track for echo detection
                    self.plugin_registry()
                        .track_file_for_sync(&canonical_path)
                        .await;

                    // Emit workspace sync message
                    self.emit_workspace_sync().await;
                    return Ok(Response::Ok);
                }
            } else if key == "contents"
                || key == "links"
                || key == "link_of"
                || key == "attachment_of"
            {
                // Handle contents array - format each item as markdown link
                if let YamlValue::Sequence(ref arr) = value {
                    let mut formatted_links: Vec<YamlValue> = Vec::new();

                    for item in arr {
                        if let YamlValue::String(s) = item {
                            let canonical_target = self.resolve_attachment_link_target_with_hint(
                                s,
                                &canonical_path,
                                Some(self.link_format()),
                            );
                            let formatted =
                                self.format_link_for_file(&canonical_target, &canonical_path);
                            formatted_links.push(YamlValue::String(formatted));
                        }
                    }

                    // Write formatted links to file - CrdtFs extracts metadata automatically
                    let yaml_value = YamlValue::Sequence(formatted_links);
                    self.entry()
                        .set_frontmatter_property(&path, &key, yaml_value)
                        .await?;

                    // Track for echo detection
                    self.plugin_registry()
                        .track_file_for_sync(&canonical_path)
                        .await;

                    // Emit workspace sync message
                    self.emit_workspace_sync().await;
                    return Ok(Response::Ok);
                }
            } else if key == "attachments" {
                // Attachments now point to attachment notes, not binary assets.
                if let YamlValue::Sequence(ref arr) = value {
                    let mut formatted_links: Vec<YamlValue> = Vec::new();

                    for item in arr {
                        if let YamlValue::String(s) = item {
                            let canonical_target =
                                self.resolve_frontmatter_link_target(s, &canonical_path);
                            let formatted =
                                self.format_link_for_file(&canonical_target, &canonical_path);
                            formatted_links.push(YamlValue::String(formatted));
                        }
                    }

                    let yaml_value = YamlValue::Sequence(formatted_links);
                    self.entry()
                        .set_frontmatter_property(&path, &key, yaml_value)
                        .await?;

                    // Track for echo detection
                    self.plugin_registry()
                        .track_file_for_sync(&canonical_path)
                        .await;

                    self.emit_workspace_sync().await;
                    return Ok(Response::Ok);
                } else if let YamlValue::String(ref s) = value {
                    let canonical_target = self.resolve_attachment_link_target_with_hint(
                        s,
                        &canonical_path,
                        Some(self.link_format()),
                    );
                    let formatted = self.format_link_for_file(&canonical_target, &canonical_path);
                    let yaml_value = YamlValue::String(formatted);
                    self.entry()
                        .set_frontmatter_property(&path, &key, yaml_value)
                        .await?;

                    // Track for echo detection
                    self.plugin_registry()
                        .track_file_for_sync(&canonical_path)
                        .await;

                    self.emit_workspace_sync().await;
                    return Ok(Response::Ok);
                }
            }
        }

        // Auto-rename on title change + sync heading
        if key == "title"
            && let Some(ref rip) = root_index_path
            && let YamlValue::String(ref new_title) = value
            && !new_title.trim().is_empty()
        {
            use crate::entry::apply_filename_style;

            let ws_config = self
                .workspace()
                .inner()
                .get_workspace_config(&self.resolve_fs_path(rip))
                .await
                .unwrap_or_default();

            let mut effective_path = path.clone();

            // Write the title FIRST so that rename_entry's resolve_title
            // reads the new title when formatting links in parent contents
            // and children's part_of references.
            self.entry()
                .set_frontmatter_property(&path, &key, value.clone())
                .await?;

            // Always auto-rename file to match title
            {
                let new_stem = apply_filename_style(new_title, &ws_config.filename_style);
                let new_filename = format!("{}.md", new_stem);

                let entry_path = self.resolve_fs_path(&path);
                let ws = self.workspace().inner();
                let is_index = ws.is_index_file(&entry_path).await;
                let is_root = ws.is_root_index(&entry_path).await;

                // Compare current name:
                // - Non-root index: dir name (index lives in dirname/dirname.md)
                // - Root index or leaf: file stem
                let current_comparable = if is_index && !is_root {
                    entry_path
                        .parent()
                        .and_then(|p| p.file_name())
                        .and_then(|n| n.to_str())
                        .unwrap_or("")
                        .to_string()
                } else {
                    entry_path
                        .file_stem()
                        .and_then(|n| n.to_str())
                        .unwrap_or("")
                        .to_string()
                };

                if current_comparable != new_stem {
                    let new_path = ws.rename_entry(&entry_path, &new_filename).await?;
                    let new_path_str = new_path.to_string_lossy().to_string();

                    // Migrate body CRDT doc to new path
                    {
                        let canonical_old = self.get_canonical_path(&path);
                        let canonical_new = self.get_canonical_path(&new_path_str);
                        if canonical_old != canonical_new {
                            self.plugin_registry()
                                .emit_body_doc_renamed(&canonical_old, &canonical_new)
                                .await;
                        }
                    }

                    effective_path = new_path_str;
                }
            }

            // Always sync title to H1 heading
            self.sync_heading_to_title(&effective_path, new_title)
                .await?;

            // Emit workspace sync (covers both rename + frontmatter update)
            self.emit_workspace_sync().await;

            // Return new path if rename happened, Ok otherwise
            if effective_path != path {
                return Ok(Response::String(effective_path));
            } else {
                return Ok(Response::Ok);
            }
        }

        // Default: just set the property as-is (non-title keys, or title without root_index_path)
        self.entry()
            .set_frontmatter_property(&path, &key, value.clone())
            .await?;

        Ok(Response::Ok)
    }

    pub(crate) async fn cmd_remove_frontmatter_property(
        &self,
        path: String,
        key: String,
    ) -> Result<Response> {
        // Remove property from frontmatter - CrdtFs extracts metadata automatically
        self.entry()
            .remove_frontmatter_property(&path, &key)
            .await?;

        // CrdtFs handles CRDT updates automatically via write_file hook.
        // We only need to track for echo detection and emit sync.
        {
            if key == "link"
                || key == "attachment"
                || key == "links"
                || key == "link_of"
                || key == "attachment_of"
                || key == "part_of"
                || key == "contents"
                || key == "attachments"
            {
                let canonical_path = self.get_canonical_path(&path);

                // Track for echo detection
                self.plugin_registry()
                    .track_file_for_sync(&canonical_path)
                    .await;

                // Emit workspace sync message
                self.emit_workspace_sync().await;
            }
        }

        Ok(Response::Ok)
    }

    pub(crate) async fn cmd_add_link(
        &self,
        source_path: String,
        target_path: String,
        _content: Option<String>,
    ) -> Result<Response> {
        let source_fs_path = self.resolve_fs_path(&source_path);
        let target_fs_path = self.resolve_fs_path(&target_path);
        if !self.fs().exists(&source_fs_path).await {
            return Err(DiaryxError::Validation(format!(
                "Source entry not found: {}",
                Path::new(&source_path).display()
            )));
        }
        if !self.fs().exists(&target_fs_path).await {
            return Err(DiaryxError::Validation(format!(
                "Target entry not found: {}",
                Path::new(&target_path).display()
            )));
        }

        let source_canonical = self.get_canonical_path(&source_path);
        let target_canonical = self.get_canonical_path(&target_path);

        let mut changed = false;
        changed |= self
            .upsert_frontmatter_link_array_item(&source_path, "links", &target_canonical)
            .await?;
        changed |= self
            .upsert_frontmatter_link_array_item(&target_path, "link_of", &source_canonical)
            .await?;
        changed |= self.ensure_self_link_property(&target_path).await?;

        if changed {
            self.track_link_metadata_change(&source_path).await;
            self.track_link_metadata_change(&target_path).await;
            self.emit_workspace_sync().await;
        }

        Ok(Response::Ok)
    }

    pub(crate) async fn cmd_remove_link(
        &self,
        source_path: String,
        target_path: String,
        content: Option<String>,
    ) -> Result<Response> {
        let source_fs_path = self.resolve_fs_path(&source_path);
        if !self.fs().exists(&source_fs_path).await {
            return Err(DiaryxError::Validation(format!(
                "Source entry not found: {}",
                Path::new(&source_path).display()
            )));
        }

        let target_canonical = self.get_canonical_path(&target_path);
        if self
            .content_uses_target(&source_path, &target_canonical, content.as_deref())
            .await
        {
            return Ok(Response::Ok);
        }

        let source_canonical = self.get_canonical_path(&source_path);
        let mut changed = false;
        changed |= self
            .remove_frontmatter_link_array_item(&source_path, "links", &target_canonical)
            .await?;

        let target_fs_path = self.resolve_fs_path(&target_path);
        if self.fs().exists(&target_fs_path).await {
            changed |= self
                .remove_frontmatter_link_array_item(&target_path, "link_of", &source_canonical)
                .await?;
        }

        if changed {
            self.track_link_metadata_change(&source_path).await;
            if self.fs().exists(&target_fs_path).await {
                self.track_link_metadata_change(&target_path).await;
            }
            self.emit_workspace_sync().await;
        }

        Ok(Response::Ok)
    }

    pub(crate) async fn cmd_reorder_frontmatter_keys(
        &self,
        path: String,
        keys: Vec<String>,
    ) -> Result<Response> {
        self.entry().reorder_frontmatter_keys(&path, &keys).await?;
        Ok(Response::Ok)
    }

    pub(crate) async fn cmd_move_frontmatter_section_to_file(
        &self,
        source_path: String,
        section_key: String,
        target_path: String,
        create_if_missing: bool,
    ) -> Result<Response> {
        self.entry()
            .move_frontmatter_section_to_file(
                &source_path,
                &section_key,
                &target_path,
                create_if_missing,
            )
            .await?;
        Ok(Response::Ok)
    }
}