diff --git a/app/lib/src/rust/api/dto.dart b/app/lib/src/rust/api/dto.dart index dee0406..621f01e 100644 --- a/app/lib/src/rust/api/dto.dart +++ b/app/lib/src/rust/api/dto.dart @@ -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 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 members; + + /// Ids of the members that are hubs themselves. + final List 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 members; + + /// Blocks that are prose rather than links (what "keep the outline" would save). + final int proseBlocks; + final int blocks; + + /// `" (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 hubs; + + /// Ids of the hubs that are not a member of any hub, by title. + final List 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 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 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 members; + + /// Hubs the page belongs to (its own membership list), by title. + final List inHubs; + + /// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist). + final List nsPath; + final List 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; diff --git a/app/lib/src/rust/api/graph.dart b/app/lib/src/rust/api/graph.dart index 90eca95..2af7fd2 100644 --- a/app/lib/src/rust/api/graph.dart +++ b/app/lib/src/rust/api/graph.dart @@ -15,6 +15,14 @@ import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart'; abstract class SynapseGraph implements RustOpaqueInterface { Future addAlias({required String pageId, required String alias}); + Future addPageTag({required String pageId, required String tag}); + + Future 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 addToHub({required String pageId, required String hubId}); + Future> aliases({required String pageId}); /// Local file path of an asset (for `asset://` images), if present. @@ -26,6 +34,32 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// Target of a `((block ref))`. Future 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 convertToHub({ + required String pageId, + required String title, + required String description, + required List memberIds, + String? keepOutlineAs, + }); + + /// Turns a hub back into a note: description, then one `[[Member]]` block per member. + Future convertToNote({required String pageId}); + + /// Creates an empty hub. Fails when the title is taken. + Future createHub({ + required String title, + required String description, + }); + + /// Creates a note in the hub, starting from a copy of the hub's template. + Future createPageFromTemplate({ + required String hubId, + required String title, + }); + /// Deletes a block and its subtree. Future> deleteBlock({required String id}); @@ -38,6 +72,16 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// graph changes. Future graphData(); + /// Defaults for converting a note into a hub. + Future 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 hubTemplate({required String hubId}); + + /// Every hub with its members, and the root hubs. + Future hubs(); + /// Tab: the block becomes the last child of its previous sibling (no-op for a first child). Future> indentBlock({required String id}); @@ -56,6 +100,12 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// journal); otherwise at the newest journal strictly before `before`. Future> 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> legacyCandidates(); + /// Pages ordered by last update, most recent first. Future> listPages({ required bool includeJournals, @@ -95,6 +145,15 @@ abstract class SynapseGraph implements RustOpaqueInterface { /// Page by title or alias, without creating it. Future pageByTitle({required String title}); + /// Hub and namespace context of a page. + Future pageStructure({required String pageId}); + + /// Pages carrying a tag, most recently updated first. + Future> pagesWithTag({required String tag}); + + /// Deletes pages and their blocks in one transaction. Returns how many existed. + Future purgePages({required List ids}); + /// Stores in-memory bytes (clipboard, Android content URIs). Future putAssetBytes({ required List bytes, @@ -116,6 +175,13 @@ abstract class SynapseGraph implements RustOpaqueInterface { Future removeAlias({required String alias}); + /// Takes a page out of a hub (no-op when it is not in it). + Future removeFromHub({required String pageId, required String hubId}); + + Future removePageTag({required String pageId, required String tag}); + + Future removePageType({required String pageId, required String ty}); + Future 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 setCollapsed({required String id, required bool collapsed}); + Future 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 setPageTags({ + required String pageId, + required List tags, + }); + + /// Replaces the types of a page. Journals and templates cannot be typed. + Future setPageTypes({ + required String pageId, + required List types, + }); + + /// Every tag page with its number of pages, most used first. + Future> tagCatalog(); + /// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions. Future 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> typeCatalog(); + /// Replaces a block's Markdown (the debounced save while typing). Future updateBlock({required String id, required String content}); } diff --git a/app/lib/src/rust/frb_generated.dart b/app/lib/src/rust/frb_generated.dart index f7406cd..879f8bb 100644 --- a/app/lib/src/rust/frb_generated.dart +++ b/app/lib/src/rust/frb_generated.dart @@ -69,7 +69,7 @@ class RustLib extends BaseEntrypoint { String get codegenVersion => '2.13.0'; @override - int get rustContentHash => -553305025; + int get rustContentHash => 465538383; static const kDefaultExternalLibraryLoaderConfig = ExternalLibraryLoaderConfig( @@ -117,6 +117,24 @@ abstract class RustLibApi extends BaseApi { required String alias, }); + Future crateApiGraphSynapseGraphAddPageTag({ + required SynapseGraph that, + required String pageId, + required String tag, + }); + + Future crateApiGraphSynapseGraphAddPageType({ + required SynapseGraph that, + required String pageId, + required String ty, + }); + + Future crateApiGraphSynapseGraphAddToHub({ + required SynapseGraph that, + required String pageId, + required String hubId, + }); + Future> crateApiGraphSynapseGraphAliases({ required SynapseGraph that, required String pageId, @@ -137,6 +155,32 @@ abstract class RustLibApi extends BaseApi { required String id, }); + Future crateApiGraphSynapseGraphConvertToHub({ + required SynapseGraph that, + required String pageId, + required String title, + required String description, + required List memberIds, + String? keepOutlineAs, + }); + + Future crateApiGraphSynapseGraphConvertToNote({ + required SynapseGraph that, + required String pageId, + }); + + Future crateApiGraphSynapseGraphCreateHub({ + required SynapseGraph that, + required String title, + required String description, + }); + + Future crateApiGraphSynapseGraphCreatePageFromTemplate({ + required SynapseGraph that, + required String hubId, + required String title, + }); + Future> crateApiGraphSynapseGraphDeleteBlock({ required SynapseGraph that, required String id, @@ -153,6 +197,18 @@ abstract class RustLibApi extends BaseApi { required SynapseGraph that, }); + Future crateApiGraphSynapseGraphHubConversionPreview({ + required SynapseGraph that, + required String pageId, + }); + + Future crateApiGraphSynapseGraphHubTemplate({ + required SynapseGraph that, + required String hubId, + }); + + Future crateApiGraphSynapseGraphHubs({required SynapseGraph that}); + Future> crateApiGraphSynapseGraphIndentBlock({ required SynapseGraph that, required String id, @@ -181,6 +237,10 @@ abstract class RustLibApi extends BaseApi { required int limit, }); + Future> crateApiGraphSynapseGraphLegacyCandidates({ + required SynapseGraph that, + }); + Future> crateApiGraphSynapseGraphListPages({ required SynapseGraph that, required bool includeJournals, @@ -228,6 +288,21 @@ abstract class RustLibApi extends BaseApi { required String title, }); + Future crateApiGraphSynapseGraphPageStructure({ + required SynapseGraph that, + required String pageId, + }); + + Future> crateApiGraphSynapseGraphPagesWithTag({ + required SynapseGraph that, + required String tag, + }); + + Future crateApiGraphSynapseGraphPurgePages({ + required SynapseGraph that, + required List ids, + }); + Future crateApiGraphSynapseGraphPutAssetBytes({ required SynapseGraph that, required List bytes, @@ -258,6 +333,24 @@ abstract class RustLibApi extends BaseApi { required String alias, }); + Future crateApiGraphSynapseGraphRemoveFromHub({ + required SynapseGraph that, + required String pageId, + required String hubId, + }); + + Future crateApiGraphSynapseGraphRemovePageTag({ + required SynapseGraph that, + required String pageId, + required String tag, + }); + + Future crateApiGraphSynapseGraphRemovePageType({ + required SynapseGraph that, + required String pageId, + required String ty, + }); + Future crateApiGraphSynapseGraphRenamePage({ required SynapseGraph that, required String id, @@ -282,6 +375,28 @@ abstract class RustLibApi extends BaseApi { required bool collapsed, }); + Future crateApiGraphSynapseGraphSetHubDescription({ + required SynapseGraph that, + required String hubId, + required String description, + }); + + Future crateApiGraphSynapseGraphSetPageTags({ + required SynapseGraph that, + required String pageId, + required List tags, + }); + + Future crateApiGraphSynapseGraphSetPageTypes({ + required SynapseGraph that, + required String pageId, + required List types, + }); + + Future> crateApiGraphSynapseGraphTagCatalog({ + required SynapseGraph that, + }); + Future crateApiGraphSynapseGraphTimeline({ required SynapseGraph that, required String from, @@ -290,6 +405,10 @@ abstract class RustLibApi extends BaseApi { String crateApiGraphSynapseGraphToday({required SynapseGraph that}); + Future> crateApiGraphSynapseGraphTypeCatalog({ + required SynapseGraph that, + }); + Future crateApiGraphSynapseGraphUpdateBlock({ required SynapseGraph that, required String id, @@ -554,6 +673,126 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "pageId", "alias"], ); + @override + Future crateApiGraphSynapseGraphAddPageTag({ + required SynapseGraph that, + required String pageId, + required String tag, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(tag, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 7, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphAddPageTagConstMeta, + argValues: [that, pageId, tag], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphAddPageTagConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_add_page_tag", + argNames: ["that", "pageId", "tag"], + ); + + @override + Future crateApiGraphSynapseGraphAddPageType({ + required SynapseGraph that, + required String pageId, + required String ty, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(ty, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 8, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphAddPageTypeConstMeta, + argValues: [that, pageId, ty], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphAddPageTypeConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_add_page_type", + argNames: ["that", "pageId", "ty"], + ); + + @override + Future crateApiGraphSynapseGraphAddToHub({ + required SynapseGraph that, + required String pageId, + required String hubId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(hubId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 9, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphAddToHubConstMeta, + argValues: [that, pageId, hubId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphAddToHubConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_add_to_hub", + argNames: ["that", "pageId", "hubId"], + ); + @override Future> crateApiGraphSynapseGraphAliases({ required SynapseGraph that, @@ -571,7 +810,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 7, + funcId: 10, port: port_, ); }, @@ -606,7 +845,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { serializer, ); sse_encode_String(hash, serializer); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 8)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 11)!; }, codec: SseCodec( decodeSuccessData: sse_decode_opt_String, @@ -642,7 +881,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 9, + funcId: 12, port: port_, ); }, @@ -680,7 +919,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 10, + funcId: 13, port: port_, ); }, @@ -701,6 +940,177 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "id"], ); + @override + Future crateApiGraphSynapseGraphConvertToHub({ + required SynapseGraph that, + required String pageId, + required String title, + required String description, + required List memberIds, + String? keepOutlineAs, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(title, serializer); + sse_encode_String(description, serializer); + sse_encode_list_String(memberIds, serializer); + sse_encode_opt_String(keepOutlineAs, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 14, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphConvertToHubConstMeta, + argValues: [that, pageId, title, description, memberIds, keepOutlineAs], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphConvertToHubConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_convert_to_hub", + argNames: [ + "that", + "pageId", + "title", + "description", + "memberIds", + "keepOutlineAs", + ], + ); + + @override + Future crateApiGraphSynapseGraphConvertToNote({ + required SynapseGraph that, + required String pageId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 15, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphConvertToNoteConstMeta, + argValues: [that, pageId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphConvertToNoteConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_convert_to_note", + argNames: ["that", "pageId"], + ); + + @override + Future crateApiGraphSynapseGraphCreateHub({ + required SynapseGraph that, + required String title, + required String description, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(title, serializer); + sse_encode_String(description, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 16, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphCreateHubConstMeta, + argValues: [that, title, description], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphCreateHubConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_create_hub", + argNames: ["that", "title", "description"], + ); + + @override + Future crateApiGraphSynapseGraphCreatePageFromTemplate({ + required SynapseGraph that, + required String hubId, + required String title, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(hubId, serializer); + sse_encode_String(title, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 17, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphCreatePageFromTemplateConstMeta, + argValues: [that, hubId, title], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphCreatePageFromTemplateConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_create_page_from_template", + argNames: ["that", "hubId", "title"], + ); + @override Future> crateApiGraphSynapseGraphDeleteBlock({ required SynapseGraph that, @@ -718,7 +1128,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 11, + funcId: 18, port: port_, ); }, @@ -756,7 +1166,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 12, + funcId: 19, port: port_, ); }, @@ -787,7 +1197,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 13)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 20)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -818,7 +1228,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 14, + funcId: 21, port: port_, ); }, @@ -839,6 +1249,113 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that"], ); + @override + Future crateApiGraphSynapseGraphHubConversionPreview({ + required SynapseGraph that, + required String pageId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 22, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_hub_preview_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphHubConversionPreviewConstMeta, + argValues: [that, pageId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphHubConversionPreviewConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_hub_conversion_preview", + argNames: ["that", "pageId"], + ); + + @override + Future crateApiGraphSynapseGraphHubTemplate({ + required SynapseGraph that, + required String hubId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(hubId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 23, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_String, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphHubTemplateConstMeta, + argValues: [that, hubId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphHubTemplateConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_hub_template", + argNames: ["that", "hubId"], + ); + + @override + Future crateApiGraphSynapseGraphHubs({required SynapseGraph that}) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 24, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_hubs_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphHubsConstMeta, + argValues: [that], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphHubsConstMeta => + const TaskConstMeta(debugName: "SynapseGraph_hubs", argNames: ["that"]); + @override Future> crateApiGraphSynapseGraphIndentBlock({ required SynapseGraph that, @@ -856,7 +1373,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 15, + funcId: 25, port: port_, ); }, @@ -898,7 +1415,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 16, + funcId: 26, port: port_, ); }, @@ -936,7 +1453,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 17, + funcId: 27, port: port_, ); }, @@ -974,7 +1491,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 18, + funcId: 28, port: port_, ); }, @@ -1014,7 +1531,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 19, + funcId: 29, port: port_, ); }, @@ -1035,6 +1552,42 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "before", "limit"], ); + @override + Future> crateApiGraphSynapseGraphLegacyCandidates({ + required SynapseGraph that, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 30, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_legacy_candidate, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphLegacyCandidatesConstMeta, + argValues: [that], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphLegacyCandidatesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_legacy_candidates", + argNames: ["that"], + ); + @override Future> crateApiGraphSynapseGraphListPages({ required SynapseGraph that, @@ -1056,7 +1609,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 20, + funcId: 31, port: port_, ); }, @@ -1096,7 +1649,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 21, + funcId: 32, port: port_, ); }, @@ -1138,7 +1691,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 22, + funcId: 33, port: port_, ); }, @@ -1169,7 +1722,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 23, + funcId: 34, port: port_, ); }, @@ -1205,7 +1758,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 24, + funcId: 35, port: port_, ); }, @@ -1243,7 +1796,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 25, + funcId: 36, port: port_, ); }, @@ -1281,7 +1834,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 26, + funcId: 37, port: port_, ); }, @@ -1319,7 +1872,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 27, + funcId: 38, port: port_, ); }, @@ -1357,7 +1910,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 28, + funcId: 39, port: port_, ); }, @@ -1378,6 +1931,120 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "title"], ); + @override + Future crateApiGraphSynapseGraphPageStructure({ + required SynapseGraph that, + required String pageId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 40, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_structure, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPageStructureConstMeta, + argValues: [that, pageId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPageStructureConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_page_structure", + argNames: ["that", "pageId"], + ); + + @override + Future> crateApiGraphSynapseGraphPagesWithTag({ + required SynapseGraph that, + required String tag, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(tag, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 41, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_page_brief, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPagesWithTagConstMeta, + argValues: [that, tag], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPagesWithTagConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_pages_with_tag", + argNames: ["that", "tag"], + ); + + @override + Future crateApiGraphSynapseGraphPurgePages({ + required SynapseGraph that, + required List ids, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_list_String(ids, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 42, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_u_32, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphPurgePagesConstMeta, + argValues: [that, ids], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphPurgePagesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_purge_pages", + argNames: ["that", "ids"], + ); + @override Future crateApiGraphSynapseGraphPutAssetBytes({ required SynapseGraph that, @@ -1399,7 +2066,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 29, + funcId: 43, port: port_, ); }, @@ -1439,7 +2106,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 30, + funcId: 44, port: port_, ); }, @@ -1479,7 +2146,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 31, + funcId: 45, port: port_, ); }, @@ -1519,7 +2186,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 32, + funcId: 46, port: port_, ); }, @@ -1557,7 +2224,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 33, + funcId: 47, port: port_, ); }, @@ -1578,6 +2245,126 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "alias"], ); + @override + Future crateApiGraphSynapseGraphRemoveFromHub({ + required SynapseGraph that, + required String pageId, + required String hubId, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(hubId, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 48, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_unit, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRemoveFromHubConstMeta, + argValues: [that, pageId, hubId], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRemoveFromHubConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_remove_from_hub", + argNames: ["that", "pageId", "hubId"], + ); + + @override + Future crateApiGraphSynapseGraphRemovePageTag({ + required SynapseGraph that, + required String pageId, + required String tag, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(tag, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 49, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRemovePageTagConstMeta, + argValues: [that, pageId, tag], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRemovePageTagConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_remove_page_tag", + argNames: ["that", "pageId", "tag"], + ); + + @override + Future crateApiGraphSynapseGraphRemovePageType({ + required SynapseGraph that, + required String pageId, + required String ty, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_String(ty, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 50, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphRemovePageTypeConstMeta, + argValues: [that, pageId, ty], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphRemovePageTypeConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_remove_page_type", + argNames: ["that", "pageId", "ty"], + ); + @override Future crateApiGraphSynapseGraphRenamePage({ required SynapseGraph that, @@ -1597,7 +2384,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 34, + funcId: 51, port: port_, ); }, @@ -1637,7 +2424,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 35, + funcId: 52, port: port_, ); }, @@ -1677,7 +2464,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 36, + funcId: 53, port: port_, ); }, @@ -1717,7 +2504,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 37, + funcId: 54, port: port_, ); }, @@ -1738,6 +2525,162 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { argNames: ["that", "id", "collapsed"], ); + @override + Future crateApiGraphSynapseGraphSetHubDescription({ + required SynapseGraph that, + required String hubId, + required String description, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(hubId, serializer); + sse_encode_String(description, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 55, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSetHubDescriptionConstMeta, + argValues: [that, hubId, description], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSetHubDescriptionConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_set_hub_description", + argNames: ["that", "hubId", "description"], + ); + + @override + Future crateApiGraphSynapseGraphSetPageTags({ + required SynapseGraph that, + required String pageId, + required List tags, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_list_String(tags, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 56, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSetPageTagsConstMeta, + argValues: [that, pageId, tags], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSetPageTagsConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_set_page_tags", + argNames: ["that", "pageId", "tags"], + ); + + @override + Future crateApiGraphSynapseGraphSetPageTypes({ + required SynapseGraph that, + required String pageId, + required List types, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + sse_encode_String(pageId, serializer); + sse_encode_list_String(types, serializer); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 57, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_page_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphSetPageTypesConstMeta, + argValues: [that, pageId, types], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphSetPageTypesConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_set_page_types", + argNames: ["that", "pageId", "types"], + ); + + @override + Future> crateApiGraphSynapseGraphTagCatalog({ + required SynapseGraph that, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 58, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_tag_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphTagCatalogConstMeta, + argValues: [that], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphTagCatalogConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_tag_catalog", + argNames: ["that"], + ); + @override Future crateApiGraphSynapseGraphTimeline({ required SynapseGraph that, @@ -1757,7 +2700,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 38, + funcId: 59, port: port_, ); }, @@ -1788,7 +2731,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { that, serializer, ); - return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 39)!; + return pdeCallFfi(generalizedFrbRustBinding, serializer, funcId: 60)!; }, codec: SseCodec( decodeSuccessData: sse_decode_String, @@ -1804,6 +2747,42 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { TaskConstMeta get kCrateApiGraphSynapseGraphTodayConstMeta => const TaskConstMeta(debugName: "SynapseGraph_today", argNames: ["that"]); + @override + Future> crateApiGraphSynapseGraphTypeCatalog({ + required SynapseGraph that, + }) { + return handler.executeNormal( + NormalTask( + callFfi: (port_) { + final serializer = SseSerializer(generalizedFrbRustBinding); + sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph( + that, + serializer, + ); + pdeCallFfi( + generalizedFrbRustBinding, + serializer, + funcId: 61, + port: port_, + ); + }, + codec: SseCodec( + decodeSuccessData: sse_decode_list_tag_dto, + decodeErrorData: sse_decode_AnyhowException, + ), + constMeta: kCrateApiGraphSynapseGraphTypeCatalogConstMeta, + argValues: [that], + apiImpl: this, + ), + ); + } + + TaskConstMeta get kCrateApiGraphSynapseGraphTypeCatalogConstMeta => + const TaskConstMeta( + debugName: "SynapseGraph_type_catalog", + argNames: ["that"], + ); + @override Future crateApiGraphSynapseGraphUpdateBlock({ required SynapseGraph that, @@ -1823,7 +2802,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { pdeCallFfi( generalizedFrbRustBinding, serializer, - funcId: 40, + funcId: 62, port: port_, ); }, @@ -2065,8 +3044,8 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { GraphNode dco_decode_graph_node(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 9) - throw Exception('unexpected arr length: expect 9 but see ${arr.length}'); + if (arr.length != 12) + throw Exception('unexpected arr length: expect 12 but see ${arr.length}'); return GraphNode( id: dco_decode_String(arr[0]), title: dco_decode_String(arr[1]), @@ -2077,6 +3056,53 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { backlinks: dco_decode_u_32(arr[6]), cluster: dco_decode_u_32(arr[7]), primaryTag: dco_decode_opt_box_autoadd_u_32(arr[8]), + isHub: dco_decode_bool(arr[9]), + homeHub: dco_decode_opt_box_autoadd_u_32(arr[10]), + tags: dco_decode_list_String(arr[11]), + ); + } + + @protected + HubDto dco_decode_hub_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return HubDto( + id: dco_decode_String(arr[0]), + title: dco_decode_String(arr[1]), + description: dco_decode_String(arr[2]), + depth: dco_decode_u_32(arr[3]), + members: dco_decode_list_page_brief(arr[4]), + subHubs: dco_decode_list_String(arr[5]), + ); + } + + @protected + HubPreviewDto dco_decode_hub_preview_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return HubPreviewDto( + suggestedTitle: dco_decode_String(arr[0]), + suggestedDescription: dco_decode_String(arr[1]), + members: dco_decode_list_page_brief(arr[2]), + proseBlocks: dco_decode_u_32(arr[3]), + blocks: dco_decode_u_32(arr[4]), + suggestedNoteTitle: dco_decode_String(arr[5]), + ); + } + + @protected + HubsDto dco_decode_hubs_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) + throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + return HubsDto( + hubs: dco_decode_list_hub_dto(arr[0]), + roots: dco_decode_list_String(arr[1]), ); } @@ -2104,6 +3130,21 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } + @protected + LegacyCandidate dco_decode_legacy_candidate(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 5) + throw Exception('unexpected arr length: expect 5 but see ${arr.length}'); + return LegacyCandidate( + id: dco_decode_String(arr[0]), + title: dco_decode_String(arr[1]), + reason: dco_decode_String(arr[2]), + blocks: dco_decode_u_32(arr[3]), + preselected: dco_decode_bool(arr[4]), + ); + } + @protected List dco_decode_list_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2140,6 +3181,24 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_graph_node).toList(); } + @protected + List dco_decode_list_hub_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_hub_dto).toList(); + } + + @protected + List dco_decode_list_legacy_candidate(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_legacy_candidate).toList(); + } + + @protected + List dco_decode_list_namespace_entry(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_namespace_entry).toList(); + } + @protected List dco_decode_list_page_brief(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2200,6 +3259,12 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_related_dto).toList(); } + @protected + List dco_decode_list_tag_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + return (raw as List).map(dco_decode_tag_dto).toList(); + } + @protected List dco_decode_list_timeline_day_dto(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2212,6 +3277,18 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return (raw as List).map(dco_decode_title_hit).toList(); } + @protected + NamespaceEntry dco_decode_namespace_entry(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 2) + throw Exception('unexpected arr length: expect 2 but see ${arr.length}'); + return NamespaceEntry( + title: dco_decode_String(arr[0]), + id: dco_decode_opt_String(arr[1]), + ); + } + @protected String? dco_decode_opt_String(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2246,12 +3323,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { PageBrief dco_decode_page_brief(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 3) - throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + if (arr.length != 4) + throw Exception('unexpected arr length: expect 4 but see ${arr.length}'); return PageBrief( id: dco_decode_String(arr[0]), title: dco_decode_String(arr[1]), isJournal: dco_decode_bool(arr[2]), + isHub: dco_decode_bool(arr[3]), ); } @@ -2274,8 +3352,8 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { PageDto dco_decode_page_dto(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs final arr = raw as List; - if (arr.length != 6) - throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + if (arr.length != 11) + throw Exception('unexpected arr length: expect 11 but see ${arr.length}'); return PageDto( id: dco_decode_String(arr[0]), title: dco_decode_String(arr[1]), @@ -2283,6 +3361,27 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { originJournal: dco_decode_opt_String(arr[3]), createdAt: dco_decode_i_64(arr[4]), updatedAt: dco_decode_i_64(arr[5]), + isHub: dco_decode_bool(arr[6]), + description: dco_decode_String(arr[7]), + tags: dco_decode_list_String(arr[8]), + isTag: dco_decode_bool(arr[9]), + types: dco_decode_list_String(arr[10]), + ); + } + + @protected + PageStructure dco_decode_page_structure(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 6) + throw Exception('unexpected arr length: expect 6 but see ${arr.length}'); + return PageStructure( + isHub: dco_decode_bool(arr[0]), + description: dco_decode_String(arr[1]), + members: dco_decode_list_page_brief(arr[2]), + inHubs: dco_decode_list_page_brief(arr[3]), + nsPath: dco_decode_list_namespace_entry(arr[4]), + nsChildren: dco_decode_list_namespace_entry(arr[5]), ); } @@ -2326,6 +3425,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { ); } + @protected + TagDto dco_decode_tag_dto(dynamic raw) { + // Codec=Dco (DartCObject based), see doc to use other codecs + final arr = raw as List; + if (arr.length != 3) + throw Exception('unexpected arr length: expect 3 but see ${arr.length}'); + return TagDto( + name: dco_decode_String(arr[0]), + count: dco_decode_u_32(arr[1]), + suggested: dco_decode_bool(arr[2]), + ); + } + @protected TimelineDayDto dco_decode_timeline_day_dto(dynamic raw) { // Codec=Dco (DartCObject based), see doc to use other codecs @@ -2631,6 +3743,9 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_backlinks = sse_decode_u_32(deserializer); var var_cluster = sse_decode_u_32(deserializer); var var_primaryTag = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_isHub = sse_decode_bool(deserializer); + var var_homeHub = sse_decode_opt_box_autoadd_u_32(deserializer); + var var_tags = sse_decode_list_String(deserializer); return GraphNode( id: var_id, title: var_title, @@ -2641,9 +3756,58 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { backlinks: var_backlinks, cluster: var_cluster, primaryTag: var_primaryTag, + isHub: var_isHub, + homeHub: var_homeHub, + tags: var_tags, ); } + @protected + HubDto sse_decode_hub_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_title = sse_decode_String(deserializer); + var var_description = sse_decode_String(deserializer); + var var_depth = sse_decode_u_32(deserializer); + var var_members = sse_decode_list_page_brief(deserializer); + var var_subHubs = sse_decode_list_String(deserializer); + return HubDto( + id: var_id, + title: var_title, + description: var_description, + depth: var_depth, + members: var_members, + subHubs: var_subHubs, + ); + } + + @protected + HubPreviewDto sse_decode_hub_preview_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_suggestedTitle = sse_decode_String(deserializer); + var var_suggestedDescription = sse_decode_String(deserializer); + var var_members = sse_decode_list_page_brief(deserializer); + var var_proseBlocks = sse_decode_u_32(deserializer); + var var_blocks = sse_decode_u_32(deserializer); + var var_suggestedNoteTitle = sse_decode_String(deserializer); + return HubPreviewDto( + suggestedTitle: var_suggestedTitle, + suggestedDescription: var_suggestedDescription, + members: var_members, + proseBlocks: var_proseBlocks, + blocks: var_blocks, + suggestedNoteTitle: var_suggestedNoteTitle, + ); + } + + @protected + HubsDto sse_decode_hubs_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_hubs = sse_decode_list_hub_dto(deserializer); + var var_roots = sse_decode_list_String(deserializer); + return HubsDto(hubs: var_hubs, roots: var_roots); + } + @protected int sse_decode_i_32(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2664,6 +3828,23 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return LayoutFrame(positions: var_positions, alpha: var_alpha); } + @protected + LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_id = sse_decode_String(deserializer); + var var_title = sse_decode_String(deserializer); + var var_reason = sse_decode_String(deserializer); + var var_blocks = sse_decode_u_32(deserializer); + var var_preselected = sse_decode_bool(deserializer); + return LegacyCandidate( + id: var_id, + title: var_title, + reason: var_reason, + blocks: var_blocks, + preselected: var_preselected, + ); + } + @protected List sse_decode_list_String(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2738,6 +3919,46 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } + @protected + List sse_decode_list_hub_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_hub_dto(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_legacy_candidate( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_legacy_candidate(deserializer)); + } + return ans_; + } + + @protected + List sse_decode_list_namespace_entry( + SseDeserializer deserializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_namespace_entry(deserializer)); + } + return ans_; + } + @protected List sse_decode_list_page_brief(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2828,6 +4049,18 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } + @protected + List sse_decode_list_tag_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + + var len_ = sse_decode_i_32(deserializer); + var ans_ = []; + for (var idx_ = 0; idx_ < len_; ++idx_) { + ans_.add(sse_decode_tag_dto(deserializer)); + } + return ans_; + } + @protected List sse_decode_list_timeline_day_dto( SseDeserializer deserializer, @@ -2854,6 +4087,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return ans_; } + @protected + NamespaceEntry sse_decode_namespace_entry(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_title = sse_decode_String(deserializer); + var var_id = sse_decode_opt_String(deserializer); + return NamespaceEntry(title: var_title, id: var_id); + } + @protected String? sse_decode_opt_String(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -2919,7 +4160,13 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_id = sse_decode_String(deserializer); var var_title = sse_decode_String(deserializer); var var_isJournal = sse_decode_bool(deserializer); - return PageBrief(id: var_id, title: var_title, isJournal: var_isJournal); + var var_isHub = sse_decode_bool(deserializer); + return PageBrief( + id: var_id, + title: var_title, + isJournal: var_isJournal, + isHub: var_isHub, + ); } @protected @@ -2948,6 +4195,11 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { var var_originJournal = sse_decode_opt_String(deserializer); var var_createdAt = sse_decode_i_64(deserializer); var var_updatedAt = sse_decode_i_64(deserializer); + var var_isHub = sse_decode_bool(deserializer); + var var_description = sse_decode_String(deserializer); + var var_tags = sse_decode_list_String(deserializer); + var var_isTag = sse_decode_bool(deserializer); + var var_types = sse_decode_list_String(deserializer); return PageDto( id: var_id, title: var_title, @@ -2955,6 +4207,30 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { originJournal: var_originJournal, createdAt: var_createdAt, updatedAt: var_updatedAt, + isHub: var_isHub, + description: var_description, + tags: var_tags, + isTag: var_isTag, + types: var_types, + ); + } + + @protected + PageStructure sse_decode_page_structure(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_isHub = sse_decode_bool(deserializer); + var var_description = sse_decode_String(deserializer); + var var_members = sse_decode_list_page_brief(deserializer); + var var_inHubs = sse_decode_list_page_brief(deserializer); + var var_nsPath = sse_decode_list_namespace_entry(deserializer); + var var_nsChildren = sse_decode_list_namespace_entry(deserializer); + return PageStructure( + isHub: var_isHub, + description: var_description, + members: var_members, + inHubs: var_inHubs, + nsPath: var_nsPath, + nsChildren: var_nsChildren, ); } @@ -2991,6 +4267,15 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { return RelatedDto(page: var_page, score: var_score); } + @protected + TagDto sse_decode_tag_dto(SseDeserializer deserializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + var var_name = sse_decode_String(deserializer); + var var_count = sse_decode_u_32(deserializer); + var var_suggested = sse_decode_bool(deserializer); + return TagDto(name: var_name, count: var_count, suggested: var_suggested); + } + @protected TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3263,6 +4548,41 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_u_32(self.backlinks, serializer); sse_encode_u_32(self.cluster, serializer); sse_encode_opt_box_autoadd_u_32(self.primaryTag, serializer); + sse_encode_bool(self.isHub, serializer); + sse_encode_opt_box_autoadd_u_32(self.homeHub, serializer); + sse_encode_list_String(self.tags, serializer); + } + + @protected + void sse_encode_hub_dto(HubDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.title, serializer); + sse_encode_String(self.description, serializer); + sse_encode_u_32(self.depth, serializer); + sse_encode_list_page_brief(self.members, serializer); + sse_encode_list_String(self.subHubs, serializer); + } + + @protected + void sse_encode_hub_preview_dto( + HubPreviewDto self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.suggestedTitle, serializer); + sse_encode_String(self.suggestedDescription, serializer); + sse_encode_list_page_brief(self.members, serializer); + sse_encode_u_32(self.proseBlocks, serializer); + sse_encode_u_32(self.blocks, serializer); + sse_encode_String(self.suggestedNoteTitle, serializer); + } + + @protected + void sse_encode_hubs_dto(HubsDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_list_hub_dto(self.hubs, serializer); + sse_encode_list_String(self.roots, serializer); } @protected @@ -3284,6 +4604,19 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_f_32(self.alpha, serializer); } + @protected + void sse_encode_legacy_candidate( + LegacyCandidate self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.id, serializer); + sse_encode_String(self.title, serializer); + sse_encode_String(self.reason, serializer); + sse_encode_u_32(self.blocks, serializer); + sse_encode_bool(self.preselected, serializer); + } + @protected void sse_encode_list_String(List self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3350,6 +4683,39 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + void sse_encode_list_hub_dto(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_hub_dto(item, serializer); + } + } + + @protected + void sse_encode_list_legacy_candidate( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_legacy_candidate(item, serializer); + } + } + + @protected + void sse_encode_list_namespace_entry( + List self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_namespace_entry(item, serializer); + } + } + @protected void sse_encode_list_page_brief( List self, @@ -3461,6 +4827,15 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + void sse_encode_list_tag_dto(List self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_i_32(self.length, serializer); + for (final item in self) { + sse_encode_tag_dto(item, serializer); + } + } + @protected void sse_encode_list_timeline_day_dto( List self, @@ -3485,6 +4860,16 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { } } + @protected + void sse_encode_namespace_entry( + NamespaceEntry self, + SseSerializer serializer, + ) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.title, serializer); + sse_encode_opt_String(self.id, serializer); + } + @protected void sse_encode_opt_String(String? self, SseSerializer serializer) { // Codec=Sse (Serialization based), see doc to use other codecs @@ -3550,6 +4935,7 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_String(self.id, serializer); sse_encode_String(self.title, serializer); sse_encode_bool(self.isJournal, serializer); + sse_encode_bool(self.isHub, serializer); } @protected @@ -3571,6 +4957,22 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_opt_String(self.originJournal, serializer); sse_encode_i_64(self.createdAt, serializer); sse_encode_i_64(self.updatedAt, serializer); + sse_encode_bool(self.isHub, serializer); + sse_encode_String(self.description, serializer); + sse_encode_list_String(self.tags, serializer); + sse_encode_bool(self.isTag, serializer); + sse_encode_list_String(self.types, serializer); + } + + @protected + void sse_encode_page_structure(PageStructure self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_bool(self.isHub, serializer); + sse_encode_String(self.description, serializer); + sse_encode_list_page_brief(self.members, serializer); + sse_encode_list_page_brief(self.inHubs, serializer); + sse_encode_list_namespace_entry(self.nsPath, serializer); + sse_encode_list_namespace_entry(self.nsChildren, serializer); } @protected @@ -3603,6 +5005,14 @@ class RustLibApiImpl extends RustLibApiImplPlatform implements RustLibApi { sse_encode_f_32(self.score, serializer); } + @protected + void sse_encode_tag_dto(TagDto self, SseSerializer serializer) { + // Codec=Sse (Serialization based), see doc to use other codecs + sse_encode_String(self.name, serializer); + sse_encode_u_32(self.count, serializer); + sse_encode_bool(self.suggested, serializer); + } + @protected void sse_encode_timeline_day_dto( TimelineDayDto self, @@ -3730,6 +5140,29 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { alias: alias, ); + Future addPageTag({required String pageId, required String tag}) => + RustLib.instance.api.crateApiGraphSynapseGraphAddPageTag( + that: this, + pageId: pageId, + tag: tag, + ); + + Future addPageType({required String pageId, required String ty}) => + RustLib.instance.api.crateApiGraphSynapseGraphAddPageType( + that: this, + pageId: pageId, + ty: 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 addToHub({required String pageId, required String hubId}) => + RustLib.instance.api.crateApiGraphSynapseGraphAddToHub( + that: this, + pageId: pageId, + hubId: hubId, + ); + Future> aliases({required String pageId}) => RustLib.instance.api .crateApiGraphSynapseGraphAliases(that: this, pageId: pageId); @@ -3747,6 +5180,50 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { Future blockRef({required String id}) => RustLib.instance.api .crateApiGraphSynapseGraphBlockRef(that: this, id: 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 convertToHub({ + required String pageId, + required String title, + required String description, + required List memberIds, + String? keepOutlineAs, + }) => RustLib.instance.api.crateApiGraphSynapseGraphConvertToHub( + that: this, + pageId: pageId, + title: title, + description: description, + memberIds: memberIds, + keepOutlineAs: keepOutlineAs, + ); + + /// Turns a hub back into a note: description, then one `[[Member]]` block per member. + Future convertToNote({required String pageId}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphConvertToNote(that: this, pageId: pageId); + + /// Creates an empty hub. Fails when the title is taken. + Future createHub({ + required String title, + required String description, + }) => RustLib.instance.api.crateApiGraphSynapseGraphCreateHub( + that: this, + title: title, + description: description, + ); + + /// Creates a note in the hub, starting from a copy of the hub's template. + Future createPageFromTemplate({ + required String hubId, + required String title, + }) => RustLib.instance.api.crateApiGraphSynapseGraphCreatePageFromTemplate( + that: this, + hubId: hubId, + title: title, + ); + /// Deletes a block and its subtree. Future> deleteBlock({required String id}) => RustLib .instance @@ -3764,6 +5241,22 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { Future graphData() => RustLib.instance.api.crateApiGraphSynapseGraphGraphData(that: this); + /// Defaults for converting a note into a hub. + Future hubConversionPreview({required String pageId}) => + RustLib.instance.api.crateApiGraphSynapseGraphHubConversionPreview( + that: this, + pageId: 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 hubTemplate({required String hubId}) => RustLib.instance.api + .crateApiGraphSynapseGraphHubTemplate(that: this, hubId: hubId); + + /// Every hub with its members, and the root hubs. + Future hubs() => + RustLib.instance.api.crateApiGraphSynapseGraphHubs(that: this); + /// Tab: the block becomes the last child of its previous sibling (no-op for a first child). Future> indentBlock({required String id}) => RustLib .instance @@ -3799,6 +5292,13 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { limit: 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> legacyCandidates() => RustLib.instance.api + .crateApiGraphSynapseGraphLegacyCandidates(that: this); + /// Pages ordered by last update, most recent first. Future> listPages({ required bool includeJournals, @@ -3860,6 +5360,22 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { Future pageByTitle({required String title}) => RustLib.instance.api .crateApiGraphSynapseGraphPageByTitle(that: this, title: title); + /// Hub and namespace context of a page. + Future pageStructure({required String pageId}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphPageStructure(that: this, pageId: pageId); + + /// Pages carrying a tag, most recently updated first. + Future> pagesWithTag({required String tag}) => RustLib + .instance + .api + .crateApiGraphSynapseGraphPagesWithTag(that: this, tag: tag); + + /// Deletes pages and their blocks in one transaction. Returns how many existed. + Future purgePages({required List ids}) => RustLib.instance.api + .crateApiGraphSynapseGraphPurgePages(that: this, ids: ids); + /// Stores in-memory bytes (clipboard, Android content URIs). Future putAssetBytes({ required List bytes, @@ -3899,6 +5415,32 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { Future removeAlias({required String alias}) => RustLib.instance.api .crateApiGraphSynapseGraphRemoveAlias(that: this, alias: alias); + /// Takes a page out of a hub (no-op when it is not in it). + Future removeFromHub({required String pageId, required String hubId}) => + RustLib.instance.api.crateApiGraphSynapseGraphRemoveFromHub( + that: this, + pageId: pageId, + hubId: hubId, + ); + + Future removePageTag({ + required String pageId, + required String tag, + }) => RustLib.instance.api.crateApiGraphSynapseGraphRemovePageTag( + that: this, + pageId: pageId, + tag: tag, + ); + + Future removePageType({ + required String pageId, + required String ty, + }) => RustLib.instance.api.crateApiGraphSynapseGraphRemovePageType( + that: this, + pageId: pageId, + ty: ty, + ); + Future renamePage({required String id, required String newTitle}) => RustLib.instance.api.crateApiGraphSynapseGraphRenamePage( that: this, @@ -3934,6 +5476,40 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { collapsed: collapsed, ); + Future setHubDescription({ + required String hubId, + required String description, + }) => RustLib.instance.api.crateApiGraphSynapseGraphSetHubDescription( + that: this, + hubId: hubId, + description: 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 setPageTags({ + required String pageId, + required List tags, + }) => RustLib.instance.api.crateApiGraphSynapseGraphSetPageTags( + that: this, + pageId: pageId, + tags: tags, + ); + + /// Replaces the types of a page. Journals and templates cannot be typed. + Future setPageTypes({ + required String pageId, + required List types, + }) => RustLib.instance.api.crateApiGraphSynapseGraphSetPageTypes( + that: this, + pageId: pageId, + types: types, + ); + + /// Every tag page with its number of pages, most used first. + Future> tagCatalog() => + RustLib.instance.api.crateApiGraphSynapseGraphTagCatalog(that: this); + /// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions. Future timeline({required String from, required String to}) => RustLib.instance.api.crateApiGraphSynapseGraphTimeline( @@ -3946,6 +5522,10 @@ class SynapseGraphImpl extends RustOpaque implements SynapseGraph { String today() => RustLib.instance.api.crateApiGraphSynapseGraphToday(that: this); + /// Types in use (most used first) followed by the seeded suggestions not used yet. + Future> typeCatalog() => + RustLib.instance.api.crateApiGraphSynapseGraphTypeCatalog(that: this); + /// Replaces a block's Markdown (the debounced save while typing). Future updateBlock({required String id, required String content}) => RustLib.instance.api.crateApiGraphSynapseGraphUpdateBlock( diff --git a/app/lib/src/rust/frb_generated.io.dart b/app/lib/src/rust/frb_generated.io.dart index 0d2c2aa..a75d160 100644 --- a/app/lib/src/rust/frb_generated.io.dart +++ b/app/lib/src/rust/frb_generated.io.dart @@ -115,6 +115,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @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 { @protected LayoutFrame dco_decode_layout_frame(dynamic raw); + @protected + LegacyCandidate dco_decode_legacy_candidate(dynamic raw); + @protected List dco_decode_list_String(dynamic raw); @@ -142,6 +154,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_graph_node(dynamic raw); + @protected + List dco_decode_list_hub_dto(dynamic raw); + + @protected + List dco_decode_list_legacy_candidate(dynamic raw); + + @protected + List dco_decode_list_namespace_entry(dynamic raw); + @protected List dco_decode_list_page_brief(dynamic raw); @@ -172,12 +193,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_related_dto(dynamic raw); + @protected + List dco_decode_list_tag_dto(dynamic raw); + @protected List dco_decode_list_timeline_day_dto(dynamic raw); @protected List 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 { @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 { @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 { @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 { @protected LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer); + @protected + LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer); + @protected List sse_decode_list_String(SseDeserializer deserializer); @@ -353,6 +398,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List sse_decode_list_graph_node(SseDeserializer deserializer); + @protected + List sse_decode_list_hub_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_legacy_candidate( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_namespace_entry( + SseDeserializer deserializer, + ); + @protected List sse_decode_list_page_brief(SseDeserializer deserializer); @@ -383,6 +441,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List sse_decode_list_related_dto(SseDeserializer deserializer); + @protected + List sse_decode_list_tag_dto(SseDeserializer deserializer); + @protected List sse_decode_list_timeline_day_dto( SseDeserializer deserializer, @@ -391,6 +452,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List 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 { @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 { @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 { @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 { @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 self, SseSerializer serializer); @@ -589,6 +674,21 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); + @protected + void sse_encode_list_hub_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_legacy_candidate( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_namespace_entry( + List self, + SseSerializer serializer, + ); + @protected void sse_encode_list_page_brief( List self, @@ -640,6 +740,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); + @protected + void sse_encode_list_tag_dto(List self, SseSerializer serializer); + @protected void sse_encode_list_timeline_day_dto( List self, @@ -649,6 +752,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_list_title_hit(List 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 { @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 { @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, diff --git a/app/lib/src/rust/frb_generated.web.dart b/app/lib/src/rust/frb_generated.web.dart index 941cdee..7fcbfef 100644 --- a/app/lib/src/rust/frb_generated.web.dart +++ b/app/lib/src/rust/frb_generated.web.dart @@ -117,6 +117,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @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 { @protected LayoutFrame dco_decode_layout_frame(dynamic raw); + @protected + LegacyCandidate dco_decode_legacy_candidate(dynamic raw); + @protected List dco_decode_list_String(dynamic raw); @@ -144,6 +156,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_graph_node(dynamic raw); + @protected + List dco_decode_list_hub_dto(dynamic raw); + + @protected + List dco_decode_list_legacy_candidate(dynamic raw); + + @protected + List dco_decode_list_namespace_entry(dynamic raw); + @protected List dco_decode_list_page_brief(dynamic raw); @@ -174,12 +195,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List dco_decode_list_related_dto(dynamic raw); + @protected + List dco_decode_list_tag_dto(dynamic raw); + @protected List dco_decode_list_timeline_day_dto(dynamic raw); @protected List 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 { @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 { @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 { @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 { @protected LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer); + @protected + LegacyCandidate sse_decode_legacy_candidate(SseDeserializer deserializer); + @protected List sse_decode_list_String(SseDeserializer deserializer); @@ -355,6 +400,19 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List sse_decode_list_graph_node(SseDeserializer deserializer); + @protected + List sse_decode_list_hub_dto(SseDeserializer deserializer); + + @protected + List sse_decode_list_legacy_candidate( + SseDeserializer deserializer, + ); + + @protected + List sse_decode_list_namespace_entry( + SseDeserializer deserializer, + ); + @protected List sse_decode_list_page_brief(SseDeserializer deserializer); @@ -385,6 +443,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List sse_decode_list_related_dto(SseDeserializer deserializer); + @protected + List sse_decode_list_tag_dto(SseDeserializer deserializer); + @protected List sse_decode_list_timeline_day_dto( SseDeserializer deserializer, @@ -393,6 +454,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected List 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 { @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 { @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 { @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 { @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 self, SseSerializer serializer); @@ -591,6 +676,21 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); + @protected + void sse_encode_list_hub_dto(List self, SseSerializer serializer); + + @protected + void sse_encode_list_legacy_candidate( + List self, + SseSerializer serializer, + ); + + @protected + void sse_encode_list_namespace_entry( + List self, + SseSerializer serializer, + ); + @protected void sse_encode_list_page_brief( List self, @@ -642,6 +742,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { SseSerializer serializer, ); + @protected + void sse_encode_list_tag_dto(List self, SseSerializer serializer); + @protected void sse_encode_list_timeline_day_dto( List self, @@ -651,6 +754,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl { @protected void sse_encode_list_title_hit(List 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 { @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 { @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, diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index f4b3383..d877e03 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -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; diff --git a/crates/synapse-core/src/model.rs b/crates/synapse-core/src/model.rs index d5792b1..f37af4e 100644 --- a/crates/synapse-core/src/model.rs +++ b/crates/synapse-core/src/model.rs @@ -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, + /// 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, + /// What kind of thing this is ("persona", "lugar"...): plain names, not pages; see `types`. + #[serde(default)] + pub types: Vec, } 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)] diff --git a/crates/synapse-core/src/parse.rs b/crates/synapse-core/src/parse.rs index 01fd94f..adf3226 100644 --- a/crates/synapse-core/src/parse.rs +++ b/crates/synapse-core/src/parse.rs @@ -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 { +pub(crate) fn find_close(s: &str, from: usize) -> Option { let mut depth = 0; let mut i = from; while i + 1 < s.len() { diff --git a/crates/synapse-core/src/schema.rs b/crates/synapse-core/src/schema.rs index cbf1efb..e8d1ef6 100644 --- a/crates/synapse-core/src/schema.rs +++ b/crates/synapse-core/src/schema.rs @@ -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::>()? + }; + 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 = 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::>()? + }; + 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 = 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 = 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()], diff --git a/crates/synapse-core/src/store.rs b/crates/synapse-core/src/store.rs index 7c3f749..645664d 100644 --- a/crates/synapse-core/src/store.rs +++ b/crates/synapse-core/src/store.rs @@ -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(&self, sql: &str, params: P) -> rusqlite::Result { + pub(crate) fn exec( + &self, + sql: &str, + params: P, + ) -> rusqlite::Result { self.conn.prepare_cached(sql)?.execute(params) } /// `query_row` through the statement cache. - fn row( + pub(crate) fn row( &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> { + pub(crate) fn tx(&self) -> Result> { if self.conn.is_autocommit() { return self.savepoint(); } @@ -214,7 +219,16 @@ impl Graph { Ok(page) } - fn create_page_tx(&self, new: NewPage) -> Result { + pub(crate) fn create_page_tx(&self, new: NewPage) -> Result { + 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 { 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> { + // 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::>()? }; - 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 = { 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 { + 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 { + 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 = 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> { 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 { 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(), }) } diff --git a/crates/synapse-core/src/structure.rs b/crates/synapse-core/src/structure.rs new file mode 100644 index 0000000..8e59c58 --- /dev/null +++ b/crates/synapse-core/src/structure.rs @@ -0,0 +1,1017 @@ +//! Organisation of pages: namespaces (title kinship, `A/B` is a child of `A`) and hubs. +//! +//! A hub is a page *kind* ([`PageKind::Hub`]): a container of pages (notes and other hubs) +//! with a short description and no blocks. Membership lives on the member side, like tags: +//! [`Page::hubs`] lists the hubs a page belongs to (synced with the page, last writer wins), and +//! the local `page_hubs` table indexes it for "members of a hub". A page belongs to at most one hub; +//! hub nesting is a DAG (cycles are refused locally and ignored on read, see +//! [`Graph::structure`]). Notes become hubs only by explicit conversion +//! ([`Graph::convert_to_hub`]). + +use crate::error::{Error, Result}; +use crate::model::{BlockId, NewPage, Page, PageId, PageKind, Placement, RefKind, title_key}; +use crate::parse::{extract_refs, find_close, property_split}; +use crate::store::{Graph, parse_id}; +use serde_json::Value; +use std::collections::{HashMap, HashSet, VecDeque}; + +/// Longest suggested hub description, in characters. +const MAX_DESCRIPTION_CHARS: usize = 280; + +#[derive(Debug, Clone, PartialEq)] +pub struct HubInfo { + pub page: PageId, + pub title: String, + pub description: String, + /// Member pages: sub-hubs first, then notes, by title key (existing, non-journal pages). + pub members: Vec, + /// Nesting level: 0 for root hubs (not a member of any hub). + pub depth: u32, +} + +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Structure { + /// Every hub, sorted by title key. + pub hubs: Vec, + /// Page → its deepest hub (a hub maps to itself). Pages in no hub are absent. + pub home: HashMap, +} + +/// What converting a note into a hub would produce (defaults for the conversion dialog). +#[derive(Debug, Clone, PartialEq)] +pub struct HubPreview { + /// Last namespace segment of the title (`A/B/C` → `C`), trimmed. + pub suggested_title: String, + /// First prose block as plain text (refs rendered as titles), at most 280 characters. + pub suggested_description: String, + /// Candidate members in order: pages linked or tagged from the outline (outline order), + /// then pages whose page properties reference this page, then pages with blocks tagging + /// it or referencing it in a block property. Existing non-journal pages, no duplicates. + pub members: Vec, + /// Blocks with text beyond links, headings and properties. + pub prose_blocks: u32, + pub blocks: u32, +} + +/// Parameters of [`Graph::convert_to_hub`]. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct HubConversion { + /// New title (the page is renamed, links rewritten, when it differs). + pub title: String, + pub description: String, + pub members: Vec, + /// Title of a new note that receives the whole original outline (moved, structure kept) + /// and becomes a member of the hub. `None` deletes the blocks. + pub keep_outline_as: Option, +} + +/// Parent namespace of a title: everything before the last `/`. Titles with leading, trailing +/// or empty segments have none. +pub fn namespace_parent(title: &str) -> Option<&str> { + let title = title.trim(); + let (parent, _) = title.rsplit_once('/')?; + title + .split('/') + .all(|s| !s.trim().is_empty()) + .then(|| parent.trim_end()) +} + +/// Logseq's organisational built-in pages (and PDF highlight pages), useless in Synapse. +pub fn is_legacy_page(title: &str) -> bool { + const BUILTIN: [&str; 15] = [ + "contents", + "journals", + "favorites", + "card", + "all pages", + "now", + "later", + "todo", + "doing", + "done", + "canceled", + "cancelled", + "in-progress", + "wait", + "waiting", + ]; + let key = title_key(title); + key.starts_with("hls__") || BUILTIN.contains(&key.as_str()) +} + +/// Strings found anywhere inside a property value. +fn value_strings<'a>(v: &'a Value, out: &mut Vec<&'a str>) { + match v { + Value::String(s) => out.push(s), + Value::Array(a) => a.iter().for_each(|x| value_strings(x, out)), + _ => {} + } +} + +/// Block text without its `key:: value` lines. +fn content_lines(content: &str) -> String { + content + .lines() + .filter(|l| property_split(l).is_none()) + .collect::>() + .join("\n") +} + +fn heading_level(text: &str) -> usize { + let hashes = text.chars().take_while(|&c| c == '#').count(); + if (1..=6).contains(&hashes) && text[hashes..].starts_with(char::is_whitespace) { + hashes + } else { + 0 + } +} + +fn is_pure_heading(text: &str) -> bool { + heading_level(text) > 0 && !text.contains('\n') +} + +/// Number of words left in `text` once refs and separators are removed. +fn remaining_words(text: &str) -> usize { + let mut plain = String::with_capacity(text.len()); + let mut i = 0; + while i < text.len() { + let rest = &text[i..]; + let (skip, close) = if rest.starts_with("#[[") { + (3, Some("]]")) + } else if rest.starts_with("[[") { + (2, Some("]]")) + } else if rest.starts_with("((") { + (2, Some("))")) + } else { + (0, None) + }; + if let Some(close) = close { + let end = if close == "]]" { + find_close(text, i + skip) + } else { + text[i + skip..].find("))").map(|j| i + skip + j) + }; + if let Some(end) = end { + plain.push(' '); + i = end + 2; + continue; + } + } + let c = rest.chars().next().unwrap_or(' '); + let tag_start = c == '#' + && !rest[1..].starts_with(['#', '[', ' ']) + && (i == 0 || text[..i].ends_with(char::is_whitespace)); + if tag_start { + let body = &rest[1..]; + let len = body + .find(|c: char| c.is_whitespace() || ",.;:!?()[]{}\"'".contains(c)) + .unwrap_or(body.len()); + plain.push(' '); + i += 1 + len; + continue; + } + plain.push(if ",;:-–—·|*>".contains(c) { + ' ' + } else { + c + }); + i += c.len_utf8(); + } + plain + .split_whitespace() + .filter(|w| w.chars().any(char::is_alphanumeric)) + .count() +} + +/// A block with real text: not empty, not a bare heading, with words besides its refs. +fn is_prose(text: &str) -> bool { + !text.is_empty() + && !(is_pure_heading(text) && extract_refs(text).pages.is_empty()) + && remaining_words(&text[heading_level(text)..]) > 0 +} + +/// Plain text of a block: refs rendered as their titles, Markdown and Logseq markup removed, +/// whitespace collapsed. +fn plain_text(text: &str) -> String { + const MARKERS: [&str; 11] = [ + "TODO ", + "DOING ", + "DONE ", + "LATER ", + "NOW ", + "WAITING ", + "WAIT ", + "CANCELED ", + "CANCELLED ", + "IN-PROGRESS ", + "[#", + ]; + let mut out = String::with_capacity(text.len()); + for line in text.lines() { + let mut line = line.trim(); + line = line[heading_level(line)..].trim_start(); + for m in MARKERS { + if let Some(rest) = line.strip_prefix(m) { + line = if m == "[#" { + rest.split_once(']').map_or(rest, |(_, r)| r).trim_start() + } else { + rest.trim_start() + }; + } + } + out.push(' '); + let mut i = 0; + while i < line.len() { + let rest = &line[i..]; + if let Some(after) = rest.strip_prefix("![") + && let Some(end) = after.find("](") + && let Some(close) = after[end..].find(')') + { + i += 2 + end + close + 1; + continue; + } + if rest.starts_with("#[[") || rest.starts_with("[[") { + let skip = if rest.starts_with('#') { 3 } else { 2 }; + if let Some(end) = find_close(line, i + skip) { + out.push_str(&line[i + skip..end]); + i = end + 2; + continue; + } + } + if let Some(after) = rest.strip_prefix('[') + && let Some(end) = after.find("](") + && let Some(close) = after[end..].find(')') + { + out.push_str(&after[..end]); + i += 1 + end + close + 1; + continue; + } + if let Some(after) = rest.strip_prefix("((") + && let Some(end) = after.find("))") + { + i += 2 + end + 2; + continue; + } + if let Some(after) = rest.strip_prefix("{{") + && let Some(end) = after.find("}}") + { + i += 2 + end + 2; + continue; + } + if rest.starts_with('#') + && !rest[1..].starts_with(['#', ' ']) + && (i == 0 || line[..i].ends_with(char::is_whitespace)) + { + i += 1; // `#tag` → `tag` + continue; + } + if let Some(m) = ["**", "__", "~~", "==", "^^"] + .iter() + .find(|m| rest.starts_with(**m)) + { + i += m.len(); + continue; + } + let c = rest.chars().next().unwrap_or(' '); + if c != '`' && c != '*' { + out.push(c); + } + i += c.len_utf8(); + } + } + out.split_whitespace().collect::>().join(" ") +} + +/// Cuts `text` to at most `max` characters at a word boundary, marking the cut with `…`. +fn shorten(text: &str, max: usize) -> String { + if text.chars().count() <= max { + return text.to_string(); + } + let head: String = text.chars().take(max - 1).collect(); + let whole_word = text[head.len()..].starts_with(char::is_whitespace); + let cut = match head.rfind(char::is_whitespace) { + Some(i) if i > 0 && !whole_word => &head[..i], + _ => head.as_str(), + }; + format!( + "{}…", + cut.trim_end_matches(|c: char| c.is_whitespace() || ",;:".contains(c)) + ) +} + +struct PageRow { + title: String, + key: String, + journal: bool, + kind: PageKind, + description: String, + hubs: Vec, + hlc: String, +} + +impl Graph { + // ------------------------------------------------------------- hubs + + /// Creates an empty hub. + pub fn create_hub(&self, title: &str, description: &str) -> Result { + let tx = self.tx()?; + let page = self.create_page_kind_tx( + NewPage::titled(title), + PageKind::Hub, + description.trim().to_string(), + )?; + self.ensure_hub_template(&page)?; + tx.commit()?; + Ok(page) + } + + /// The template of `hub`: the page whose outline new notes of the hub start from. Every hub + /// has exactly one (possibly empty); hubs created before templates existed, or whose + /// template was lost to a concurrent edit, get a new one here. + pub fn hub_template(&self, hub: PageId) -> Result { + let tx = self.tx()?; + let page = self.hub_page(hub)?; + let id = self.ensure_hub_template(&page)?; + tx.commit()?; + Ok(id) + } + + /// Creates a note in `hub` titled `title`, with a copy of the hub's template outline. + pub fn create_page_from_template(&self, hub: PageId, title: &str) -> Result { + self.transaction(|g| { + let hub_page = g.hub_page(hub)?; + let template = g.ensure_hub_template(&hub_page)?; + let page = g.create_page_tx(NewPage::titled(title))?; + let mut copies: HashMap = HashMap::new(); + for (_, b) in g.page_tree(template)? { + let at = Placement::LastChildOf(b.parent_id.and_then(|p| copies.get(&p).copied())); + let copy = g.insert_block(page.id, at, &b.content)?; + if !b.properties.is_empty() { + g.set_block_properties(copy.id, b.properties.clone())?; + } + if b.collapsed { + g.set_collapsed(copy.id, true)?; + } + copies.insert(b.id, copy.id); + } + g.add_to_hub(page.id, hub)?; + g.get_page(page.id)? + .ok_or_else(|| Error::NotFound(page.id.to_string())) + }) + } + + /// Ids of the template pages that belong to `hub` (one, unless replicas raced). + pub(crate) fn hub_template_ids(&self, hub: PageId) -> Result> { + let mut st = self.conn().prepare_cached( + "SELECT p.id FROM page_hubs ph JOIN pages p ON p.id = ph.page_id + WHERE ph.hub_id=?1 AND p.kind='template' ORDER BY p.created_at, p.id", + )?; + let rows = st.query_map([hub.to_string()], |r| r.get::<_, String>(0))?; + rows.map(|r| parse_id(&r?)).collect() + } + + /// Returns the template of `hub`, creating an empty one when there is none. When several + /// exist the oldest wins. + fn ensure_hub_template(&self, hub: &Page) -> Result { + if let Some(&t) = self.hub_template_ids(hub.id)?.first() { + return Ok(t); + } + let base = format!("Template: {}", hub.title); + let mut title = base.clone(); + let mut n = 2; + while self.page_by_title(&title)?.is_some() { + title = format!("{base} ({n})"); + n += 1; + } + let t = + self.create_page_kind_tx(NewPage::titled(title), PageKind::Template, String::new())?; + self.add_to_hub(t.id, hub.id)?; + Ok(t.id) + } + + pub fn set_hub_description(&self, hub: PageId, description: &str) -> Result { + let tx = self.tx()?; + let mut page = self.hub_page(hub)?; + let description = description.trim(); + if page.description != description { + page.description = description.to_string(); + page.updated_at = self.now_ms(); + self.write_page(&page, &self.tick())?; + } + tx.commit()?; + Ok(page) + } + + /// Members of `hub`: sub-hubs first, then notes, each by title key (existing, non-journal + /// pages whose `hubs` contain it). + pub fn hub_members(&self, hub: PageId) -> Result> { + let mut st = self.conn().prepare_cached( + "SELECT p.id FROM page_hubs ph JOIN pages p ON p.id = ph.page_id + WHERE ph.hub_id=?1 AND p.id != ?1 AND p.journal_date IS NULL AND p.kind != 'template' + ORDER BY p.kind != 'hub', p.title_key", + )?; + let rows = st.query_map([hub.to_string()], |r| r.get::<_, String>(0))?; + rows.map(|r| parse_id(&r?)).collect() + } + + /// Hubs containing `page` (its own `hubs` that still exist as hubs), by title key. + pub fn hubs_of(&self, page: PageId) -> Result> { + let mut st = self.conn().prepare_cached( + "SELECT h.id FROM page_hubs ph JOIN pages h ON h.id = ph.hub_id + WHERE ph.page_id=?1 AND h.kind='hub' AND h.id != ?1 AND h.journal_date IS NULL + ORDER BY h.title_key", + )?; + let rows = st.query_map([page.to_string()], |r| r.get::<_, String>(0))?; + rows.map(|r| parse_id(&r?)).collect() + } + + /// Sets the hub `page` belongs to (at most one; duplicates dropped). Newly added hubs must + /// be hub pages other than `page` and not nested inside it (no cycles); journals belong to + /// no hub. Ids already in the list are kept as they are, even when they dangle. + pub fn set_page_hubs(&self, page: PageId, hubs: Vec) -> Result { + let tx = self.tx()?; + let mut p = self + .get_page(page)? + .ok_or_else(|| Error::NotFound(page.to_string()))?; + let mut next: Vec = Vec::with_capacity(hubs.len()); + for h in hubs { + if !next.contains(&h) { + next.push(h); + } + } + if next == p.hubs { + tx.commit()?; + return Ok(p); + } + if next.len() > 1 { + return Err(Error::Invalid("a page can belong to only one hub".into())); + } + if p.is_template() && !p.hubs.is_empty() { + return Err(Error::Invalid("a template stays in its hub".into())); + } + if p.is_journal() && !next.is_empty() { + return Err(Error::Invalid("journals cannot be in hubs".into())); + } + let mut inside: Option> = None; + for &h in &next { + if h == page { + return Err(Error::Invalid("a hub cannot contain itself".into())); + } + if p.hubs.contains(&h) { + continue; + } + let hub = self.hub_page(h)?; + if p.is_hub() { + let nested = match &inside { + Some(set) => set, + None => inside.insert(self.nested_in(page)?), + }; + if nested.contains(&h) { + return Err(Error::Invalid(format!( + "{:?} is inside {:?}; adding it would create a cycle", + hub.title, p.title + ))); + } + } + } + p.hubs = next; + p.updated_at = self.now_ms(); + self.write_page(&p, &self.tick())?; + tx.commit()?; + Ok(p) + } + + /// Puts `page` in `hub`, taking it out of the hub it was in (no-op when already there). + pub fn add_to_hub(&self, page: PageId, hub: PageId) -> Result { + self.set_page_hubs(page, vec![hub]) + } + + /// Takes `page` out of `hub` (no-op when it is not in it). + pub fn remove_from_hub(&self, page: PageId, hub: PageId) -> Result { + let p = self + .get_page(page)? + .ok_or_else(|| Error::NotFound(page.to_string()))?; + let hubs = p.hubs.iter().copied().filter(|&h| h != hub).collect(); + self.set_page_hubs(page, hubs) + } + + /// Suggested title, description and members for converting a note into a hub. + pub fn hub_conversion_preview(&self, page: PageId) -> Result { + let p = self.note_page(page)?; + let conn = self.conn(); + let mut pages: HashMap = HashMap::new(); + { + let mut st = + conn.prepare("SELECT id, title_key, journal_date IS NOT NULL FROM pages")?; + let rows = st.query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + r.get::<_, String>(1)?, + r.get::<_, bool>(2)?, + )) + })?; + for row in rows { + let (id, key, journal) = row?; + pages.insert(parse_id(&id)?, (key, journal)); + } + } + // Titles first, so a title beats an alias with the same key; aliases may dangle. + let mut by_key: HashMap = HashMap::new(); + let mut own_keys: HashSet = HashSet::new(); + for (t, id) in self.all_titles()? { + if !pages.contains_key(&id) { + continue; + } + let key = title_key(&t); + if id == page { + own_keys.insert(key.clone()); + } + by_key.entry(key).or_insert(id); + } + + let mut members = Vec::new(); + let mut seen: HashSet = HashSet::from([page]); + let mut add = |id: PageId, members: &mut Vec| { + if pages.get(&id).is_some_and(|(_, journal)| !journal) && seen.insert(id) { + members.push(id); + } + }; + let tree = self.page_tree(page)?; + let mut prose_blocks = 0u32; + let mut description = None; + for (_, b) in &tree { + let text = content_lines(&b.content); + let text = text.trim(); + for (t, kind) in extract_refs(text).pages { + if kind != RefKind::Property + && let Some(&id) = by_key.get(&title_key(&t)) + { + add(id, &mut members); + } + } + if is_prose(text) { + prose_blocks += 1; + if description.is_none() { + let plain = plain_text(text); + if !plain.is_empty() { + description = Some(shorten(&plain, MAX_DESCRIPTION_CHARS)); + } + } + } + } + // Pages whose page properties reference this page, by title key. + { + let mut st = conn.prepare( + "SELECT id, properties FROM pages WHERE journal_date IS NULL ORDER BY title_key", + )?; + let rows = + st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + for row in rows { + let (id, props) = row?; + let props: serde_json::Map = + serde_json::from_str(&props).unwrap_or_default(); + let mut strings = Vec::new(); + props.values().for_each(|v| value_strings(v, &mut strings)); + let points = strings.iter().any(|s| { + extract_refs(s) + .pages + .iter() + .any(|(t, _)| own_keys.contains(&title_key(t))) + }); + if points { + add(parse_id(&id)?, &mut members); + } + } + } + // Pages with blocks tagging this page or pointing at it from a block property. + { + let mut st = conn.prepare( + "SELECT DISTINCT b.page_id, p.title_key, r.target_key FROM refs r + JOIN blocks b ON b.id = r.block_id JOIN pages p ON p.id = b.page_id + WHERE r.kind IN ('tag', 'property') AND p.journal_date IS NULL + ORDER BY p.title_key", + )?; + let rows = + st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(2)?)))?; + for row in rows { + let (id, target) = row?; + if own_keys.contains(&target) { + add(parse_id(&id)?, &mut members); + } + } + } + + let suggested_title = match namespace_parent(&p.title) { + Some(_) => p.title.rsplit('/').next().unwrap_or(&p.title).trim(), + None => p.title.trim(), + } + .to_string(); + Ok(HubPreview { + suggested_title, + suggested_description: description.unwrap_or_default(), + members, + prose_blocks, + blocks: tree.len() as u32, + }) + } + + /// Turns a note into a hub in one transaction: rename (links rewritten) when the title + /// differs, move the outline into a new note or delete it, set the description and add + /// the members (invalid ones, such as journals or cycles, are skipped). + pub fn convert_to_hub(&self, page: PageId, c: &HubConversion) -> Result { + self.transaction(|g| { + let mut p = g.note_page(page)?; + let title = c.title.trim(); + if title.is_empty() { + return Err(Error::Invalid("empty page title".into())); + } + if title != p.title { + p = g.rename_page(page, title)?; + } + let mut members: Vec = Vec::new(); + let roots: Vec<_> = g + .page_tree(page)? + .into_iter() + .filter(|(d, _)| *d == 0) + .map(|(_, b)| b.id) + .collect(); + if let Some(note_title) = &c.keep_outline_as { + let note = g.create_page_tx(NewPage { + title: note_title.trim().to_string(), + origin_journal: p.origin_journal, + created_at: Some(p.created_at), + ..Default::default() + })?; + for id in roots { + g.move_block(id, note.id, Placement::LastChildOf(None))?; + } + members.push(note.id); + } else { + for id in roots { + if g.get_block(id)?.is_some() { + g.delete_block(id)?; + } + } + } + // Anything page_tree could not place (should not happen) goes too. + let left: Vec = { + let mut st = g.conn().prepare("SELECT id FROM blocks WHERE page_id=?1")?; + st.query_map([page.to_string()], |r| r.get(0))? + .collect::>()? + }; + for id in left { + let id = parse_id(&id)?; + if g.get_block(id)?.is_some() { + g.delete_block(id)?; + } + } + let mut p = g + .get_page(page)? + .ok_or_else(|| Error::NotFound(page.to_string()))?; + p.kind = PageKind::Hub; + p.description = c.description.trim().to_string(); + p.updated_at = g.now_ms(); + g.write_page(&p, &g.tick())?; + g.ensure_hub_template(&p)?; + for &m in &c.members { + if !members.contains(&m) { + members.push(m); + } + } + for m in members { + match g.add_to_hub(m, page) { + Ok(_) | Err(Error::Invalid(_) | Error::NotFound(_)) => {} + Err(e) => return Err(e), + } + } + Ok(p) + }) + } + + /// Turns a hub back into a note: the description becomes the first block, then one + /// `[[Member]]` block per member; the members leave the hub. + pub fn convert_to_note(&self, hub: PageId) -> Result { + self.transaction(|g| { + let mut p = g.hub_page(hub)?; + let members = g.hub_members(hub)?; + for t in g.hub_template_ids(hub)? { + g.delete_page_rows(t)?; + } + let description = std::mem::take(&mut p.description); + p.kind = PageKind::Note; + p.updated_at = g.now_ms(); + g.write_page(&p, &g.tick())?; + if !description.is_empty() { + g.insert_block(hub, Placement::LastChildOf(None), &description)?; + } + for m in &members { + if let Some(mp) = g.get_page(*m)? { + g.insert_block( + hub, + Placement::LastChildOf(None), + &format!("[[{}]]", mp.title), + )?; + } + } + g.drop_hub_from_members(hub)?; + g.get_page(hub)? + .ok_or_else(|| Error::NotFound(hub.to_string())) + }) + } + + /// Hubs of the whole graph with their members, nesting depth and every page's home hub. + /// + /// Hub ids that dangle (missing pages, pages that are no longer hubs) and journals are + /// ignored. Concurrent edits on two replicas can store a cycle; memberships are then taken + /// by the HLC of the member page's last write, oldest first, and the one closing a cycle + /// is ignored, which every replica decides the same way. + pub fn structure(&self) -> Result { + let conn = self.conn(); + let mut pages: HashMap = HashMap::new(); + { + let mut st = conn.prepare( + "SELECT id, title, title_key, journal_date IS NOT NULL, kind, description, hubs, hlc + FROM pages", + )?; + let rows = st.query_map([], |r| { + Ok(( + r.get::<_, String>(0)?, + PageRow { + title: r.get(1)?, + key: r.get(2)?, + journal: r.get(3)?, + kind: PageKind::parse(&r.get::<_, String>(4)?), + description: r.get(5)?, + hubs: serde_json::from_str(&r.get::<_, String>(6)?).unwrap_or_default(), + hlc: r.get(7)?, + }, + )) + })?; + for row in rows { + let (id, p) = row?; + pages.insert(parse_id(&id)?, p); + } + } + let is_hub = |id: &PageId| { + pages + .get(id) + .is_some_and(|p| p.kind == PageKind::Hub && !p.journal) + }; + + // Hub → members, from every page's own `hubs`, oldest page write first. + let mut edges: Vec<(&str, PageId, PageId)> = Vec::new(); + for (&id, p) in &pages { + if p.journal || p.kind == PageKind::Template { + continue; + } + // One hub per page: the first entry counts. + for &h in p.hubs.iter().take(1) { + if h != id && is_hub(&h) { + edges.push((p.hlc.as_str(), id, h)); + } + } + } + edges.sort(); + edges.dedup(); + let mut members: HashMap> = HashMap::new(); + let mut sub_hubs: HashMap> = HashMap::new(); + for (_, member, hub) in edges { + if is_hub(&member) { + if reaches(&sub_hubs, member, hub) { + continue; // closes a cycle + } + sub_hubs.entry(hub).or_default().push(member); + } + members.entry(hub).or_default().push(member); + } + + let mut hubs: Vec = pages + .iter() + .filter(|(id, _)| is_hub(id)) + .map(|(&id, p)| { + let mut m = members.remove(&id).unwrap_or_default(); + m.sort_by_cached_key(|x| { + let row = pages.get(x); + ( + !is_hub(x), + row.map(|r| r.key.clone()).unwrap_or_default(), + *x, + ) + }); + HubInfo { + page: id, + title: p.title.clone(), + description: p.description.clone(), + members: m, + depth: 0, + } + }) + .collect(); + let key = |id: &PageId| pages.get(id).map(|p| p.key.as_str()).unwrap_or(""); + hubs.sort_by(|a, b| key(&a.page).cmp(key(&b.page)).then(a.page.cmp(&b.page))); + assign_depth(&mut hubs); + let home = home_hubs(&hubs, |id| key(id).to_string()); + Ok(Structure { hubs, home }) + } + + /// Direct children of a namespace as `(full title, page id)`; levels that only exist as a + /// prefix of deeper titles come with no id. Sorted by title key. + pub fn namespace_children(&self, page_title: &str) -> Result)>> { + let parent: Vec = page_title.split('/').map(title_key).collect(); + if parent.iter().any(|s| s.is_empty()) { + return Ok(Vec::new()); + } + let mut st = self.conn().prepare( + "SELECT id, title FROM pages WHERE journal_date IS NULL AND title LIKE '%/%'", + )?; + let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?; + // Child key → (display title, page when the child exists as a page itself). + let mut found: HashMap)> = HashMap::new(); + for row in rows { + let (id, title) = row?; + let segs: Vec<&str> = title.split('/').map(str::trim).collect(); + if segs.len() <= parent.len() + || segs.iter().any(|s| s.is_empty()) + || !segs.iter().zip(&parent).all(|(s, p)| title_key(s) == *p) + { + continue; + } + let depth = parent.len() + 1; + let child = segs[..depth].join("/"); + let entry = found + .entry(title_key(&child)) + .or_insert_with(|| (child.clone(), None)); + if segs.len() == depth { + *entry = (title, Some(parse_id(&id)?)); + } + } + let mut out: Vec<(String, (String, Option))> = found.into_iter().collect(); + out.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(out.into_iter().map(|(_, v)| v).collect()) + } + + // ---------------------------------------------------------- helpers + + fn hub_page(&self, id: PageId) -> Result { + let p = self + .get_page(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + if !p.is_hub() { + return Err(Error::Invalid(format!("{:?} is not a hub", p.title))); + } + Ok(p) + } + + fn note_page(&self, id: PageId) -> Result { + let p = self + .get_page(id)? + .ok_or_else(|| Error::NotFound(id.to_string()))?; + if p.is_journal() { + return Err(Error::Invalid("journals cannot be hubs".into())); + } + if p.is_hub() { + return Err(Error::Invalid(format!("{:?} is already a hub", p.title))); + } + Ok(p) + } + + /// Every page nested (at any depth) inside hub `hub`, from the `page_hubs` index. + fn nested_in(&self, hub: PageId) -> Result> { + let mut seen = HashSet::new(); + let mut queue = VecDeque::from([hub]); + let mut st = self + .conn() + .prepare_cached("SELECT page_id FROM page_hubs WHERE hub_id=?1")?; + while let Some(h) = queue.pop_front() { + let kids: Vec = st + .query_map([h.to_string()], |r| r.get(0))? + .collect::>()?; + for k in kids { + if let Ok(k) = parse_id(&k) + && seen.insert(k) + { + queue.push_back(k); + } + } + } + Ok(seen) + } + + /// Removes `hub` from the `hubs` of every page in it (each page rewritten and logged). + pub(crate) fn drop_hub_from_members(&self, hub: PageId) -> Result<()> { + let ids: Vec = { + let mut st = self + .conn() + .prepare_cached("SELECT page_id FROM page_hubs WHERE hub_id=?1 ORDER BY page_id")?; + st.query_map([hub.to_string()], |r| r.get(0))? + .collect::>()? + }; + for id in ids { + if let Some(mut p) = self.get_page(parse_id(&id)?)? { + p.hubs.retain(|&h| h != hub); + self.write_page(&p, &self.tick())?; + } + } + Ok(()) + } +} + +/// Whether `to` is reachable from `from` over accepted hub → sub-hub edges. +fn reaches(sub_hubs: &HashMap>, from: PageId, to: PageId) -> bool { + let mut seen = HashSet::from([from]); + let mut stack = vec![from]; + while let Some(h) = stack.pop() { + if h == to { + return true; + } + for &k in sub_hubs.get(&h).into_iter().flatten() { + if seen.insert(k) { + stack.push(k); + } + } + } + false +} + +/// BFS from the root hubs (members of no hub) over hub → sub-hub membership. +fn assign_depth(hubs: &mut [HubInfo]) { + let index: HashMap = hubs.iter().enumerate().map(|(i, h)| (h.page, i)).collect(); + let mut is_member = vec![false; hubs.len()]; + for h in hubs.iter() { + for m in &h.members { + if let Some(&i) = index.get(m) { + is_member[i] = true; + } + } + } + let mut depth: Vec> = vec![None; hubs.len()]; + let mut queue = VecDeque::new(); + for (i, &member) in is_member.iter().enumerate() { + if !member { + depth[i] = Some(0); + queue.push_back(i); + } + } + while let Some(i) = queue.pop_front() { + let d = depth[i].unwrap_or(0); + for m in &hubs[i].members { + if let Some(&j) = index.get(m) + && depth[j].is_none() + { + depth[j] = Some(d + 1); + queue.push_back(j); + } + } + } + for (h, d) in hubs.iter_mut().zip(depth) { + h.depth = d.unwrap_or(0); + } +} + +/// Deepest hub of every member; ties go to the hub with fewer members, then the smaller key. +fn home_hubs(hubs: &[HubInfo], key: impl Fn(&PageId) -> String) -> HashMap { + let rank = |h: &HubInfo| (std::cmp::Reverse(h.depth), h.members.len(), key(&h.page)); + let mut best: HashMap = HashMap::new(); + for h in hubs { + for m in &h.members { + if best.get(m).is_none_or(|b| rank(h) < rank(b)) { + best.insert(*m, h); + } + } + } + let mut home: HashMap = best.into_iter().map(|(p, h)| (p, h.page)).collect(); + for h in hubs { + home.insert(h.page, h.page); + } + home +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn prose_and_plain_text() { + assert!(!is_prose("## Things")); + assert!(!is_prose("[[Film]]")); + assert!(!is_prose("#Music, [[Games]]")); + assert!(is_prose("[[Books]] I want to read")); + assert!(is_prose("## [[Film]] and more words")); + assert_eq!( + plain_text( + "## TODO **Read** [[Big Book]] with #rust and [site](http://x) ![i](a.png) `x`" + ), + "Read Big Book with rust and site x" + ); + assert_eq!(plain_text("line one\nline two"), "line one line two"); + } + + #[test] + fn shorten_cuts_at_words() { + let long = "word ".repeat(100); + let s = shorten(long.trim(), 20); + assert!(s.chars().count() <= 20, "{s}"); + assert_eq!(s, "word word word word…"); + assert_eq!(shorten("short", 20), "short"); + } +} diff --git a/crates/synapse-core/src/tags.rs b/crates/synapse-core/src/tags.rs new file mode 100644 index 0000000..6f57947 --- /dev/null +++ b/crates/synapse-core/src/tags.rs @@ -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 { + let t = raw.trim().trim_start_matches('#'); + let t = t.split_whitespace().collect::>().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 { + 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) -> Result { + let tx = self.tx()?; + let mut p = self + .get_page(page)? + .ok_or_else(|| Error::NotFound(page.to_string()))?; + let mut wanted: Vec = 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 { + 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 { + 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> { + 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>> { + 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> { + 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 = { + 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::>()? + }; + 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(()) + } +} diff --git a/crates/synapse-core/src/types.rs b/crates/synapse-core/src/types.rs new file mode 100644 index 0000000..4c5178c --- /dev/null +++ b/crates/synapse-core/src/types.rs @@ -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) -> Result { + let tx = self.tx()?; + let mut p = self + .get_page(page)? + .ok_or_else(|| Error::NotFound(page.to_string()))?; + let mut next: Vec = 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 { + 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 { + 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> { + 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 = HashMap::new(); + for row in rows { + let types: Vec = 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 = 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) + } +} diff --git a/crates/synapse-core/tests/structure.rs b/crates/synapse-core/tests/structure.rs new file mode 100644 index 0000000..822ef1c --- /dev/null +++ b/crates/synapse-core/tests/structure.rs @@ -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 { + 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(r: synapse_core::Result) -> 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[¬e], 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 + ); +} diff --git a/crates/synapse-ffi/src/api/dto.rs b/crates/synapse-ffi/src/api/dto.rs index 962acdf..d92db8a 100644 --- a/crates/synapse-ffi/src/api/dto.rs +++ b/crates/synapse-ffi/src/api/dto.rs @@ -14,6 +14,16 @@ pub struct PageDto { pub origin_journal: Option, 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, + /// 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, } 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, pub origin_journal: Option, 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, + /// 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, + /// Tag names of the page (see `PageDto::tags`), for grouping by tag. + pub tags: Vec, } /// 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, + /// Ids of the members that are hubs themselves. + pub sub_hubs: Vec, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct HubsDto { + /// Sorted by title. + pub hubs: Vec, + /// Ids of the hubs that are not a member of any hub, by title. + pub roots: Vec, +} + +/// 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, +} + +/// 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, + /// Hubs the page belongs to (its own membership list), by title. + pub in_hubs: Vec, + /// Ancestor namespaces from the root: `A`, `A/B` for `A/B/C` (they may not exist). + pub ns_path: Vec, + pub ns_children: Vec, +} + +/// 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, + /// Blocks that are prose rather than links (what "keep the outline" would save). + pub prose_blocks: u32, + pub blocks: u32, + /// `" (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, +} diff --git a/crates/synapse-ffi/src/api/graph.rs b/crates/synapse-ffi/src/api/graph.rs index 3897030..b0c457f 100644 --- a/crates/synapse-ffi/src/api/graph.rs +++ b/crates/synapse-ffi/src/api/graph.rs @@ -18,6 +18,8 @@ pub struct SynapseGraph { graph: Arc>, /// Page-level graph for the graph views, keyed by what invalidates it. pub(crate) graph_cache: Mutex)>>, + /// Hubs and home hubs, keyed by op-log sequence. + pub(crate) structure_cache: Mutex)>>, } 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), }) } diff --git a/crates/synapse-ffi/src/api/graph_view.rs b/crates/synapse-ffi/src/api/graph_view.rs index 90134f7..f95f2c6 100644 --- a/crates/synapse-ffi/src/api/graph_view.rs +++ b/crates/synapse-ffi/src/api/graph_view.rs @@ -78,9 +78,15 @@ pub(crate) fn build(g: &Graph, seq: i64) -> Result { // Nodes. let mut nodes = Vec::new(); let mut index: HashMap = HashMap::new(); + let page_tags: HashMap> = 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 { })?; 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 { 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 { } } + // 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 { .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 { Ok(out) } +/// A page filed under a tag page gets one `TAGGED` edge to it. +fn tagged( + g: &Graph, + index: &HashMap, + by_key: &HashMap, + 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. diff --git a/crates/synapse-ffi/src/api/mod.rs b/crates/synapse-ffi/src/api/mod.rs index b00b704..b7ba4ba 100644 --- a/crates/synapse-ffi/src/api/mod.rs +++ b/crates/synapse-ffi/src/api/mod.rs @@ -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; diff --git a/crates/synapse-ffi/src/api/structure.rs b/crates/synapse-ffi/src/api/structure.rs new file mode 100644 index 0000000..ec05071 --- /dev/null +++ b/crates/synapse-ffi/src/api/structure.rs @@ -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 { + let g = self.lock(); + let s = self.structure_of(&g)?; + let hub_ids: HashSet = s.hubs.iter().map(|h| h.page).collect(); + let member_of_hub: HashSet = s + .hubs + .iter() + .flat_map(|h| h.members.iter().copied()) + .collect(); + let mut briefs: HashMap = 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::>>()?; + 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 { + 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::>>()? + } else { + Vec::new() + }; + let in_hubs = g + .hubs_of(id)? + .into_iter() + .map(|h| brief(&g, &mut briefs, h)) + .collect::>>()?; + + 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::>>()?; + let ns_children = g + .namespace_children(&page.title)? + .into_iter() + .map(|(t, id)| entry(&g, t, id)) + .collect::>>()?; + 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 { + 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 { + 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 { + 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 { + 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 { + 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::>>()?; + 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, + keep_outline_as: Option, + ) -> Result { + let members = member_ids + .iter() + .map(|i| parse_id(i)) + .collect::>>()?; + 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 { + 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> { + 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) -> Result { + let ids = ids + .iter() + .map(|i| parse_id(i)) + .collect::>>()?; + 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> { + 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, id: PageId) -> Result { + 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) -> Result { + 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()), + }) +} diff --git a/crates/synapse-ffi/src/api/tags.rs b/crates/synapse-ffi/src/api/tags.rs new file mode 100644 index 0000000..096c0cb --- /dev/null +++ b/crates/synapse-ffi/src/api/tags.rs @@ -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) -> Result { + 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 { + 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 { + 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> { + 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> { + 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) -> Result { + 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 { + 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 { + 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> { + Ok(self + .lock() + .type_catalog()? + .into_iter() + .map(|t| TagDto { + name: t.name, + count: t.count, + suggested: t.suggested, + }) + .collect()) + } +} diff --git a/crates/synapse-ffi/src/frb_generated.rs b/crates/synapse-ffi/src/frb_generated.rs index eefba47..5e9703c 100644 --- a/crates/synapse-ffi/src/frb_generated.rs +++ b/crates/synapse-ffi/src/frb_generated.rs @@ -41,7 +41,7 @@ flutter_rust_bridge::frb_generated_boilerplate!( default_rust_auto_opaque = RustAutoOpaqueMoi, ); pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0"; -pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -553305025; +pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 465538383; // Section: executor @@ -362,6 +362,177 @@ fn wire__crate__api__graph__SynapseGraph_add_alias_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_add_page_tag_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_add_page_tag", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_tag = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::add_page_tag( + &*api_that_guard, + api_page_id, + api_tag, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_add_page_type_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_add_page_type", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_ty = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::add_page_type( + &*api_that_guard, + api_page_id, + api_ty, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_add_to_hub_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_add_to_hub", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_hub_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::add_to_hub( + &*api_that_guard, + api_page_id, + api_hub_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_aliases_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -575,6 +746,238 @@ fn wire__crate__api__graph__SynapseGraph_block_ref_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_convert_to_hub_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_convert_to_hub", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_title = ::sse_decode(&mut deserializer); + let api_description = ::sse_decode(&mut deserializer); + let api_member_ids = >::sse_decode(&mut deserializer); + let api_keep_outline_as = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::convert_to_hub( + &*api_that_guard, + api_page_id, + api_title, + api_description, + api_member_ids, + api_keep_outline_as, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_convert_to_note_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_convert_to_note", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::convert_to_note( + &*api_that_guard, + api_page_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_create_hub_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_create_hub", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_title = ::sse_decode(&mut deserializer); + let api_description = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::create_hub( + &*api_that_guard, + api_title, + api_description, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_create_page_from_template_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_create_page_from_template", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_hub_id = ::sse_decode(&mut deserializer); + let api_title = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::create_page_from_template( + &*api_that_guard, + api_hub_id, + api_title, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_delete_block_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -782,6 +1185,167 @@ fn wire__crate__api__graph__SynapseGraph_graph_data_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_hub_conversion_preview_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_hub_conversion_preview", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::hub_conversion_preview( + &*api_that_guard, + api_page_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_hub_template_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_hub_template", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_hub_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::hub_template( + &*api_that_guard, + api_hub_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_hubs_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_hubs", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::hubs(&*api_that_guard)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_indent_block_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -1061,6 +1625,58 @@ fn wire__crate__api__graph__SynapseGraph_journals_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_legacy_candidates_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_legacy_candidates", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::legacy_candidates(&*api_that_guard)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_list_pages_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -1544,6 +2160,171 @@ fn wire__crate__api__graph__SynapseGraph_page_by_title_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_page_structure_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_page_structure", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::page_structure( + &*api_that_guard, + api_page_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_pages_with_tag_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_pages_with_tag", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_tag = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::pages_with_tag( + &*api_that_guard, + api_tag, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_purge_pages_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_purge_pages", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_ids = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::purge_pages( + &*api_that_guard, + api_ids, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -1829,6 +2610,177 @@ fn wire__crate__api__graph__SynapseGraph_remove_alias_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_remove_from_hub_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_remove_from_hub", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_hub_id = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::remove_from_hub( + &*api_that_guard, + api_page_id, + api_hub_id, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_remove_page_tag_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_remove_page_tag", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_tag = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::remove_page_tag( + &*api_that_guard, + api_page_id, + api_tag, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_remove_page_type_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_remove_page_type", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_ty = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::remove_page_type( + &*api_that_guard, + api_page_id, + api_ty, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_rename_page_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -2057,6 +3009,229 @@ fn wire__crate__api__graph__SynapseGraph_set_collapsed_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_set_hub_description_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_set_hub_description", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_hub_id = ::sse_decode(&mut deserializer); + let api_description = ::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::set_hub_description( + &*api_that_guard, + api_hub_id, + api_description, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_set_page_tags_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_set_page_tags", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_tags = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::set_page_tags( + &*api_that_guard, + api_page_id, + api_tags, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_set_page_types_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_set_page_types", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + let api_page_id = ::sse_decode(&mut deserializer); + let api_types = >::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = crate::api::graph::SynapseGraph::set_page_types( + &*api_that_guard, + api_page_id, + api_types, + )?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} +fn wire__crate__api__graph__SynapseGraph_tag_catalog_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_tag_catalog", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::tag_catalog(&*api_that_guard)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_timeline_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -2161,6 +3336,58 @@ fn wire__crate__api__graph__SynapseGraph_today_impl( }, ) } +fn wire__crate__api__graph__SynapseGraph_type_catalog_impl( + port_: flutter_rust_bridge::for_generated::MessagePort, + ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, + rust_vec_len_: i32, + data_len_: i32, +) { + FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::( + flutter_rust_bridge::for_generated::TaskInfo { + debug_name: "SynapseGraph_type_catalog", + port: Some(port_), + mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal, + }, + move || { + let message = unsafe { + flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire( + ptr_, + rust_vec_len_, + data_len_, + ) + }; + let mut deserializer = + flutter_rust_bridge::for_generated::SseDeserializer::new(message); + let api_that = , + >>::sse_decode(&mut deserializer); + deserializer.end(); + move |context| { + transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>( + (move || { + let mut api_that_guard = None; + let decode_indices_ = + flutter_rust_bridge::for_generated::lockable_compute_decode_order( + vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new( + &api_that, 0, false, + )], + ); + for i in decode_indices_ { + match i { + 0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()), + _ => unreachable!(), + } + } + let api_that_guard = api_that_guard.unwrap(); + let output_ok = + crate::api::graph::SynapseGraph::type_catalog(&*api_that_guard)?; + std::result::Result::Ok(output_ok) + })(), + ) + } + }, + ) +} fn wire__crate__api__graph__SynapseGraph_update_block_impl( port_: flutter_rust_bridge::for_generated::MessagePort, ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr, @@ -2426,6 +3653,9 @@ impl SseDecode for crate::api::dto::GraphNode { let mut var_backlinks = ::sse_decode(deserializer); let mut var_cluster = ::sse_decode(deserializer); let mut var_primaryTag = >::sse_decode(deserializer); + let mut var_isHub = ::sse_decode(deserializer); + let mut var_homeHub = >::sse_decode(deserializer); + let mut var_tags = >::sse_decode(deserializer); return crate::api::dto::GraphNode { id: var_id, title: var_title, @@ -2436,6 +3666,61 @@ impl SseDecode for crate::api::dto::GraphNode { backlinks: var_backlinks, cluster: var_cluster, primary_tag: var_primaryTag, + is_hub: var_isHub, + home_hub: var_homeHub, + tags: var_tags, + }; + } +} + +impl SseDecode for crate::api::dto::HubDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_title = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_depth = ::sse_decode(deserializer); + let mut var_members = >::sse_decode(deserializer); + let mut var_subHubs = >::sse_decode(deserializer); + return crate::api::dto::HubDto { + id: var_id, + title: var_title, + description: var_description, + depth: var_depth, + members: var_members, + sub_hubs: var_subHubs, + }; + } +} + +impl SseDecode for crate::api::dto::HubPreviewDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_suggestedTitle = ::sse_decode(deserializer); + let mut var_suggestedDescription = ::sse_decode(deserializer); + let mut var_members = >::sse_decode(deserializer); + let mut var_proseBlocks = ::sse_decode(deserializer); + let mut var_blocks = ::sse_decode(deserializer); + let mut var_suggestedNoteTitle = ::sse_decode(deserializer); + return crate::api::dto::HubPreviewDto { + suggested_title: var_suggestedTitle, + suggested_description: var_suggestedDescription, + members: var_members, + prose_blocks: var_proseBlocks, + blocks: var_blocks, + suggested_note_title: var_suggestedNoteTitle, + }; + } +} + +impl SseDecode for crate::api::dto::HubsDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_hubs = >::sse_decode(deserializer); + let mut var_roots = >::sse_decode(deserializer); + return crate::api::dto::HubsDto { + hubs: var_hubs, + roots: var_roots, }; } } @@ -2466,6 +3751,24 @@ impl SseDecode for crate::api::dto::LayoutFrame { } } +impl SseDecode for crate::api::dto::LegacyCandidate { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_id = ::sse_decode(deserializer); + let mut var_title = ::sse_decode(deserializer); + let mut var_reason = ::sse_decode(deserializer); + let mut var_blocks = ::sse_decode(deserializer); + let mut var_preselected = ::sse_decode(deserializer); + return crate::api::dto::LegacyCandidate { + id: var_id, + title: var_title, + reason: var_reason, + blocks: var_blocks, + preselected: var_preselected, + }; + } +} + impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2538,6 +3841,42 @@ impl SseDecode for Vec { } } +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2622,6 +3961,18 @@ impl SseDecode for Vec { } } +impl SseDecode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut len_ = ::sse_decode(deserializer); + let mut ans_ = Vec::with_capacity(len_ as usize); + for idx_ in 0..len_ { + ans_.push(::sse_decode(deserializer)); + } + return ans_; + } +} + impl SseDecode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2646,6 +3997,18 @@ impl SseDecode for Vec { } } +impl SseDecode for crate::api::dto::NamespaceEntry { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_title = ::sse_decode(deserializer); + let mut var_id = >::sse_decode(deserializer); + return crate::api::dto::NamespaceEntry { + title: var_title, + id: var_id, + }; + } +} + impl SseDecode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2707,10 +4070,12 @@ impl SseDecode for crate::api::dto::PageBrief { let mut var_id = ::sse_decode(deserializer); let mut var_title = ::sse_decode(deserializer); let mut var_isJournal = ::sse_decode(deserializer); + let mut var_isHub = ::sse_decode(deserializer); return crate::api::dto::PageBrief { id: var_id, title: var_title, is_journal: var_isJournal, + is_hub: var_isHub, }; } } @@ -2742,6 +4107,11 @@ impl SseDecode for crate::api::dto::PageDto { let mut var_originJournal = >::sse_decode(deserializer); let mut var_createdAt = ::sse_decode(deserializer); let mut var_updatedAt = ::sse_decode(deserializer); + let mut var_isHub = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_tags = >::sse_decode(deserializer); + let mut var_isTag = ::sse_decode(deserializer); + let mut var_types = >::sse_decode(deserializer); return crate::api::dto::PageDto { id: var_id, title: var_title, @@ -2749,6 +4119,31 @@ impl SseDecode for crate::api::dto::PageDto { origin_journal: var_originJournal, created_at: var_createdAt, updated_at: var_updatedAt, + is_hub: var_isHub, + description: var_description, + tags: var_tags, + is_tag: var_isTag, + types: var_types, + }; + } +} + +impl SseDecode for crate::api::dto::PageStructure { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_isHub = ::sse_decode(deserializer); + let mut var_description = ::sse_decode(deserializer); + let mut var_members = >::sse_decode(deserializer); + let mut var_inHubs = >::sse_decode(deserializer); + let mut var_nsPath = >::sse_decode(deserializer); + let mut var_nsChildren = >::sse_decode(deserializer); + return crate::api::dto::PageStructure { + is_hub: var_isHub, + description: var_description, + members: var_members, + in_hubs: var_inHubs, + ns_path: var_nsPath, + ns_children: var_nsChildren, }; } } @@ -2800,6 +4195,20 @@ impl SseDecode for crate::api::dto::RelatedDto { } } +impl SseDecode for crate::api::dto::TagDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { + let mut var_name = ::sse_decode(deserializer); + let mut var_count = ::sse_decode(deserializer); + let mut var_suggested = ::sse_decode(deserializer); + return crate::api::dto::TagDto { + name: var_name, + count: var_count, + suggested: var_suggested, + }; + } +} + impl SseDecode for crate::api::dto::TimelineDayDto { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self { @@ -2891,133 +4300,254 @@ fn pde_ffi_dispatcher_primary_impl( 6 => { wire__crate__api__graph__SynapseGraph_add_alias_impl(port, ptr, rust_vec_len, data_len) } - 7 => wire__crate__api__graph__SynapseGraph_aliases_impl(port, ptr, rust_vec_len, data_len), + 7 => wire__crate__api__graph__SynapseGraph_add_page_tag_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 8 => wire__crate__api__graph__SynapseGraph_add_page_type_impl( + port, + ptr, + rust_vec_len, + data_len, + ), 9 => { + wire__crate__api__graph__SynapseGraph_add_to_hub_impl(port, ptr, rust_vec_len, data_len) + } + 10 => wire__crate__api__graph__SynapseGraph_aliases_impl(port, ptr, rust_vec_len, data_len), + 12 => { wire__crate__api__graph__SynapseGraph_backlinks_impl(port, ptr, rust_vec_len, data_len) } - 10 => { + 13 => { wire__crate__api__graph__SynapseGraph_block_ref_impl(port, ptr, rust_vec_len, data_len) } - 11 => wire__crate__api__graph__SynapseGraph_delete_block_impl( + 14 => wire__crate__api__graph__SynapseGraph_convert_to_hub_impl( port, ptr, rust_vec_len, data_len, ), - 12 => wire__crate__api__graph__SynapseGraph_delete_page_impl( + 15 => wire__crate__api__graph__SynapseGraph_convert_to_note_impl( port, ptr, rust_vec_len, data_len, ), - 14 => { + 16 => { + wire__crate__api__graph__SynapseGraph_create_hub_impl(port, ptr, rust_vec_len, data_len) + } + 17 => wire__crate__api__graph__SynapseGraph_create_page_from_template_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 18 => wire__crate__api__graph__SynapseGraph_delete_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 19 => wire__crate__api__graph__SynapseGraph_delete_page_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 21 => { wire__crate__api__graph__SynapseGraph_graph_data_impl(port, ptr, rust_vec_len, data_len) } - 15 => wire__crate__api__graph__SynapseGraph_indent_block_impl( + 22 => wire__crate__api__graph__SynapseGraph_hub_conversion_preview_impl( port, ptr, rust_vec_len, data_len, ), - 16 => wire__crate__api__graph__SynapseGraph_insert_block_impl( + 23 => wire__crate__api__graph__SynapseGraph_hub_template_impl( port, ptr, rust_vec_len, data_len, ), - 17 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len), - 18 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl( + 24 => wire__crate__api__graph__SynapseGraph_hubs_impl(port, ptr, rust_vec_len, data_len), + 25 => wire__crate__api__graph__SynapseGraph_indent_block_impl( port, ptr, rust_vec_len, data_len, ), - 19 => { + 26 => wire__crate__api__graph__SynapseGraph_insert_block_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 27 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len), + 28 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 29 => { wire__crate__api__graph__SynapseGraph_journals_impl(port, ptr, rust_vec_len, data_len) } - 20 => { + 30 => wire__crate__api__graph__SynapseGraph_legacy_candidates_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 31 => { wire__crate__api__graph__SynapseGraph_list_pages_impl(port, ptr, rust_vec_len, data_len) } - 21 => wire__crate__api__graph__SynapseGraph_merge_block_impl( + 32 => wire__crate__api__graph__SynapseGraph_merge_block_impl( port, ptr, rust_vec_len, data_len, ), - 22 => { + 33 => { wire__crate__api__graph__SynapseGraph_move_block_impl(port, ptr, rust_vec_len, data_len) } - 23 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len), - 24 => { + 34 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len), + 35 => { wire__crate__api__graph__SynapseGraph_open_page_impl(port, ptr, rust_vec_len, data_len) } - 25 => wire__crate__api__graph__SynapseGraph_outdent_block_impl( + 36 => wire__crate__api__graph__SynapseGraph_outdent_block_impl( port, ptr, rust_vec_len, data_len, ), - 26 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len), - 27 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len), - 28 => wire__crate__api__graph__SynapseGraph_page_by_title_impl( + 37 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len), + 38 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len), + 39 => wire__crate__api__graph__SynapseGraph_page_by_title_impl( port, ptr, rust_vec_len, data_len, ), - 29 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( + 40 => wire__crate__api__graph__SynapseGraph_page_structure_impl( port, ptr, rust_vec_len, data_len, ), - 30 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl( + 41 => wire__crate__api__graph__SynapseGraph_pages_with_tag_impl( port, ptr, rust_vec_len, data_len, ), - 31 => wire__crate__api__graph__SynapseGraph_record_visit_impl( + 42 => wire__crate__api__graph__SynapseGraph_purge_pages_impl( port, ptr, rust_vec_len, data_len, ), - 32 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len), - 33 => wire__crate__api__graph__SynapseGraph_remove_alias_impl( + 43 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl( port, ptr, rust_vec_len, data_len, ), - 34 => wire__crate__api__graph__SynapseGraph_rename_page_impl( + 44 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl( port, ptr, rust_vec_len, data_len, ), - 35 => wire__crate__api__graph__SynapseGraph_search_blocks_impl( + 45 => wire__crate__api__graph__SynapseGraph_record_visit_impl( port, ptr, rust_vec_len, data_len, ), - 36 => wire__crate__api__graph__SynapseGraph_search_titles_impl( + 46 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len), + 47 => wire__crate__api__graph__SynapseGraph_remove_alias_impl( port, ptr, rust_vec_len, data_len, ), - 37 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl( + 48 => wire__crate__api__graph__SynapseGraph_remove_from_hub_impl( port, ptr, rust_vec_len, data_len, ), - 38 => { + 49 => wire__crate__api__graph__SynapseGraph_remove_page_tag_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 50 => wire__crate__api__graph__SynapseGraph_remove_page_type_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 51 => wire__crate__api__graph__SynapseGraph_rename_page_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 52 => wire__crate__api__graph__SynapseGraph_search_blocks_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 53 => wire__crate__api__graph__SynapseGraph_search_titles_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 54 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 55 => wire__crate__api__graph__SynapseGraph_set_hub_description_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 56 => wire__crate__api__graph__SynapseGraph_set_page_tags_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 57 => wire__crate__api__graph__SynapseGraph_set_page_types_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 58 => wire__crate__api__graph__SynapseGraph_tag_catalog_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 59 => { wire__crate__api__graph__SynapseGraph_timeline_impl(port, ptr, rust_vec_len, data_len) } - 40 => wire__crate__api__graph__SynapseGraph_update_block_impl( + 61 => wire__crate__api__graph__SynapseGraph_type_catalog_impl( + port, + ptr, + rust_vec_len, + data_len, + ), + 62 => wire__crate__api__graph__SynapseGraph_update_block_impl( port, ptr, rust_vec_len, @@ -3036,9 +4566,9 @@ fn pde_ffi_dispatcher_sync_impl( // Codec=Pde (Serialization + dispatch), see doc to use other codecs match func_id { 1 => wire__crate__api__layout__ForceLayout_new_impl(ptr, rust_vec_len, data_len), - 8 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len), - 13 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len), - 39 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len), + 11 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len), + 20 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len), + 60 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len), _ => unreachable!(), } } @@ -3222,6 +4752,9 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::GraphNode { self.backlinks.into_into_dart().into_dart(), self.cluster.into_into_dart().into_dart(), self.primary_tag.into_into_dart().into_dart(), + self.is_hub.into_into_dart().into_dart(), + self.home_hub.into_into_dart().into_dart(), + self.tags.into_into_dart().into_dart(), ] .into_dart() } @@ -3233,6 +4766,67 @@ impl flutter_rust_bridge::IntoIntoDart for crate::ap } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::HubDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.title.into_into_dart().into_dart(), + self.description.into_into_dart().into_dart(), + self.depth.into_into_dart().into_dart(), + self.members.into_into_dart().into_dart(), + self.sub_hubs.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::HubDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::HubDto { + fn into_into_dart(self) -> crate::api::dto::HubDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::HubPreviewDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.suggested_title.into_into_dart().into_dart(), + self.suggested_description.into_into_dart().into_dart(), + self.members.into_into_dart().into_dart(), + self.prose_blocks.into_into_dart().into_dart(), + self.blocks.into_into_dart().into_dart(), + self.suggested_note_title.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::dto::HubPreviewDto +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::HubPreviewDto +{ + fn into_into_dart(self) -> crate::api::dto::HubPreviewDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::HubsDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.hubs.into_into_dart().into_dart(), + self.roots.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::HubsDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::HubsDto { + fn into_into_dart(self) -> crate::api::dto::HubsDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::dto::LayoutFrame { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -3251,12 +4845,58 @@ impl flutter_rust_bridge::IntoIntoDart } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::LegacyCandidate { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.id.into_into_dart().into_dart(), + self.title.into_into_dart().into_dart(), + self.reason.into_into_dart().into_dart(), + self.blocks.into_into_dart().into_dart(), + self.preselected.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::dto::LegacyCandidate +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::LegacyCandidate +{ + fn into_into_dart(self) -> crate::api::dto::LegacyCandidate { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::NamespaceEntry { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.title.into_into_dart().into_dart(), + self.id.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::dto::NamespaceEntry +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::NamespaceEntry +{ + fn into_into_dart(self) -> crate::api::dto::NamespaceEntry { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::dto::PageBrief { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ self.id.into_into_dart().into_dart(), self.title.into_into_dart().into_dart(), self.is_journal.into_into_dart().into_dart(), + self.is_hub.into_into_dart().into_dart(), ] .into_dart() } @@ -3296,6 +4936,11 @@ impl flutter_rust_bridge::IntoDart for crate::api::dto::PageDto { self.origin_journal.into_into_dart().into_dart(), self.created_at.into_into_dart().into_dart(), self.updated_at.into_into_dart().into_dart(), + self.is_hub.into_into_dart().into_dart(), + self.description.into_into_dart().into_dart(), + self.tags.into_into_dart().into_dart(), + self.is_tag.into_into_dart().into_dart(), + self.types.into_into_dart().into_dart(), ] .into_dart() } @@ -3307,6 +4952,31 @@ impl flutter_rust_bridge::IntoIntoDart for crate::api: } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::PageStructure { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.is_hub.into_into_dart().into_dart(), + self.description.into_into_dart().into_dart(), + self.members.into_into_dart().into_dart(), + self.in_hubs.into_into_dart().into_dart(), + self.ns_path.into_into_dart().into_dart(), + self.ns_children.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive + for crate::api::dto::PageStructure +{ +} +impl flutter_rust_bridge::IntoIntoDart + for crate::api::dto::PageStructure +{ + fn into_into_dart(self) -> crate::api::dto::PageStructure { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::dto::Place { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -3359,6 +5029,23 @@ impl flutter_rust_bridge::IntoIntoDart } } // Codec=Dco (DartCObject based), see doc to use other codecs +impl flutter_rust_bridge::IntoDart for crate::api::dto::TagDto { + fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { + [ + self.name.into_into_dart().into_dart(), + self.count.into_into_dart().into_dart(), + self.suggested.into_into_dart().into_dart(), + ] + .into_dart() + } +} +impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::TagDto {} +impl flutter_rust_bridge::IntoIntoDart for crate::api::dto::TagDto { + fn into_into_dart(self) -> crate::api::dto::TagDto { + self + } +} +// Codec=Dco (DartCObject based), see doc to use other codecs impl flutter_rust_bridge::IntoDart for crate::api::dto::TimelineDayDto { fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi { [ @@ -3564,6 +5251,41 @@ impl SseEncode for crate::api::dto::GraphNode { ::sse_encode(self.backlinks, serializer); ::sse_encode(self.cluster, serializer); >::sse_encode(self.primary_tag, serializer); + ::sse_encode(self.is_hub, serializer); + >::sse_encode(self.home_hub, serializer); + >::sse_encode(self.tags, serializer); + } +} + +impl SseEncode for crate::api::dto::HubDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.title, serializer); + ::sse_encode(self.description, serializer); + ::sse_encode(self.depth, serializer); + >::sse_encode(self.members, serializer); + >::sse_encode(self.sub_hubs, serializer); + } +} + +impl SseEncode for crate::api::dto::HubPreviewDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.suggested_title, serializer); + ::sse_encode(self.suggested_description, serializer); + >::sse_encode(self.members, serializer); + ::sse_encode(self.prose_blocks, serializer); + ::sse_encode(self.blocks, serializer); + ::sse_encode(self.suggested_note_title, serializer); + } +} + +impl SseEncode for crate::api::dto::HubsDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + >::sse_encode(self.hubs, serializer); + >::sse_encode(self.roots, serializer); } } @@ -3589,6 +5311,17 @@ impl SseEncode for crate::api::dto::LayoutFrame { } } +impl SseEncode for crate::api::dto::LegacyCandidate { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.id, serializer); + ::sse_encode(self.title, serializer); + ::sse_encode(self.reason, serializer); + ::sse_encode(self.blocks, serializer); + ::sse_encode(self.preselected, serializer); + } +} + impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3649,6 +5382,36 @@ impl SseEncode for Vec { } } +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3719,6 +5482,16 @@ impl SseEncode for Vec { } } +impl SseEncode for Vec { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.len() as _, serializer); + for item in self { + ::sse_encode(item, serializer); + } + } +} + impl SseEncode for Vec { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3739,6 +5512,14 @@ impl SseEncode for Vec { } } +impl SseEncode for crate::api::dto::NamespaceEntry { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.title, serializer); + >::sse_encode(self.id, serializer); + } +} + impl SseEncode for Option { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { @@ -3795,6 +5576,7 @@ impl SseEncode for crate::api::dto::PageBrief { ::sse_encode(self.id, serializer); ::sse_encode(self.title, serializer); ::sse_encode(self.is_journal, serializer); + ::sse_encode(self.is_hub, serializer); } } @@ -3818,6 +5600,23 @@ impl SseEncode for crate::api::dto::PageDto { >::sse_encode(self.origin_journal, serializer); ::sse_encode(self.created_at, serializer); ::sse_encode(self.updated_at, serializer); + ::sse_encode(self.is_hub, serializer); + ::sse_encode(self.description, serializer); + >::sse_encode(self.tags, serializer); + ::sse_encode(self.is_tag, serializer); + >::sse_encode(self.types, serializer); + } +} + +impl SseEncode for crate::api::dto::PageStructure { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.is_hub, serializer); + ::sse_encode(self.description, serializer); + >::sse_encode(self.members, serializer); + >::sse_encode(self.in_hubs, serializer); + >::sse_encode(self.ns_path, serializer); + >::sse_encode(self.ns_children, serializer); } } @@ -3863,6 +5662,15 @@ impl SseEncode for crate::api::dto::RelatedDto { } } +impl SseEncode for crate::api::dto::TagDto { + // Codec=Sse (Serialization based), see doc to use other codecs + fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { + ::sse_encode(self.name, serializer); + ::sse_encode(self.count, serializer); + ::sse_encode(self.suggested, serializer); + } +} + impl SseEncode for crate::api::dto::TimelineDayDto { // Codec=Sse (Serialization based), see doc to use other codecs fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) { diff --git a/crates/synapse-ffi/tests/api.rs b/crates/synapse-ffi/tests/api.rs index a27c683..8423889 100644 --- a/crates/synapse-ffi/tests/api.rs +++ b/crates/synapse-ffi/tests/api.rs @@ -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(¬e).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 = 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() + ); +} diff --git a/crates/synapse-history/src/export.rs b/crates/synapse-history/src/export.rs index 6583f3a..d86b49a 100644 --- a/crates/synapse-history/src/export.rs +++ b/crates/synapse-history/src/export.rs @@ -3,7 +3,8 @@ //! Layout: `pages/.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) pub fn render_page(graph: &Graph, page: &Page, referenced: &HashSet) -> Result { 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() { diff --git a/crates/synapse-history/src/history.rs b/crates/synapse-history/src/history.rs index 0ca919e..a1e45ca 100644 --- a/crates/synapse-history/src/history.rs +++ b/crates/synapse-history/src/history.rs @@ -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, } diff --git a/crates/synapse-history/src/parse.rs b/crates/synapse-history/src/parse.rs index c6cd99a..4b6667f 100644 --- a/crates/synapse-history/src/parse.rs +++ b/crates/synapse-history/src/parse.rs @@ -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, + /// `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, + /// Tag page titles from `synapse-tags::`. + pub tags: Vec, + /// Names from `synapse-types::`. + pub types: Vec, pub blocks: Vec, } @@ -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. diff --git a/crates/synapse-history/src/restore.rs b/crates/synapse-history/src/restore.rs index a75183e..27aa9a8 100644 --- a/crates/synapse-history/src/restore.rs +++ b/crates/synapse-history/src/restore.rs @@ -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(graph: &Graph, f: impl FnOnce() -> Result) -> Result { } struct Plan { + page: PageId, + is_hub: bool, + is_tag: bool, + description: String, + /// Titles of the hubs the page belongs to. + hubs: Vec, + tags: Vec, + types: Vec, blocks: Vec, delete: Vec, } @@ -67,8 +75,20 @@ fn find_or_create(graph: &Graph, title: &str) -> Result { /// Matches parsed blocks to existing ones and decides what to write and delete. fn plan(graph: &Graph, title: &str, parsed: &ParsedPage, steal: bool) -> Result { - 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 = existing.iter().map(|b| (b.id, b)).collect(); let mut claimed: HashSet = HashSet::new(); - let mut ids: Vec> = vec![None; parsed.blocks.len()]; + let mut ids: Vec> = 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 = Vec::with_capacity(parsed.blocks.len()); + let mut blocks: Vec = Vec::with_capacity(parsed_blocks.len()); let mut stack: Vec = Vec::new(); let mut last_pos: HashMap, 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 { 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 { + 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 { + 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(r: synapse_core::Result) -> Result> { + 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 { 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 { diff --git a/crates/synapse-history/tests/history.rs b/crates/synapse-history/tests/history.rs index e6cf2c2..448edc1 100644 --- a/crates/synapse-history/tests/history.rs +++ b/crates/synapse-history/tests/history.rs @@ -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}" + ); + } +} diff --git a/crates/synapse-import/examples/import.rs b/crates/synapse-import/examples/import.rs index 0aaf875..769034c 100644 --- a/crates/synapse-import/examples/import.rs +++ b/crates/synapse-import/examples/import.rs @@ -1,4 +1,4 @@ -//! `cargo run -p synapse-import --example import -- [--skip-existing]` +//! `cargo run -p synapse-import --example import -- [--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 = 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 = args .iter() .filter(|a| !a.starts_with("--")) .map(PathBuf::from) .collect(); let [src, dst] = paths.as_slice() else { - eprintln!("usage: import [--skip-existing]"); + eprintln!("usage: import [--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); diff --git a/crates/synapse-import/src/lib.rs b/crates/synapse-import/src/lib.rs index 0c46aa6..99b1eb5 100644 --- a/crates/synapse-import/src/lib.rs +++ b/crates/synapse-import/src/lib.rs @@ -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, + /// Legacy organisational pages left out (relative paths), see `skip_legacy_pages`. + pub skipped_legacy: Vec, pub warnings: Vec, } @@ -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 = 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 = 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> { + 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) -> Result<()> { + let stubs: Vec = 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); } diff --git a/crates/synapse-import/tests/import.rs b/crates/synapse-import/tests/import.rs index bebe5aa..1e4c99f 100644 --- a/crates/synapse-import/tests/import.rs +++ b/crates/synapse-import/tests/import.rs @@ -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]); +} diff --git a/crates/synapse-search/src/fulltext.rs b/crates/synapse-search/src/fulltext.rs index 9786c38..1d31c08 100644 --- a/crates/synapse-search/src/fulltext.rs +++ b/crates/synapse-search/src/fulltext.rs @@ -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)?; diff --git a/crates/synapse-search/src/lib.rs b/crates/synapse-search/src/lib.rs index 8a4b479..637907f 100644 --- a/crates/synapse-search/src/lib.rs +++ b/crates/synapse-search/src/lib.rs @@ -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(()) diff --git a/crates/synapse-search/src/vectors.rs b/crates/synapse-search/src/vectors.rs index 0f6ba2e..27f99ea 100644 --- a/crates/synapse-search/src/vectors.rs +++ b/crates/synapse-search/src/vectors.rs @@ -40,15 +40,15 @@ pub(crate) fn quantize(v: &[f32]) -> (Vec, 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 diff --git a/crates/synapse-search/tests/search.rs b/crates/synapse-search/tests/search.rs index 5b7945b..d1e6567 100644 --- a/crates/synapse-search/tests/search.rs +++ b/crates/synapse-search/tests/search.rs @@ -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); +} diff --git a/crates/synapse-server/tests/e2e.rs b/crates/synapse-server/tests/e2e.rs index 3ab5f37..099bb05 100644 --- a/crates/synapse-server/tests/e2e.rs +++ b/crates/synapse-server/tests/e2e.rs @@ -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;