Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions apps/obsidian/src/utils/conceptConversion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,15 @@ const getNodeExtraData = (
/* eslint-enable @typescript-eslint/naming-convention */
};

export const discourseNodeSchemaToLocalConcept = (
context: SupabaseContext,
node: DiscourseNode,
): LocalConceptDataInput => {
export const discourseNodeSchemaToLocalConcept = ({
context,
node,
templateContent,
}: {
context: SupabaseContext;
node: DiscourseNode;
templateContent?: string;
}): LocalConceptDataInput => {
const {
description,
template,
Expand All @@ -51,6 +56,7 @@ export const discourseNodeSchemaToLocalConcept = (
source_data: otherData,
};
if (template) literal_content.template = template;
if (templateContent) literal_content.template_content = templateContent;
if (importedFromRid) literal_content.importedFromRid = importedFromRid;
return {
space_id: context.spaceId,
Expand Down
32 changes: 30 additions & 2 deletions apps/obsidian/src/utils/importNodes.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { Json } from "@repo/database/dbTypes";
import matter from "gray-matter";
import { App, TFile } from "obsidian";
import { App, Notice, TFile } from "obsidian";
import type { DGSupabaseClient } from "@repo/database/lib/client";
import type DiscourseGraphPlugin from "~/index";
import { getLoggedInClient, getSupabaseContext } from "./supabaseContext";
Expand All @@ -19,6 +19,7 @@ import {
importRelationsForImportedNodes,
type RemoteRelationInstance,
} from "./importRelations";
import { createTemplateFile } from "./templates";
import { resolveFolderForSpaceUri } from "./importFolderMetadata";

export const getAvailableGroupIds = async (
Expand Down Expand Up @@ -1019,7 +1020,7 @@ const parseSchemaLiteralContent = (
): Pick<
DiscourseNode,
"name" | "format" | "color" | "tag" | "template" | "keyImage"
> => {
> & { templateContent?: string } => {
const obj =
typeof literalContent === "string"
? (JSON.parse(literalContent) as Record<string, unknown>)
Expand All @@ -1036,6 +1037,7 @@ const parseSchemaLiteralContent = (
color: (src.color as string) || (obj.color as string) || undefined,
tag: (src.tag as string) || (obj.tag as string) || undefined,
template: (obj.template as string) || undefined,
templateContent: (obj.template_content as string) || undefined,
keyImage:
(src.keyImage as boolean) ?? (obj.keyImage as boolean) ?? undefined,
};
Expand Down Expand Up @@ -1111,6 +1113,32 @@ export const mapNodeTypeIdToLocal = async ({
authorId: schemaData.author_id ?? undefined,
importedFromRid,
};

if (parsed.templateContent && parsed.template) {
const result = await createTemplateFile({
app: plugin.app,
templateName: parsed.template,
content: parsed.templateContent,
});
if (result.created) {
new Notice(
`Template "${parsed.template}" created for imported node type "${parsed.name}".`,
4000,
);
} else if (
result.reason === "Templates plugin is not enabled" ||
result.reason === "Templates folder path is not configured"
) {
// Don't store a template filename that can never resolve
newNodeType.template = undefined;
new Notice(
`Node type "${parsed.name}" imported without template: ${result.reason}. Configure the Templates plugin to use templates.`,
6000,
);
}
// If reason is "template already exists", keep newNodeType.template — local file takes precedence
}

plugin.settings.nodeTypes = [...plugin.settings.nodeTypes, newNodeType];
await plugin.saveSettings();
return newNodeType.id;
Expand Down
27 changes: 24 additions & 3 deletions apps/obsidian/src/utils/syncDgNodesToSupabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
collectDiscourseNodesFromVault,
} from "./getDiscourseNodes";
import { isAcceptedSchema } from "./typeUtils";
import { getTemplatePluginInfo } from "./templates";

const DEFAULT_TIME = "1970-01-01";
export type ChangeType = "title" | "content";
Expand Down Expand Up @@ -472,9 +473,29 @@ const convertDgToSupabaseConcepts = async ({
nodeTypes.map((nodeType) => [nodeType.id, nodeType]),
);

const nodesTypesToLocalConcepts = nodeTypes
.filter((nodeType) => nodeType.modified > lastNodeSchemaSync)
.map((nodeType) => discourseNodeSchemaToLocalConcept(context, nodeType));
const { isEnabled: templatesEnabled, folderPath: templatesFolderPath } =
getTemplatePluginInfo(plugin.app);

const nodesTypesToLocalConcepts = await Promise.all(
nodeTypes
.filter((nodeType) => nodeType.modified > lastNodeSchemaSync)
.map(async (nodeType) => {
let templateContent: string | undefined;
if (nodeType.template && templatesEnabled && templatesFolderPath) {
const templateFilePath = `${templatesFolderPath}/${nodeType.template}.md`;
const templateFile =
plugin.app.vault.getAbstractFileByPath(templateFilePath);
if (templateFile instanceof TFile) {
templateContent = await plugin.app.vault.read(templateFile);
}
}
return discourseNodeSchemaToLocalConcept({
context,
node: nodeType,
templateContent,
});
}),
);

const relationTypesById = Object.fromEntries(
relationTypes.map((relationType) => [relationType.id, relationType]),
Expand Down
51 changes: 51 additions & 0 deletions apps/obsidian/src/utils/templates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,57 @@ export const getTemplateFiles = (app: App): string[] => {
}
};

type CreateTemplateFileResult =
| { created: true }
| { created: false; reason: string };

export const createTemplateFile = async ({
app,
templateName,
content,
}: {
app: App;
templateName: string;
content: string;
}): Promise<CreateTemplateFileResult> => {
const { isEnabled, folderPath } = getTemplatePluginInfo(app);

if (!isEnabled) {
return { created: false, reason: "Templates plugin is not enabled" };
}

if (!folderPath) {
return {
created: false,
reason: "Templates folder path is not configured",
};
}

// Ensure every segment of the folder path exists, creating missing ones
const segments = folderPath.split("/").filter(Boolean);
let currentPath = "";
for (const segment of segments) {
currentPath = currentPath ? `${currentPath}/${segment}` : segment;
const existing = app.vault.getAbstractFileByPath(currentPath);
if (!existing) {
await app.vault.createFolder(currentPath);
}
}

// Sanitize to prevent path traversal (e.g. "../../sensitive" from a malicious sync)
const sanitizedName = templateName.replace(/[/\\]/g, "-");
const templateFilePath = `${folderPath}/${sanitizedName}.md`;

// Don't overwrite an existing template — the local file takes precedence
const existingFile = app.vault.getAbstractFileByPath(templateFilePath);
if (existingFile instanceof TFile) {
return { created: false, reason: "template already exists" };
}

await app.vault.create(templateFilePath, content);
return { created: true };
};

export const applyTemplate = async ({
app,
targetFile,
Expand Down
Loading