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): add optional template gallery across web, mobile, and iOS (#609)
Dariusz Koryto4954d651bfbf
diff --git a/apps/api/src/template-routes.test.mjs b/apps/api/src/template-routes.test.mjsindex b0da01ff..b6790694 100644--- a/apps/api/src/template-routes.test.mjs+++ b/apps/api/src/template-routes.test.mjs@@ -1,5 +1,7 @@import { describe, expect, test } from "bun:test";-import { mapMemoTemplateRow } from "./template-routes.ts";+import { Hono } from "hono";+import { listMemoTemplateGallery } from "@edgeever/shared/memo-template-gallery";+import { mapMemoTemplateRow, registerTemplateRoutes } from "./template-routes.ts";const row = {id: "template_1",@@ -35,3 +37,16 @@ describe("template route mapping", () => {});});});++describe("template gallery route", () => {+ test("lists the gallery in the requested language without touching storage", async () => {+ const app = new Hono();+ registerTemplateRoutes(app, { createMemoRecord: async () => null, getMemoDetail: async () => null });++ const response = await app.request("/api/v1/templates/gallery?locale=pl-PL", {}, {});+ const body = await response.json();++ expect(response.status).toBe(200);+ expect(body.templates).toEqual(listMemoTemplateGallery("pl"));+ });+});diff --git a/apps/api/src/template-routes.ts b/apps/api/src/template-routes.tsindex 7052cd53..f59d9869 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 { listMemoTemplateGallery } from "@edgeever/shared/memo-template-gallery";import { localizeDefaultMemoTemplate } from "@edgeever/shared/memo-template-seeds";import { zValidator } from "@hono/zod-validator";import type { Hono } from "hono";@@ -118,6 +119,12 @@ export const registerTemplateRoutes = (return c.json({ templates: await listMemoTemplates(c.env.storage.db, getWorkspaceId(c)) });});+ // Optional templates clients offer next to the workspace's own; reading the+ // gallery never writes to the workspace.+ app.get("/api/v1/templates/gallery", (c) => {+ return c.json({ templates: listMemoTemplateGallery(c.req.query("locale")) });+ });+app.post("/api/v1/templates", zValidator("json", TemplateCreateSchema), async (c) => {const input = c.req.valid("json");const workspaceId = getWorkspaceId(c);diff --git a/apps/ios/EdgeEver/Data/Models/MemoTemplates.swift b/apps/ios/EdgeEver/Data/Models/MemoTemplates.swiftindex 8ce261de..68527ecc 100644--- a/apps/ios/EdgeEver/Data/Models/MemoTemplates.swift+++ b/apps/ios/EdgeEver/Data/Models/MemoTemplates.swift@@ -15,6 +15,20 @@ struct TemplatesResponse: Codable, Sendable {var templates: [MemoTemplate]}+/// Optional template from the server's gallery; it is not saved in the workspace.+struct MemoTemplateGalleryEntry: Codable, Equatable, Sendable {+ var key: String+ var name: String+ var description: String+ var title: String+ var contentMarkdown: String+ var tags: [String]+}++struct TemplateGalleryResponse: Codable, Sendable {+ var templates: [MemoTemplateGalleryEntry]+}+struct CreateMemoSeed: Equatable, Sendable {var title: Stringvar contentMarkdown: String@@ -44,6 +58,15 @@ struct SelectableMemoTemplate: Identifiable, Equatable, Sendable {tags = template.tags}+ init(_ entry: MemoTemplateGalleryEntry) {+ id = "gallery:\(entry.key)"+ name = entry.name+ description = entry.description+ title = entry.title+ contentMarkdown = entry.contentMarkdown+ tags = entry.tags+ }+var createSeed: CreateMemoSeed {CreateMemoSeed(title: title,diff --git a/apps/ios/EdgeEver/Data/Network/APIClient.swift b/apps/ios/EdgeEver/Data/Network/APIClient.swiftindex f8d4e0dd..4e7934cf 100644--- a/apps/ios/EdgeEver/Data/Network/APIClient.swift+++ b/apps/ios/EdgeEver/Data/Network/APIClient.swift@@ -311,6 +311,14 @@ actor APIClient {return response.templates}+ func listTemplateGallery(locale: String) async throws -> [MemoTemplateGalleryEntry] {+ let response: TemplateGalleryResponse = try await request(+ path: "/api/v1/templates/gallery",+ query: [.init(name: "locale", value: locale)]+ )+ return response.templates+ }+func useTemplate(templateId: String, notebookId: String) async throws -> MemoDetail {struct Body: Encodable {var notebookId: Stringdiff --git a/apps/ios/EdgeEver/Features/Workspace/TemplatePickerSheet.swift b/apps/ios/EdgeEver/Features/Workspace/TemplatePickerSheet.swiftindex 62e4b466..25f4dfa5 100644--- a/apps/ios/EdgeEver/Features/Workspace/TemplatePickerSheet.swift+++ b/apps/ios/EdgeEver/Features/Workspace/TemplatePickerSheet.swift@@ -120,6 +120,7 @@ struct TemplatePickerSheet: View {var onSelect: (CreateMemoSeed) -> Void@State private var templates: [SelectableMemoTemplate] = []+ @State private var galleryTemplates: [SelectableMemoTemplate] = []@State private var isLoading = false@State private var loadFailed = false@@ -193,6 +194,13 @@ struct TemplatePickerSheet: View {ForEach(templates) { template intemplateRow(template)}++ if !galleryTemplates.isEmpty {+ sectionTitle(env.preferences.t("模板库", en: "Template Gallery", pl: "Galeria szablonów"))+ ForEach(galleryTemplates) { template in+ templateRow(template)+ }+ }}.padding(.horizontal, 8).padding(.vertical, 8)@@ -204,6 +212,7 @@ struct TemplatePickerSheet: View {.presentationDragIndicator(.hidden).accessibilityIdentifier("templatePickerSheet").task { await loadTemplates() }+ .task { await loadGallery() }}private func loadTemplates() async {@@ -219,6 +228,16 @@ struct TemplatePickerSheet: View {}}+ /// Servers without the gallery endpoint simply leave the section hidden.+ private func loadGallery() async {+ do {+ let list = try await env.session.client.listTemplateGallery(locale: env.preferences.apiLocale)+ galleryTemplates = list.map(SelectableMemoTemplate.init)+ } catch {+ galleryTemplates = []+ }+ }+private func sectionTitle(_ text: String) -> some View {Text(text).font(.system(size: 12, weight: .bold))diff --git a/apps/ios/Tests/EdgeEverTests/MemoTemplatesTests.swift b/apps/ios/Tests/EdgeEverTests/MemoTemplatesTests.swiftindex 2f9feaeb..8b951c8b 100644--- a/apps/ios/Tests/EdgeEverTests/MemoTemplatesTests.swift+++ b/apps/ios/Tests/EdgeEverTests/MemoTemplatesTests.swift@@ -36,4 +36,14 @@ final class MemoTemplatesTests: XCTestCase {XCTAssertEqual(row.title, "自定义")XCTAssertEqual(row.contentMarkdown, "# Hi")}++ func testGalleryEntryBecomesCreateSeed() throws {+ let json = #"{"templates":[{"key":"daily-journal","name":"Dziennik dnia","description":"Opis","title":"Dziennik dnia","contentMarkdown":"- Plan","tags":["template","daily-journal"]}]}"#+ let response = try EdgeEverJSON.decoder.decode(TemplateGalleryResponse.self, from: Data(json.utf8))+ let row = SelectableMemoTemplate(try XCTUnwrap(response.templates.first))+ XCTAssertEqual(row.id, "gallery:daily-journal")+ XCTAssertEqual(row.createSeed.title, "Dziennik dnia")+ XCTAssertEqual(row.createSeed.contentMarkdown, "- Plan")+ XCTAssertEqual(row.createSeed.tagsText, "template, daily-journal")+ }}diff --git a/apps/mobile/src/components/MobileTemplatePicker.tsx b/apps/mobile/src/components/MobileTemplatePicker.tsxindex 5aa0817a..a97c7013 100644--- a/apps/mobile/src/components/MobileTemplatePicker.tsx+++ b/apps/mobile/src/components/MobileTemplatePicker.tsx@@ -1,12 +1,14 @@import { useMemo } from "react";import { useQuery } from "@tanstack/react-query";import type { MemoTemplate } from "@edgeever/shared";+import { listMemoTemplateGallery } from "@edgeever/shared/memo-template-gallery";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";import { Text } from "./LocalizedText";import {+ galleryEntryToMobileSelectableTemplate,mobileTemplateToCreateSeed,toMobileSelectableTemplate,type MobileCreateMemoSeed,@@ -63,6 +65,10 @@ export const MobileTemplatePickerModal = ({)),[resolvedLocale, savedTemplatesQuery.data],);+ const galleryTemplates = useMemo(+ () => listMemoTemplateGallery(resolvedLocale).map(galleryEntryToMobileSelectableTemplate),+ [resolvedLocale],+ );const isLoadingSaved = savedTemplatesQuery.isLoading || savedTemplatesQuery.isFetching;const savedLoadErrorMessage = savedTemplatesQuery.error instanceof Error? savedTemplatesQuery.error.message@@ -137,6 +143,10 @@ export const MobileTemplatePickerModal = ({{savedTemplates.map((template) => (<TemplateRow key={template.id} onPress={() => handleSelect(template)} template={template} />))}+ <Text style={styles.actionSheetSectionTitle}>{translate("模板库")}</Text>+ {galleryTemplates.map((template) => (+ <TemplateRow key={template.id} onPress={() => handleSelect(template)} template={template} />+ ))}</ScrollView></Pressable></Pressable>diff --git a/apps/mobile/src/lib/mobile-templates.test.ts b/apps/mobile/src/lib/mobile-templates.test.tsindex 7d66f3ca..4c6a983a 100644--- a/apps/mobile/src/lib/mobile-templates.test.ts+++ b/apps/mobile/src/lib/mobile-templates.test.ts@@ -1,11 +1,25 @@import { describe, expect, test } from "bun:test";+import { localizeMemoTemplateGalleryItem, MEMO_TEMPLATE_GALLERY } from "@edgeever/shared/memo-template-gallery";import {createMemoSeedHasContent,+ galleryEntryToMobileSelectableTemplate,mobileTemplateToCreateSeed,toMobileSelectableTemplate,} from "./mobile-templates";describe("mobile-templates", () => {+ test("turns a gallery template into a create seed without saving it", () => {+ const entry = localizeMemoTemplateGalleryItem(MEMO_TEMPLATE_GALLERY[0], "pl");+ const selectable = galleryEntryToMobileSelectableTemplate(entry);++ expect(selectable.id).toBe("gallery:daily-journal");+ expect(mobileTemplateToCreateSeed(selectable)).toEqual({+ title: entry.title,+ contentMarkdown: entry.contentMarkdown,+ tagsText: "template, daily-journal",+ });+ });+test("maps a persisted template to a selectable row", () => {const selectableSaved = toMobileSelectableTemplate({diff --git a/apps/mobile/src/lib/mobile-templates.ts b/apps/mobile/src/lib/mobile-templates.tsindex deab7df4..371ede46 100644--- a/apps/mobile/src/lib/mobile-templates.ts+++ b/apps/mobile/src/lib/mobile-templates.ts@@ -1,4 +1,5 @@import type { MemoTemplate } from "@edgeever/shared";+import type { MemoTemplateGalleryEntry } from "@edgeever/shared/memo-template-gallery";export type MobileCreateMemoSeed = {title: string;@@ -28,6 +29,17 @@ export const toMobileSelectableTemplate = (};};+export const galleryEntryToMobileSelectableTemplate = (+ entry: MemoTemplateGalleryEntry,+): MobileSelectableTemplate => ({+ id: `gallery:${entry.key}`,+ name: entry.name,+ description: entry.description,+ title: entry.title,+ contentMarkdown: entry.contentMarkdown,+ tags: entry.tags,+});+export const mobileTemplateToCreateSeed = (template: MobileSelectableTemplate): MobileCreateMemoSeed => ({title: template.title,contentMarkdown: template.contentMarkdown,diff --git a/apps/web/src/components/TemplatesPane.tsx b/apps/web/src/components/TemplatesPane.tsxindex 37857bf8..b1847b71 100644--- a/apps/web/src/components/TemplatesPane.tsx+++ b/apps/web/src/components/TemplatesPane.tsx@@ -1,4 +1,4 @@-import { useMemo, useState, type MouseEvent, type ReactNode } from "react";+import { useMemo, useRef, useState, type MouseEvent, type ReactNode } from "react";import {Check,ChevronLeft,@@ -12,7 +12,8 @@ import {X,Tag,ArrowRight,- FilePlus+ FilePlus,+ LibraryBig} from "lucide-react";import { useTranslation } from "react-i18next";import { safeMarkdownPreview } from "@/lib/safe-markdown-preview";@@ -23,6 +24,7 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/compimport { WORKSPACE_PAGE_TITLE_CLASSNAME } from "@/lib/workspace-ui";import { copyTextToClipboard } from "@/lib/clipboard";import { createTemplateCards, createTemplateDraft, templateDraftToPayload } from "@/lib/template-center";+import { listMemoTemplateGallery, type MemoTemplateGalleryEntry } from "@edgeever/shared/memo-template-gallery";import { ClipboardCopyNotice } from "@/components/ClipboardCopyNotice";import type { MemoTemplate as SavedMemoTemplate } from "@edgeever/shared";import { ExecutionCenterButton } from "@/components/execution/ExecutionCenterButton";@@ -89,8 +91,13 @@ export const TemplatesPane = ({noteTitle?: string | null;tags: string[];contentMarkdown: string;+ actionLabel: string;+ actionDisabled: boolean;onUse: () => void;} | null>(null);+ const [addingGalleryKey, setAddingGalleryKey] = useState<string | null>(null);+ // State lags a render behind, so a double click would pass the state check twice.+ const addingGalleryRef = useRef(false);const [deleteConfirmTemplate, setDeleteConfirmTemplate] = useState<SavedMemoTemplate | null>(null);const [templateIdCopyNotice, setTemplateIdCopyNotice] = useState<{@@ -141,6 +148,38 @@ export const TemplatesPane = ({[i18n.resolvedLanguage, savedTemplates],);+ const galleryEntries = useMemo(+ () => listMemoTemplateGallery(i18n.resolvedLanguage),+ [i18n.resolvedLanguage],+ );++ // Gallery templates are tagged with their key, so a saved template carrying+ // that tag marks the gallery entry as added.+ const addedGalleryTags = useMemo(+ () => new Set(savedTemplates.flatMap((template) => template.tags)),+ [savedTemplates],+ );++ const addGalleryTemplate = async (entry: MemoTemplateGalleryEntry) => {+ if (addingGalleryRef.current) return;+ addingGalleryRef.current = true;+ setAddingGalleryKey(entry.key);+ try {+ await onCreateSavedTemplate({+ name: entry.name,+ description: entry.description,+ title: entry.title,+ contentMarkdown: entry.contentMarkdown,+ tags: entry.tags,+ });+ } catch {+ // The workspace shows the save failure notice; the entry stays available to retry.+ } finally {+ addingGalleryRef.current = false;+ setAddingGalleryKey(null);+ }+ };+const draftHtmlPreview = useMemo(() => (draft.contentMarkdown ? safeMarkdownPreview(draft.contentMarkdown) : ""),[draft.contentMarkdown]@@ -331,6 +370,8 @@ export const TemplatesPane = ({noteTitle: template.title,tags: template.tags,contentMarkdown: template.contentMarkdown,+ actionLabel: t("templates.useThisTemplate"),+ actionDisabled: !canCreateMemo || isCreating,onUse: () => onUseSavedTemplate(template),})}@@ -406,6 +447,8 @@ export const TemplatesPane = ({noteTitle: template.title,tags: template.tags,contentMarkdown: template.contentMarkdown,+ actionLabel: t("templates.useThisTemplate"),+ actionDisabled: !canCreateMemo || isCreating,onUse: () => onUseSavedTemplate(template),});}}@@ -445,6 +488,98 @@ export const TemplatesPane = ({) : null}</section>+ <section>+ <div className="mb-4">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-slate-900">+ <span>{t("templates.gallery")}</span>+ <span className="rounded-full bg-slate-100 px-2 py-0.5 text-xs font-semibold text-slate-700">+ {galleryEntries.length}+ </span>+ </h2>+ <p className="mt-1 text-xs text-slate-500">{t("templates.galleryHint")}</p>+ </div>++ <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">+ {galleryEntries.map((entry) => {+ const added = addedGalleryTags.has(entry.key);+ const addDisabled = isCreating || addingGalleryKey !== null;+ return (+ <div+ key={entry.key}+ 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"+ onClick={() =>+ setPreviewTemplate({+ title: entry.name,+ description: entry.description,+ noteTitle: entry.title,+ tags: entry.tags,+ contentMarkdown: entry.contentMarkdown,+ actionLabel: t("templates.addToMyTemplates"),+ actionDisabled: addDisabled,+ onUse: () => void addGalleryTemplate(entry),+ })+ }+ >+ <div>+ <div className="mb-2 flex items-center gap-2 min-w-0">+ <span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-slate-100 text-slate-800">+ <LibraryBig className="h-4 w-4" />+ </span>+ <h3 className="truncate text-sm font-semibold text-slate-900">{entry.name}</h3>+ </div>+ <p className="mt-1 line-clamp-2 text-xs leading-relaxed text-slate-500 min-h-[2.25rem]">+ {entry.description}+ </p>+ </div>++ <div className="mt-4 border-t border-slate-100 pt-3 flex items-center justify-between gap-2">+ <div className="flex items-center gap-1 text-slate-400">+ <TemplateIconAction+ className="p-1 hover:text-slate-700 transition rounded-md hover:bg-slate-100"+ label={t("templates.previewTemplate")}+ onClick={(e) => {+ e.stopPropagation();+ setPreviewTemplate({+ title: entry.name,+ description: entry.description,+ noteTitle: entry.title,+ tags: entry.tags,+ contentMarkdown: entry.contentMarkdown,+ actionLabel: t("templates.addToMyTemplates"),+ actionDisabled: addDisabled,+ onUse: () => void addGalleryTemplate(entry),+ });+ }}+ >+ <Eye className="h-3.5 w-3.5" />+ </TemplateIconAction>+ {added && (+ <span className="inline-flex items-center gap-1 whitespace-nowrap text-xs font-medium text-slate-500">+ <Check className="h-3.5 w-3.5" />+ {t("templates.addedToMyTemplates")}+ </span>+ )}+ </div>++ <button+ type="button"+ className="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg border border-slate-200 bg-card px-3 py-1.5 text-xs font-semibold text-slate-800 shadow-2xs transition-colors hover:bg-slate-50 hover:text-slate-950 disabled:opacity-50"+ disabled={addDisabled}+ onClick={(e) => {+ e.stopPropagation();+ void addGalleryTemplate(entry);+ }}+ >+ <Plus className="h-3 w-3" />+ {t("templates.addToMyTemplates")}+ </button>+ </div>+ </div>+ );+ })}+ </div>+ </section>+{!canCreateMemo && (<div className="rounded-xl border border-amber-200 bg-amber-50 p-3.5 text-xs font-medium text-amber-900">{t("templates.unavailable")}@@ -491,14 +626,14 @@ export const TemplatesPane = ({size="sm"variant="solid"className="gap-1.5 font-semibold"- disabled={!canCreateMemo || isCreating}+ disabled={previewTemplate.actionDisabled}onClick={() => {const onUse = previewTemplate.onUse;setPreviewTemplate(null);onUse();}}>- {t("templates.useThisTemplate")}+ {previewTemplate.actionLabel}<ArrowRight className="h-3.5 w-3.5" /></Button></DialogFooter>diff --git a/apps/web/src/components/WorkspaceApp.tsx b/apps/web/src/components/WorkspaceApp.tsxindex 04807f42..c69d102c 100644--- a/apps/web/src/components/WorkspaceApp.tsx+++ b/apps/web/src/components/WorkspaceApp.tsx@@ -1347,6 +1347,9 @@ export const WorkspaceApp = ({await queryClient.invalidateQueries({ queryKey: ["templates"] });setAppNoticeDialog({ title: t("templates.templateCreated"), description: t("templates.templateCreated") });},+ onError: () => {+ setAppNoticeDialog({ title: t("templates.createFailedTitle"), description: t("templates.createFailed") });+ },});const useTemplateMutation = useMutation({diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 4d54b27e..156a84dd 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -24,6 +24,7 @@"./i18n/ru": "./src/i18n/ru.ts","./i18n/locales": "./src/i18n/locales.ts","./memo-template-seeds": "./src/memo-template-seeds.ts",+ "./memo-template-gallery": "./src/memo-template-gallery.ts","./default-workspace-seeds": "./src/default-workspace-seeds.ts","./mathematics": "./src/mathematics.ts","./mobile-editor": "./src/mobile-editor.ts",diff --git a/packages/shared/src/i18n/en-US.ts b/packages/shared/src/i18n/en-US.tsindex f14e855f..595b3f50 100644--- a/packages/shared/src/i18n/en-US.ts+++ b/packages/shared/src/i18n/en-US.ts@@ -3342,6 +3342,10 @@ export const enUS = {savedDescription: "A reusable note template.",emptyMyTemplates: "No templates yet",emptyMyTemplatesHint: "Click \"New Template\" above or save any note as a template directly in the editor.",+ gallery: "Template Gallery",+ galleryHint: "Pick a ready-made template. Once added, you can edit and use it like your own.",+ addToMyTemplates: "Add to my templates",+ addedToMyTemplates: "Added",delete: "Delete template",copyId: "Copy template ID",idCopied: "Template ID copied: {{id}}",@@ -3368,6 +3372,8 @@ export const enUS = {templateNamePrompt: "Enter a template name",templateSaved: "Template saved",templateCreated: "Template created",+ createFailedTitle: "Template not saved",+ createFailed: "Could not save the template. Check your connection and try again.",unavailable: "Select an available notebook before creating a note.",items: memoTemplateSeedTranslations("en-US"),},diff --git a/packages/shared/src/i18n/ja.ts b/packages/shared/src/i18n/ja.tsindex 8070b103..08d22b8b 100644--- a/packages/shared/src/i18n/ja.ts+++ b/packages/shared/src/i18n/ja.ts@@ -3331,6 +3331,10 @@ export const ja = {savedDescription: "再利用できるノートテンプレートです。",emptyMyTemplates: "まだテンプレートがありません",emptyMyTemplatesHint: "上の「新しいテンプレート」をクリックするか、エディタで任意のノートをテンプレートとして保存できます。",+ gallery: "テンプレートギャラリー",+ galleryHint: "用意されたテンプレートから選べます。追加すると自分のテンプレートと同様に編集・利用できます。",+ addToMyTemplates: "マイテンプレートに追加",+ addedToMyTemplates: "追加済み",delete: "テンプレートを削除",copyId: "テンプレート ID をコピー",idCopied: "テンプレート ID をコピーしました:{{id}}",@@ -3357,6 +3361,8 @@ export const ja = {templateNamePrompt: "テンプレート名を入力",templateSaved: "テンプレートを保存しました",templateCreated: "テンプレートを作成しました",+ createFailedTitle: "テンプレートを保存できませんでした",+ createFailed: "テンプレートを保存できませんでした。接続を確認してもう一度お試しください。",unavailable: "ノートを作成する前に、利用できるノートブックを選んでください。",items: memoTemplateSeedTranslations("ja"),},diff --git a/packages/shared/src/i18n/pl.ts b/packages/shared/src/i18n/pl.tsindex ad5de4df..057e76c1 100644--- a/packages/shared/src/i18n/pl.ts+++ b/packages/shared/src/i18n/pl.ts@@ -3331,6 +3331,10 @@ export const pl = {savedDescription: "Szablon notatki wielokrotnego użytku.",emptyMyTemplates: "Nie masz jeszcze szablonów",emptyMyTemplatesHint: "Kliknij „Nowy szablon” powyżej albo zapisz dowolną notatkę jako szablon bezpośrednio w edytorze.",+ gallery: "Galeria szablonów",+ galleryHint: "Wybierz gotowy szablon. Po dodaniu możesz go edytować i używać jak własnego.",+ addToMyTemplates: "Dodaj do moich szablonów",+ addedToMyTemplates: "Dodano",delete: "Usuń szablon",copyId: "Kopiuj ID szablonu",idCopied: "Skopiowano ID szablonu: {{id}}",@@ -3357,6 +3361,8 @@ export const pl = {templateNamePrompt: "Wpisz nazwę szablonu",templateSaved: "Zapisano szablon",templateCreated: "Utworzono szablon",+ createFailedTitle: "Nie zapisano szablonu",+ createFailed: "Nie udało się zapisać szablonu. Sprawdź połączenie i spróbuj ponownie.",unavailable: "Przed utworzeniem notatki wybierz dostępny notatnik.",items: memoTemplateSeedTranslations("pl"),},diff --git a/packages/shared/src/i18n/ru.ts b/packages/shared/src/i18n/ru.tsindex e150e65d..0fc5f853 100644--- a/packages/shared/src/i18n/ru.ts+++ b/packages/shared/src/i18n/ru.ts@@ -3342,6 +3342,10 @@ export const ru = {savedDescription: "Переиспользуемый шаблон заметки.",emptyMyTemplates: "Пока нет шаблонов",emptyMyTemplatesHint: "Нажмите «Новый шаблон» выше или сохраните любую заметку как шаблон прямо в редакторе.",+ gallery: "Галерея шаблонов",+ galleryHint: "Выберите готовый шаблон. После добавления его можно редактировать и использовать как свой.",+ addToMyTemplates: "Добавить в мои шаблоны",+ addedToMyTemplates: "Добавлено",delete: "Удалить шаблон",copyId: "Копировать ID шаблона",idCopied: "ID шаблона скопирован: {{id}}",@@ -3368,6 +3372,8 @@ export const ru = {templateNamePrompt: "Введите название шаблона",templateSaved: "Шаблон сохранён",templateCreated: "Шаблон создан",+ createFailedTitle: "Шаблон не сохранён",+ createFailed: "Не удалось сохранить шаблон. Проверьте подключение и повторите попытку.",unavailable: "Выберите доступный блокнот перед созданием заметки.",items: memoTemplateSeedTranslations("ru"),},diff --git a/packages/shared/src/i18n/zh-CN.ts b/packages/shared/src/i18n/zh-CN.tsindex 6ce9cbaa..10b952a2 100644--- a/packages/shared/src/i18n/zh-CN.ts+++ b/packages/shared/src/i18n/zh-CN.ts@@ -3340,6 +3340,10 @@ export const zhCN = {savedDescription: "可重复使用的笔记模板。",emptyMyTemplates: "暂无模板",emptyMyTemplatesHint: "你可以点击上方「新建模板」,或在笔记编辑器中将常用笔记另存为模板。",+ gallery: "模板库",+ galleryHint: "从精选模板中挑选,添加后即可像自己的模板一样编辑和使用。",+ addToMyTemplates: "添加到我的模板",+ addedToMyTemplates: "已添加",delete: "删除模板",copyId: "复制模板 ID",idCopied: "模板 ID 已复制:{{id}}",@@ -3366,6 +3370,8 @@ export const zhCN = {templateNamePrompt: "请输入模板名称",templateSaved: "模板已保存",templateCreated: "模板已创建",+ createFailedTitle: "模板未保存",+ createFailed: "无法保存模板,请检查网络连接后重试。",unavailable: "当前无法创建笔记,请先选择可用笔记本。",items: memoTemplateSeedTranslations("zh-CN"),},diff --git a/packages/shared/src/memo-template-gallery.test.mjs b/packages/shared/src/memo-template-gallery.test.mjsnew file mode 100644index 00000000..de8647d7--- /dev/null+++ b/packages/shared/src/memo-template-gallery.test.mjs@@ -0,0 +1,54 @@+import { describe, expect, test } from "bun:test";+import {+ listMemoTemplateGallery,+ localizeMemoTemplateGalleryItem,+ MEMO_TEMPLATE_GALLERY,+} from "./memo-template-gallery.ts";+import { DEFAULT_MEMO_TEMPLATE_SEEDS } from "./memo-template-seeds.ts";++const locales = ["zh-CN", "en-US", "ja", "pl", "ru"];++describe("memo template gallery", () => {+ test("offers unique templates that do not overlap the default seeds", () => {+ const keys = MEMO_TEMPLATE_GALLERY.map((item) => item.key);+ const seedKeys = new Set(DEFAULT_MEMO_TEMPLATE_SEEDS.map((seed) => seed.key));++ expect(new Set(keys).size).toBe(keys.length);+ expect(keys.filter((key) => seedKeys.has(key))).toEqual([]);+ });++ test("translates every template into every supported language", () => {+ for (const item of MEMO_TEMPLATE_GALLERY) {+ for (const locale of locales) {+ const translation = item.translations[locale];+ expect(translation.title.trim()).not.toBe("");+ expect(translation.description.trim()).not.toBe("");+ expect(translation.contentMarkdown.trim()).not.toBe("");+ }+ }+ });++ test("localizes entries ready to save as user templates", () => {+ const [journal] = MEMO_TEMPLATE_GALLERY;++ expect(localizeMemoTemplateGalleryItem(journal, "pl-PL")).toEqual({+ key: "daily-journal",+ name: journal.translations.pl.title,+ description: journal.translations.pl.description,+ title: journal.translations.pl.title,+ contentMarkdown: journal.translations.pl.contentMarkdown,+ tags: ["template", "daily-journal"],+ });+ expect(localizeMemoTemplateGalleryItem(journal, "ko-KR").name).toBe("Daily Journal");+ expect(localizeMemoTemplateGalleryItem(journal, null).name).toBe("每日日志");+ });++ test("lists the whole gallery in the requested language", () => {+ const entries = listMemoTemplateGallery("ja");++ expect(entries).toHaveLength(MEMO_TEMPLATE_GALLERY.length);+ expect(entries.map((entry) => entry.name)).toEqual(+ MEMO_TEMPLATE_GALLERY.map((item) => item.translations.ja.title),+ );+ });+});diff --git a/packages/shared/src/memo-template-gallery.ts b/packages/shared/src/memo-template-gallery.tsnew file mode 100644index 00000000..e331af66--- /dev/null+++ b/packages/shared/src/memo-template-gallery.ts@@ -0,0 +1,283 @@+import {+ normalizeMemoTemplateSeedLocale,+ type MemoTemplateSeedLocale,+ type MemoTemplateSeedTranslation,+} from "./memo-template-seeds";++/**+ * Optional templates a user can add to their own templates. Unlike the default+ * seeds they are never provisioned into a workspace, so the gallery can grow+ * without changing what new or existing workspaces contain.+ */+export type MemoTemplateGalleryItem = {+ key: string;+ tag: string;+ translations: Record<MemoTemplateSeedLocale, MemoTemplateSeedTranslation>;+};++export type MemoTemplateGalleryEntry = {+ key: string;+ name: string;+ description: string;+ title: string;+ contentMarkdown: string;+ tags: string[];+};++const item = (+ key: string,+ zhCN: MemoTemplateSeedTranslation,+ enUS: MemoTemplateSeedTranslation,+ ja: MemoTemplateSeedTranslation,+ pl: MemoTemplateSeedTranslation,+ ru: MemoTemplateSeedTranslation,+): MemoTemplateGalleryItem => ({+ key,+ tag: key,+ translations: { "zh-CN": zhCN, "en-US": enUS, ja, pl, ru },+});++export const MEMO_TEMPLATE_GALLERY: readonly MemoTemplateGalleryItem[] = [+ item(+ "daily-journal",+ {+ title: "每日日志",+ description: "规划当天重点,记录发生的事情与当日反思。",+ contentMarkdown: "## 🎯 今日三件要事\n\n1. \n2. \n3. \n\n## 📅 今日记录\n\n- \n\n## 🙏 值得感恩\n\n- \n\n## 🌙 今日反思\n\n- 做得好的:\n- 可以改进的:\n- 明天要做的:\n",+ },+ {+ title: "Daily Journal",+ description: "Plan the day's priorities, log what happened, and reflect in the evening.",+ contentMarkdown: "## 🎯 Top 3 for Today\n\n1. \n2. \n3. \n\n## 📅 Log\n\n- \n\n## 🙏 Grateful For\n\n- \n\n## 🌙 Reflection\n\n- What went well:\n- What to improve:\n- Tomorrow:\n",+ },+ {+ title: "デイリージャーナル",+ description: "その日の優先事項を決め、出来事を記録し、一日を振り返ります。",+ contentMarkdown: "## 🎯 今日の3つの重点\n\n1. \n2. \n3. \n\n## 📅 今日の記録\n\n- \n\n## 🙏 感謝していること\n\n- \n\n## 🌙 振り返り\n\n- うまくいったこと:\n- 改善したいこと:\n- 明日やること:\n",+ },+ {+ title: "Dziennik dnia",+ description: "Zaplanuj priorytety dnia, zapisz, co się wydarzyło, i podsumuj dzień wieczorem.",+ contentMarkdown: "## 🎯 Trzy priorytety na dziś\n\n1. \n2. \n3. \n\n## 📅 Przebieg dnia\n\n- \n\n## 🙏 Wdzięczność\n\n- \n\n## 🌙 Refleksja\n\n- Co poszło dobrze:\n- Co poprawić:\n- Na jutro:\n",+ },+ {+ title: "Ежедневный дневник",+ description: "Определите приоритеты дня, запишите, что произошло, и подведите итоги вечером.",+ contentMarkdown: "## 🎯 Три главных дела на сегодня\n\n1. \n2. \n3. \n\n## 📅 Записи за день\n\n- \n\n## 🙏 Благодарность\n\n- \n\n## 🌙 Итоги дня\n\n- Что получилось:\n- Что улучшить:\n- На завтра:\n",+ },+ ),+ item(+ "retrospective",+ {+ title: "复盘回顾",+ description: "回顾一个阶段:哪些做得好、哪些不足,以及具体改进行动。",+ contentMarkdown: "# 🔁 复盘回顾\n\n- **周期**:\n- **参与人**:\n\n## ✅ 做得好的\n\n- \n\n## ⚠️ 不足与问题\n\n- \n\n## 💡 可以尝试的改进\n\n- \n\n## 📋 改进行动\n\n- [ ] **[负责人]** 行动描述 (截止日期:MM-DD)\n",+ },+ {+ title: "Retrospective",+ description: "Look back on a period: what went well, what didn't, and concrete improvements.",+ contentMarkdown: "# 🔁 Retrospective\n\n- **Period**:\n- **Participants**:\n\n## ✅ What Went Well\n\n- \n\n## ⚠️ What Didn't Go Well\n\n- \n\n## 💡 Ideas to Try\n\n- \n\n## 📋 Action Items\n\n- [ ] **[Owner]** Action (Due: MM-DD)\n",+ },+ {+ title: "振り返り",+ description: "一定期間を振り返り、良かった点・課題・具体的な改善策をまとめます。",+ contentMarkdown: "# 🔁 振り返り\n\n- **期間**:\n- **参加者**:\n\n## ✅ 良かったこと\n\n- \n\n## ⚠️ 課題\n\n- \n\n## 💡 試してみたいこと\n\n- \n\n## 📋 改善アクション\n\n- [ ] **[担当者]** アクション (期限:MM-DD)\n",+ },+ {+ title: "Retrospektywa",+ description: "Podsumuj okres pracy: co poszło dobrze, co nie i jakie konkretne usprawnienia wprowadzić.",+ contentMarkdown: "# 🔁 Retrospektywa\n\n- **Okres**:\n- **Uczestnicy**:\n\n## ✅ Co poszło dobrze\n\n- \n\n## ⚠️ Co nie zadziałało\n\n- \n\n## 💡 Co warto wypróbować\n\n- \n\n## 📋 Działania\n\n- [ ] **[Osoba odpowiedzialna]** Działanie (Termin: DD.MM)\n",+ },+ {+ title: "Ретроспектива",+ description: "Оглянитесь на период: что получилось, что нет и какие конкретные улучшения внести.",+ contentMarkdown: "# 🔁 Ретроспектива\n\n- **Период**:\n- **Участники**:\n\n## ✅ Что получилось\n\n- \n\n## ⚠️ Что не получилось\n\n- \n\n## 💡 Что попробовать\n\n- \n\n## 📋 Действия\n\n- [ ] **[Ответственный]** Действие (Срок: ММ-ДД)\n",+ },+ ),+ item(+ "one-on-one",+ {+ title: "一对一沟通",+ description: "记录 1:1 沟通的议题、反馈、共识与后续跟进。",+ contentMarkdown: "# 🤝 一对一沟通\n\n- **时间**:\n- **参与人**:\n\n## 🗂️ 议题\n\n- \n\n## 💬 反馈\n\n- 给对方的:\n- 收到的:\n\n## ✅ 共识\n\n- \n\n## 📋 后续跟进\n\n- [ ] \n",+ },+ {+ title: "1:1 Meeting",+ description: "Track 1:1 topics, feedback both ways, agreements, and follow-ups.",+ contentMarkdown: "# 🤝 1:1 Meeting\n\n- **Date**:\n- **With**:\n\n## 🗂️ Topics\n\n- \n\n## 💬 Feedback\n\n- Given:\n- Received:\n\n## ✅ Agreements\n\n- \n\n## 📋 Follow-ups\n\n- [ ] \n",+ },+ {+ title: "1on1ミーティング",+ description: "1on1 の話題、相互フィードバック、合意事項、フォローアップを記録します。",+ contentMarkdown: "# 🤝 1on1ミーティング\n\n- **日時**:\n- **相手**:\n\n## 🗂️ 話題\n\n- \n\n## 💬 フィードバック\n\n- 伝えたこと:\n- 受け取ったこと:\n\n## ✅ 合意事項\n\n- \n\n## 📋 フォローアップ\n\n- [ ] \n",+ },+ {+ title: "Rozmowa 1:1",+ description: "Zapisuj tematy rozmowy 1:1, wzajemny feedback, ustalenia i dalsze kroki.",+ contentMarkdown: "# 🤝 Rozmowa 1:1\n\n- **Data**:\n- **Z kim**:\n\n## 🗂️ Tematy\n\n- \n\n## 💬 Feedback\n\n- Przekazany:\n- Otrzymany:\n\n## ✅ Ustalenia\n\n- \n\n## 📋 Dalsze kroki\n\n- [ ] \n",+ },+ {+ title: "Встреча 1:1",+ description: "Темы встречи 1:1, взаимная обратная связь, договорённости и следующие шаги.",+ contentMarkdown: "# 🤝 Встреча 1:1\n\n- **Дата**:\n- **С кем**:\n\n## 🗂️ Темы\n\n- \n\n## 💬 Обратная связь\n\n- Дал(а):\n- Получил(а):\n\n## ✅ Договорённости\n\n- \n\n## 📋 Следующие шаги\n\n- [ ] \n",+ },+ ),+ item(+ "project-plan",+ {+ title: "项目计划",+ description: "明确项目目标、范围、里程碑、风险与相关人员。",+ contentMarkdown: "# 🗺️ 项目计划\n\n- **负责人**:\n- **开始 / 截止日期**:\n\n## 🎯 目标\n\n- \n\n## 📦 范围\n\n- 包含:\n- 不包含:\n\n## 🏁 里程碑\n\n- [ ] 里程碑 1 (MM-DD)\n- [ ] 里程碑 2 (MM-DD)\n\n## ⚠️ 风险与应对\n\n- \n\n## 👥 相关人员\n\n- \n",+ },+ {+ title: "Project Plan",+ description: "Define the project's goals, scope, milestones, risks, and stakeholders.",+ contentMarkdown: "# 🗺️ Project Plan\n\n- **Owner**:\n- **Start / Due**:\n\n## 🎯 Goals\n\n- \n\n## 📦 Scope\n\n- In scope:\n- Out of scope:\n\n## 🏁 Milestones\n\n- [ ] Milestone 1 (MM-DD)\n- [ ] Milestone 2 (MM-DD)\n\n## ⚠️ Risks & Mitigations\n\n- \n\n## 👥 Stakeholders\n\n- \n",+ },+ {+ title: "プロジェクト計画",+ description: "プロジェクトの目標、範囲、マイルストーン、リスク、関係者を整理します。",+ contentMarkdown: "# 🗺️ プロジェクト計画\n\n- **責任者**:\n- **開始 / 期限**:\n\n## 🎯 目標\n\n- \n\n## 📦 範囲\n\n- 対象:\n- 対象外:\n\n## 🏁 マイルストーン\n\n- [ ] マイルストーン 1 (MM-DD)\n- [ ] マイルストーン 2 (MM-DD)\n\n## ⚠️ リスクと対策\n\n- \n\n## 👥 関係者\n\n- \n",+ },+ {+ title: "Plan projektu",+ description: "Określ cele projektu, zakres, kamienie milowe, ryzyka i interesariuszy.",+ contentMarkdown: "# 🗺️ Plan projektu\n\n- **Właściciel**:\n- **Start / termin**:\n\n## 🎯 Cele\n\n- \n\n## 📦 Zakres\n\n- W zakresie:\n- Poza zakresem:\n\n## 🏁 Kamienie milowe\n\n- [ ] Kamień milowy 1 (DD.MM)\n- [ ] Kamień milowy 2 (DD.MM)\n\n## ⚠️ Ryzyka i sposoby ograniczenia\n\n- \n\n## 👥 Interesariusze\n\n- \n",+ },+ {+ title: "План проекта",+ description: "Опишите цели проекта, его рамки, вехи, риски и заинтересованных лиц.",+ contentMarkdown: "# 🗺️ План проекта\n\n- **Ответственный**:\n- **Начало / Срок**:\n\n## 🎯 Цели\n\n- \n\n## 📦 Рамки\n\n- Входит:\n- Не входит:\n\n## 🏁 Вехи\n\n- [ ] Веха 1 (ММ-ДД)\n- [ ] Веха 2 (ММ-ДД)\n\n## ⚠️ Риски и меры\n\n- \n\n## 👥 Заинтересованные лица\n\n- \n",+ },+ ),+ item(+ "cornell-notes",+ {+ title: "康奈尔笔记",+ description: "用线索问题、课堂笔记和总结三段式整理学习内容。",+ contentMarkdown: "# 🎓 康奈尔笔记\n\n- **主题**:\n- **来源**:\n\n## ❓ 线索与问题\n\n- \n\n## 📝 笔记\n\n- \n\n## 🧾 总结\n\n\n",+ },+ {+ title: "Cornell Notes",+ description: "Organize what you learn into cue questions, notes, and a summary.",+ contentMarkdown: "# 🎓 Cornell Notes\n\n- **Topic**:\n- **Source**:\n\n## ❓ Cues & Questions\n\n- \n\n## 📝 Notes\n\n- \n\n## 🧾 Summary\n\n\n",+ },+ {+ title: "コーネル式ノート",+ description: "学んだ内容をキーワード・ノート・まとめの3つに整理します。",+ contentMarkdown: "# 🎓 コーネル式ノート\n\n- **テーマ**:\n- **出典**:\n\n## ❓ キーワードと問い\n\n- \n\n## 📝 ノート\n\n- \n\n## 🧾 まとめ\n\n\n",+ },+ {+ title: "Notatka Cornella",+ description: "Porządkuj naukę w trzech częściach: pytania kluczowe, notatki i podsumowanie.",+ contentMarkdown: "# 🎓 Notatka Cornella\n\n- **Temat**:\n- **Źródło**:\n\n## ❓ Pytania kluczowe\n\n- \n\n## 📝 Notatki\n\n- \n\n## 🧾 Podsumowanie\n\n\n",+ },+ {+ title: "Корнелльские заметки",+ description: "Разложите изученное на ключевые вопросы, заметки и краткий итог.",+ contentMarkdown: "# 🎓 Корнелльские заметки\n\n- **Тема**:\n- **Источник**:\n\n## ❓ Ключевые вопросы\n\n- \n\n## 📝 Заметки\n\n- \n\n## 🧾 Итог\n\n\n",+ },+ ),+ item(+ "bug-report",+ {+ title: "问题报告",+ description: "记录复现步骤、预期与实际结果、运行环境和附加信息。",+ contentMarkdown: "# 🐞 问题报告\n\n## 📄 概述\n\n\n\n## 🔁 复现步骤\n\n1. \n2. \n3. \n\n## ✅ 预期结果\n\n\n\n## ❌ 实际结果\n\n\n\n## 🖥️ 运行环境\n\n- 版本:\n- 系统 / 浏览器:\n\n## 📎 附加信息\n\n- \n",+ },+ {+ title: "Bug Report",+ description: "Capture reproduction steps, expected vs. actual results, environment, and extra context.",+ contentMarkdown: "# 🐞 Bug Report\n\n## 📄 Summary\n\n\n\n## 🔁 Steps to Reproduce\n\n1. \n2. \n3. \n\n## ✅ Expected Result\n\n\n\n## ❌ Actual Result\n\n\n\n## 🖥️ Environment\n\n- Version:\n- OS / Browser:\n\n## 📎 Additional Context\n\n- \n",+ },+ {+ title: "不具合報告",+ description: "再現手順、期待結果と実際の結果、環境、補足情報を記録します。",+ contentMarkdown: "# 🐞 不具合報告\n\n## 📄 概要\n\n\n\n## 🔁 再現手順\n\n1. \n2. \n3. \n\n## ✅ 期待される結果\n\n\n\n## ❌ 実際の結果\n\n\n\n## 🖥️ 環境\n\n- バージョン:\n- OS / ブラウザ:\n\n## 📎 補足情報\n\n- \n",+ },+ {+ title: "Raport błędu",+ description: "Zapisz kroki odtworzenia, oczekiwany i faktyczny wynik, środowisko oraz dodatkowy kontekst.",+ contentMarkdown: "# 🐞 Raport błędu\n\n## 📄 Opis\n\n\n\n## 🔁 Kroki odtworzenia\n\n1. \n2. \n3. \n\n## ✅ Oczekiwany wynik\n\n\n\n## ❌ Faktyczny wynik\n\n\n\n## 🖥️ Środowisko\n\n- Wersja:\n- System / przeglądarka:\n\n## 📎 Dodatkowy kontekst\n\n- \n",+ },+ {+ title: "Отчёт об ошибке",+ description: "Зафиксируйте шаги воспроизведения, ожидаемый и фактический результат, окружение и контекст.",+ contentMarkdown: "# 🐞 Отчёт об ошибке\n\n## 📄 Кратко\n\n\n\n## 🔁 Шаги воспроизведения\n\n1. \n2. \n3. \n\n## ✅ Ожидаемый результат\n\n\n\n## ❌ Фактический результат\n\n\n\n## 🖥️ Окружение\n\n- Версия:\n- ОС / браузер:\n\n## 📎 Дополнительно\n\n- \n",+ },+ ),+ item(+ "decision-record",+ {+ title: "决策记录",+ description: "记录决策背景、备选方案、最终决定及其影响。",+ contentMarkdown: "# ⚖️ 决策记录\n\n- **日期**:\n- **状态**:提议 / 已采纳 / 已废弃\n- **决策人**:\n\n## 🧭 背景\n\n\n\n## 🔀 备选方案\n\n1. **方案 A**:\n - 优点:\n - 缺点:\n2. **方案 B**:\n - 优点:\n - 缺点:\n\n## ✅ 决定\n\n\n\n## 📈 影响\n\n- \n",+ },+ {+ title: "Decision Record",+ description: "Document the context, options considered, the decision, and its consequences.",+ contentMarkdown: "# ⚖️ Decision Record\n\n- **Date**:\n- **Status**: Proposed / Accepted / Superseded\n- **Decided by**:\n\n## 🧭 Context\n\n\n\n## 🔀 Options Considered\n\n1. **Option A**:\n - Pros:\n - Cons:\n2. **Option B**:\n - Pros:\n - Cons:\n\n## ✅ Decision\n\n\n\n## 📈 Consequences\n\n- \n",+ },+ {+ title: "意思決定記録",+ description: "背景、検討した選択肢、決定内容とその影響を記録します。",+ contentMarkdown: "# ⚖️ 意思決定記録\n\n- **日付**:\n- **ステータス**:提案 / 採用 / 廃止\n- **決定者**:\n\n## 🧭 背景\n\n\n\n## 🔀 検討した選択肢\n\n1. **案 A**:\n - 長所:\n - 短所:\n2. **案 B**:\n - 長所:\n - 短所:\n\n## ✅ 決定\n\n\n\n## 📈 影響\n\n- \n",+ },+ {+ title: "Rejestr decyzji",+ description: "Opisz kontekst, rozważane opcje, podjętą decyzję i jej konsekwencje.",+ contentMarkdown: "# ⚖️ Rejestr decyzji\n\n- **Data**:\n- **Status**: Proponowana / Przyjęta / Zastąpiona\n- **Decyzja podjęta przez**:\n\n## 🧭 Kontekst\n\n\n\n## 🔀 Rozważane opcje\n\n1. **Opcja A**:\n - Zalety:\n - Wady:\n2. **Opcja B**:\n - Zalety:\n - Wady:\n\n## ✅ Decyzja\n\n\n\n## 📈 Konsekwencje\n\n- \n",+ },+ {+ title: "Запись решения",+ description: "Задокументируйте контекст, рассмотренные варианты, принятое решение и его последствия.",+ contentMarkdown: "# ⚖️ Запись решения\n\n- **Дата**:\n- **Статус**: Предложено / Принято / Заменено\n- **Кто решил**:\n\n## 🧭 Контекст\n\n\n\n## 🔀 Рассмотренные варианты\n\n1. **Вариант A**:\n - Плюсы:\n - Минусы:\n2. **Вариант B**:\n - Плюсы:\n - Минусы:\n\n## ✅ Решение\n\n\n\n## 📈 Последствия\n\n- \n",+ },+ ),+ item(+ "travel-checklist",+ {+ title: "旅行清单",+ description: "整理行程、预订信息、行李清单和出发前待办。",+ contentMarkdown: "# ✈️ 旅行清单\n\n- **目的地**:\n- **日期**:\n\n## 🗓️ 行程\n\n- 第 1 天:\n- 第 2 天:\n\n## 🎫 预订信息\n\n- 交通:\n- 住宿:\n\n## 🧳 行李清单\n\n- [ ] 证件\n- [ ] 充电器\n- [ ] 衣物\n- [ ] 洗漱用品\n- [ ] 常用药品\n\n## ✅ 出发前待办\n\n- [ ] \n",+ },+ {+ title: "Travel Checklist",+ description: "Keep the itinerary, bookings, packing list, and pre-departure to-dos in one place.",+ contentMarkdown: "# ✈️ Travel Checklist\n\n- **Destination**:\n- **Dates**:\n\n## 🗓️ Itinerary\n\n- Day 1:\n- Day 2:\n\n## 🎫 Bookings\n\n- Transport:\n- Accommodation:\n\n## 🧳 Packing List\n\n- [ ] Documents\n- [ ] Chargers\n- [ ] Clothes\n- [ ] Toiletries\n- [ ] Medication\n\n## ✅ Before Leaving\n\n- [ ] \n",+ },+ {+ title: "旅行チェックリスト",+ description: "旅程、予約情報、持ち物リスト、出発前のやることをまとめます。",+ contentMarkdown: "# ✈️ 旅行チェックリスト\n\n- **行き先**:\n- **日程**:\n\n## 🗓️ 旅程\n\n- 1 日目:\n- 2 日目:\n\n## 🎫 予約情報\n\n- 交通:\n- 宿泊:\n\n## 🧳 持ち物リスト\n\n- [ ] 身分証明書\n- [ ] 充電器\n- [ ] 衣類\n- [ ] 洗面用具\n- [ ] 常備薬\n\n## ✅ 出発前のやること\n\n- [ ] \n",+ },+ {+ title: "Lista podróży",+ description: "Zbierz w jednym miejscu plan podróży, rezerwacje, listę pakowania i sprawy do załatwienia przed wyjazdem.",+ contentMarkdown: "# ✈️ Lista podróży\n\n- **Cel podróży**:\n- **Termin**:\n\n## 🗓️ Plan\n\n- Dzień 1:\n- Dzień 2:\n\n## 🎫 Rezerwacje\n\n- Transport:\n- Nocleg:\n\n## 🧳 Lista pakowania\n\n- [ ] Dokumenty\n- [ ] Ładowarki\n- [ ] Ubrania\n- [ ] Kosmetyki\n- [ ] Leki\n\n## ✅ Przed wyjazdem\n\n- [ ] \n",+ },+ {+ title: "Чек-лист поездки",+ description: "Маршрут, бронирования, список вещей и дела перед отъездом в одном месте.",+ contentMarkdown: "# ✈️ Чек-лист поездки\n\n- **Куда**:\n- **Даты**:\n\n## 🗓️ Маршрут\n\n- День 1:\n- День 2:\n\n## 🎫 Бронирования\n\n- Транспорт:\n- Жильё:\n\n## 🧳 Список вещей\n\n- [ ] Документы\n- [ ] Зарядки\n- [ ] Одежда\n- [ ] Средства гигиены\n- [ ] Лекарства\n\n## ✅ Перед отъездом\n\n- [ ] \n",+ },+ ),+];++export const localizeMemoTemplateGalleryItem = (+ galleryItem: MemoTemplateGalleryItem,+ locale: string | null | undefined,+): MemoTemplateGalleryEntry => {+ const translation = galleryItem.translations[normalizeMemoTemplateSeedLocale(locale)];+ return {+ key: galleryItem.key,+ name: translation.title,+ description: translation.description,+ title: translation.title,+ contentMarkdown: translation.contentMarkdown,+ tags: ["template", galleryItem.tag],+ };+};++export const listMemoTemplateGallery = (locale: string | null | undefined): MemoTemplateGalleryEntry[] =>+ MEMO_TEMPLATE_GALLERY.map((galleryItem) => localizeMemoTemplateGalleryItem(galleryItem, locale));diff --git a/tests/template-gallery-errors.test.ts b/tests/template-gallery-errors.test.tsnew file mode 100644index 00000000..46e0a4af--- /dev/null+++ b/tests/template-gallery-errors.test.ts@@ -0,0 +1,35 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";++const read = (path: string) => readFileSync(new URL(path, import.meta.url), "utf8");+const templatesPaneSource = read("../apps/web/src/components/TemplatesPane.tsx");+const workspaceSource = read("../apps/web/src/components/WorkspaceApp.tsx");++describe("template gallery save failures", () => {+ test("shows a notice when creating a template fails", () => {+ const start = workspaceSource.indexOf("const createTemplateMutation = useMutation({");+ const end = workspaceSource.indexOf("const useTemplateMutation", start);+ const mutation = workspaceSource.slice(start, end);+ expect(mutation).toContain("onError:");+ expect(mutation).toContain('t("templates.createFailedTitle")');+ expect(mutation).toContain('t("templates.createFailed")');+ });++ test("handles a rejected gallery add instead of leaving it unhandled", () => {+ const start = templatesPaneSource.indexOf("const addGalleryTemplate = async");+ const end = templatesPaneSource.indexOf("const draftHtmlPreview", start);+ const handler = templatesPaneSource.slice(start, end);+ expect(handler).toContain("} catch {");+ expect(handler).toContain("setAddingGalleryKey(null);");+ });++ test("ignores a second gallery add while the first is still saving", () => {+ const start = templatesPaneSource.indexOf("const addGalleryTemplate = async");+ const end = templatesPaneSource.indexOf("const draftHtmlPreview", start);+ const handler = templatesPaneSource.slice(start, end);+ expect(handler.indexOf("if (addingGalleryRef.current) return;"))+ .toBeLessThan(handler.indexOf("await onCreateSavedTemplate"));+ expect(handler).toContain("addingGalleryRef.current = true;");+ expect(handler).toContain("addingGalleryRef.current = false;");+ });+});