feat(core): hubs, tag pages and types, with ffi, history and import support

Hubs and templates are page kinds; tags are pages of kind tag linked by a TAGGED
edge; types are plain names on the page. Schema v5. Snapshots carry
synapse-kind/tags/types. Also adapts search, import and server tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Sonnet 5.5 committed 2026-10-26 02:45:22 +01:00
1 parent 91a8276966
commit b800248d67
35 files changed
+7983 -141

No files matched your search

+310 -8
View File
@@ -8,7 +8,7 @@ import '../frb_generated.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
// These functions are ignored because they are not marked as `pub`: `new`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`
class AssetDto {
final String hash;
@@ -236,7 +236,8 @@ class GraphNode {
final String? originJournal;
final PlatformInt64 createdAt;
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
/// Distinct neighbours over structural edges (links, tags, properties, block refs, hub
/// membership).
final int degree;
/// Distinct pages referencing this one.
@@ -248,6 +249,15 @@ class GraphNode {
/// Node index of the tag this page uses most, if any.
final int? primaryTag;
/// The page is a hub (`PageKind::Hub`).
final bool isHub;
/// Node index of the deepest hub containing this page (a hub: itself).
final int? homeHub;
/// Tag names of the page (see `PageDto::tags`), for grouping by tag.
final List<String> tags;
const GraphNode({
required this.id,
required this.title,
@@ -258,6 +268,9 @@ class GraphNode {
required this.backlinks,
required this.cluster,
this.primaryTag,
required this.isHub,
this.homeHub,
required this.tags,
});
@override
@@ -270,7 +283,10 @@ class GraphNode {
degree.hashCode ^
backlinks.hashCode ^
cluster.hashCode ^
primaryTag.hashCode;
primaryTag.hashCode ^
isHub.hashCode ^
homeHub.hashCode ^
tags.hashCode;
@override
bool operator ==(Object other) =>
@@ -285,7 +301,127 @@ class GraphNode {
degree == other.degree &&
backlinks == other.backlinks &&
cluster == other.cluster &&
primaryTag == other.primaryTag;
primaryTag == other.primaryTag &&
isHub == other.isHub &&
homeHub == other.homeHub &&
tags == other.tags;
}
/// A hub (folder-like page) with its members.
class HubDto {
final String id;
final String title;
final String description;
/// 0 for root hubs, one more per level of nesting.
final int depth;
/// Sub-hubs first, then notes, each by title.
final List<PageBrief> members;
/// Ids of the members that are hubs themselves.
final List<String> subHubs;
const HubDto({
required this.id,
required this.title,
required this.description,
required this.depth,
required this.members,
required this.subHubs,
});
@override
int get hashCode =>
id.hashCode ^
title.hashCode ^
description.hashCode ^
depth.hashCode ^
members.hashCode ^
subHubs.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HubDto &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
description == other.description &&
depth == other.depth &&
members == other.members &&
subHubs == other.subHubs;
}
/// Defaults for the "convert to hub" dialog.
class HubPreviewDto {
/// Last namespace segment of the title.
final String suggestedTitle;
/// First prose block as plain text (<= 280 chars).
final String suggestedDescription;
/// Candidate members: pages the outline links or tags (outline order), then pages
/// referencing the note from properties or tags.
final List<PageBrief> members;
/// Blocks that are prose rather than links (what "keep the outline" would save).
final int proseBlocks;
final int blocks;
/// `"<suggested_title> (notes)"`, for the note receiving the outline.
final String suggestedNoteTitle;
const HubPreviewDto({
required this.suggestedTitle,
required this.suggestedDescription,
required this.members,
required this.proseBlocks,
required this.blocks,
required this.suggestedNoteTitle,
});
@override
int get hashCode =>
suggestedTitle.hashCode ^
suggestedDescription.hashCode ^
members.hashCode ^
proseBlocks.hashCode ^
blocks.hashCode ^
suggestedNoteTitle.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HubPreviewDto &&
runtimeType == other.runtimeType &&
suggestedTitle == other.suggestedTitle &&
suggestedDescription == other.suggestedDescription &&
members == other.members &&
proseBlocks == other.proseBlocks &&
blocks == other.blocks &&
suggestedNoteTitle == other.suggestedNoteTitle;
}
class HubsDto {
/// Sorted by title.
final List<HubDto> hubs;
/// Ids of the hubs that are not a member of any hub, by title.
final List<String> roots;
const HubsDto({required this.hubs, required this.roots});
@override
int get hashCode => hubs.hashCode ^ roots.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is HubsDto &&
runtimeType == other.runtimeType &&
hubs == other.hubs &&
roots == other.roots;
}
/// One batch of layout iterations.
@@ -310,19 +446,77 @@ class LayoutFrame {
alpha == other.alpha;
}
/// A page the legacy purge offers to delete.
class LegacyCandidate {
final String id;
final String title;
final String reason;
final int blocks;
final bool preselected;
const LegacyCandidate({
required this.id,
required this.title,
required this.reason,
required this.blocks,
required this.preselected,
});
@override
int get hashCode =>
id.hashCode ^
title.hashCode ^
reason.hashCode ^
blocks.hashCode ^
preselected.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LegacyCandidate &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
reason == other.reason &&
blocks == other.blocks &&
preselected == other.preselected;
}
/// A level of a namespace (`A/B` under `A`); `id` is `None` when only deeper pages exist.
class NamespaceEntry {
final String title;
final String? id;
const NamespaceEntry({required this.title, this.id});
@override
int get hashCode => title.hashCode ^ id.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is NamespaceEntry &&
runtimeType == other.runtimeType &&
title == other.title &&
id == other.id;
}
class PageBrief {
final String id;
final String title;
final bool isJournal;
final bool isHub;
const PageBrief({
required this.id,
required this.title,
required this.isJournal,
required this.isHub,
});
@override
int get hashCode => id.hashCode ^ title.hashCode ^ isJournal.hashCode;
int get hashCode =>
id.hashCode ^ title.hashCode ^ isJournal.hashCode ^ isHub.hashCode;
@override
bool operator ==(Object other) =>
@@ -331,7 +525,8 @@ class PageBrief {
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
isJournal == other.isJournal;
isJournal == other.isJournal &&
isHub == other.isHub;
}
/// Everything the page view needs in one call.
@@ -385,6 +580,21 @@ class PageDto {
final PlatformInt64 createdAt;
final PlatformInt64 updatedAt;
/// The page is a hub (no blocks; members list instead of an outline).
final bool isHub;
/// Hub description (empty for notes).
final String description;
/// Titles of the tag pages this page is filed under, in the order they were added.
final List<String> tags;
/// The page is a tag page (a topic that other pages are filed under).
final bool isTag;
/// Type names ("persona", "lugar"...: plain names, not pages), in the order added.
final List<String> types;
const PageDto({
required this.id,
required this.title,
@@ -392,6 +602,11 @@ class PageDto {
this.originJournal,
required this.createdAt,
required this.updatedAt,
required this.isHub,
required this.description,
required this.tags,
required this.isTag,
required this.types,
});
@override
@@ -401,7 +616,12 @@ class PageDto {
journalDate.hashCode ^
originJournal.hashCode ^
createdAt.hashCode ^
updatedAt.hashCode;
updatedAt.hashCode ^
isHub.hashCode ^
description.hashCode ^
tags.hashCode ^
isTag.hashCode ^
types.hashCode;
@override
bool operator ==(Object other) =>
@@ -413,7 +633,60 @@ class PageDto {
journalDate == other.journalDate &&
originJournal == other.originJournal &&
createdAt == other.createdAt &&
updatedAt == other.updatedAt;
updatedAt == other.updatedAt &&
isHub == other.isHub &&
description == other.description &&
tags == other.tags &&
isTag == other.isTag &&
types == other.types;
}
/// Hub and namespace context of one page.
class PageStructure {
final bool isHub;
/// Hub description (empty for notes).
final String description;
/// Empty unless the page is a hub; sub-hubs first, then notes.
final List<PageBrief> members;
/// Hubs the page belongs to (its own membership list), by title.
final List<PageBrief> inHubs;
/// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist).
final List<NamespaceEntry> nsPath;
final List<NamespaceEntry> nsChildren;
const PageStructure({
required this.isHub,
required this.description,
required this.members,
required this.inHubs,
required this.nsPath,
required this.nsChildren,
});
@override
int get hashCode =>
isHub.hashCode ^
description.hashCode ^
members.hashCode ^
inHubs.hashCode ^
nsPath.hashCode ^
nsChildren.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PageStructure &&
runtimeType == other.runtimeType &&
isHub == other.isHub &&
description == other.description &&
members == other.members &&
inHubs == other.inHubs &&
nsPath == other.nsPath &&
nsChildren == other.nsChildren;
}
class Place {
@@ -464,6 +737,35 @@ class RelatedDto {
score == other.score;
}
/// A tag or type of the vocabulary.
class TagDto {
final String name;
/// Pages using it.
final int count;
/// One of the seeded suggestions.
final bool suggested;
const TagDto({
required this.name,
required this.count,
required this.suggested,
});
@override
int get hashCode => name.hashCode ^ count.hashCode ^ suggested.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TagDto &&
runtimeType == other.runtimeType &&
name == other.name &&
count == other.count &&
suggested == other.suggested;
}
class TimelineDayDto {
final String date;
final String? journalId;
+90
View File
@@ -15,6 +15,14 @@ import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> addAlias({required String pageId, required String alias});
Future<PageDto> addPageTag({required String pageId, required String tag});
Future<PageDto> addPageType({required String pageId, required String ty});
/// Puts a page in a hub (no-op when it already is). Fails for journals, non-hub targets,
/// the hub itself and memberships that would create a cycle.
Future<void> addToHub({required String pageId, required String hubId});
Future<List<String>> aliases({required String pageId});
/// Local file path of an asset (for `asset://<hash>` images), if present.
@@ -26,6 +34,32 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// Target of a `((block ref))`.
Future<BlockRefDto?> blockRef({required String id});
/// Turns a note into a hub in one transaction: renames it to `title` (links rewritten),
/// moves its outline to a new note `keep_outline_as` (or deletes it when `None`; a blank title is an error), sets the
/// description and adds `member_ids` (invalid members are skipped).
Future<PageDto> convertToHub({
required String pageId,
required String title,
required String description,
required List<String> memberIds,
String? keepOutlineAs,
});
/// Turns a hub back into a note: description, then one `[[Member]]` block per member.
Future<PageDto> convertToNote({required String pageId});
/// Creates an empty hub. Fails when the title is taken.
Future<PageDto> createHub({
required String title,
required String description,
});
/// Creates a note in the hub, starting from a copy of the hub's template.
Future<PageDto> createPageFromTemplate({
required String hubId,
required String title,
});
/// Deletes a block and its subtree.
Future<List<BlockDto>> deleteBlock({required String id});
@@ -38,6 +72,16 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// graph changes.
Future<GraphData> graphData();
/// Defaults for converting a note into a hub.
Future<HubPreviewDto> hubConversionPreview({required String pageId});
/// Id of the hub's template page (created empty when missing). Open it like any note to
/// edit the outline new notes of the hub start from.
Future<String> hubTemplate({required String hubId});
/// Every hub with its members, and the root hubs.
Future<HubsDto> hubs();
/// Tab: the block becomes the last child of its previous sibling (no-op for a first child).
Future<List<BlockDto>> indentBlock({required String id});
@@ -56,6 +100,12 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// journal); otherwise at the newest journal strictly before `before`.
Future<List<PageData>> journals({String? before, required int limit});
/// Pages that are probably leftovers of Logseq: its built-ins and pages with
/// `type:: system`. Only the organisational files (`contents`, `card`, `favorites`,
/// `hls__*`) and empty pages are preselected, and never a hub: a built-in title such as
/// `todo` may hold real content.
Future<List<LegacyCandidate>> legacyCandidates();
/// Pages ordered by last update, most recent first.
Future<List<PageDto>> listPages({
required bool includeJournals,
@@ -95,6 +145,15 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// Page by title or alias, without creating it.
Future<PageData?> pageByTitle({required String title});
/// Hub and namespace context of a page.
Future<PageStructure> pageStructure({required String pageId});
/// Pages carrying a tag, most recently updated first.
Future<List<PageBrief>> pagesWithTag({required String tag});
/// Deletes pages and their blocks in one transaction. Returns how many existed.
Future<int> purgePages({required List<String> ids});
/// Stores in-memory bytes (clipboard, Android content URIs).
Future<AssetDto> putAssetBytes({
required List<int> bytes,
@@ -116,6 +175,13 @@ abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> removeAlias({required String alias});
/// Takes a page out of a hub (no-op when it is not in it).
Future<void> removeFromHub({required String pageId, required String hubId});
Future<PageDto> removePageTag({required String pageId, required String tag});
Future<PageDto> removePageType({required String pageId, required String ty});
Future<PageDto> renamePage({required String id, required String newTitle});
/// Blocks whose text contains `query` (for `((` autocomplete), most recent first.
@@ -133,12 +199,36 @@ abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> setCollapsed({required String id, required bool collapsed});
Future<PageDto> setHubDescription({
required String hubId,
required String description,
});
/// Replaces the tags of a page (each title gets a tag page if it has none). Journals,
/// templates and tag pages cannot be tagged.
Future<PageDto> setPageTags({
required String pageId,
required List<String> tags,
});
/// Replaces the types of a page. Journals and templates cannot be typed.
Future<PageDto> setPageTypes({
required String pageId,
required List<String> types,
});
/// Every tag page with its number of pages, most used first.
Future<List<TagDto>> tagCatalog();
/// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions.
Future<TimelineDto> timeline({required String from, required String to});
/// Today's date (graph clock) as `YYYY-MM-DD`.
String today();
/// Types in use (most used first) followed by the seeded suggestions not used yet.
Future<List<TagDto>> typeCatalog();
/// Replaces a block's Markdown (the debounced save while typing).
Future<void> updateBlock({required String id, required String content});
}
File diff suppressed because it is too large. Load diff
+115
View File
@@ -115,6 +115,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode dco_decode_graph_node(dynamic raw);
@protected
HubDto dco_decode_hub_dto(dynamic raw);
@protected
HubPreviewDto dco_decode_hub_preview_dto(dynamic raw);
@protected
HubsDto dco_decode_hubs_dto(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@@ -124,6 +133,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame dco_decode_layout_frame(dynamic raw);
@protected
LegacyCandidate dco_decode_legacy_candidate(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@@ -142,6 +154,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> dco_decode_list_graph_node(dynamic raw);
@protected
List<HubDto> dco_decode_list_hub_dto(dynamic raw);
@protected
List<LegacyCandidate> dco_decode_list_legacy_candidate(dynamic raw);
@protected
List<NamespaceEntry> dco_decode_list_namespace_entry(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@@ -172,12 +193,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
@protected
List<TagDto> dco_decode_list_tag_dto(dynamic raw);
@protected
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
@protected
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
@protected
NamespaceEntry dco_decode_namespace_entry(dynamic raw);
@protected
String? dco_decode_opt_String(dynamic raw);
@@ -202,6 +229,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto dco_decode_page_dto(dynamic raw);
@protected
PageStructure dco_decode_page_structure(dynamic raw);
@protected
Place dco_decode_place(dynamic raw);
@@ -214,6 +244,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto dco_decode_related_dto(dynamic raw);
@protected
TagDto dco_decode_tag_dto(dynamic raw);
@protected
TimelineDayDto dco_decode_timeline_day_dto(dynamic raw);
@@ -324,6 +357,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode sse_decode_graph_node(SseDeserializer deserializer);
@protected
HubDto sse_decode_hub_dto(SseDeserializer deserializer);
@protected
HubPreviewDto sse_decode_hub_preview_dto(SseDeserializer deserializer);
@protected
HubsDto sse_decode_hubs_dto(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@@ -333,6 +375,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer);
@protected
LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@@ -353,6 +398,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> sse_decode_list_graph_node(SseDeserializer deserializer);
@protected
List<HubDto> sse_decode_list_hub_dto(SseDeserializer deserializer);
@protected
List<LegacyCandidate> sse_decode_list_legacy_candidate(
SseDeserializer deserializer,
);
@protected
List<NamespaceEntry> sse_decode_list_namespace_entry(
SseDeserializer deserializer,
);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@@ -383,6 +441,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
@protected
List<TagDto> sse_decode_list_tag_dto(SseDeserializer deserializer);
@protected
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
SseDeserializer deserializer,
@@ -391,6 +452,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
@protected
NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer);
@protected
String? sse_decode_opt_String(SseDeserializer deserializer);
@@ -419,6 +483,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto sse_decode_page_dto(SseDeserializer deserializer);
@protected
PageStructure sse_decode_page_structure(SseDeserializer deserializer);
@protected
Place sse_decode_place(SseDeserializer deserializer);
@@ -433,6 +500,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto sse_decode_related_dto(SseDeserializer deserializer);
@protected
TagDto sse_decode_tag_dto(SseDeserializer deserializer);
@protected
TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer);
@@ -556,6 +626,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_graph_node(GraphNode self, SseSerializer serializer);
@protected
void sse_encode_hub_dto(HubDto self, SseSerializer serializer);
@protected
void sse_encode_hub_preview_dto(HubPreviewDto self, SseSerializer serializer);
@protected
void sse_encode_hubs_dto(HubsDto self, SseSerializer serializer);
@protected
void sse_encode_i_32(int self, SseSerializer serializer);
@@ -565,6 +644,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_layout_frame(LayoutFrame self, SseSerializer serializer);
@protected
void sse_encode_legacy_candidate(
LegacyCandidate self,
SseSerializer serializer,
);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@@ -589,6 +674,21 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_hub_dto(List<HubDto> self, SseSerializer serializer);
@protected
void sse_encode_list_legacy_candidate(
List<LegacyCandidate> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_namespace_entry(
List<NamespaceEntry> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
@@ -640,6 +740,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_tag_dto(List<TagDto> self, SseSerializer serializer);
@protected
void sse_encode_list_timeline_day_dto(
List<TimelineDayDto> self,
@@ -649,6 +752,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
@protected
void sse_encode_namespace_entry(
NamespaceEntry self,
SseSerializer serializer,
);
@protected
void sse_encode_opt_String(String? self, SseSerializer serializer);
@@ -682,6 +791,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_page_dto(PageDto self, SseSerializer serializer);
@protected
void sse_encode_page_structure(PageStructure self, SseSerializer serializer);
@protected
void sse_encode_place(Place self, SseSerializer serializer);
@@ -697,6 +809,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_related_dto(RelatedDto self, SseSerializer serializer);
@protected
void sse_encode_tag_dto(TagDto self, SseSerializer serializer);
@protected
void sse_encode_timeline_day_dto(
TimelineDayDto self,
+115
View File
@@ -117,6 +117,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode dco_decode_graph_node(dynamic raw);
@protected
HubDto dco_decode_hub_dto(dynamic raw);
@protected
HubPreviewDto dco_decode_hub_preview_dto(dynamic raw);
@protected
HubsDto dco_decode_hubs_dto(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@@ -126,6 +135,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame dco_decode_layout_frame(dynamic raw);
@protected
LegacyCandidate dco_decode_legacy_candidate(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@@ -144,6 +156,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> dco_decode_list_graph_node(dynamic raw);
@protected
List<HubDto> dco_decode_list_hub_dto(dynamic raw);
@protected
List<LegacyCandidate> dco_decode_list_legacy_candidate(dynamic raw);
@protected
List<NamespaceEntry> dco_decode_list_namespace_entry(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@@ -174,12 +195,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
@protected
List<TagDto> dco_decode_list_tag_dto(dynamic raw);
@protected
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
@protected
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
@protected
NamespaceEntry dco_decode_namespace_entry(dynamic raw);
@protected
String? dco_decode_opt_String(dynamic raw);
@@ -204,6 +231,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto dco_decode_page_dto(dynamic raw);
@protected
PageStructure dco_decode_page_structure(dynamic raw);
@protected
Place dco_decode_place(dynamic raw);
@@ -216,6 +246,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto dco_decode_related_dto(dynamic raw);
@protected
TagDto dco_decode_tag_dto(dynamic raw);
@protected
TimelineDayDto dco_decode_timeline_day_dto(dynamic raw);
@@ -326,6 +359,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
GraphNode sse_decode_graph_node(SseDeserializer deserializer);
@protected
HubDto sse_decode_hub_dto(SseDeserializer deserializer);
@protected
HubPreviewDto sse_decode_hub_preview_dto(SseDeserializer deserializer);
@protected
HubsDto sse_decode_hubs_dto(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@@ -335,6 +377,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer);
@protected
LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@@ -355,6 +400,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<GraphNode> sse_decode_list_graph_node(SseDeserializer deserializer);
@protected
List<HubDto> sse_decode_list_hub_dto(SseDeserializer deserializer);
@protected
List<LegacyCandidate> sse_decode_list_legacy_candidate(
SseDeserializer deserializer,
);
@protected
List<NamespaceEntry> sse_decode_list_namespace_entry(
SseDeserializer deserializer,
);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@@ -385,6 +443,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
@protected
List<TagDto> sse_decode_list_tag_dto(SseDeserializer deserializer);
@protected
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
SseDeserializer deserializer,
@@ -393,6 +454,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
@protected
NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer);
@protected
String? sse_decode_opt_String(SseDeserializer deserializer);
@@ -421,6 +485,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageDto sse_decode_page_dto(SseDeserializer deserializer);
@protected
PageStructure sse_decode_page_structure(SseDeserializer deserializer);
@protected
Place sse_decode_place(SseDeserializer deserializer);
@@ -435,6 +502,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
RelatedDto sse_decode_related_dto(SseDeserializer deserializer);
@protected
TagDto sse_decode_tag_dto(SseDeserializer deserializer);
@protected
TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer);
@@ -558,6 +628,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_graph_node(GraphNode self, SseSerializer serializer);
@protected
void sse_encode_hub_dto(HubDto self, SseSerializer serializer);
@protected
void sse_encode_hub_preview_dto(HubPreviewDto self, SseSerializer serializer);
@protected
void sse_encode_hubs_dto(HubsDto self, SseSerializer serializer);
@protected
void sse_encode_i_32(int self, SseSerializer serializer);
@@ -567,6 +646,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_layout_frame(LayoutFrame self, SseSerializer serializer);
@protected
void sse_encode_legacy_candidate(
LegacyCandidate self,
SseSerializer serializer,
);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@@ -591,6 +676,21 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_hub_dto(List<HubDto> self, SseSerializer serializer);
@protected
void sse_encode_list_legacy_candidate(
List<LegacyCandidate> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_namespace_entry(
List<NamespaceEntry> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
@@ -642,6 +742,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_list_tag_dto(List<TagDto> self, SseSerializer serializer);
@protected
void sse_encode_list_timeline_day_dto(
List<TimelineDayDto> self,
@@ -651,6 +754,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
@protected
void sse_encode_namespace_entry(
NamespaceEntry self,
SseSerializer serializer,
);
@protected
void sse_encode_opt_String(String? self, SseSerializer serializer);
@@ -684,6 +793,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_page_dto(PageDto self, SseSerializer serializer);
@protected
void sse_encode_page_structure(PageStructure self, SseSerializer serializer);
@protected
void sse_encode_place(Place self, SseSerializer serializer);
@@ -699,6 +811,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_related_dto(RelatedDto self, SseSerializer serializer);
@protected
void sse_encode_tag_dto(TagDto self, SseSerializer serializer);
@protected
void sse_encode_timeline_day_dto(
TimelineDayDto self,
+8
View File
@@ -13,8 +13,16 @@ pub mod parse;
pub mod position;
mod schema;
pub mod store;
pub mod structure;
pub mod synapse;
pub mod tags;
pub mod types;
pub use error::{Error, Result};
pub use model::*;
pub use store::Graph;
pub use structure::{
HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent,
};
pub use tags::{MAX_TAG_CHARS, TagInfo, normalize_tag};
pub use types::SUGGESTED_TYPES;
+60
View File
@@ -11,6 +11,40 @@ pub fn new_id() -> Uuid {
Uuid::now_v7()
}
/// What a page is: a note (an outline of blocks), a hub (a container of pages with a short
/// description and an ordered member list, and no blocks) or a template (the outline that new
/// notes of a hub start from; every hub owns exactly one, see `Graph::hub_template`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PageKind {
#[default]
Note,
Hub,
Template,
/// A topic page: notes point at it from their `tags`.
Tag,
}
impl PageKind {
pub fn as_str(self) -> &'static str {
match self {
PageKind::Note => "note",
PageKind::Hub => "hub",
PageKind::Template => "template",
PageKind::Tag => "tag",
}
}
/// Unknown values read as notes.
pub fn parse(s: &str) -> Self {
match s {
"hub" => PageKind::Hub,
"template" => PageKind::Template,
"tag" => PageKind::Tag,
_ => PageKind::Note,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Page {
pub id: PageId,
@@ -22,12 +56,38 @@ pub struct Page {
pub properties: Properties,
pub created_at: i64,
pub updated_at: i64,
/// Defaults to `Note` so ops and snapshots from older versions parse.
#[serde(default)]
pub kind: PageKind,
/// Short plain-text description (hubs).
#[serde(default)]
pub description: String,
/// Hubs this page belongs to (its "parents", like tags). Ids may dangle (deleted pages,
/// pages no longer hubs); readers ignore those.
#[serde(default)]
pub hubs: Vec<PageId>,
/// Titles of the tag pages ([`PageKind::Tag`]) this page is filed under, any number; see
/// `tags`. Always in step with the tag pages (created on first use).
#[serde(default)]
pub tags: Vec<String>,
/// What kind of thing this is ("persona", "lugar"...): plain names, not pages; see `types`.
#[serde(default)]
pub types: Vec<String>,
}
impl Page {
pub fn is_journal(&self) -> bool {
self.journal_date.is_some()
}
pub fn is_hub(&self) -> bool {
self.kind == PageKind::Hub
}
pub fn is_template(&self) -> bool {
self.kind == PageKind::Template
}
pub fn is_tag(&self) -> bool {
self.kind == PageKind::Tag
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+1 -1
View File
@@ -126,7 +126,7 @@ fn scan_line(line: &str, is_prop: bool, refs: &mut Refs) {
}
/// Finds the `]]` closing a `[[` that opened before `from`, allowing nested `[[..]]`.
fn find_close(s: &str, from: usize) -> Option<usize> {
pub(crate) fn find_close(s: &str, from: usize) -> Option<usize> {
let mut depth = 0;
let mut i = from;
while i + 1 < s.len() {
+94 -2
View File
@@ -1,4 +1,6 @@
pub const VERSION: i64 = 2;
use rusqlite::OptionalExtension;
pub const VERSION: i64 = 5;
pub const SCHEMA: &str = r#"
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
@@ -12,7 +14,12 @@ CREATE TABLE IF NOT EXISTS pages (
properties TEXT NOT NULL DEFAULT '{}',
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL,
hlc TEXT NOT NULL
hlc TEXT NOT NULL,
kind TEXT NOT NULL DEFAULT 'note',
description TEXT NOT NULL DEFAULT '',
hubs TEXT NOT NULL DEFAULT '[]',
tags TEXT NOT NULL DEFAULT '[]',
types TEXT NOT NULL DEFAULT '[]'
);
CREATE INDEX IF NOT EXISTS pages_updated ON pages(updated_at);
CREATE INDEX IF NOT EXISTS pages_origin ON pages(origin_journal);
@@ -25,6 +32,23 @@ CREATE TABLE IF NOT EXISTS aliases (
);
CREATE INDEX IF NOT EXISTS aliases_page ON aliases(page_id);
-- Derived index of `pages.hubs` (hub membership lives on the member page), kept in step on
-- every page write like `refs`.
CREATE TABLE IF NOT EXISTS page_hubs (
page_id TEXT NOT NULL,
hub_id TEXT NOT NULL,
PRIMARY KEY (page_id, hub_id)
);
CREATE INDEX IF NOT EXISTS page_hubs_hub ON page_hubs(hub_id);
-- Derived index of `pages.tags` (normalised tag key per page), kept in step on every page write.
CREATE TABLE IF NOT EXISTS page_tags (
page_id TEXT NOT NULL,
tag_key TEXT NOT NULL,
PRIMARY KEY (page_id, tag_key)
);
CREATE INDEX IF NOT EXISTS page_tags_key ON page_tags(tag_key);
CREATE TABLE IF NOT EXISTS blocks (
id TEXT PRIMARY KEY,
page_id TEXT NOT NULL,
@@ -92,6 +116,44 @@ CREATE TABLE IF NOT EXISTS ops (
);
"#;
/// Rebuilds the `page_tags` index from every page's `tags` column.
pub fn rebuild_page_tags(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_tags", [])?;
let rows: Vec<(String, String)> = {
let mut st = conn.prepare("SELECT id, tags FROM pages WHERE tags != '[]'")?;
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?
};
let mut ins =
conn.prepare("INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)")?;
for (id, tags) in rows {
let tags: Vec<String> = serde_json::from_str(&tags).unwrap_or_default();
for t in tags {
ins.execute([&id, &crate::model::title_key(&t)])?;
}
}
Ok(())
}
/// Rebuilds the `page_hubs` index from every page's `hubs` column.
pub fn rebuild_page_hubs(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
conn.execute("DELETE FROM page_hubs", [])?;
let rows: Vec<(String, String)> = {
let mut st = conn.prepare("SELECT id, hubs FROM pages WHERE hubs != '[]'")?;
st.query_map([], |r| Ok((r.get(0)?, r.get(1)?)))?
.collect::<rusqlite::Result<_>>()?
};
let mut ins =
conn.prepare("INSERT OR IGNORE INTO page_hubs(page_id, hub_id) VALUES (?1, ?2)")?;
for (id, hubs) in rows {
let hubs: Vec<uuid::Uuid> = serde_json::from_str(&hubs).unwrap_or_default();
for h in hubs.into_iter().take(1) {
ins.execute([&id, &h.to_string()])?;
}
}
Ok(())
}
/// Upgrades databases created by older versions in place.
pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
let has_alias_hlc: bool = conn
@@ -100,6 +162,36 @@ pub fn migrate(conn: &rusqlite::Connection) -> rusqlite::Result<()> {
if !has_alias_hlc {
conn.execute_batch("ALTER TABLE aliases ADD COLUMN hlc TEXT NOT NULL DEFAULT ''")?;
}
// v3: page kinds (hubs), descriptions and hub membership; `page_hubs` is created by
// `SCHEMA` and rebuilt from `pages.hubs`.
for (col, ddl) in [
("kind", "kind TEXT NOT NULL DEFAULT 'note'"),
("description", "description TEXT NOT NULL DEFAULT ''"),
("hubs", "hubs TEXT NOT NULL DEFAULT '[]'"),
// v4: free-form tags per page; `page_tags` is created by `SCHEMA`.
("tags", "tags TEXT NOT NULL DEFAULT '[]'"),
// v5: tag pages (kind 'tag') and plain-name types per page.
("types", "types TEXT NOT NULL DEFAULT '[]'"),
] {
let has: bool = conn
.prepare("SELECT 1 FROM pragma_table_info('pages') WHERE name=?1")?
.exists([col])?;
if !has {
conn.execute_batch(&format!("ALTER TABLE pages ADD COLUMN {ddl}"))?;
}
}
let version: Option<i64> = conn
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
r.get::<_, String>(0)
})
.optional()?
.and_then(|v| v.parse().ok());
if version.is_some_and(|v| v < 3) {
rebuild_page_hubs(conn)?;
}
if version.is_some_and(|v| v < 4) {
rebuild_page_tags(conn)?;
}
conn.execute(
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema', ?1)",
[VERSION.to_string()],
+123 -23
View File
@@ -21,8 +21,7 @@ pub fn journal_id(date: NaiveDate) -> PageId {
Uuid::new_v5(&JOURNAL_NS, journal_title(date).as_bytes())
}
const PAGE_COLS: &str =
"id, title, journal_date, origin_journal, properties, created_at, updated_at";
const PAGE_COLS: &str = "id, title, journal_date, origin_journal, properties, created_at, updated_at, kind, description, hubs, tags, types";
const BLOCK_COLS: &str =
"id, page_id, parent_id, position, content, properties, collapsed, created_at, updated_at";
@@ -76,13 +75,15 @@ impl Graph {
clock.observe(&last);
}
let blobs = BlobStore::open(dir.join("blobs"))?;
Ok(Self {
let graph = Self {
conn,
blobs,
clock,
dir,
now_override: Cell::new(None),
})
};
graph.repair_tag_pages()?;
Ok(graph)
}
/// Runs `f` atomically. Calls nest (SQLite savepoints), so callers such as importers can
@@ -99,12 +100,16 @@ impl Graph {
}
/// `execute` through the statement cache (hot paths run millions of times on imports).
fn exec<P: rusqlite::Params>(&self, sql: &str, params: P) -> rusqlite::Result<usize> {
pub(crate) fn exec<P: rusqlite::Params>(
&self,
sql: &str,
params: P,
) -> rusqlite::Result<usize> {
self.conn.prepare_cached(sql)?.execute(params)
}
/// `query_row` through the statement cache.
fn row<T, P: rusqlite::Params>(
pub(crate) fn row<T, P: rusqlite::Params>(
&self,
sql: &str,
params: P,
@@ -124,7 +129,7 @@ impl Graph {
/// Atomic scope for one graph operation: a savepoint at top level, a no-op when an
/// enclosing transaction already provides atomicity.
fn tx(&self) -> Result<Tx<'_>> {
pub(crate) fn tx(&self) -> Result<Tx<'_>> {
if self.conn.is_autocommit() {
return self.savepoint();
}
@@ -214,7 +219,16 @@ impl Graph {
Ok(page)
}
fn create_page_tx(&self, new: NewPage) -> Result<Page> {
pub(crate) fn create_page_tx(&self, new: NewPage) -> Result<Page> {
self.create_page_kind_tx(new, PageKind::Note, String::new())
}
pub(crate) fn create_page_kind_tx(
&self,
new: NewPage,
kind: PageKind,
description: String,
) -> Result<Page> {
let title = new.title.trim().to_string();
if title.is_empty() {
return Err(Error::Invalid("empty page title".into()));
@@ -238,6 +252,11 @@ impl Graph {
properties: new.properties,
created_at: new.created_at.unwrap_or(now),
updated_at: new.updated_at.unwrap_or(now),
kind,
description,
hubs: Vec::new(),
tags: Vec::new(),
types: Vec::new(),
};
self.write_page(&page, &self.tick())?;
Ok(page)
@@ -270,10 +289,11 @@ impl Graph {
/// Pages ordered by last update (most recent first).
pub fn list_pages(&self, include_journals: bool, limit: u32, offset: u32) -> Result<Vec<Page>> {
// Templates are reached through their hub, never listed as pages.
let filter = if include_journals {
""
"WHERE kind != 'template'"
} else {
"WHERE journal_date IS NULL"
"WHERE journal_date IS NULL AND kind != 'template'"
};
let mut st = self.conn.prepare_cached(&format!(
"SELECT {PAGE_COLS} FROM pages {filter} ORDER BY updated_at DESC LIMIT ?1 OFFSET ?2"
@@ -338,9 +358,12 @@ impl Graph {
st.query_map([&old_key], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
page.title = new_title.to_string();
let old_title = std::mem::replace(&mut page.title, new_title.to_string());
page.updated_at = self.now_ms();
self.write_page(&page, &self.tick())?;
if page.is_tag() {
self.retitle_tag(&old_title, new_title)?;
}
for bid in referencing {
if let Some(mut b) = self.get_block(parse_id(&bid)?)? {
let rewritten = parse::rewrite_refs(&b.content, &old_key, new_title);
@@ -365,9 +388,34 @@ impl Graph {
Ok(page)
}
/// Deletes a page and all its blocks.
/// Deletes a page and all its blocks; when it is a hub, its members leave it.
pub fn delete_page(&self, id: PageId) -> Result<()> {
let tx = self.tx()?;
if let Some(p) = self.get_page(id)? {
if p.is_template() {
return Err(Error::Invalid(
"a template cannot be deleted on its own; it goes with its hub".into(),
));
}
if p.is_hub() {
for t in self.hub_template_ids(id)? {
self.delete_page_rows(t)?;
}
}
}
self.delete_page_rows(id)?;
tx.commit()?;
Ok(())
}
pub(crate) fn delete_page_rows(&self, id: PageId) -> Result<()> {
// Members of a deleted hub leave it (each member page is rewritten and logged).
self.drop_hub_from_members(id)?;
if let Some(p) = self.get_page(id)?
&& p.is_tag()
{
self.drop_tag_from_members(&p.title)?;
}
let ids: Vec<String> = {
let mut st = self
.conn
@@ -379,7 +427,6 @@ impl Graph {
self.remove_block_row(parse_id(&b)?, &self.tick())?;
}
self.remove_page_row(id, &self.tick())?;
tx.commit()?;
Ok(())
}
@@ -437,6 +484,11 @@ impl Graph {
properties: Properties::new(),
created_at: ms,
updated_at: ms,
kind: PageKind::Note,
description: String::new(),
hubs: Vec::new(),
tags: Vec::new(),
types: Vec::new(),
};
self.write_page(&page, &self.tick())?;
Ok(page)
@@ -593,6 +645,7 @@ impl Graph {
/// Inserts a new block with `content` and indexes its refs.
pub fn insert_block(&self, page: PageId, at: Placement, content: &str) -> Result<Block> {
self.ensure_not_hub(page)?;
let tx = self.tx()?;
let (parent_id, position) = self.resolve_placement(page, at)?;
let now = self.now_ms();
@@ -615,6 +668,7 @@ impl Graph {
/// Writes a fully specified block (importer). Pages referenced by it are created, born in
/// the block's journal when it lives in one. Does not record edit activity.
pub fn put_block(&self, block: &Block) -> Result<()> {
self.ensure_not_hub(block.page_id)?;
let tx = self.tx()?;
self.write_block(block, &self.tick())?;
self.ensure_ref_pages(block)?;
@@ -660,6 +714,7 @@ impl Graph {
/// Moves a block (with its subtree) to a new place, possibly on another page.
pub fn move_block(&self, id: BlockId, page: PageId, at: Placement) -> Result<Block> {
self.ensure_not_hub(page)?;
let tx = self.tx()?;
let mut b = self
.get_block(id)?
@@ -712,6 +767,21 @@ impl Graph {
Ok(())
}
/// Hubs have no outline: block writes into them are refused.
fn ensure_not_hub(&self, page: PageId) -> Result<()> {
let kind: Option<String> = self
.row(
"SELECT kind FROM pages WHERE id=?1",
[page.to_string()],
|r| r.get(0),
)
.optional()?;
if kind.as_deref() == Some(PageKind::Hub.as_str()) {
return Err(Error::Invalid("hubs have no blocks".into()));
}
Ok(())
}
fn descendants(&self, id: BlockId) -> Result<Vec<BlockId>> {
let mut st = self.conn.prepare_cached(
"WITH RECURSIVE d(id) AS (SELECT id FROM blocks WHERE parent_id=?1
@@ -878,7 +948,7 @@ impl Graph {
}
/// Bumps `updated_at` and records today's activity for a page.
fn touch_page(&self, page: PageId) -> Result<()> {
pub(crate) fn touch_page(&self, page: PageId) -> Result<()> {
let now = self.now_ms();
let day = journal_title(day_of(now));
self.exec(
@@ -1110,11 +1180,11 @@ impl Graph {
// ----------------------------------------------------------- raw writes
fn tick(&self) -> String {
pub(crate) fn tick(&self) -> String {
self.clock.tick(self.now_ms())
}
fn log(&self, hlc: &str, op: &Op) -> Result<()> {
pub(crate) fn log(&self, hlc: &str, op: &Op) -> Result<()> {
self.exec(
"INSERT INTO ops(hlc, payload) VALUES (?1, ?2)",
params![hlc, serde_json::to_string(op)?],
@@ -1122,17 +1192,17 @@ impl Graph {
Ok(())
}
fn write_page(&self, page: &Page, hlc: &str) -> Result<()> {
pub(crate) fn write_page(&self, page: &Page, hlc: &str) -> Result<()> {
self.write_page_row(page, hlc)?;
self.log(hlc, &Op::UpsertPage { page: page.clone() })
}
fn write_page_row(&self, p: &Page, hlc: &str) -> Result<()> {
self.exec(
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)
"INSERT INTO pages(id, title, title_key, journal_date, origin_journal, properties, created_at, updated_at, hlc, kind, description, hubs, tags, types)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
ON CONFLICT(id) DO UPDATE SET title=?2, title_key=?3, journal_date=?4, origin_journal=?5,
properties=?6, created_at=?7, updated_at=?8, hlc=?9",
properties=?6, created_at=?7, updated_at=?8, hlc=?9, kind=?10, description=?11, hubs=?12, tags=?13, types=?14",
params![
p.id.to_string(),
p.title,
@@ -1142,9 +1212,30 @@ impl Graph {
serde_json::to_string(&p.properties)?,
p.created_at,
p.updated_at,
hlc
hlc,
p.kind.as_str(),
p.description,
serde_json::to_string(&p.hubs)?,
serde_json::to_string(&p.tags)?,
serde_json::to_string(&p.types)?
],
)?;
let id = p.id.to_string();
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&id])?;
for t in &p.tags {
self.exec(
"INSERT OR IGNORE INTO page_tags(page_id, tag_key) VALUES (?1, ?2)",
params![id, title_key(t)],
)?;
}
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&id])?;
// A page belongs to one hub: only the first entry counts (older replicas may sync more).
for h in p.hubs.iter().take(1) {
self.exec(
"INSERT OR IGNORE INTO page_hubs(page_id, hub_id) VALUES (?1, ?2)",
params![id, h.to_string()],
)?;
}
Ok(())
}
@@ -1177,6 +1268,10 @@ impl Graph {
.execute("DELETE FROM page_activity WHERE page_id=?1", [&s])?;
self.conn
.execute("DELETE FROM synapses WHERE a=?1 OR b=?1", [&s])?;
// Only the page's own memberships: rows naming it as a hub mirror other pages'
// `hubs` and dangle until those pages are rewritten.
self.exec("DELETE FROM page_hubs WHERE page_id=?1", [&s])?;
self.exec("DELETE FROM page_tags WHERE page_id=?1", [&s])?;
self.exec(
"INSERT OR REPLACE INTO tombstones(id, hlc) VALUES (?1, ?2)",
params![s, hlc],
@@ -1329,7 +1424,7 @@ impl Graph {
}
/// Savepoint guard: rolled back on drop unless committed.
struct Tx<'a> {
pub(crate) struct Tx<'a> {
conn: &'a Connection,
/// Whether this guard opened a savepoint (false when nested in a transaction).
active: bool,
@@ -1337,7 +1432,7 @@ struct Tx<'a> {
}
impl Tx<'_> {
fn commit(mut self) -> Result<()> {
pub(crate) fn commit(mut self) -> Result<()> {
if self.active {
self.conn.execute_batch("RELEASE graph")?;
}
@@ -1397,6 +1492,11 @@ fn page_row(r: &Row) -> rusqlite::Result<Page> {
properties: props(r.get(4)?),
created_at: r.get(5)?,
updated_at: r.get(6)?,
kind: PageKind::parse(&r.get::<_, String>(7)?),
description: r.get(8)?,
hubs: serde_json::from_str(&r.get::<_, String>(9)?).unwrap_or_default(),
tags: serde_json::from_str(&r.get::<_, String>(10)?).unwrap_or_default(),
types: serde_json::from_str(&r.get::<_, String>(11)?).unwrap_or_default(),
})
}
File diff suppressed because it is too large. Load diff
+226
View File
@@ -0,0 +1,226 @@
//! Tags: topic pages ("neurociencia", "finanzas") that notes are filed under.
//!
//! A tag is a page of kind [`PageKind::Tag`]: it has an outline, backlinks and a place in the
//! graph like any note. A page lists the titles of its tag pages in [`Page::tags`] (synced
//! with the page, last writer wins), any number of them, and a derived `page_tags` index
//! answers "which pages have this tag". Tagging with a title that has no page creates the tag
//! page; tagging with an existing note turns that note into a tag page. Renaming or deleting
//! a tag page keeps its members in step. Names compare case-insensitively ([`title_key`]).
//! What a page *is* ("persona", "lugar") is a different, name-only mechanism: see `types`.
use crate::error::{Error, Result};
use crate::model::{NewPage, Page, PageId, PageKind, title_key};
use crate::store::{Graph, parse_id};
use std::collections::HashMap;
/// Longest tag (or type) name, in characters.
pub const MAX_TAG_CHARS: usize = 48;
/// A tag with the number of pages filed under it (tag pages with no members count 0).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagInfo {
pub name: String,
pub count: u32,
/// Part of the seeded suggestions (types only; tag pages are never seeded).
pub suggested: bool,
}
/// Cleans a tag name: leading `#` dropped, whitespace collapsed. `None` when nothing is left.
pub fn normalize_tag(raw: &str) -> Option<String> {
let t = raw.trim().trim_start_matches('#');
let t = t.split_whitespace().collect::<Vec<_>>().join(" ");
(!t.is_empty()).then_some(t)
}
impl Graph {
/// The tag page called `name`, created (or made out of a note of that name) on demand.
fn ensure_tag_page(&self, name: &str) -> Result<Page> {
if let Some(mut p) = self.page_by_title(name)? {
return match p.kind {
PageKind::Tag => Ok(p),
PageKind::Note if !p.is_journal() => {
p.kind = PageKind::Tag;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
Ok(p)
}
_ => Err(Error::Invalid(format!(
"{name:?} is a hub, template or journal and cannot be a tag"
))),
};
}
self.create_page_kind_tx(NewPage::titled(name), PageKind::Tag, String::new())
}
/// Replaces the tags of `page` (names cleaned, duplicates dropped case-insensitively,
/// order kept; each becomes the title of a tag page). Journals, templates and tag pages
/// cannot be tagged, nor can a page be tagged with itself.
pub fn set_page_tags(&self, page: PageId, tags: Vec<String>) -> Result<Page> {
let tx = self.tx()?;
let mut p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut wanted: Vec<String> = Vec::with_capacity(tags.len());
for raw in tags {
let Some(t) = normalize_tag(&raw) else {
continue;
};
if t.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"tag {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
if !wanted.iter().any(|x| title_key(x) == title_key(&t)) {
wanted.push(t);
}
}
if (p.is_journal() || p.is_template() || p.is_tag()) && !wanted.is_empty() {
return Err(Error::Invalid(
"journals, templates and tag pages cannot have tags".into(),
));
}
if wanted.iter().any(|t| title_key(t) == title_key(&p.title)) {
return Err(Error::Invalid("a page cannot be its own tag".into()));
}
let mut next = Vec::with_capacity(wanted.len());
for t in wanted {
next.push(self.ensure_tag_page(&t)?.title);
}
if next == p.tags {
tx.commit()?;
return Ok(p);
}
p.tags = next;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
tx.commit()?;
Ok(p)
}
/// Adds a tag (no-op when the page already has it).
pub fn add_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut tags = p.tags;
tags.push(tag.to_string());
self.set_page_tags(page, tags)
}
/// Removes a tag (no-op when the page does not have it). The tag page stays.
pub fn remove_page_tag(&self, page: PageId, tag: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let key = title_key(tag);
let tags = p.tags.into_iter().filter(|t| title_key(t) != key).collect();
self.set_page_tags(page, tags)
}
/// Pages carrying `tag`, most recently updated first.
pub fn pages_with_tag(&self, tag: &str) -> Result<Vec<PageId>> {
let mut st = self.conn().prepare_cached(
"SELECT p.id FROM page_tags t JOIN pages p ON p.id = t.page_id
WHERE t.tag_key=?1 ORDER BY p.updated_at DESC, p.id",
)?;
let rows = st.query_map([title_key(tag)], |r| r.get::<_, String>(0))?;
rows.map(|r| parse_id(&r?)).collect()
}
/// Tags of every tagged page, as stored.
pub fn all_page_tags(&self) -> Result<HashMap<PageId, Vec<String>>> {
let mut st = self
.conn()
.prepare_cached("SELECT id, tags FROM pages WHERE tags != '[]'")?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut out = HashMap::new();
for row in rows {
let (id, tags) = row?;
out.insert(
parse_id(&id)?,
serde_json::from_str(&tags).unwrap_or_default(),
);
}
Ok(out)
}
/// Every tag page with the number of pages under it: most used first, then by name.
pub fn tag_catalog(&self) -> Result<Vec<TagInfo>> {
let mut st = self.conn().prepare_cached(
"SELECT p.title, (SELECT COUNT(*) FROM page_tags t WHERE t.tag_key = p.title_key)
FROM pages p WHERE p.kind = 'tag'",
)?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, u32>(1)?)))?;
let mut out = Vec::new();
for row in rows {
let (name, count) = row?;
out.push(TagInfo {
name,
count,
suggested: false,
});
}
out.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| title_key(&a.name).cmp(&title_key(&b.name)))
});
Ok(out)
}
/// A tag page was renamed: its members now list the new title.
pub(crate) fn retitle_tag(&self, old: &str, new: &str) -> Result<()> {
for id in self.pages_with_tag(old)? {
if let Some(mut p) = self.get_page(id)? {
let key = title_key(old);
for t in &mut p.tags {
if title_key(t) == key {
*t = new.to_string();
}
}
self.write_page(&p, &self.tick())?;
}
}
Ok(())
}
/// A tag page was deleted: its members stop listing it.
pub(crate) fn drop_tag_from_members(&self, title: &str) -> Result<()> {
let key = title_key(title);
for id in self.pages_with_tag(title)? {
if let Some(mut p) = self.get_page(id)? {
p.tags.retain(|t| title_key(t) != key);
self.write_page(&p, &self.tick())?;
}
}
Ok(())
}
/// Databases from before tag pages (or snapshots of them) list tags that have no page:
/// create the missing pages, keeping the spelling first used.
pub(crate) fn repair_tag_pages(&self) -> Result<()> {
let missing: Vec<String> = {
let mut st = self.conn().prepare_cached(
"SELECT DISTINCT tag_key FROM page_tags
WHERE tag_key NOT IN (SELECT title_key FROM pages)",
)?;
st.query_map([], |r| r.get(0))?
.collect::<std::result::Result<_, _>>()?
};
if missing.is_empty() {
return Ok(());
}
let tx = self.tx()?;
let mut done = std::collections::HashSet::new();
for (_, tags) in self.all_page_tags()? {
for t in tags {
let key = title_key(&t);
if missing.contains(&key) && done.insert(key) {
self.ensure_tag_page(&t)?;
}
}
}
tx.commit()?;
Ok(())
}
}
+128
View File
@@ -0,0 +1,128 @@
//! Types: what kind of thing a page is ("persona", "lugar", "empresa").
//!
//! Types are plain names from a small vocabulary, not pages: a page carries its own list
//! ([`Page::types`], synced with the page, last writer wins). Topics are a different
//! mechanism: see `tags`.
use crate::error::{Error, Result};
use crate::model::{Page, PageId, title_key};
use crate::store::Graph;
use crate::tags::{MAX_TAG_CHARS, TagInfo, normalize_tag};
use std::collections::HashMap;
/// Types offered in pickers before they are used anywhere (the seed of the vocabulary).
pub const SUGGESTED_TYPES: [&str; 10] = [
"persona",
"lugar",
"empresa",
"cliente",
"herramienta",
"concepto",
"idea",
"evento",
"recurso",
"receta",
];
impl Graph {
/// Replaces the types of `page` (names cleaned, duplicates dropped case-insensitively,
/// order kept). Journals and templates cannot be typed.
pub fn set_page_types(&self, page: PageId, types: Vec<String>) -> Result<Page> {
let tx = self.tx()?;
let mut p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut next: Vec<String> = Vec::with_capacity(types.len());
for raw in types {
let Some(t) = normalize_tag(&raw) else {
continue;
};
if t.chars().count() > MAX_TAG_CHARS {
return Err(Error::Invalid(format!(
"type {t:?} is longer than {MAX_TAG_CHARS} characters"
)));
}
if !next.iter().any(|x| title_key(x) == title_key(&t)) {
next.push(t);
}
}
if next == p.types {
tx.commit()?;
return Ok(p);
}
if (p.is_journal() || p.is_template()) && !next.is_empty() {
return Err(Error::Invalid(
"journals and templates cannot have types".into(),
));
}
p.types = next;
p.updated_at = self.now_ms();
self.write_page(&p, &self.tick())?;
tx.commit()?;
Ok(p)
}
/// Adds a type (no-op when the page already has it).
pub fn add_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let mut types = p.types;
types.push(ty.to_string());
self.set_page_types(page, types)
}
/// Removes a type (no-op when the page does not have it).
pub fn remove_page_type(&self, page: PageId, ty: &str) -> Result<Page> {
let p = self
.get_page(page)?
.ok_or_else(|| Error::NotFound(page.to_string()))?;
let key = title_key(ty);
let types = p
.types
.into_iter()
.filter(|t| title_key(t) != key)
.collect();
self.set_page_types(page, types)
}
/// The vocabulary: every type in use (spelling of its first page) plus the suggestions not
/// used yet. Used types first by count then name, then unused suggestions in seed order.
pub fn type_catalog(&self) -> Result<Vec<TagInfo>> {
let mut st = self.conn().prepare_cached(
"SELECT types FROM pages WHERE types != '[]' ORDER BY created_at, id",
)?;
let rows = st.query_map([], |r| r.get::<_, String>(0))?;
let mut used: HashMap<String, (String, u32)> = HashMap::new();
for row in rows {
let types: Vec<String> = serde_json::from_str(&row?).unwrap_or_default();
for t in types {
used.entry(title_key(&t)).or_insert((t, 0)).1 += 1;
}
}
let suggested = |k: &str| SUGGESTED_TYPES.iter().any(|s| title_key(s) == k);
let mut out: Vec<TagInfo> = used
.iter()
.map(|(k, (name, count))| TagInfo {
name: name.clone(),
count: *count,
suggested: suggested(k),
})
.collect();
out.sort_by(|a, b| {
b.count
.cmp(&a.count)
.then_with(|| title_key(&a.name).cmp(&title_key(&b.name)))
});
for s in SUGGESTED_TYPES {
if !used.contains_key(&title_key(s)) {
out.push(TagInfo {
name: s.to_string(),
count: 0,
suggested: true,
});
}
}
Ok(out)
}
}
+806
View File
@@ -0,0 +1,806 @@
use serde_json::json;
use synapse_core::{
Error, Graph, HubConversion, NewPage, Op, PageId, PageKind, Placement, is_legacy_page,
namespace_parent,
};
fn graph() -> (tempfile::TempDir, Graph) {
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
(dir, g)
}
fn page(g: &Graph, title: &str, blocks: &[&str]) -> PageId {
let p = g.ensure_page(title, None).unwrap();
for b in blocks {
g.insert_block(p.id, Placement::LastChildOf(None), b)
.unwrap();
}
p.id
}
fn hub(g: &Graph, title: &str) -> PageId {
g.create_hub(title, "").unwrap().id
}
fn titles(g: &Graph, ids: &[PageId]) -> Vec<String> {
ids.iter()
.map(|&i| g.get_page(i).unwrap().unwrap().title)
.collect()
}
fn texts(g: &Graph, id: PageId) -> Vec<(usize, String)> {
g.page_tree(id)
.unwrap()
.into_iter()
.map(|(d, b)| (d, b.content))
.collect()
}
fn invalid<T: std::fmt::Debug>(r: synapse_core::Result<T>) -> bool {
matches!(r, Err(Error::Invalid(_)))
}
/// Ships every op of `from` newer than `after` to `to`; returns how many applied.
fn ship(from: &Graph, to: &Graph, after: i64) -> usize {
from.ops_since(after, 100_000)
.unwrap()
.iter()
.filter(|r| to.apply_remote(&r.hlc, &r.op).unwrap())
.count()
}
#[test]
fn a_page_belongs_to_at_most_one_hub() {
let (_d, g) = graph();
let media = g.create_hub("Media", " Things I watch ").unwrap();
assert_eq!(media.kind, PageKind::Hub);
assert_eq!(media.description, "Things I watch");
let work = hub(&g, "Work");
let books = hub(&g, "Books");
let zeta = page(&g, "Zeta", &["z"]);
let alpha = page(&g, "Alpha", &["a"]);
g.add_to_hub(zeta, media.id).unwrap();
g.add_to_hub(alpha, media.id).unwrap();
g.add_to_hub(books, media.id).unwrap();
// Duplicates are no-ops.
let seq = g.last_seq().unwrap();
g.add_to_hub(alpha, media.id).unwrap();
assert_eq!(g.last_seq().unwrap(), seq);
// Sub-hubs first, then notes, each by title.
assert_eq!(
titles(&g, &g.hub_members(media.id).unwrap()),
["Books", "Alpha", "Zeta"]
);
assert_eq!(titles(&g, &g.hubs_of(alpha).unwrap()), ["Media"]);
// A page lives in one hub: adding it elsewhere moves it.
g.add_to_hub(alpha, work).unwrap();
assert_eq!(titles(&g, &g.hubs_of(alpha).unwrap()), ["Work"]);
assert_eq!(g.get_page(alpha).unwrap().unwrap().hubs, [work]);
assert_eq!(
titles(&g, &g.hub_members(media.id).unwrap()),
["Books", "Zeta"]
);
assert!(invalid(g.set_page_hubs(zeta, vec![work, media.id])));
let p = g.set_page_hubs(zeta, vec![work, work]).unwrap();
assert_eq!(p.hubs, [work]);
g.remove_from_hub(zeta, work).unwrap();
assert!(g.hubs_of(zeta).unwrap().is_empty());
// A template cannot leave its hub.
let t = g.hub_template(work).unwrap();
assert!(invalid(g.add_to_hub(t, media.id)));
let s = g.set_hub_description(media.id, "Screen and paper").unwrap();
assert_eq!(s.description, "Screen and paper");
assert!(invalid(g.set_hub_description(zeta, "x")));
}
#[test]
fn hubs_have_no_blocks() {
let (_d, g) = graph();
let h = hub(&g, "Hub");
let n = page(&g, "Note", &["one"]);
assert!(invalid(g.insert_block(
h,
Placement::LastChildOf(None),
"x"
)));
let b = g.page_tree(n).unwrap()[0].1.clone();
assert!(invalid(g.move_block(b.id, h, Placement::LastChildOf(None))));
let mut moved = b.clone();
moved.page_id = h;
assert!(invalid(g.put_block(&moved)));
assert!(g.page_tree(h).unwrap().is_empty());
// A date title cannot be a hub.
assert!(invalid(g.create_hub("2024-01-02", "")));
}
#[test]
fn membership_validation_and_cycles() {
let (_d, g) = graph();
let a = hub(&g, "A");
let b = hub(&g, "B");
let c = hub(&g, "C");
let note = page(&g, "Note", &[]);
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap())
.unwrap();
g.add_to_hub(b, a).unwrap(); // A ⊃ B
g.add_to_hub(c, b).unwrap(); // B ⊃ C
assert!(invalid(g.add_to_hub(a, a)), "self");
assert!(invalid(g.add_to_hub(a, c)), "A inside C would be a cycle");
assert!(invalid(g.add_to_hub(a, b)), "direct cycle");
assert!(invalid(g.add_to_hub(j.id, a)), "journals are never members");
assert!(invalid(g.add_to_hub(note, note)));
assert!(invalid(g.add_to_hub(a, note)), "a note is not a hub");
assert!(matches!(
g.add_to_hub(note, synapse_core::new_id()),
Err(Error::NotFound(_))
));
// A note can be in a hub nested anywhere; a hub can be in two branches (DAG).
g.add_to_hub(note, c).unwrap();
g.add_to_hub(c, a).unwrap();
let s = g.structure().unwrap();
let info = |id| s.hubs.iter().find(|h| h.page == id).unwrap();
assert_eq!(info(a).members, [b, c]);
assert_eq!(info(c).depth, 1, "shortest path from a root");
assert_eq!(s.home[&note], c);
}
#[test]
fn delete_page_cleans_memberships() {
let (_d, g) = graph();
let h = hub(&g, "H");
let other = hub(&g, "Other");
let n = page(&g, "N", &["x"]);
g.add_to_hub(n, h).unwrap();
g.add_to_hub(h, other).unwrap();
let seq = g.last_seq().unwrap();
g.delete_page(h).unwrap();
assert!(g.get_page(n).unwrap().unwrap().hubs.is_empty());
let logged: Vec<_> = g
.ops_since(seq, 100)
.unwrap()
.into_iter()
.filter_map(|r| match r.op {
Op::UpsertPage { page } => Some(page),
_ => None,
})
.collect();
assert!(logged.iter().any(|p| p.id == n && p.hubs.is_empty()));
assert!(g.hub_members(other).unwrap().is_empty());
g.delete_page(n).unwrap();
let s = g.structure().unwrap();
assert_eq!(s.hubs.len(), 1);
assert!(s.hubs[0].members.is_empty());
}
#[test]
fn conversion_preview() {
let (_d, g) = graph();
g.set_now(Some(1_700_000_000_000));
let p = page(
&g,
"Entretenimiento/TV/Anime",
&[
"## Series",
"[[Naruto]]",
"#Bleach, [[2024-01-02]]",
"type:: [[Genre]]",
"My **favourite** ones, see [[One Piece]] and #[[Death Note]]",
"[[Entretenimiento/TV/Anime]]",
"[[Naruto]] again with words",
],
);
// A dangling alias (its page is gone) must not break anything.
let gone = page(&g, "Gone", &[]);
g.set_alias("Ghost", Some(gone)).unwrap();
g.conn()
.execute("DELETE FROM pages WHERE id=?1", [gone.to_string()])
.unwrap();
page(&g, "Uses", &["mentions [[Ghost]]"]);
let prop = page(&g, "Props", &[]);
let mut props = serde_json::Map::new();
props.insert("parent".into(), json!("[[Entretenimiento/TV/Anime]]"));
g.set_page_properties(prop, props).unwrap();
g.set_alias("Animu", Some(p)).unwrap();
page(&g, "Tagger", &["watch #Animu"]);
page(
&g,
"BlockProp",
&["x\ncategory:: [[Entretenimiento/TV/Anime]]"],
);
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 3, 3).unwrap())
.unwrap();
g.insert_block(j.id, Placement::LastChildOf(None), "#Animu")
.unwrap();
let pv = g.hub_conversion_preview(p).unwrap();
assert_eq!(pv.suggested_title, "Anime");
assert_eq!(
pv.suggested_description,
"My favourite ones, see One Piece and Death Note"
);
assert_eq!(
titles(&g, &pv.members),
[
"Naruto",
"Bleach",
"One Piece",
"Death Note",
"Props",
"BlockProp",
"Tagger"
]
);
assert_eq!(pv.prose_blocks, 2);
assert_eq!(pv.blocks, 7);
let plain = page(&g, "Plain", &[]);
let pv = g.hub_conversion_preview(plain).unwrap();
assert_eq!(pv.suggested_title, "Plain");
assert!(pv.suggested_description.is_empty() && pv.members.is_empty());
assert!(invalid(g.hub_conversion_preview(j.id)));
let h = hub(&g, "Hub");
assert!(invalid(g.hub_conversion_preview(h)));
}
#[test]
fn convert_to_hub_shortens_title_and_keeps_outline() {
let (_d, g) = graph();
let p = page(&g, "Media/Anime", &["Intro text", "[[Naruto]]"]);
let root = g.page_tree(p).unwrap()[0].1.id;
g.insert_block(p, Placement::LastChildOf(Some(root)), "child")
.unwrap();
let parent = hub(&g, "Media");
g.add_to_hub(p, parent).unwrap();
let refr = page(&g, "Elsewhere", &["see [[Media/Anime]]"]);
let naruto = g.page_by_title("Naruto").unwrap().unwrap().id;
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2024, 1, 2).unwrap())
.unwrap();
let h = g
.convert_to_hub(
p,
&HubConversion {
title: "Anime".into(),
description: " Japanese animation ".into(),
// Journals and cycles (the hub's own parent) are skipped silently.
members: vec![naruto, j.id, parent, naruto],
keep_outline_as: Some("Anime (notes)".into()),
},
)
.unwrap();
assert_eq!(h.title, "Anime");
assert!(h.is_hub() && h.description == "Japanese animation");
assert_eq!(h.hubs, [parent], "the hub stays where it was");
assert!(g.page_tree(p).unwrap().is_empty());
assert_eq!(texts(&g, refr), [(0, "see [[Anime]]".to_string())]);
let note = g.page_by_title("Anime (notes)").unwrap().unwrap();
assert_eq!(
texts(&g, note.id),
[
(0, "Intro text".to_string()),
(1, "child".to_string()),
(0, "[[Naruto]]".to_string())
]
);
assert_eq!(
titles(&g, &g.hub_members(p).unwrap()),
["Anime (notes)", "Naruto"]
);
assert!(g.get_page(parent).unwrap().unwrap().hubs.is_empty());
// Back to a note: description, then one link per member; members leave the hub.
let n = g.convert_to_note(p).unwrap();
assert_eq!(n.kind, PageKind::Note);
assert!(n.description.is_empty());
assert_eq!(
texts(&g, p),
[
(0, "Japanese animation".to_string()),
(0, "[[Anime (notes)]]".to_string()),
(0, "[[Naruto]]".to_string())
]
);
assert!(g.hub_members(p).unwrap().is_empty());
assert!(g.get_page(naruto).unwrap().unwrap().hubs.is_empty());
assert!(invalid(g.convert_to_note(p)));
}
#[test]
fn convert_to_hub_without_outline_and_title_clash() {
let (_d, g) = graph();
let p = page(&g, "Projects/Ideas", &["[[A]]", "some prose"]);
page(&g, "Ideas", &["taken"]);
let before = g.last_seq().unwrap();
let clash = g.convert_to_hub(
p,
&HubConversion {
title: "Ideas".into(),
..Default::default()
},
);
assert!(matches!(clash, Err(Error::Conflict(_))), "{clash:?}");
// Nothing changed.
assert_eq!(g.last_seq().unwrap(), before);
let cur = g.get_page(p).unwrap().unwrap();
assert_eq!(cur.title, "Projects/Ideas");
assert!(!cur.is_hub());
assert_eq!(g.page_tree(p).unwrap().len(), 2);
// An existing title for the kept-outline note is refused too.
let clash = g.convert_to_hub(
p,
&HubConversion {
title: "Projects/Ideas".into(),
keep_outline_as: Some("ideas".into()),
..Default::default()
},
);
assert!(matches!(clash, Err(Error::Conflict(_))));
assert_eq!(g.page_tree(p).unwrap().len(), 2);
let a = g.page_by_title("A").unwrap().unwrap().id;
let h = g
.convert_to_hub(
p,
&HubConversion {
title: "Projects/Ideas".into(),
description: String::new(),
members: vec![a],
keep_outline_as: None,
},
)
.unwrap();
assert_eq!(h.title, "Projects/Ideas");
assert!(g.page_tree(p).unwrap().is_empty());
assert_eq!(g.hub_members(p).unwrap(), [a]);
assert!(invalid(g.convert_to_hub(p, &HubConversion::default())));
}
#[test]
fn structure_depth_home_and_dangling_ids() {
let (_d, g) = graph();
let root = hub(&g, "Root");
let sub = hub(&g, "Sub");
let leaf = page(&g, "Leaf", &[]);
let r1 = page(&g, "R1", &[]);
g.add_to_hub(sub, root).unwrap();
g.add_to_hub(leaf, sub).unwrap();
g.add_to_hub(r1, root).unwrap();
// Dangling ids: a deleted page and a note.
let gone = synapse_core::new_id();
let mut p = g.get_page(r1).unwrap().unwrap();
p.hubs.push(gone);
p.hubs.push(leaf);
g.put_page(&p).unwrap();
let s = g.structure().unwrap();
let info = |id| s.hubs.iter().find(|h| h.page == id).unwrap();
assert_eq!((info(root).depth, info(sub).depth), (0, 1));
assert_eq!(info(root).members, [sub, r1]);
assert_eq!(info(sub).members, [leaf]);
assert_eq!(s.home[&leaf], sub, "deepest wins");
assert_eq!(
(s.home[&sub], s.home[&root], s.home[&r1]),
(sub, root, root)
);
assert_eq!(s.hubs.len(), 2);
assert_eq!(g.hubs_of(r1).unwrap(), [root]);
let alone = page(&g, "Alone", &[]);
assert!(!g.structure().unwrap().home.contains_key(&alone));
}
#[test]
fn replicas_converge_in_any_order_and_break_concurrent_cycles() {
let (_a, a) = graph();
let (_b, b) = graph();
let h = a.create_hub("Hub", "desc").unwrap().id;
let x = hub(&a, "X");
let n = page(&a, "Note", &["text"]);
a.add_to_hub(n, h).unwrap();
a.add_to_hub(x, h).unwrap();
// Out of order: members' pages arrive before the hub page.
let mut ops = a.ops_since(0, 1000).unwrap();
ops.reverse();
for r in &ops {
b.apply_remote(&r.hlc, &r.op).unwrap();
}
let hub_b = b.get_page(h).unwrap().unwrap();
assert!(hub_b.is_hub() && hub_b.description == "desc");
assert_eq!(b.structure().unwrap(), a.structure().unwrap());
assert_eq!(b.hub_members(h).unwrap(), [x, n]);
// Idempotent: replaying applies nothing; applied ops were re-logged on B.
assert_eq!(ship(&a, &b, 0), 0);
assert!(
b.ops_since(0, 1000)
.unwrap()
.iter()
.any(|r| matches!(&r.op, Op::UpsertPage { page } if page.id == n && page.hubs == [h]))
);
// Hub deletion on B reaches A, members included.
let seq_b = b.last_seq().unwrap();
b.delete_page(x).unwrap();
ship(&b, &a, seq_b);
assert!(a.get_page(x).unwrap().is_none());
assert_eq!(a.hub_members(h).unwrap(), [n]);
// Concurrent cycle: A puts Y in Z while B puts Z in Y.
let y = hub(&a, "Y");
let z = hub(&a, "Z");
ship(&a, &b, 0);
let (sa, sb) = (a.last_seq().unwrap(), b.last_seq().unwrap());
a.add_to_hub(y, z).unwrap();
std::thread::sleep(std::time::Duration::from_millis(2));
b.add_to_hub(z, y).unwrap();
ship(&a, &b, sa);
ship(&b, &a, sb);
let (s1, s2) = (a.structure().unwrap(), b.structure().unwrap());
assert_eq!(s1, s2);
let members = |s: &synapse_core::Structure, id| {
s.hubs
.iter()
.find(|h| h.page == id)
.unwrap()
.members
.clone()
};
// The older write (Y in Z) stands; the one closing the cycle is ignored.
assert_eq!(members(&s1, z), [y]);
assert!(members(&s1, y).is_empty());
}
#[test]
fn old_ops_and_v2_databases_load() {
// An op written before page kinds existed.
let id = synapse_core::new_id();
let op: Op = serde_json::from_value(json!({
"type": "upsert_page",
"page": {"id": id, "title": "Old", "journal_date": null, "origin_journal": null,
"properties": {}, "created_at": 1, "updated_at": 2}
}))
.unwrap();
let Op::UpsertPage { page } = op else {
panic!()
};
assert_eq!(page.kind, PageKind::Note);
assert!(page.description.is_empty() && page.hubs.is_empty());
// A database created with the v2 schema.
let dir = tempfile::tempdir().unwrap();
{
let conn = rusqlite::Connection::open(dir.path().join("synapse.db")).unwrap();
conn.execute_batch(
"CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
INSERT INTO meta VALUES ('schema', '2'), ('actor', 'oldactor0001');
CREATE TABLE pages (
id TEXT PRIMARY KEY, title TEXT NOT NULL, title_key TEXT NOT NULL UNIQUE,
journal_date TEXT UNIQUE, origin_journal TEXT,
properties TEXT NOT NULL DEFAULT '{}', created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL, hlc TEXT NOT NULL);
CREATE TABLE aliases (alias_key TEXT PRIMARY KEY, alias TEXT NOT NULL,
page_id TEXT NOT NULL, hlc TEXT NOT NULL DEFAULT '');",
)
.unwrap();
conn.execute(
"INSERT INTO pages VALUES (?1, 'Legacy', 'legacy', NULL, NULL, '{}', 1, 2, '0000000000001-00000-oldactor0001')",
[id.to_string()],
)
.unwrap();
}
let g = Graph::open(dir.path()).unwrap();
let schema: String = g
.conn()
.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| {
r.get(0)
})
.unwrap();
assert_eq!(schema, "5");
let p = g.get_page(id).unwrap().unwrap();
assert_eq!((p.kind, p.title.as_str()), (PageKind::Note, "Legacy"));
let h = g.create_hub("New hub", "").unwrap();
g.add_to_hub(id, h.id).unwrap();
assert_eq!(g.hub_members(h.id).unwrap(), [id]);
g.add_page_tag(id, "idea").unwrap();
assert_eq!(g.pages_with_tag("idea").unwrap(), [id]);
drop(g);
// Reopening keeps everything (migration is idempotent).
let g = Graph::open(dir.path()).unwrap();
assert_eq!(g.hub_members(h.id).unwrap(), [id]);
let n = g.create_page(NewPage::titled("After")).unwrap();
assert_eq!(n.kind, PageKind::Note);
}
#[test]
fn namespace_helpers() {
assert_eq!(namespace_parent("A/B/C"), Some("A/B"));
assert_eq!(namespace_parent("A / B"), Some("A"));
assert_eq!(namespace_parent("A"), None);
assert_eq!(namespace_parent("/A"), None);
assert_eq!(namespace_parent("A/"), None);
assert_eq!(namespace_parent("A//B"), None);
let (_d, g) = graph();
let ab = page(&g, "A/B", &[]);
let abc = page(&g, "A/B/C", &[]);
let ad = page(&g, "A/d", &[]);
page(&g, "X/Y/Z", &[]);
let kids = g.namespace_children("a").unwrap();
assert_eq!(
kids,
vec![("A/B".to_string(), Some(ab)), ("A/d".to_string(), Some(ad))]
);
assert_eq!(
g.namespace_children("A/B").unwrap(),
vec![("A/B/C".to_string(), Some(abc))]
);
// Virtual intermediate levels.
assert_eq!(
g.namespace_children("X").unwrap(),
vec![("X/Y".to_string(), None)]
);
assert_eq!(g.namespace_children("X/Y").unwrap().len(), 1);
assert!(g.namespace_children("nothing").unwrap().is_empty());
}
#[test]
fn legacy_titles() {
for t in [
"contents",
"TODO",
"All pages",
"hls__book_123",
"In-Progress",
] {
assert!(is_legacy_page(t), "{t}");
}
for t in ["Todo list", "Projects", "hls"] {
assert!(!is_legacy_page(t), "{t}");
}
}
#[test]
fn every_hub_has_a_hidden_template_that_seeds_new_notes() {
let (_d, g) = graph();
let h = hub(&g, "Fun");
let t = g.hub_template(h).unwrap();
assert_eq!(g.get_page(t).unwrap().unwrap().kind, PageKind::Template);
assert_eq!(g.hub_template(h).unwrap(), t, "idempotent");
// Hidden from members, listings and the structure.
assert!(g.hub_members(h).unwrap().is_empty());
assert!(
g.list_pages(true, 100, 0)
.unwrap()
.iter()
.all(|p| p.id != t)
);
assert!(g.structure().unwrap().hubs[0].members.is_empty());
let root = g
.insert_block(t, Placement::LastChildOf(None), "Rating")
.unwrap();
g.insert_block(t, Placement::LastChildOf(Some(root.id)), "Notes")
.unwrap();
let n = g.create_page_from_template(h, "Chess").unwrap();
assert_eq!(g.hubs_of(n.id).unwrap(), vec![h]);
assert_eq!(
texts(&g, n.id),
vec![(0, "Rating".to_string()), (1, "Notes".to_string())]
);
// An empty template is fine, and the template cannot be deleted alone.
let h2 = hub(&g, "Empty");
let n2 = g.create_page_from_template(h2, "Blank").unwrap();
assert!(texts(&g, n2.id).is_empty());
assert!(invalid(g.delete_page(t)));
g.delete_page(h).unwrap();
assert!(g.get_page(t).unwrap().is_none());
}
#[test]
fn converting_to_a_hub_creates_a_template_and_back_removes_it() {
let (_d, g) = graph();
let p = page(&g, "Projects", &["a"]);
g.convert_to_hub(
p,
&HubConversion {
title: "Projects".into(),
..Default::default()
},
)
.unwrap();
let t = g.hub_template(p).unwrap();
g.convert_to_note(p).unwrap();
assert!(g.get_page(t).unwrap().is_none());
}
#[test]
fn tags_are_pages_many_per_page() {
let (_d, g) = graph();
let a = page(&g, "Rust", &["x"]);
let b = page(&g, "Madrid", &["y"]);
g.add_page_tag(a, " #Tecnología ").unwrap();
g.add_page_tag(a, "herramientas").unwrap();
g.add_page_tag(a, "TECNOLOGÍA").unwrap(); // same tag, other case
g.add_page_tag(b, "Tecnología").unwrap();
assert_eq!(
g.get_page(a).unwrap().unwrap().tags,
["Tecnología", "herramientas"]
);
// The first use creates the tag page; it is an ordinary page of kind tag.
let tp = g.page_by_title("tecnología").unwrap().unwrap();
assert_eq!(tp.kind, PageKind::Tag);
assert_eq!(tp.title, "Tecnología");
g.insert_block(tp.id, Placement::LastChildOf(None), "About tech")
.unwrap();
assert_eq!(
g.pages_with_tag("tecnologia").unwrap().len(),
0,
"accents matter"
);
let mut with = g.pages_with_tag("Tecnología").unwrap();
with.sort();
let mut want = vec![a, b];
want.sort();
assert_eq!(with, want);
let cat = g.tag_catalog().unwrap();
assert_eq!((cat[0].name.as_str(), cat[0].count), ("Tecnología", 2));
assert_eq!((cat[1].name.as_str(), cat[1].count), ("herramientas", 1));
assert_eq!(cat.len(), 2, "no seeded tags: tags are pages you create");
g.remove_page_tag(a, "TECNOLOGÍA").unwrap();
assert_eq!(g.pages_with_tag("Tecnología").unwrap(), [b]);
assert!(
g.page_by_title("Tecnología").unwrap().is_some(),
"the tag page stays"
);
g.set_page_tags(a, vec![]).unwrap();
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
// Rules.
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
.unwrap();
assert!(invalid(g.add_page_tag(j.id, "x")));
let h = hub(&g, "H");
let t = g.hub_template(h).unwrap();
assert!(invalid(g.add_page_tag(t, "x")));
assert!(invalid(g.add_page_tag(a, &"x".repeat(49))));
assert!(invalid(g.add_page_tag(a, "H")), "a hub cannot be a tag");
assert!(invalid(g.add_page_tag(a, "Rust")), "not its own tag");
assert!(
invalid(g.add_page_tag(tp.id, "x")),
"tag pages are not tagged"
);
g.add_page_tag(a, " ").unwrap(); // blank: ignored
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
// Deleting a tagged page drops it from the index.
g.delete_page(b).unwrap();
assert!(g.pages_with_tag("Tecnología").unwrap().is_empty());
}
#[test]
fn a_note_becomes_a_tag_page_when_used_as_a_tag() {
let (_d, g) = graph();
let n = page(&g, "Neurociencia", &["brains", "memory"]);
let other = page(&g, "Plasticidad", &["x"]);
g.add_page_tag(other, "neurociencia").unwrap();
let p = g.get_page(n).unwrap().unwrap();
assert_eq!(p.kind, PageKind::Tag);
assert_eq!(texts(&g, n).len(), 2, "its content is kept");
assert_eq!(g.get_page(other).unwrap().unwrap().tags, ["Neurociencia"]);
}
#[test]
fn renaming_or_deleting_a_tag_page_keeps_members_in_step() {
let (_d, g) = graph();
let a = page(&g, "A", &["x"]);
let b = page(&g, "B", &["y"]);
g.add_page_tag(a, "web").unwrap();
g.add_page_tag(b, "Web").unwrap();
g.add_page_tag(b, "otro").unwrap();
let tag = g.page_by_title("web").unwrap().unwrap().id;
g.rename_page(tag, "Sitios web").unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().tags, ["Sitios web"]);
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["Sitios web", "otro"]);
assert_eq!(g.pages_with_tag("Sitios web").unwrap().len(), 2);
assert!(g.pages_with_tag("web").unwrap().is_empty());
g.delete_page(tag).unwrap();
assert!(g.get_page(a).unwrap().unwrap().tags.is_empty());
assert_eq!(g.get_page(b).unwrap().unwrap().tags, ["otro"]);
}
#[test]
fn tags_without_a_page_get_one_when_the_graph_opens() {
let dir = tempfile::tempdir().unwrap();
let id = {
let g = Graph::open(dir.path()).unwrap();
let id = page(&g, "Old", &["x"]);
g.add_page_tag(id, "Idea").unwrap();
// Simulate a pre-v5 database: the tag exists only on the note.
let tag = g.page_by_title("Idea").unwrap().unwrap().id;
g.conn()
.execute("DELETE FROM pages WHERE id=?1", [tag.to_string()])
.unwrap();
id
};
let g = Graph::open(dir.path()).unwrap();
let tag = g.page_by_title("idea").unwrap().unwrap();
assert_eq!((tag.kind, tag.title.as_str()), (PageKind::Tag, "Idea"));
assert_eq!(g.pages_with_tag("Idea").unwrap(), [id]);
}
#[test]
fn types_are_names_many_per_page_with_a_seeded_vocabulary() {
let (_d, g) = graph();
let a = page(&g, "Ana", &["x"]);
let b = page(&g, "Madrid", &["y"]);
let pages_before = g.list_pages(true, 100, 0).unwrap().len();
g.add_page_type(a, " Persona ").unwrap();
g.add_page_type(a, "cliente").unwrap();
g.add_page_type(a, "PERSONA").unwrap();
g.add_page_type(b, "lugar").unwrap();
assert_eq!(
g.get_page(a).unwrap().unwrap().types,
["Persona", "cliente"]
);
// Types never become pages.
assert_eq!(g.list_pages(true, 100, 0).unwrap().len(), pages_before);
assert!(g.page_by_title("persona").unwrap().is_none());
let cat = g.type_catalog().unwrap();
assert!(cat.iter().any(|t| t.name == "Persona" && t.count == 1));
let names: Vec<&str> = cat.iter().map(|t| t.name.as_str()).collect();
assert!(names.contains(&"empresa"), "unused suggestions are listed");
assert_eq!(
names
.iter()
.filter(|n| n.to_lowercase() == "persona")
.count(),
1
);
g.remove_page_type(a, "persona").unwrap();
assert_eq!(g.get_page(a).unwrap().unwrap().types, ["cliente"]);
let j = g
.journal(chrono::NaiveDate::from_ymd_opt(2026, 1, 2).unwrap())
.unwrap();
assert!(invalid(g.add_page_type(j.id, "x")));
}
#[test]
fn tags_sync_with_the_page() {
let (_a, a) = graph();
let (_b, b) = graph();
let p = page(&a, "Note", &["x"]);
a.add_page_tag(p, "idea").unwrap();
a.add_page_tag(p, "proyecto").unwrap();
a.add_page_type(p, "concepto").unwrap();
ship(&a, &b, 0);
let q = b.get_page(p).unwrap().unwrap();
assert_eq!(q.tags, ["idea", "proyecto"]);
assert_eq!(q.types, ["concepto"]);
assert_eq!(b.pages_with_tag("IDEA").unwrap(), [p]);
// The tag pages travel with it.
assert_eq!(
b.page_by_title("idea").unwrap().unwrap().kind,
PageKind::Tag
);
}
+111 -1
View File
@@ -14,6 +14,16 @@ pub struct PageDto {
pub origin_journal: Option<String>,
pub created_at: i64,
pub updated_at: i64,
/// The page is a hub (no blocks; members list instead of an outline).
pub is_hub: bool,
/// Hub description (empty for notes).
pub description: String,
/// Titles of the tag pages this page is filed under, in the order they were added.
pub tags: Vec<String>,
/// The page is a tag page (a topic that other pages are filed under).
pub is_tag: bool,
/// Type names ("persona", "lugar"...: plain names, not pages), in the order added.
pub types: Vec<String>,
}
impl From<&Page> for PageDto {
@@ -25,10 +35,25 @@ impl From<&Page> for PageDto {
origin_journal: p.origin_journal.map(journal_title),
created_at: p.created_at,
updated_at: p.updated_at,
is_hub: p.is_hub(),
description: p.description.clone(),
tags: p.tags.clone(),
is_tag: p.is_tag(),
types: p.types.clone(),
}
}
}
/// A tag or type of the vocabulary.
#[derive(Debug, Clone, PartialEq)]
pub struct TagDto {
pub name: String,
/// Pages using it.
pub count: u32,
/// One of the seeded suggestions.
pub suggested: bool,
}
/// One row of the outline, in pre-order.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockDto {
@@ -95,6 +120,7 @@ pub struct PageBrief {
pub id: String,
pub title: String,
pub is_journal: bool,
pub is_hub: bool,
}
impl From<&Page> for PageBrief {
@@ -103,6 +129,7 @@ impl From<&Page> for PageBrief {
id: p.id.to_string(),
title: p.title.clone(),
is_journal: p.is_journal(),
is_hub: p.is_hub(),
}
}
}
@@ -181,6 +208,11 @@ pub mod edge_kind {
pub const MENTION: u8 = 5;
/// Hebbian association (undirected), weight = decayed synapse strength.
pub const SYNAPSE: u8 = 6;
/// Hub membership, hub → member (structural, weight 1).
pub const CONTAINS: u8 = 7;
/// A page filed under a tag page (page → tag page, weight 1). Unlike `TAG` (an inline
/// `#tag` in the text) it comes from the page's own `tags` list.
pub const TAGGED: u8 = 8;
}
#[derive(Debug, Clone, PartialEq)]
@@ -190,7 +222,8 @@ pub struct GraphNode {
pub journal_date: Option<String>,
pub origin_journal: Option<String>,
pub created_at: i64,
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
/// Distinct neighbours over structural edges (links, tags, properties, block refs, hub
/// membership).
pub degree: u32,
/// Distinct pages referencing this one.
pub backlinks: u32,
@@ -198,6 +231,12 @@ pub struct GraphNode {
pub cluster: u32,
/// Node index of the tag this page uses most, if any.
pub primary_tag: Option<u32>,
/// The page is a hub (`PageKind::Hub`).
pub is_hub: bool,
/// Node index of the deepest hub containing this page (a hub: itself).
pub home_hub: Option<u32>,
/// Tag names of the page (see `PageDto::tags`), for grouping by tag.
pub tags: Vec<String>,
}
/// The whole page-level graph, edges as parallel arrays (cheap to move across the FFI).
@@ -223,3 +262,74 @@ pub struct LayoutFrame {
/// Remaining "temperature"; the layout is settled when it reaches 0.
pub alpha: f32,
}
/// A hub (folder-like page) with its members.
#[derive(Debug, Clone, PartialEq)]
pub struct HubDto {
pub id: String,
pub title: String,
pub description: String,
/// 0 for root hubs, one more per level of nesting.
pub depth: u32,
/// Sub-hubs first, then notes, each by title.
pub members: Vec<PageBrief>,
/// Ids of the members that are hubs themselves.
pub sub_hubs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct HubsDto {
/// Sorted by title.
pub hubs: Vec<HubDto>,
/// Ids of the hubs that are not a member of any hub, by title.
pub roots: Vec<String>,
}
/// A level of a namespace (`A/B` under `A`); `id` is `None` when only deeper pages exist.
#[derive(Debug, Clone, PartialEq)]
pub struct NamespaceEntry {
pub title: String,
pub id: Option<String>,
}
/// Hub and namespace context of one page.
#[derive(Debug, Clone, PartialEq)]
pub struct PageStructure {
pub is_hub: bool,
/// Hub description (empty for notes).
pub description: String,
/// Empty unless the page is a hub; sub-hubs first, then notes.
pub members: Vec<PageBrief>,
/// Hubs the page belongs to (its own membership list), by title.
pub in_hubs: Vec<PageBrief>,
/// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist).
pub ns_path: Vec<NamespaceEntry>,
pub ns_children: Vec<NamespaceEntry>,
}
/// Defaults for the "convert to hub" dialog.
#[derive(Debug, Clone, PartialEq)]
pub struct HubPreviewDto {
/// Last namespace segment of the title.
pub suggested_title: String,
/// First prose block as plain text (<= 280 chars).
pub suggested_description: String,
/// Candidate members: pages the outline links or tags (outline order), then pages
/// referencing the note from properties or tags.
pub members: Vec<PageBrief>,
/// Blocks that are prose rather than links (what "keep the outline" would save).
pub prose_blocks: u32,
pub blocks: u32,
/// `"<suggested_title> (notes)"`, for the note receiving the outline.
pub suggested_note_title: String,
}
/// A page the legacy purge offers to delete.
#[derive(Debug, Clone, PartialEq)]
pub struct LegacyCandidate {
pub id: String,
pub title: String,
pub reason: String,
pub blocks: u32,
pub preselected: bool,
}
+3
View File
@@ -18,6 +18,8 @@ pub struct SynapseGraph {
graph: Arc<Mutex<Graph>>,
/// Page-level graph for the graph views, keyed by what invalidates it.
pub(crate) graph_cache: Mutex<Option<(super::graph_view::CacheKey, Arc<GraphData>)>>,
/// Hubs and home hubs, keyed by op-log sequence.
pub(crate) structure_cache: Mutex<Option<(i64, Arc<synapse_core::Structure>)>>,
}
impl SynapseGraph {
@@ -27,6 +29,7 @@ impl SynapseGraph {
Ok(SynapseGraph {
graph: Arc::new(Mutex::new(graph)),
graph_cache: Mutex::new(None),
structure_cache: Mutex::new(None),
})
}
+50
View File
@@ -78,9 +78,15 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
// Nodes.
let mut nodes = Vec::new();
let mut index: HashMap<String, u32> = HashMap::new();
let page_tags: HashMap<String, Vec<String>> = g
.all_page_tags()?
.into_iter()
.map(|(id, t)| (id.to_string(), t))
.collect();
{
let mut st = conn.prepare(
"SELECT id, title, journal_date, origin_journal, created_at FROM pages
WHERE kind != 'template'
ORDER BY journal_date IS NOT NULL, created_at",
)?;
let rows = st.query_map([], |r| {
@@ -94,6 +100,7 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
})?;
for row in rows {
let (id, title, journal_date, origin_journal, created_at) = row?;
let tags = page_tags.get(&id).cloned().unwrap_or_default();
index.insert(id.clone(), nodes.len() as u32);
nodes.push(GraphNode {
id,
@@ -105,6 +112,9 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
backlinks: 0,
cluster: 0,
primary_tag: None,
is_hub: false,
home_hub: None,
tags,
});
}
}
@@ -203,6 +213,22 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
}
}
// Hub membership (hub → member), cycles already broken by `structure()`.
let structure = g.structure()?;
for h in &structure.hubs {
let Some(&hi) = index.get(&h.page.to_string()) else {
continue;
};
nodes[hi as usize].is_hub = true;
for m in &h.members {
if let Some(&mi) = index.get(&m.to_string()) {
b.add(hi, mi, edge_kind::CONTAINS, 1.0);
}
}
}
tagged(g, &index, &by_key, &mut b)?;
// Stable edge order (sources, then targets, then kind).
let mut edges: Vec<((u32, u32, u8), f32)> = b.edges.into_iter().collect();
edges.sort_by_key(|&(k, _)| k);
@@ -234,6 +260,12 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
.map(|(&t, _)| t);
}
for (page, home) in &structure.home {
if let (Some(&i), Some(&h)) = (index.get(&page.to_string()), index.get(&home.to_string())) {
nodes[i as usize].home_hub = Some(h);
}
}
let mut out = GraphData {
nodes,
sources: Vec::with_capacity(edges.len()),
@@ -251,6 +283,24 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
Ok(out)
}
/// A page filed under a tag page gets one `TAGGED` edge to it.
fn tagged(
g: &Graph,
index: &HashMap<String, u32>,
by_key: &HashMap<String, u32>,
b: &mut Builder,
) -> Result<()> {
let mut st = g.conn().prepare("SELECT tag_key, page_id FROM page_tags")?;
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
for row in rows {
let (tag, page) = row?;
if let (Some(&s), Some(&t)) = (index.get(&page), by_key.get(&tag)) {
b.add(s, t, edge_kind::TAGGED, 1.0);
}
}
Ok(())
}
/// Unlinked references: a non-journal page title (or alias) appearing as whole words in a
/// block of another page that does not already reference it. Titles are indexed by their
/// first word so each block is scanned once.
+4
View File
@@ -4,6 +4,8 @@
//! - `outline`: block editing (insert, update, move, indent/outdent, merge, delete).
//! - `search`: title/block lookup (stopgap until `synapse-search` is wired).
//! - `graph_view`: the whole page-level graph for the graph views (cached by op seq).
//! - `structure`: hubs (folder-like pages), namespaces and the legacy page purge.
//! - `tags`: free-form tags on pages (names, not pages) and their vocabulary.
//! - `layout`: Barnes-Hut force-directed layout, stepped from Dart off the UI thread.
//!
//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own
@@ -17,3 +19,5 @@ pub mod graph_view;
pub mod layout;
pub mod outline;
pub mod search;
pub mod structure;
pub mod tags;
+304
View File
@@ -0,0 +1,304 @@
//! Hubs (folder-like pages), namespaces and the legacy page purge. Rules and membership
//! live in `synapse_core::structure`; this module shapes them for the UI.
use super::dto::{
HubDto, HubPreviewDto, HubsDto, LegacyCandidate, NamespaceEntry, PageBrief, PageDto,
PageStructure,
};
use super::graph::{SynapseGraph, parse_id};
use anyhow::{Result, anyhow};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use synapse_core::{
Graph, HubConversion, PageId, Structure, is_legacy_page, namespace_parent, title_key,
};
impl SynapseGraph {
/// Every hub with its members, and the root hubs.
pub fn hubs(&self) -> Result<HubsDto> {
let g = self.lock();
let s = self.structure_of(&g)?;
let hub_ids: HashSet<PageId> = s.hubs.iter().map(|h| h.page).collect();
let member_of_hub: HashSet<PageId> = s
.hubs
.iter()
.flat_map(|h| h.members.iter().copied())
.collect();
let mut briefs: HashMap<PageId, PageBrief> = HashMap::new();
let mut hubs = Vec::with_capacity(s.hubs.len());
for h in &s.hubs {
let members = h
.members
.iter()
.map(|&m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?;
hubs.push(HubDto {
id: h.page.to_string(),
title: h.title.clone(),
description: h.description.clone(),
depth: h.depth,
sub_hubs: h
.members
.iter()
.filter(|m| hub_ids.contains(m))
.map(|m| m.to_string())
.collect(),
members,
});
}
let roots = s
.hubs
.iter()
.filter(|h| !member_of_hub.contains(&h.page))
.map(|h| h.page.to_string())
.collect();
Ok(HubsDto { hubs, roots })
}
/// Hub and namespace context of a page.
pub fn page_structure(&self, page_id: String) -> Result<PageStructure> {
let g = self.lock();
let id = parse_id(&page_id)?;
let page = g
.get_page(id)?
.ok_or_else(|| anyhow!("page {page_id} not found"))?;
let mut briefs = HashMap::new();
let members = if page.is_hub() {
g.hub_members(id)?
.into_iter()
.map(|m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?
} else {
Vec::new()
};
let in_hubs = g
.hubs_of(id)?
.into_iter()
.map(|h| brief(&g, &mut briefs, h))
.collect::<Result<Vec<_>>>()?;
let mut path = Vec::new();
let mut title = page.title.as_str();
while let Some(parent) = namespace_parent(title) {
path.push(parent);
title = parent;
}
let ns_path = path
.into_iter()
.rev()
.map(|t| entry(&g, t.to_string(), None))
.collect::<Result<Vec<_>>>()?;
let ns_children = g
.namespace_children(&page.title)?
.into_iter()
.map(|(t, id)| entry(&g, t, id))
.collect::<Result<Vec<_>>>()?;
Ok(PageStructure {
is_hub: page.is_hub(),
description: page.description.clone(),
members,
in_hubs,
ns_path,
ns_children,
})
}
/// Creates an empty hub. Fails when the title is taken.
pub fn create_hub(&self, title: String, description: String) -> Result<PageDto> {
Ok(PageDto::from(
&self.lock().create_hub(&title, &description)?,
))
}
/// Id of the hub's template page (created empty when missing). Open it like any note to
/// edit the outline new notes of the hub start from.
pub fn hub_template(&self, hub_id: String) -> Result<String> {
Ok(self.lock().hub_template(parse_id(&hub_id)?)?.to_string())
}
/// Creates a note in the hub, starting from a copy of the hub's template.
pub fn create_page_from_template(&self, hub_id: String, title: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.create_page_from_template(parse_id(&hub_id)?, &title)?,
))
}
pub fn set_hub_description(&self, hub_id: String, description: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.set_hub_description(parse_id(&hub_id)?, &description)?,
))
}
/// Puts a page in a hub (no-op when it already is). Fails for journals, non-hub targets,
/// the hub itself and memberships that would create a cycle.
pub fn add_to_hub(&self, page_id: String, hub_id: String) -> Result<()> {
self.lock()
.add_to_hub(parse_id(&page_id)?, parse_id(&hub_id)?)?;
Ok(())
}
/// Takes a page out of a hub (no-op when it is not in it).
pub fn remove_from_hub(&self, page_id: String, hub_id: String) -> Result<()> {
self.lock()
.remove_from_hub(parse_id(&page_id)?, parse_id(&hub_id)?)?;
Ok(())
}
/// Defaults for converting a note into a hub.
pub fn hub_conversion_preview(&self, page_id: String) -> Result<HubPreviewDto> {
let g = self.lock();
let p = g.hub_conversion_preview(parse_id(&page_id)?)?;
let mut briefs = HashMap::new();
let members = p
.members
.iter()
.map(|&m| brief(&g, &mut briefs, m))
.collect::<Result<Vec<_>>>()?;
Ok(HubPreviewDto {
suggested_note_title: format!("{} (notes)", p.suggested_title),
suggested_title: p.suggested_title,
suggested_description: p.suggested_description,
members,
prose_blocks: p.prose_blocks,
blocks: p.blocks,
})
}
/// Turns a note into a hub in one transaction: renames it to `title` (links rewritten),
/// moves its outline to a new note `keep_outline_as` (or deletes it when `None`; a blank title is an error), sets the
/// description and adds `member_ids` (invalid members are skipped).
pub fn convert_to_hub(
&self,
page_id: String,
title: String,
description: String,
member_ids: Vec<String>,
keep_outline_as: Option<String>,
) -> Result<PageDto> {
let members = member_ids
.iter()
.map(|i| parse_id(i))
.collect::<Result<Vec<_>>>()?;
if keep_outline_as
.as_ref()
.is_some_and(|t| t.trim().is_empty())
{
return Err(anyhow!("the note that keeps the outline needs a title"));
}
let c = HubConversion {
title,
description,
members,
keep_outline_as,
};
let g = self.lock();
Ok(PageDto::from(&g.convert_to_hub(parse_id(&page_id)?, &c)?))
}
/// Turns a hub back into a note: description, then one `[[Member]]` block per member.
pub fn convert_to_note(&self, page_id: String) -> Result<PageDto> {
Ok(PageDto::from(
&self.lock().convert_to_note(parse_id(&page_id)?)?,
))
}
/// Pages that are probably leftovers of Logseq: its built-ins and pages with
/// `type:: system`. Only the organisational files (`contents`, `card`, `favorites`,
/// `hls__*`) and empty pages are preselected, and never a hub: a built-in title such as
/// `todo` may hold real content.
pub fn legacy_candidates(&self) -> Result<Vec<LegacyCandidate>> {
let g = self.lock();
let mut out = Vec::new();
for p in g.list_pages(false, u32::MAX, 0)? {
let key = title_key(&p.title);
let reason = if is_legacy_page(&p.title) {
if key.starts_with("hls__") {
"Logseq PDF highlights"
} else {
"Logseq built-in"
}
} else if p.properties.get("type").and_then(|v| v.as_str()) == Some("system") {
"type:: system"
} else {
continue;
};
let blocks = g.page_tree(p.id)?.len() as u32;
let organisational = matches!(key.as_str(), "contents" | "card" | "favorites")
|| key.starts_with("hls__");
out.push(LegacyCandidate {
id: p.id.to_string(),
title: p.title.clone(),
reason: reason.into(),
blocks,
preselected: !p.is_hub() && (blocks == 0 || organisational),
});
}
out.sort_by_key(|c| title_key(&c.title));
Ok(out)
}
/// Deletes pages and their blocks in one transaction. Returns how many existed.
pub fn purge_pages(&self, ids: Vec<String>) -> Result<u32> {
let ids = ids
.iter()
.map(|i| parse_id(i))
.collect::<Result<Vec<_>>>()?;
let n = self.lock().transaction(|g| {
let mut n = 0;
for id in ids {
if g.get_page(id)?.is_some() {
g.delete_page(id)?;
n += 1;
}
}
Ok(n)
})?;
Ok(n)
}
/// Structure of the graph, cached until it changes.
fn structure_of(&self, g: &Graph) -> Result<Arc<Structure>> {
let seq = g.last_seq()?;
let mut cache = self
.structure_cache
.lock()
.unwrap_or_else(|e| e.into_inner());
if let Some((s, data)) = cache.as_ref()
&& *s == seq
{
return Ok(Arc::clone(data));
}
let data = Arc::new(g.structure()?);
*cache = Some((seq, Arc::clone(&data)));
Ok(data)
}
}
fn brief(g: &Graph, cache: &mut HashMap<PageId, PageBrief>, id: PageId) -> Result<PageBrief> {
if let Some(b) = cache.get(&id) {
return Ok(b.clone());
}
let p = g
.get_page(id)?
.ok_or_else(|| anyhow!("page {id} not found"))?;
let b = PageBrief::from(&p);
cache.insert(id, b.clone());
Ok(b)
}
/// Namespace level; looks the page up when the caller does not know it.
fn entry(g: &Graph, title: String, id: Option<PageId>) -> Result<NamespaceEntry> {
let id = match id {
Some(id) => Some(id),
None => g
.page_by_title(&title)?
.filter(|p| !p.is_journal())
.map(|p| p.id),
};
Ok(NamespaceEntry {
title,
id: id.map(|i| i.to_string()),
})
}
+87
View File
@@ -0,0 +1,87 @@
//! Tags (topic pages that notes are filed under) and types (plain names saying what a page
//! is). Rules live in `synapse_core::{tags, types}`; this module shapes them for the UI.
use super::dto::{PageBrief, PageDto, TagDto};
use super::graph::{SynapseGraph, parse_id};
use anyhow::Result;
impl SynapseGraph {
/// Replaces the tags of a page (each title gets a tag page if it has none). Journals,
/// templates and tag pages cannot be tagged.
pub fn set_page_tags(&self, page_id: String, tags: Vec<String>) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.set_page_tags(parse_id(&page_id)?, tags)?))
}
pub fn add_page_tag(&self, page_id: String, tag: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.add_page_tag(parse_id(&page_id)?, &tag)?))
}
pub fn remove_page_tag(&self, page_id: String, tag: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.remove_page_tag(parse_id(&page_id)?, &tag)?,
))
}
/// Every tag page with its number of pages, most used first.
pub fn tag_catalog(&self) -> Result<Vec<TagDto>> {
Ok(self
.lock()
.tag_catalog()?
.into_iter()
.map(|t| TagDto {
name: t.name,
count: t.count,
suggested: t.suggested,
})
.collect())
}
/// Pages carrying a tag, most recently updated first.
pub fn pages_with_tag(&self, tag: String) -> Result<Vec<PageBrief>> {
let g = self.lock();
let mut out = Vec::new();
for id in g.pages_with_tag(&tag)? {
if let Some(p) = g.get_page(id)? {
out.push(PageBrief::from(&p));
}
}
Ok(out)
}
/// Replaces the types of a page. Journals and templates cannot be typed.
pub fn set_page_types(&self, page_id: String, types: Vec<String>) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.set_page_types(parse_id(&page_id)?, types)?,
))
}
pub fn add_page_type(&self, page_id: String, ty: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(&g.add_page_type(parse_id(&page_id)?, &ty)?))
}
pub fn remove_page_type(&self, page_id: String, ty: String) -> Result<PageDto> {
let g = self.lock();
Ok(PageDto::from(
&g.remove_page_type(parse_id(&page_id)?, &ty)?,
))
}
/// Types in use (most used first) followed by the seeded suggestions not used yet.
pub fn type_catalog(&self) -> Result<Vec<TagDto>> {
Ok(self
.lock()
.type_catalog()?
.into_iter()
.map(|t| TagDto {
name: t.name,
count: t.count,
suggested: t.suggested,
})
.collect())
}
}
File diff suppressed because it is too large. Load diff
+278 -1
View File
@@ -1,4 +1,4 @@
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind};
use synapse_ffi::api::dto::{BlockDto, Place, PlaceKind, edge_kind};
use synapse_ffi::api::graph::SynapseGraph;
fn open() -> (tempfile::TempDir, SynapseGraph) {
@@ -185,3 +185,280 @@ fn assets_round_trip() {
assert_eq!(std::fs::read(path).unwrap(), b"png");
assert!(g.asset_path("zz".into()).is_none());
}
#[test]
fn hubs_structure_and_graph_nodes() {
let (_d, g) = open();
let media = g.create_hub("Media".into(), " All media ".into()).unwrap();
assert!(media.is_hub);
assert_eq!(media.description, "All media");
let media = media.id;
let books = g
.create_hub("Media/Books".into(), String::new())
.unwrap()
.id;
let (novel, _) = page_with(&g, "Novel", &["text"]);
let (film, _) = page_with(&g, "Film", &["text"]);
let (note, _) = page_with(&g, "Note", &["plain text"]);
g.add_to_hub(books.clone(), media.clone()).unwrap();
g.add_to_hub(film.clone(), media.clone()).unwrap();
g.add_to_hub(novel.clone(), books.clone()).unwrap();
g.add_to_hub(novel.clone(), books.clone()).unwrap(); // no-op
// Rules surface as readable errors.
let err = g.add_to_hub(media.clone(), books.clone()).unwrap_err();
assert!(err.to_string().contains("cycle"), "{err}");
assert!(
g.add_to_hub(note.clone(), film.clone()).is_err(),
"not a hub"
);
assert!(g.add_to_hub(media.clone(), media.clone()).is_err(), "self");
let today = g.open_page(g.today()).unwrap().page.id;
assert!(g.add_to_hub(today, media.clone()).is_err(), "journal");
let err = g
.insert_block(
media.clone(),
place(PlaceKind::LastChildOf, None),
"x".into(),
)
.unwrap_err();
assert!(err.to_string().contains("hubs have no blocks"), "{err}");
let hubs = g.hubs().unwrap();
let titles: Vec<&str> = hubs.hubs.iter().map(|h| h.title.as_str()).collect();
assert_eq!(titles, ["Media", "Media/Books"]);
assert_eq!(hubs.roots, std::slice::from_ref(&media));
let m = &hubs.hubs[0];
assert_eq!((m.depth, m.description.as_str()), (0, "All media"));
let names: Vec<&str> = m.members.iter().map(|p| p.title.as_str()).collect();
assert_eq!(names, ["Media/Books", "Film"], "sub-hubs first");
assert!(m.members[0].is_hub && !m.members[1].is_hub);
assert_eq!(m.sub_hubs, std::slice::from_ref(&books));
assert_eq!(hubs.hubs[1].depth, 1);
let s = g.page_structure(novel.clone()).unwrap();
assert!(!s.is_hub && s.members.is_empty());
let in_hubs: Vec<&str> = s.in_hubs.iter().map(|p| p.title.as_str()).collect();
assert_eq!(in_hubs, ["Media/Books"], "one hub per page");
let s = g.page_structure(books.clone()).unwrap();
assert!(s.is_hub);
assert_eq!(s.members.len(), 1);
assert_eq!(s.ns_path.len(), 1);
assert_eq!(s.ns_path[0].id.as_deref(), Some(media.as_str()));
let s = g.page_structure(media.clone()).unwrap();
assert_eq!(s.description, "All media");
assert_eq!(s.ns_children[0].id.as_deref(), Some(books.as_str()));
g.set_hub_description(books.clone(), "Reading".into())
.unwrap();
g.remove_from_hub(film.clone(), media.clone()).unwrap();
assert!(g.page_structure(film.clone()).unwrap().in_hubs.is_empty());
// Graph data: hub flags, home hubs and CONTAINS edges.
let data = g.graph_data().unwrap();
let idx = |id: &str| data.nodes.iter().position(|n| n.id == id).unwrap() as u32;
let node = |id: &str| &data.nodes[idx(id) as usize];
assert!(node(&media).is_hub && node(&books).is_hub && !node(&novel).is_hub);
assert_eq!(node(&books).home_hub, Some(idx(&books)));
assert_eq!(node(&novel).home_hub, Some(idx(&books)), "deepest hub");
assert_eq!(node(&note).home_hub, None);
let contains = |s: &str, t: &str| {
(0..data.kinds.len()).any(|e| {
data.kinds[e] == edge_kind::CONTAINS
&& data.sources[e] == idx(s)
&& data.targets[e] == idx(t)
})
};
assert!(contains(&media, &books) && contains(&books, &novel));
assert!(!contains(&media, &novel));
assert!(!contains(&media, &film));
assert_eq!(node(&novel).backlinks, 1, "membership is structural");
// Converting back to a note: description, then one link per member.
let n = g.convert_to_note(books.clone()).unwrap();
assert!(!n.is_hub);
let page = g.page(books.clone()).unwrap().unwrap();
let texts: Vec<&str> = page.blocks.iter().map(|b| b.content.as_str()).collect();
assert_eq!(texts, ["Reading", "[[Novel]]"]);
let in_hubs = g.page_structure(novel.clone()).unwrap().in_hubs;
assert!(in_hubs.is_empty(), "the old hub is gone from its members");
}
#[test]
fn convert_note_to_hub() {
let (_d, g) = open();
let (area, _) = page_with(
&g,
"Work/Area",
&[
"Everything about **my** area of [[Work]].",
"[[Alpha]]",
"[[Beta]] #Gamma",
],
);
let p = g.hub_conversion_preview(area.clone()).unwrap();
assert_eq!(p.suggested_title, "Area");
assert_eq!(p.suggested_note_title, "Area (notes)");
assert_eq!(p.suggested_description, "Everything about my area of Work.");
let names: Vec<&str> = p.members.iter().map(|m| m.title.as_str()).collect();
assert_eq!(names, ["Work", "Alpha", "Beta", "Gamma"]);
assert_eq!((p.prose_blocks, p.blocks), (1, 3));
let member_ids: Vec<String> = p.members.iter().skip(1).map(|m| m.id.clone()).collect();
let hub = g
.convert_to_hub(
area.clone(),
p.suggested_title.clone(),
p.suggested_description.clone(),
member_ids,
Some(p.suggested_note_title.clone()),
)
.unwrap();
assert!(hub.is_hub);
assert_eq!(
(hub.id.as_str(), hub.title.as_str()),
(area.as_str(), "Area")
);
assert!(g.page(area.clone()).unwrap().unwrap().blocks.is_empty());
let kept = g.page_by_title("Area (notes)".into()).unwrap().unwrap();
assert_eq!(kept.blocks.len(), 3);
let s = g.page_structure(area.clone()).unwrap();
let names: Vec<&str> = s.members.iter().map(|m| m.title.as_str()).collect();
assert_eq!(
names,
["Alpha", "Area (notes)", "Beta", "Gamma"],
"kept note is a member"
);
// A blank keep title is an error (never "delete the outline") and changes nothing.
let (blank, _) = page_with(&g, "Blank", &["keep me"]);
assert!(
g.convert_to_hub(
blank.clone(),
"Blank".into(),
String::new(),
vec![],
Some(" ".into())
)
.is_err()
);
assert!(!g.page(blank.clone()).unwrap().unwrap().page.is_hub);
assert_eq!(g.page(blank).unwrap().unwrap().blocks.len(), 1);
// A title clash is a readable error and changes nothing.
let (other, _) = page_with(&g, "Other", &["[[Alpha]]"]);
let err = g
.convert_to_hub(other.clone(), "Area".into(), String::new(), vec![], None)
.unwrap_err();
assert!(!err.to_string().is_empty());
assert!(!g.page(other.clone()).unwrap().unwrap().page.is_hub);
assert_eq!(g.page(other).unwrap().unwrap().blocks.len(), 1);
}
#[test]
fn legacy_candidates_and_purge() {
let (_d, g) = open();
let (todo, _) = page_with(&g, "TODO", &["a", "b"]);
let (hl, _) = page_with(&g, "hls__book", &[]);
let (sys, _) = page_with(&g, "Template", &["x"]);
let (keep, _) = page_with(&g, "Keep", &["x"]);
page_with(&g, "contents", &["- x"]);
page_with(&g, "now", &[]);
g.create_hub("later".into(), String::new()).unwrap();
{
let shared = g.shared();
let core = shared.lock().unwrap();
let mut props = synapse_core::Properties::new();
props.insert("type".into(), "system".into());
core.set_page_properties(sys.parse().unwrap(), props)
.unwrap();
}
let c = g.legacy_candidates().unwrap();
let by = |t: &str| c.iter().find(|x| x.title == t).unwrap();
assert_eq!(by("TODO").reason, "Logseq built-in");
assert!(
!by("TODO").preselected && by("TODO").blocks == 2,
"has content"
);
assert!(by("contents").preselected, "organisational page");
assert!(by("now").preselected, "empty built-in");
assert!(!by("later").preselected, "hubs are never preselected");
assert_eq!(by("hls__book").reason, "Logseq PDF highlights");
assert!(by("hls__book").preselected);
assert!(!by("Template").preselected);
assert_eq!(by("Template").reason, "type:: system");
assert!(c.iter().all(|x| x.title != "Keep"));
// A bad id rejects the call before anything is deleted.
assert!(g.purge_pages(vec![todo.clone(), "nope".into()]).is_err());
assert!(g.page(todo.clone()).unwrap().is_some());
assert_eq!(g.purge_pages(vec![todo.clone(), hl.clone()]).unwrap(), 2);
assert!(g.page(todo).unwrap().is_none() && g.page(hl).unwrap().is_none());
assert!(g.page(keep).unwrap().is_some());
}
#[test]
fn tags_are_pages_and_their_own_edge_kind() {
let (_d, g) = open();
let (a, _) = page_with(&g, "Rust", &["x"]);
let (b, _) = page_with(&g, "Go", &["y"]);
let (c, _) = page_with(&g, "Madrid", &["z"]);
for (p, tags) in [
(&a, vec!["tecnología", "idea"]),
(&b, vec!["Tecnología", "idea"]),
(&c, vec!["lugar"]),
] {
g.set_page_tags(p.clone(), tags.into_iter().map(String::from).collect())
.unwrap();
}
let data = g.graph_data().unwrap();
let idx = |id: &str| data.nodes.iter().position(|n| n.id == id).unwrap() as u32;
let title = |i: u32| data.nodes[i as usize].title.clone();
let mut tagged: Vec<(String, String)> = (0..data.kinds.len())
.filter(|&e| data.kinds[e] == edge_kind::TAGGED)
.map(|e| (title(data.sources[e]), title(data.targets[e])))
.collect();
tagged.sort();
let pair = |a: &str, b: &str| (a.to_string(), b.to_string());
assert_eq!(
tagged,
[
pair("Go", "idea"),
pair("Go", "tecnología"),
pair("Madrid", "lugar"),
pair("Rust", "idea"),
pair("Rust", "tecnología"),
],
"each page points at its tag pages"
);
// The tag page is a real node that counts backlinks, and the DTOs flag it.
let tp = &data.nodes[data
.nodes
.iter()
.position(|n| n.title == "tecnología")
.unwrap()];
assert_eq!(tp.backlinks, 2);
assert!(g.page(tp.id.clone()).unwrap().unwrap().page.is_tag);
assert_eq!(
idx(&a),
data.nodes.iter().position(|n| n.id == a).unwrap() as u32
);
let cat = g.tag_catalog().unwrap();
assert_eq!((cat[0].name.as_str(), cat[0].count), ("idea", 2));
}
#[test]
fn types_round_trip_through_the_api() {
let (_d, g) = open();
let (a, _) = page_with(&g, "Ana", &["x"]);
let p = g.add_page_type(a.clone(), "persona".into()).unwrap();
assert_eq!(p.types, ["persona"]);
assert!(g.type_catalog().unwrap().iter().any(|t| t.name == "lugar"));
assert!(
g.remove_page_type(a, "PERSONA".into())
.unwrap()
.types
.is_empty()
);
}
+43 -1
View File
@@ -3,7 +3,8 @@
//! Layout: `pages/<encoded title>.md`, `journals/YYYY_MM_DD.md`, `assets.json`.
//! A page file starts with page properties (`key:: value`, aliases as `alias:: a, b`),
//! then one `- ` bullet per block, nested with tabs. Block properties follow the content;
//! blocks referenced by `((uuid))` carry an `id::` property.
//! blocks referenced by `((uuid))` carry an `id::` property. Hubs carry `synapse-kind:: hub`
//! and `synapse-description::`; a page in hubs lists their titles in `synapse-hubs::`.
use crate::Result;
use crate::error::Error;
@@ -15,6 +16,15 @@ use synapse_core::{Block, BlockId, Graph, Page, Properties};
pub const PAGES_DIR: &str = "pages";
pub const JOURNALS_DIR: &str = "journals";
pub const MANIFEST: &str = "assets.json";
/// Page property marking a hub or tag page (`synapse-kind:: hub|tag`); notes omit it.
pub const KIND_PROP: &str = "synapse-kind";
/// Page property holding a hub's description.
pub const DESCRIPTION_PROP: &str = "synapse-description";
/// Page property listing the titles of the hubs a page belongs to (JSON array).
pub const HUBS_PROP: &str = "synapse-hubs";
pub const TAGS_PROP: &str = "synapse-tags";
/// Page property with the type names (`synapse-types:: persona, lugar`).
pub const TYPES_PROP: &str = "synapse-types";
/// Encodes a page title as a file name (Logseq "triple-lowbar" format: `/` becomes `___`,
/// characters illegal on Windows and `%` are percent-encoded).
@@ -173,6 +183,38 @@ pub fn render_block(block: &Block, depth: usize, referenced: &HashSet<BlockId>)
pub fn render_page(graph: &Graph, page: &Page, referenced: &HashSet<BlockId>) -> Result<String> {
let mut props = page.properties.clone();
props.remove("alias");
if page.is_hub() {
props.insert(KIND_PROP.into(), Value::String("hub".into()));
} else if page.is_tag() {
props.insert(KIND_PROP.into(), Value::String("tag".into()));
}
if !page.description.is_empty() {
props.insert(
DESCRIPTION_PROP.into(),
Value::String(page.description.clone()),
);
}
let mut hubs = Vec::new();
for h in graph.hubs_of(page.id)? {
if let Some(h) = graph.get_page(h)? {
hubs.push(Value::String(h.title));
}
}
if !hubs.is_empty() {
props.insert(HUBS_PROP.into(), Value::Array(hubs));
}
if !page.tags.is_empty() {
props.insert(
TAGS_PROP.into(),
Value::Array(page.tags.iter().cloned().map(Value::String).collect()),
);
}
if !page.types.is_empty() {
props.insert(
TYPES_PROP.into(),
Value::Array(page.types.iter().cloned().map(Value::String).collect()),
);
}
let mut list = sorted_props(&props);
let aliases = graph.aliases_of(page.id)?;
if !aliases.is_empty() {
+7 -1
View File
@@ -189,14 +189,20 @@ impl History {
for rec in ops {
match rec.op {
Op::UpsertPage { page } => {
// Members list their hubs by title: a renamed hub, or one that
// became a note, changes their files.
touched.extend(graph.hub_members(page.id)?);
touched.insert(page.id);
}
Op::UpsertBlock { block } => {
touched.insert(block.page_id);
}
// A deleted hub drops out of its members' lists (their `page_hubs`
// rows outlive it when no member upsert came along).
Op::DeletePage { id } => touched.extend(graph.hub_members(id)?),
// Deletions and moves do not say which page lost a block; those
// pages are caught by the `updated_at` scan below.
Op::DeleteBlock { .. } | Op::DeletePage { .. } | Op::PutAsset { .. } => {}
Op::DeleteBlock { .. } | Op::PutAsset { .. } => {}
// The previous owner of an alias is unknown.
Op::SetAlias { .. } => everything = true,
}
+56 -2
View File
@@ -1,6 +1,6 @@
//! Parser for the Markdown files produced by [`crate::export`] (and plain Logseq pages).
use crate::export::parse_value;
use crate::export::{DESCRIPTION_PROP, HUBS_PROP, KIND_PROP, TAGS_PROP, TYPES_PROP, parse_value};
use serde_json::Value;
use synapse_core::{BlockId, Properties, parse::property_split};
@@ -16,9 +16,21 @@ pub struct ParsedBlock {
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ParsedPage {
/// Page properties except `alias`.
/// Page properties except `alias` and the `synapse-*` hub properties.
pub properties: Properties,
pub aliases: Vec<String>,
/// `synapse-kind:: hub`.
pub is_hub: bool,
/// `synapse-kind:: tag`.
pub is_tag: bool,
/// `synapse-description::`.
pub description: String,
/// Titles from `synapse-hubs::`.
pub hubs: Vec<String>,
/// Tag page titles from `synapse-tags::`.
pub tags: Vec<String>,
/// Names from `synapse-types::`.
pub types: Vec<String>,
pub blocks: Vec<ParsedBlock>,
}
@@ -106,6 +118,48 @@ pub fn parse_page(text: &str) -> ParsedPage {
}
}
let kind = page.properties.remove(KIND_PROP);
page.is_hub = matches!(&kind, Some(Value::String(k)) if k == "hub");
page.is_tag = matches!(&kind, Some(Value::String(k)) if k == "tag");
page.description = match page.properties.remove(DESCRIPTION_PROP) {
Some(Value::String(d)) => d,
Some(other) => other.to_string(),
None => String::new(),
};
page.hubs = match page.properties.remove(HUBS_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
page.tags = match page.properties.remove(TAGS_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
page.types = match page.properties.remove(TYPES_PROP) {
Some(Value::Array(items)) => items
.into_iter()
.filter_map(|v| match v {
Value::String(s) => Some(s),
_ => None,
})
.collect(),
Some(Value::String(s)) => vec![s],
_ => Vec::new(),
};
for raw in raws {
let mut lines = raw.lines;
// Blank separator lines between blocks are not content.
+154 -13
View File
@@ -8,7 +8,7 @@ use crate::parse::{ParsedPage, parse_page};
use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use synapse_core::position::between;
use synapse_core::{Block, BlockId, Graph, NewPage, Page, new_id};
use synapse_core::{Block, BlockId, Graph, NewPage, Page, PageId, PageKind, new_id};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RestoreReport {
@@ -51,6 +51,14 @@ fn atomic<T>(graph: &Graph, f: impl FnOnce() -> Result<T>) -> Result<T> {
}
struct Plan {
page: PageId,
is_hub: bool,
is_tag: bool,
description: String,
/// Titles of the hubs the page belongs to.
hubs: Vec<String>,
tags: Vec<String>,
types: Vec<String>,
blocks: Vec<Block>,
delete: Vec<BlockId>,
}
@@ -67,8 +75,20 @@ fn find_or_create(graph: &Graph, title: &str) -> Result<Page> {
/// Matches parsed blocks to existing ones and decides what to write and delete.
fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<Plan> {
let page = find_or_create(graph, title)?;
let mut page = find_or_create(graph, title)?;
let now = graph.now_ms();
// A hub cannot hold blocks: turn it back into a note before any block is written.
if page.is_hub() && !parsed.is_hub {
page.kind = PageKind::Note;
page.updated_at = now;
graph.put_page(&page)?;
// Like `convert_to_note`: members leave it, so it never regains them by surprise.
for m in graph.hub_members(page.id)? {
graph.remove_from_hub(m, page.id)?;
}
}
// A hub file has no blocks; any left over in the page are deleted.
let parsed_blocks: &[_] = if parsed.is_hub { &[] } else { &parsed.blocks };
if page.properties != parsed.properties {
graph.set_page_properties(page.id, parsed.properties.clone())?;
@@ -89,9 +109,9 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
.collect();
let by_id: HashMap<BlockId, &Block> = existing.iter().map(|b| (b.id, b)).collect();
let mut claimed: HashSet<BlockId> = HashSet::new();
let mut ids: Vec<Option<BlockId>> = vec![None; parsed.blocks.len()];
let mut ids: Vec<Option<BlockId>> = vec![None; parsed_blocks.len()];
for (i, pb) in parsed.blocks.iter().enumerate() {
for (i, pb) in parsed_blocks.iter().enumerate() {
let Some(id) = pb.id else { continue };
let usable = by_id.contains_key(&id)
|| match graph.get_block(id)? {
@@ -102,7 +122,7 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
ids[i] = Some(id);
}
}
for (i, pb) in parsed.blocks.iter().enumerate() {
for (i, pb) in parsed_blocks.iter().enumerate() {
if ids[i].is_some() {
continue;
}
@@ -115,10 +135,10 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
}
// Build the tree: parents from depth, positions kept when still ordered.
let mut blocks: Vec<Block> = Vec::with_capacity(parsed.blocks.len());
let mut blocks: Vec<Block> = Vec::with_capacity(parsed_blocks.len());
let mut stack: Vec<BlockId> = Vec::new();
let mut last_pos: HashMap<Option<BlockId>, String> = HashMap::new();
for (i, pb) in parsed.blocks.iter().enumerate() {
for (i, pb) in parsed_blocks.iter().enumerate() {
let id = ids[i].unwrap();
stack.truncate(pb.depth);
let parent = stack.last().copied();
@@ -149,7 +169,17 @@ fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result<
.filter(|b| !claimed.contains(&b.id))
.map(|b| b.id)
.collect();
Ok(Plan { blocks, delete })
Ok(Plan {
page: page.id,
is_hub: parsed.is_hub,
is_tag: parsed.is_tag,
description: parsed.description.clone(),
hubs: parsed.hubs.clone(),
tags: parsed.tags.clone(),
types: parsed.types.clone(),
blocks,
delete,
})
}
fn same(a: &Block, b: &Block) -> bool {
@@ -186,6 +216,72 @@ fn apply_puts(graph: &Graph, plan: &Plan, fault: Fault) -> Result<bool> {
Ok(wrote || !plan.delete.is_empty())
}
/// Sets kind and description once the page's blocks are gone; returns whether it changed.
fn apply_kind(graph: &Graph, plan: &Plan) -> Result<bool> {
let Some(mut page) = graph.get_page(plan.page)? else {
return Ok(false);
};
let kind = if plan.is_hub {
PageKind::Hub
} else if plan.is_tag {
PageKind::Tag
} else {
PageKind::Note
};
if page.kind == kind
&& page.description == plan.description
&& page.tags == plan.tags
&& page.types == plan.types
{
return Ok(false);
}
page.kind = kind;
page.tags = plan.tags.clone();
page.types = plan.types.clone();
page.description = plan.description.clone();
page.updated_at = graph.now_ms();
graph.put_page(&page)?;
Ok(true)
}
/// Puts the page back in the hubs named by the snapshot (once every page has its kind).
/// Hubs that no longer exist or would now be invalid (e.g. a cycle) are skipped.
fn apply_hubs(graph: &Graph, plan: &Plan) -> Result<bool> {
let Some(page) = graph.get_page(plan.page)? else {
return Ok(false);
};
let mut wanted = Vec::new();
for t in &plan.hubs {
if let Some(h) = graph.page_by_title(t)?
&& h.is_hub()
&& !wanted.contains(&h.id)
{
wanted.push(h.id);
}
}
wanted.truncate(1);
if page.hubs == wanted {
return Ok(false);
}
if skip_invalid(graph.set_page_hubs(page.id, wanted.clone()))?.is_none() {
graph.set_page_hubs(page.id, Vec::new())?;
for h in wanted {
skip_invalid(graph.add_to_hub(page.id, h))?;
}
}
Ok(true)
}
/// Rule violations (cycles, pages that are no longer hubs) become `None`; storage errors
/// still abort the restore.
fn skip_invalid<T>(r: synapse_core::Result<T>) -> Result<Option<T>> {
match r {
Ok(v) => Ok(Some(v)),
Err(synapse_core::Error::Invalid(_) | synapse_core::Error::NotFound(_)) => Ok(None),
Err(e) => Err(e.into()),
}
}
fn clear_or_delete(graph: &Graph, page: &Page) -> Result<bool> {
if page.is_journal() {
let roots: Vec<_> = graph
@@ -223,12 +319,19 @@ impl History {
..Default::default()
};
let fault = &self.fault;
let this = &*self;
atomic(graph, || {
match text {
Some(text) => {
let p = plan(graph, title, &parse_page(&text), false)?;
let parsed = parse_page(&text);
let p = plan(graph, title, &parsed, false)?;
apply_deletes(graph, &p, fault)?;
apply_puts(graph, &p, fault)?;
apply_kind(graph, &p)?;
apply_hubs(graph, &p)?;
if parsed.is_hub {
this.rejoin_members(graph, commit, title, p.page)?;
}
report.restored = 1;
}
None => {
@@ -245,6 +348,38 @@ impl History {
Ok(report)
}
/// Membership lives on the members: after restoring a hub alone, puts back the existing
/// pages that were in it at `commit` (other memberships are left alone).
fn rejoin_members(
&self,
graph: &Graph,
commit: gix::ObjectId,
title: &str,
hub: PageId,
) -> Result<()> {
let key = synapse_core::title_key(title);
for (path, oid) in &self.snapshot_files(&commit.to_string())? {
let Some(member) = export::title_from_path(path) else {
continue;
};
let parsed = parse_page(&self.read_blob(*oid)?);
if !parsed
.hubs
.iter()
.any(|h| synapse_core::title_key(h) == key)
{
continue;
}
if let Some(m) = graph.page_by_title(&member)?
&& m.id != hub
{
// Skipped when it would now be invalid (e.g. a cycle).
skip_invalid(graph.add_to_hub(m.id, hub))?;
}
}
Ok(())
}
/// Restores every page to its state at `rev`; pages created since are removed.
pub fn restore_graph(
&mut self,
@@ -275,11 +410,17 @@ impl History {
for p in &plans {
apply_deletes(graph, p, fault)?;
}
for p in &plans {
if apply_puts(graph, p, fault)? {
report.restored += 1;
}
let mut changed = vec![false; plans.len()];
for (i, p) in plans.iter().enumerate() {
changed[i] = apply_puts(graph, p, fault)?;
}
for (i, p) in plans.iter().enumerate() {
changed[i] |= apply_kind(graph, p)?;
}
for (i, p) in plans.iter().enumerate() {
changed[i] |= apply_hubs(graph, p)?;
}
report.restored += changed.iter().filter(|c| **c).count();
let mut offset = 0;
let mut extra = Vec::new();
loop {
+105
View File
@@ -341,3 +341,108 @@ fn failed_restore_leaves_graph_unchanged() {
h.restore_graph(&g, &s1.id, T0 + 4000).unwrap();
assert!(g.page_by_title("Gone").unwrap().is_some());
}
#[test]
fn tags_round_trip_through_snapshots() {
let (_d, g, mut h) = setup();
let note = add(&g, "Note", &["body"]);
g.add_page_tag(note.id, "tecnología").unwrap();
g.add_page_tag(note.id, "idea").unwrap();
g.add_page_type(note.id, "concepto").unwrap();
let s1 = h.snapshot(&g, T0 + 500).unwrap().unwrap();
let tag_md = h.page_at(&s1.id, "idea").unwrap().unwrap();
assert!(tag_md.contains("synapse-kind:: tag"), "{tag_md}");
let md = h.page_at(&s1.id, "Note").unwrap().unwrap();
assert!(
md.contains(r#"synapse-tags:: ["tecnología","idea"]"#),
"{md}"
);
at(&g, T0 + 1000);
g.set_page_tags(note.id, vec![]).unwrap();
g.set_page_types(note.id, vec![]).unwrap();
h.restore_graph(&g, &s1.id, T0 + 2000).unwrap();
assert_eq!(g.get_page(note.id).unwrap().unwrap().types, ["concepto"]);
assert!(g.page_by_title("idea").unwrap().unwrap().is_tag());
assert_eq!(
g.get_page(note.id).unwrap().unwrap().tags,
["tecnología", "idea"]
);
assert_eq!(g.pages_with_tag("idea").unwrap(), [note.id]);
}
#[test]
fn hubs_round_trip_kind_description_and_memberships() {
let (_d, g, mut h) = setup();
let top = g.create_hub("Top", "All my stuff,\nin one place").unwrap();
let sub = g.create_hub("Sub", "").unwrap();
let note = add(&g, "Note", &["body"]);
g.add_to_hub(sub.id, top.id).unwrap();
g.add_to_hub(note.id, sub.id).unwrap();
let s1 = h.snapshot(&g, T0).unwrap().unwrap();
let top_md = h.page_at(&s1.id, "Top").unwrap().unwrap();
assert!(top_md.contains("synapse-kind:: hub"), "{top_md}");
assert!(top_md.contains(r#"synapse-description:: "All my stuff,\nin one place""#));
let note_md = h.page_at(&s1.id, "Note").unwrap().unwrap();
assert!(note_md.contains(r#"synapse-hubs:: ["Sub"]"#), "{note_md}");
// Renaming a hub re-exports its members (they list hubs by title).
at(&g, T0 + 1000);
g.rename_page(sub.id, "Sub 2").unwrap();
let s2 = h.snapshot(&g, T0 + 1500).unwrap().unwrap();
let note_md = h.page_at(&s2.id, "Note").unwrap().unwrap();
assert!(note_md.contains(r#"synapse-hubs:: ["Sub 2"]"#), "{note_md}");
// Break everything, then restore the graph.
at(&g, T0 + 2000);
g.convert_to_note(top.id).unwrap();
g.remove_from_hub(note.id, sub.id).unwrap();
g.delete_page(sub.id).unwrap();
h.restore_graph(&g, &s1.id, T0 + 3000).unwrap();
let top = g.page_by_title("Top").unwrap().unwrap();
assert!(top.is_hub());
assert_eq!(top.description, "All my stuff,\nin one place");
assert!(
g.page_tree(top.id).unwrap().is_empty(),
"hubs have no blocks"
);
let sub = g.page_by_title("Sub").unwrap().expect("sub hub restored");
assert!(g.page_by_title("Sub 2").unwrap().is_none());
assert!(sub.is_hub());
assert_eq!(g.hub_members(top.id).unwrap(), vec![sub.id]);
assert_eq!(g.hub_members(sub.id).unwrap(), vec![note.id]);
assert_eq!(g.hubs_of(note.id).unwrap(), vec![sub.id]);
assert_eq!(g.page_tree(note.id).unwrap()[0].1.content, "body");
// A single page restore brings back its memberships too.
at(&g, T0 + 4000);
g.set_page_hubs(note.id, vec![]).unwrap();
h.restore_page(&g, "Note", &s1.id, T0 + 5000).unwrap();
assert_eq!(g.hubs_of(note.id).unwrap(), vec![sub.id]);
// Restoring a deleted hub alone brings its members back (they hold the membership).
at(&g, T0 + 5100);
g.delete_page(sub.id).unwrap();
let s3 = h.snapshot(&g, T0 + 5200).unwrap().unwrap();
let note_md = h.page_at(&s3.id, "Note").unwrap().unwrap();
assert!(!note_md.contains("synapse-hubs"), "{note_md}");
h.restore_page(&g, "Sub", &s1.id, T0 + 5300).unwrap();
let sub = g.page_by_title("Sub").unwrap().unwrap();
assert!(sub.is_hub());
assert_eq!(g.hub_members(sub.id).unwrap(), vec![note.id]);
assert_eq!(g.hubs_of(sub.id).unwrap(), vec![top.id]);
// The next snapshot matches the original export.
let s = h
.snapshot(&g, T0 + 6000)
.unwrap()
.unwrap_or_else(|| h.snapshots(1).unwrap().remove(0));
for title in ["Top", "Sub", "Note"] {
assert_eq!(
h.page_at(&s.id, title).unwrap(),
h.page_at(&s1.id, title).unwrap(),
"{title}"
);
}
}
+4 -2
View File
@@ -1,4 +1,4 @@
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing]`
//! `cargo run -p synapse-import --example import -- <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]`
use std::path::PathBuf;
use synapse_core::Graph;
@@ -7,13 +7,14 @@ use synapse_import::{ExistingPages, ImportOptions, import_logseq};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let skip = args.iter().any(|a| a == "--skip-existing");
let keep_legacy = args.iter().any(|a| a == "--keep-legacy");
let paths: Vec<PathBuf> = args
.iter()
.filter(|a| !a.starts_with("--"))
.map(PathBuf::from)
.collect();
let [src, dst] = paths.as_slice() else {
eprintln!("usage: import <logseq_dir> <graph_dir> [--skip-existing]");
eprintln!("usage: import <logseq_dir> <graph_dir> [--skip-existing] [--keep-legacy]");
std::process::exit(2);
};
let graph = Graph::open(dst).expect("open graph");
@@ -23,6 +24,7 @@ fn main() {
} else {
ExistingPages::Update
},
skip_legacy_pages: !keep_legacy,
};
let started = std::time::Instant::now();
let mut last = (None, 0);
+76 -3
View File
@@ -39,9 +39,22 @@ pub enum ExistingPages {
Skip,
}
#[derive(Debug, Clone, Default)]
#[derive(Debug, Clone)]
pub struct ImportOptions {
pub existing: ExistingPages,
/// Skip the files of Logseq's organisational pages (`contents`, `card`, `favorites`,
/// `hls__*`; see [`is_skipped_legacy`]) and drop the empty stubs their refs would create
/// in this import. Other built-in names (`TODO`, `NOW`, ...) are imported normally.
pub skip_legacy_pages: bool,
}
impl Default for ImportOptions {
fn default() -> Self {
Self {
existing: ExistingPages::default(),
skip_legacy_pages: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -78,6 +91,8 @@ pub struct Report {
pub unchanged: usize,
/// `.org` files imported as raw blocks (relative paths).
pub org_files: Vec<String>,
/// Legacy organisational pages left out (relative paths), see `skip_legacy_pages`.
pub skipped_legacy: Vec<String>,
pub warnings: Vec<String>,
}
@@ -163,7 +178,16 @@ pub fn import_logseq(
.collect();
docs.extend(parsed);
}
let docs = dedupe(docs, &mut report.warnings);
let mut docs = dedupe(docs, &mut report.warnings);
if opts.skip_legacy_pages {
docs.retain(|d| {
let legacy = d.journal.is_none() && is_skipped_legacy(&d.title);
if legacy {
report.skipped_legacy.push(d.rel.clone());
}
!legacy
});
}
// ---- origin journals: earliest journal referencing each page (aliases resolved)
let mut alias_to_key: HashMap<String, String> = HashMap::new();
@@ -187,10 +211,52 @@ pub fn import_logseq(
// One transaction for the whole write phase: much faster, and a failed import leaves the
// graph untouched.
track::init(graph)?;
graph.transaction(|g| write_all(g, opts, &docs, &origin, &mut report, &mut progress))?;
graph.transaction(|g| {
let before: HashSet<PageId> = if opts.skip_legacy_pages {
page_ids(g)?
} else {
HashSet::new()
};
write_all(g, opts, &docs, &origin, &mut report, &mut progress)?;
if opts.skip_legacy_pages {
drop_legacy_stubs(g, &before)?;
}
Ok(())
})?;
Ok(report)
}
/// Logseq files the importer leaves out when `skip_legacy_pages` is set: `contents`, `card`,
/// `favorites` and PDF highlight pages (`hls__*`).
pub fn is_skipped_legacy(title: &str) -> bool {
let key = title_key(title);
key.starts_with("hls__") || ["contents", "card", "favorites"].contains(&key.as_str())
}
fn page_ids(g: &Graph) -> Result<HashSet<PageId>> {
Ok(g.list_pages(false, u32::MAX, 0)?
.into_iter()
.map(|p| p.id)
.collect())
}
/// Refs to `[[contents]]`, `[[card]]`, ... make core create empty stub pages; remove the ones
/// this import created (pages that existed before are never touched).
fn drop_legacy_stubs(g: &Graph, before: &HashSet<PageId>) -> Result<()> {
let stubs: Vec<PageId> = g
.list_pages(false, u32::MAX, 0)?
.into_iter()
.filter(|p| !before.contains(&p.id) && is_skipped_legacy(&p.title))
.map(|p| p.id)
.collect();
for id in stubs {
if g.page_tree(id)?.is_empty() {
g.delete_page(id)?;
}
}
Ok(())
}
fn write_all(
graph: &Graph,
opts: &ImportOptions,
@@ -218,6 +284,13 @@ fn write_all(
let d = &docs[i];
let o = origin.get(&d.key).copied();
match graph.transaction(|g| ensure_page(g, d, o)) {
// Hubs are Synapse-only pages without blocks: a re-import never writes them.
Ok((pid, true)) if graph.get_page(pid)?.is_some_and(|p| p.is_hub()) => {
report.warnings.push(format!(
"{}: {:?} is a hub in Synapse, skipped",
d.rel, d.title
));
}
Ok(r) => {
ids.insert(i, r);
}
+79
View File
@@ -146,6 +146,7 @@ fn reimport_updates_changed_pages_and_skip_mode() {
.unwrap();
let skip = ImportOptions {
existing: ExistingPages::Skip,
..Default::default()
};
let r = import_logseq(src.path(), &g, &skip, |_| {}).unwrap();
assert_eq!(r.updated, 0);
@@ -334,3 +335,81 @@ fn renamed_page_is_not_duplicated() {
let t = texts(&g, "Renamed");
assert_eq!(t.len(), 2);
}
#[test]
fn skips_legacy_pages_and_their_stubs() {
let files = [
("pages/contents.md", "- [[Alpha]]\n"),
("pages/TODO.md", "- old\n"),
("pages/hls__book_1.md", "- highlight\n"),
(
"pages/Alpha.md",
"- see [[contents]], [[card]], [[favorites]] and [[TODO]]\n",
),
];
let src = mini_graph(&files);
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
// A page that already exists is never removed, even with a legacy title and no blocks.
let card = g.ensure_page("card", None).unwrap();
let r = imp(src.path(), &g);
assert_eq!(r.pages, 2, "Alpha and TODO");
assert_eq!(
r.skipped_legacy,
["pages/contents.md", "pages/hls__book_1.md"]
);
for t in ["contents", "favorites", "hls__book_1"] {
assert!(g.page_by_title(t).unwrap().is_none(), "{t}");
}
assert_eq!(
texts(&g, "TODO").len(),
1,
"other built-ins import normally"
);
assert_eq!(g.page_by_title("card").unwrap().unwrap().id, card.id);
let keep = ImportOptions {
skip_legacy_pages: false,
..Default::default()
};
let dir2 = tempfile::tempdir().unwrap();
let g2 = Graph::open(dir2.path()).unwrap();
let r = import_logseq(src.path(), &g2, &keep, |_| {}).unwrap();
assert!(r.skipped_legacy.is_empty());
assert!(g2.page_by_title("contents").unwrap().is_some());
}
#[test]
fn reimport_never_writes_hubs() {
let src = mini_graph(&[
("pages/Area.md", "- [[Note]]\n- more\n"),
("pages/Note.md", "- body\n"),
]);
let dir = tempfile::tempdir().unwrap();
let g = Graph::open(dir.path()).unwrap();
imp(src.path(), &g);
let area = g.page_by_title("Area").unwrap().unwrap();
let note = g.page_by_title("Note").unwrap().unwrap();
g.convert_to_hub(
area.id,
&synapse_core::HubConversion {
title: "Area".into(),
description: "d".into(),
members: vec![note.id],
keep_outline_as: None,
},
)
.unwrap();
std::fs::write(src.path().join("pages/Area.md"), "- [[Note]]\n- changed\n").unwrap();
let r = imp(src.path(), &g);
assert!(
r.warnings.iter().any(|w| w.contains("is a hub")),
"{:?}",
r.warnings
);
let area = g.page_by_title("Area").unwrap().unwrap();
assert!(area.is_hub());
assert!(g.page_tree(area.id).unwrap().is_empty());
assert_eq!(g.hub_members(area.id).unwrap(), vec![note.id]);
}
+6 -1
View File
@@ -1,4 +1,5 @@
//! tantivy-backed full-text index: one document per block and one per page (title + aliases).
//! tantivy-backed full-text index: one document per block and one per page (title + aliases,
//! plus the description of hubs as content).
use crate::error::Result;
use crate::{Filter, JournalFilter, Scope};
@@ -184,6 +185,7 @@ impl FullText {
id: Uuid,
title: &str,
aliases: &[String],
description: &str,
day: i64,
journal: bool,
) -> Result<()> {
@@ -196,6 +198,9 @@ impl FullText {
for a in aliases {
d.add_text(self.f.title, a);
}
if !description.is_empty() {
d.add_text(self.f.content, description);
}
d.add_i64(self.f.day, day);
d.add_u64(self.f.journal, journal as u64);
self.writer.add_document(d)?;
+4 -2
View File
@@ -318,7 +318,8 @@ impl Search {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(p.updated_at), false),
};
self.ft.upsert_page(id, &p.title, &aliases, day, journal)?;
self.ft
.upsert_page(id, &p.title, &aliases, &p.description, day, journal)?;
}
None => {
self.ft.delete(id);
@@ -350,7 +351,8 @@ impl Search {
Some(d) => (day_of_date(d), true),
None => (day_of_ms(p.updated_at), false),
};
self.ft.upsert_page(p.id, &p.title, &al, day, journal)?;
self.ft
.upsert_page(p.id, &p.title, &al, &p.description, day, journal)?;
}
}
Ok(())
+4 -4
View File
@@ -40,15 +40,15 @@ pub(crate) fn quantize(v: &[f32]) -> (Vec<i8>, f32) {
fn dot(row: &[i8], q: &[f32]) -> f32 {
let mut acc = [0f32; 8];
let mut rc = row.chunks_exact(8);
let mut qc = q.chunks_exact(8);
for (r, c) in (&mut rc).zip(&mut qc) {
let (rc, r_rem) = row.as_chunks::<8>();
let (qc, q_rem) = q.as_chunks::<8>();
for (r, c) in rc.iter().zip(qc) {
for i in 0..8 {
acc[i] += r[i] as f32 * c[i];
}
}
let mut s: f32 = acc.iter().sum();
for (r, c) in rc.remainder().iter().zip(qc.remainder()) {
for (r, c) in r_rem.iter().zip(q_rem) {
s += *r as f32 * c;
}
s
+18
View File
@@ -331,3 +331,21 @@ fn store_inside_graph_transaction_and_rename_delete() {
assert!(s.search(&g, "ferris", &f, 10).unwrap().is_empty());
assert_eq!(s.vector_counts(&g, "test/hash").unwrap(), (1, 0));
}
#[test]
fn hub_titles_and_descriptions_are_indexed() {
let (_d, g) = setup();
let h = g.create_hub("Anime", "Japanese animation series").unwrap();
add(&g, "Other", "nothing related");
let mut s = Search::open(&g).unwrap();
s.sync(&g).unwrap();
let f = Filter::default();
let hits = s.search(&g, "animation", &f, 5).unwrap();
assert_eq!(hits[0].kind, HitKind::Page);
assert_eq!(hits[0].page_id, h.id);
assert_eq!(s.search(&g, "anime", &f, 5).unwrap()[0].page_id, h.id);
g.set_hub_description(h.id, "Cartoons from Japan").unwrap();
s.sync(&g).unwrap();
assert!(s.search(&g, "animation", &f, 5).unwrap().is_empty());
assert_eq!(s.search(&g, "cartoons", &f, 5).unwrap()[0].page_id, h.id);
}
+33
View File
@@ -162,6 +162,39 @@ async fn concurrent_edits_resolve_last_writer_wins() {
assert_eq!(texts(&b, "Shared"), vec!["from A"]);
}
#[tokio::test(flavor = "multi_thread")]
async fn hubs_and_memberships_converge() {
let srv = TestServer::start().await;
let a = device(&srv, "h");
let b = device(&srv, "h");
let (hub, note) = {
let g = a.g();
let hub = g.create_hub("Top", "All of it").unwrap();
let note = g.create_page(NewPage::titled("Note")).unwrap();
g.add_to_hub(note.id, hub.id).unwrap();
(hub.id, note.id)
};
a.client.sync_once().await.unwrap();
b.client.sync_once().await.unwrap();
{
let g = b.g();
let h = g.get_page(hub).unwrap().unwrap();
assert!(h.is_hub());
assert_eq!(h.description, "All of it");
assert_eq!(g.hub_members(hub).unwrap(), vec![note]);
assert_eq!(g.hubs_of(note).unwrap(), vec![hub]);
// B deletes the hub: the member's list is cleaned on both sides.
g.delete_page(hub).unwrap();
}
b.client.refresh_pending().await.unwrap();
b.client.sync_once().await.unwrap();
a.client.sync_once().await.unwrap();
let g = a.g();
assert!(g.get_page(hub).unwrap().is_none());
assert!(g.get_page(note).unwrap().unwrap().hubs.is_empty());
assert!(g.hubs_of(note).unwrap().is_empty());
}
#[tokio::test(flavor = "multi_thread")]
async fn auth_failures() {
let srv = TestServer::start().await;