AI-native knowledge base & Evernote/Obsidian alternative with instant sync & native MCP. Free on Cloudflare or self-hosted via Docker.
HTML ai-agentcloudflarecloudflare-d1cloudflare-r2cloudflare-workersdockerelectronevernoteevernote-alternativeknowledge-basemcpnote-takingobsidian-alternativeoffline-firstpersonal-knowledge-basepwaself-hostedsqlitetiptapweb-clipper
feat(templates): show unedited default templates in the current UI language (#563)
Dariusz Koryto9bb3218c0356
diff --git a/apps/api/src/template-routes.ts b/apps/api/src/template-routes.tsindex 81b07746..7052cd53 100644--- a/apps/api/src/template-routes.ts+++ b/apps/api/src/template-routes.ts@@ -8,6 +8,7 @@ import {type MemoTemplate,type TiptapDoc,} from "@edgeever/shared";+import { localizeDefaultMemoTemplate } from "@edgeever/shared/memo-template-seeds";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";import { audit } from "./audit";@@ -195,10 +196,11 @@ export const registerTemplateRoutes = (const id = c.req.param("id");const input = c.req.valid("json");const workspaceId = getWorkspaceId(c);- const template = await getMemoTemplate(c.env.storage.db, workspaceId, id);- if (!template) {+ const stored = await getMemoTemplate(c.env.storage.db, workspaceId, id);+ if (!stored) {return notFound(c, "Template not found");}+ const template = input.locale ? localizeDefaultMemoTemplate(stored, input.locale) : stored;const memo = await createMemoRecord(c.env.storage.db, workspaceId, {notebookId: input.notebookId,diff --git a/apps/mobile/src/components/MobileTemplatePicker.tsx b/apps/mobile/src/components/MobileTemplatePicker.tsxindex 14041cf8..5aa0817a 100644--- a/apps/mobile/src/components/MobileTemplatePicker.tsx+++ b/apps/mobile/src/components/MobileTemplatePicker.tsx@@ -1,4 +1,7 @@+import { useMemo } from "react";import { useQuery } from "@tanstack/react-query";+import type { MemoTemplate } from "@edgeever/shared";+import { localizeDefaultMemoTemplate } from "@edgeever/shared/memo-template-seeds";import type { createEdgeEverClient } from "@edgeever/client";import { Modal, Pressable, ScrollView, View } from "react-native";import { ActivityIndicator, FileText, LayoutTemplate, X } from "./icons";@@ -35,26 +38,31 @@ export const MobileTemplatePickerModal = ({presentation?: "modal" | "overlay";visible: boolean;}) => {- const { translate } = useMobileLocale();+ const { resolvedLocale, translate } = useMobileLocale();const savedTemplatesQuery = useQuery({queryKey: ["mobile", "templates"],enabled: visible && Boolean(client),queryFn: async () => {if (!client) {- return [] as MobileSelectableTemplate[];+ return [] as MemoTemplate[];}if (typeof client.listTemplates !== "function") {throw new Error("Client is missing listTemplates; reload the app to pick up the latest bundle.");}const response = await client.listTemplates();- return response.templates.map(toMobileSelectableTemplate);+ return response.templates;},staleTime: 15_000,retry: 1,});- const savedTemplates = savedTemplatesQuery.data ?? [];+ const savedTemplates = useMemo(+ () => (savedTemplatesQuery.data ?? []).map((template) => (+ toMobileSelectableTemplate(localizeDefaultMemoTemplate(template, resolvedLocale))+ )),+ [resolvedLocale, savedTemplatesQuery.data],+ );const isLoadingSaved = savedTemplatesQuery.isLoading || savedTemplatesQuery.isFetching;const savedLoadErrorMessage = savedTemplatesQuery.error instanceof Error? savedTemplatesQuery.error.messagediff --git a/apps/web/src/components/TemplatesPane.tsx b/apps/web/src/components/TemplatesPane.tsxindex dbbe5ed1..37857bf8 100644--- a/apps/web/src/components/TemplatesPane.tsx+++ b/apps/web/src/components/TemplatesPane.tsx@@ -22,6 +22,7 @@ import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, Dimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";import { WORKSPACE_PAGE_TITLE_CLASSNAME } from "@/lib/workspace-ui";import { copyTextToClipboard } from "@/lib/clipboard";+import { createTemplateCards, createTemplateDraft, templateDraftToPayload } from "@/lib/template-center";import { ClipboardCopyNotice } from "@/components/ClipboardCopyNotice";import type { MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";import { ExecutionCenterButton } from "@/components/execution/ExecutionCenterButton";@@ -76,7 +77,7 @@ export const TemplatesPane = ({onUpdateSavedTemplate: (templateId: string, payload: { name: string; description: string | null; title: string | null; contentMarkdown: string; tags: string[] }) => Promise<void>;onOpenExecutionCenter: () => void;}) => {- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const [editingTemplate, setEditingTemplate] = useState<SavedMemoTemplate | null>(null);const [creatingTemplate, setCreatingTemplate] = useState(false);const [draft, setDraft] = useState({ name: "", description: "", title: "", contentMarkdown: "", tags: "" });@@ -107,13 +108,7 @@ export const TemplatesPane = ({setCreatingTemplate(false);setEditingTemplate(template);setEditorTab("raw");- setDraft({- name: template.name,- description: template.description ?? "",- title: template.title ?? "",- contentMarkdown: template.contentMarkdown,- tags: template.tags.join(", "),- });+ setDraft(createTemplateDraft(template));};const startCreating = () => {@@ -130,13 +125,7 @@ export const TemplatesPane = ({const saveEditing = async () => {if (!draft.name.trim()) return;- const payload = {- name: draft.name.trim(),- description: draft.description.trim() || null,- title: draft.title.trim() || null,- contentMarkdown: draft.contentMarkdown,- tags: draft.tags.split(",").map((tag) => tag.trim()).filter(Boolean),- };+ const payload = templateDraftToPayload(draft);if (creatingTemplate) {await onCreateSavedTemplate(payload);cancelEditing();@@ -147,6 +136,11 @@ export const TemplatesPane = ({cancelEditing();};+ const templateCards = useMemo(+ () => createTemplateCards(savedTemplates, i18n.resolvedLanguage),+ [i18n.resolvedLanguage, savedTemplates],+ );+const draftHtmlPreview = useMemo(() => (draft.contentMarkdown ? safeMarkdownPreview(draft.contentMarkdown) : ""),[draft.contentMarkdown]@@ -326,7 +320,7 @@ export const TemplatesPane = ({{/* Templates Grid */}{savedTemplates.length > 0 ? (<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">- {savedTemplates.map((template) => (+ {templateCards.map(({ template: storedTemplate, display: template }) => (<divkey={template.id}className="group relative flex cursor-pointer flex-col justify-between rounded-xl border border-slate-200 bg-card p-4 transition-all duration-200 hover:border-slate-300 hover:shadow-md"@@ -385,7 +379,7 @@ export const TemplatesPane = ({label={t("templates.edit")}onClick={(e) => {e.stopPropagation();- startEditing(template);+ startEditing(storedTemplate);}}><Pencil className="h-3.5 w-3.5" />diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsxindex 97c016f0..35d247fe 100644--- a/apps/web/src/components/WorkspaceApp.tsx+++ b/apps/web/src/components/WorkspaceApp.tsx@@ -1337,14 +1337,14 @@ export const WorkspaceApp = ({});const useTemplateMutation = useMutation({- mutationFn: async (input: { templateId: string; notebookId: string }) => {+ mutationFn: async (input: { templateId: string; notebookId: string; locale?: string }) => {const requiresRemoteMemo = requiresRemoteMemoForStandaloneMobileEditor({mobileViewport: !isDesktopViewport(),desktopRuntime: Boolean(window.edgeeverDesktop?.isAvailable),});const data = requiresRemoteMemo- ? await api.useTemplate(input.templateId, input.notebookId)- : await repository.useTemplate(input.templateId, input.notebookId);+ ? await api.useTemplate(input.templateId, input.notebookId, input.locale)+ : await repository.useTemplate(input.templateId, input.notebookId, input.locale);if (requiresRemoteMemo) notifyRepositoryMutation(localDataScope, { type: "note.created", note: data.memo });await putLocalMemo(localDataScope, data.memo);return data;@@ -1994,7 +1994,11 @@ export const WorkspaceApp = ({const handleUseSavedTemplate = (template: SavedMemoTemplate) => {if (!createMemoNotebookId || memoView === "trash") return;- useTemplateMutation.mutate({ templateId: template.id, notebookId: createMemoNotebookId });+ useTemplateMutation.mutate({+ templateId: template.id,+ notebookId: createMemoNotebookId,+ locale: i18n.resolvedLanguage,+ });};const handleMobileDefaultEditConsumed = useCallback(() => {diff --git a/apps/web/src/lib/desktop-repository.ts b/apps/web/src/lib/desktop-repository.tsindex db2c8830..b4fe2fd5 100644--- a/apps/web/src/lib/desktop-repository.ts+++ b/apps/web/src/lib/desktop-repository.ts@@ -8,6 +8,7 @@ import type {DesktopRpcResponses,} from "@edgeever/shared";import { docToMarkdown, docToText, type MemoDetail } from "@edgeever/shared";+import { localizeDefaultMemoTemplate } from "@edgeever/shared/memo-template-seeds";import type { EdgeEverRepository } from "@/lib/repository";import { api, getConfiguredDesktopApiBaseUrl } from "@/lib/api";import { createStagedResourceListItem, mapMarkdownResourceUrls, mapTiptapResourceUrls, toApiResourceUrl, toDesktopResourceUrl } from "@/lib/desktop-resources";@@ -180,10 +181,11 @@ export const createDesktopRepository = (): EdgeEverRepository => ({window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));return result;}),- useTemplate: async (templateId, notebookId) => {+ useTemplate: async (templateId, notebookId, locale) => {const templates = await createDesktopRepository().listTemplates();- const template = templates.templates.find((candidate) => candidate.id === templateId);- if (!template) throw new Error(`Template not found: ${templateId}`);+ const stored = templates.templates.find((candidate) => candidate.id === templateId);+ if (!stored) throw new Error(`Template not found: ${templateId}`);+ const template = locale ? localizeDefaultMemoTemplate(stored, locale) : stored;return createDesktopRepository().createMemo({ notebookId, title: template.title ?? "", contentMarkdown: template.contentMarkdown, tags: template.tags });},uploadMemoResource: async (memoId, file) => {diff --git a/apps/web/src/lib/repository-events.ts b/apps/web/src/lib/repository-events.tsindex 239877be..c6f23f5d 100644--- a/apps/web/src/lib/repository-events.ts+++ b/apps/web/src/lib/repository-events.ts@@ -59,8 +59,8 @@ export const withRepositoryMutationEvents = (repository: EdgeEverRepository, sconotifyRepositoryMutation(scope, { type: "note.updated", note: result.memo });return result;},- async useTemplate(templateId, notebookId) {- const result = await repository.useTemplate(templateId, notebookId);+ async useTemplate(templateId, notebookId, locale) {+ const result = await repository.useTemplate(templateId, notebookId, locale);notifyRepositoryMutation(scope, { type: "note.created", note: result.memo });return result;},diff --git a/apps/web/src/lib/repository.ts b/apps/web/src/lib/repository.tsindex 724c12d5..354f69b6 100644--- a/apps/web/src/lib/repository.ts+++ b/apps/web/src/lib/repository.ts@@ -1,4 +1,5 @@import { assertLocalMemoSnapshot } from "./local-memo-guard";+import { localizeDefaultMemoTemplate } from "@edgeever/shared/memo-template-seeds";import { markdownToDoc, type MemoDetail, type MemoRevision, type MemoSummary, type MemoTemplate, type Notebook, type Resource, type ResourceListItem, type ResourceStorageSummary, type TagSummary, type TiptapDoc } from "@edgeever/shared";import { api } from "@/lib/api";import {@@ -62,7 +63,8 @@ export type EdgeEverRepository = {createTemplate(input: { name: string; description?: string | null; memoId?: string; title?: string | null; contentMarkdown?: string; tags?: string[] }): Promise<{ template: MemoTemplate }>;updateTemplate(templateId: string, input: { name?: string; description?: string | null; title?: string | null; contentMarkdown?: string; tags?: string[] }): Promise<{ template: MemoTemplate }>;deleteTemplate(templateId: string): Promise<{ ok: true }>;- useTemplate(templateId: string, notebookId: string): Promise<{ memo: MemoDetail }>;+ /** With `locale`, an unedited default template is used in that UI language. */+ useTemplate(templateId: string, notebookId: string, locale?: string): Promise<{ memo: MemoDetail }>;uploadMemoResource(memoId: string, file: File): Promise<{ resource: Resource }>;readResource(resourceId: string): Promise<Blob>;updateResource(resourceId: string, file: File, expectedContentHash: string): Promise<{ resource: Resource }>;@@ -286,11 +288,12 @@ export const createWebRepository = (scope: string): EdgeEverRepository => {window.dispatchEvent(new CustomEvent("edgeever:sync-queue-changed"));return { ok: true as const };},- useTemplate: async (templateId, notebookId) => {- const template = (await listLocalTemplates(scope)).templates.find((candidate) => candidate.id === templateId);+ useTemplate: async (templateId, notebookId, locale) => {+ const stored = (await listLocalTemplates(scope)).templates.find((candidate) => candidate.id === templateId);+ const template = stored && locale ? localizeDefaultMemoTemplate(stored, locale) : stored;if (!template) {if (isOffline()) throw new Error("Template is not available offline");- const result = await api.useTemplate(templateId, notebookId);+ const result = await api.useTemplate(templateId, notebookId, locale);await putLocalMemo(scope, result.memo);return result;}diff --git a/apps/web/src/lib/template-center.test.mjs b/apps/web/src/lib/template-center.test.mjsnew file mode 100644index 00000000..00dc8a85--- /dev/null+++ b/apps/web/src/lib/template-center.test.mjs@@ -0,0 +1,41 @@+import { describe, expect, test } from "bun:test";+import { DEFAULT_MEMO_TEMPLATE_SEEDS } from "@edgeever/shared/memo-template-seeds";+import { createTemplateCards, createTemplateDraft, templateDraftToPayload } from "./template-center.ts";++const quickNote = DEFAULT_MEMO_TEMPLATE_SEEDS.find((seed) => seed.key === "quick-note");+const chinese = quickNote.translations["zh-CN"];+const polish = quickNote.translations.pl;+const storedChinese = {+ id: "ws_default_template_quick-note",+ name: chinese.title,+ description: chinese.description,+ title: chinese.title,+ contentJson: { type: "doc", content: [] },+ contentMarkdown: chinese.contentMarkdown,+ tags: ["template", "quick-note"],+ createdAt: "2026-10-14T00:00:00.000Z",+ updatedAt: "2026-10-14T00:00:00.000Z",+};++describe("template center", () => {+ test("shows an unedited default template in the UI language but edits the stored one", () => {+ const [card] = createTemplateCards([storedChinese], "pl");++ expect(card.display.name).toBe(polish.title);+ expect(card.display.contentMarkdown).toBe(polish.contentMarkdown);+ expect(card.template).toBe(storedChinese);+ });++ test("a name-only edit in another UI language keeps the other stored fields", () => {+ const [card] = createTemplateCards([storedChinese], "pl");+ const draft = { ...createTemplateDraft(card.template), name: "Moja notatka" };++ expect(templateDraftToPayload(draft)).toEqual({+ name: "Moja notatka",+ description: chinese.description,+ title: chinese.title,+ contentMarkdown: chinese.contentMarkdown,+ tags: ["template", "quick-note"],+ });+ });+});diff --git a/apps/web/src/lib/template-center.ts b/apps/web/src/lib/template-center.tsnew file mode 100644index 00000000..13b1f86d--- /dev/null+++ b/apps/web/src/lib/template-center.ts@@ -0,0 +1,44 @@+import type { MemoTemplate } from "@edgeever/shared";+import { localizeDefaultMemoTemplate } from "@edgeever/shared/memo-template-seeds";++export type TemplateCard = {+ /** The template as stored; editing starts from it. */+ template: MemoTemplate;+ /** The template as shown in the current UI language. */+ display: MemoTemplate;+};++export type TemplateDraft = {+ name: string;+ description: string;+ title: string;+ contentMarkdown: string;+ tags: string;+};++// Unedited default templates are displayed in the UI language, but the editor+// always starts from the stored fields, so saving a change to one field never+// writes the display translation of the others.+export const createTemplateCards = (+ templates: readonly MemoTemplate[],+ locale: string | null | undefined,+): TemplateCard[] => templates.map((template) => ({+ template,+ display: localizeDefaultMemoTemplate(template, locale),+}));++export const createTemplateDraft = (template: MemoTemplate): TemplateDraft => ({+ name: template.name,+ description: template.description ?? "",+ title: template.title ?? "",+ contentMarkdown: template.contentMarkdown,+ tags: template.tags.join(", "),+});++export const templateDraftToPayload = (draft: TemplateDraft) => ({+ name: draft.name.trim(),+ description: draft.description.trim() || null,+ title: draft.title.trim() || null,+ contentMarkdown: draft.contentMarkdown,+ tags: draft.tags.split(",").map((tag) => tag.trim()).filter(Boolean),+});diff --git a/packages/client/src/index.ts b/packages/client/src/index.tsindex 57610198..bf0b95e5 100644--- a/packages/client/src/index.ts+++ b/packages/client/src/index.ts@@ -1474,10 +1474,10 @@ export const createEdgeEverClient = (options: EdgeEverClientOptions = {}) => {body: JSON.stringify(payload),}),- useTemplate: (templateId: string, notebookId: string) =>+ useTemplate: (templateId: string, notebookId: string, locale?: string) =>request<MemoResponse>(`/api/v1/templates/${templateId}/use`, {method: "POST",- body: JSON.stringify({ notebookId }),+ body: JSON.stringify(locale ? { notebookId, locale } : { notebookId }),}),deleteTemplate: (templateId: string) =>diff --git a/packages/shared/src/memo-template-seeds.test.mjs b/packages/shared/src/memo-template-seeds.test.mjsindex 1c4a0037..126619e0 100644--- a/packages/shared/src/memo-template-seeds.test.mjs+++ b/packages/shared/src/memo-template-seeds.test.mjs@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";import {DEFAULT_MEMO_TEMPLATE_SEEDS,defaultMemoTemplateId,+ localizeDefaultMemoTemplate,localizeMemoTemplateSeed,} from "./memo-template-seeds.ts";@@ -20,4 +21,50 @@ describe("memo template seeds", () => {test("uses workspace-scoped deterministic ids", () => {expect(defaultMemoTemplateId("ws_1", "meeting")).toBe("ws_1_template_meeting");});++ describe("default template display language", () => {+ const [quickNote] = DEFAULT_MEMO_TEMPLATE_SEEDS;+ const stored = (locale, overrides = {}) => {+ const translation = quickNote.translations[locale];+ return {+ id: "ws_default_template_quick-note",+ name: translation.title,+ description: translation.description,+ title: translation.title,+ contentMarkdown: translation.contentMarkdown,+ tags: ["template", "quick-note"],+ ...overrides,+ };+ };++ test("shows an unedited default template in the viewer's language, whatever language it was stored in", () => {+ expect(localizeDefaultMemoTemplate(stored("zh-CN"), "pl-PL")).toEqual(stored("pl"));+ expect(localizeDefaultMemoTemplate(stored("pl"), "ja")).toEqual(stored("ja"));+ expect(localizeDefaultMemoTemplate(stored("ja"), "fr-FR")).toEqual(stored("en-US"));+ });++ test("keeps templates the user edited or created as they are", () => {+ const renamed = stored("zh-CN", { name: "My spark" });+ const rewritten = stored("en-US", { contentMarkdown: "## Mine" });+ const custom = { ...stored("en-US"), id: "template_abc" };++ expect(localizeDefaultMemoTemplate(renamed, "pl")).toBe(renamed);+ expect(localizeDefaultMemoTemplate(rewritten, "pl")).toBe(rewritten);+ expect(localizeDefaultMemoTemplate(custom, "pl")).toBe(custom);+ });++ test("keeps a default template whose tags were changed", () => {+ const retagged = stored("zh-CN", { tags: ["template", "quick-note", "mine"] });+ const reordered = stored("zh-CN", { tags: ["quick-note", "template"] });++ expect(localizeDefaultMemoTemplate(retagged, "pl")).toBe(retagged);+ expect(localizeDefaultMemoTemplate(reordered, "pl")).toBe(reordered);+ });++ test("does not mix fields from different translations", () => {+ const mixed = stored("zh-CN", { description: quickNote.translations["en-US"].description });++ expect(localizeDefaultMemoTemplate(mixed, "pl")).toBe(mixed);+ });+ });});diff --git a/packages/shared/src/memo-template-seeds.ts b/packages/shared/src/memo-template-seeds.tsindex 2dddc3c6..396b8163 100644--- a/packages/shared/src/memo-template-seeds.ts+++ b/packages/shared/src/memo-template-seeds.ts@@ -161,3 +161,51 @@ export const memoTemplateSeedTranslations = (locale: MemoTemplateSeedLocale) =>item.translationKey,item.translations[locale],])) as Record<MemoTemplateSeed["translationKey"], MemoTemplateSeedTranslation>;++type LocalizableMemoTemplate = {+ id: string;+ name: string;+ description: string | null;+ title: string | null;+ contentMarkdown: string;+ tags: readonly string[];+};++const findUntouchedSeedTranslation = (+ template: LocalizableMemoTemplate,+): MemoTemplateSeed | null => {+ const templateSeed = DEFAULT_MEMO_TEMPLATE_SEEDS.find((item) => template.id.endsWith(`_template_${item.key}`));+ if (!templateSeed) return null;+ const seededTags = ["template", templateSeed.tag];+ if (+ template.tags.length !== seededTags.length+ || template.tags.some((tag, index) => tag !== seededTags[index])+ ) return null;+ const untouched = Object.values(templateSeed.translations).some((translation) =>+ template.name === translation.title+ && template.title === translation.title+ && template.description === translation.description+ && template.contentMarkdown === translation.contentMarkdown);+ return untouched ? templateSeed : null;+};++/**+ * Shows a default template in the viewer's UI language while it still equals+ * one of its seeded translations, including its seeded tags. Templates the+ * user created or edited in any field are returned unchanged.+ */+export const localizeDefaultMemoTemplate = <Template extends LocalizableMemoTemplate>(+ template: Template,+ locale: string | null | undefined,+): Template => {+ const templateSeed = findUntouchedSeedTranslation(template);+ if (!templateSeed) return template;+ const localized = localizeMemoTemplateSeed(templateSeed, locale);+ return {+ ...template,+ name: localized.title,+ title: localized.title,+ description: localized.description,+ contentMarkdown: localized.contentMarkdown,+ };+};diff --git a/packages/shared/src/schemas.ts b/packages/shared/src/schemas.tsindex bccfb563..7977326a 100644--- a/packages/shared/src/schemas.ts+++ b/packages/shared/src/schemas.ts@@ -75,6 +75,9 @@ export const TemplateUpdateSchema = z.object({export const TemplateUseSchema = z.object({notebookId: z.string().trim().min(1),+ // The client's UI language. Default templates nobody edited are used in+ // this language; without it every template is used as stored.+ locale: z.string().trim().min(1).max(64).optional(),});const ScheduledPluginCommandPayloadSchema = z.object({