diff --git a/app/actions/definitions/templates.tsx b/app/actions/definitions/templates.tsx
index 130faf1071..59d973ea8f 100644
--- a/app/actions/definitions/templates.tsx
+++ b/app/actions/definitions/templates.tsx
@@ -8,10 +8,13 @@ import {
NewDocumentIcon,
PlusIcon,
PrintIcon,
+ PublishIcon,
TrashIcon,
} from "outline-icons";
import { Trans } from "react-i18next";
import { toast } from "sonner";
+import { errToString } from "@shared/utils/error";
+import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import ConfirmationDialog from "~/components/ConfirmationDialog";
import TemplateMove from "~/components/DocumentExplorer/TemplateMove";
import {
@@ -86,6 +89,34 @@ export const deleteTemplate = createAction({
},
});
+export const publishTemplate = createAction({
+ name: ({ t }) => t("Publish"),
+ analyticsName: "Publish template",
+ section: ActiveTemplateSection,
+ icon: ,
+ visible: ({ getActiveModel, getActivePolicies }) =>
+ !!getActiveModel(Template)?.isDraft &&
+ getActivePolicies(Template).some((policy) => policy.abilities.update),
+ perform: async ({ getActiveModel, t }) => {
+ const template = getActiveModel(Template);
+ if (!template) {
+ return;
+ }
+
+ if (!template.data || ProsemirrorDataHelper.isEmpty(template.data)) {
+ toast.message(t("A template must have content"));
+ return;
+ }
+
+ try {
+ await template.publish();
+ toast.success(t("Template published"));
+ } catch (error) {
+ toast.error(errToString(error));
+ }
+ },
+});
+
export const moveTemplateToWorkspace = createAction({
name: ({ t }) => t("Move to workspace"),
analyticsName: "Move template to workspace",
@@ -119,6 +150,7 @@ export const moveTemplateToCollection = createAction({
analyticsName: "Move template to collection",
section: ActiveTemplateSection,
icon: ,
+ visible: ({ getActiveModel }) => !!getActiveModel(Template),
perform: ({ getActiveModel, stores, t }) => {
const template = getActiveModel(Template);
if (!template) {
@@ -202,6 +234,7 @@ export const copyTemplateLink = createAction({
section: ActiveTemplateSection,
icon: ,
iconInContextMenu: false,
+ visible: ({ getActiveModel }) => !!getActiveModel(Template),
perform: ({ getActiveModel, t }) => {
const template = getActiveModel(Template);
if (template) {
@@ -217,6 +250,7 @@ export const copyTemplateAsPlainText = createAction({
section: ActiveTemplateSection,
icon: ,
iconInContextMenu: false,
+ visible: ({ getActiveModel }) => !!getActiveModel(Template),
perform: async ({ getActiveModel, t }) => {
const template = getActiveModel(Template);
if (template) {
@@ -232,6 +266,7 @@ export const copyTemplate = createActionWithChildren({
section: ActiveTemplateSection,
icon: ,
keywords: "clipboard",
+ visible: ({ getActiveModel }) => !!getActiveModel(Template),
children: [copyTemplateLink, copyTemplateAsPlainText],
});
@@ -246,4 +281,13 @@ export const printTemplate = createAction({
},
});
-export const rootTemplateActions = [moveTemplate, createDocumentFromTemplate];
+export const rootTemplateActions = [
+ createTemplate,
+ publishTemplate,
+ duplicateTemplate,
+ moveTemplate,
+ createDocumentFromTemplate,
+ copyTemplate,
+ printTemplate,
+ deleteTemplate,
+];
diff --git a/app/actions/root.ts b/app/actions/root.ts
index 7d64029a65..20a4f18364 100644
--- a/app/actions/root.ts
+++ b/app/actions/root.ts
@@ -6,6 +6,7 @@ import { rootNotificationActions } from "./definitions/notifications";
import { rootRevisionActions } from "./definitions/revisions";
import { rootSettingsActions } from "./definitions/settings";
import { rootTeamActions } from "./definitions/teams";
+import { rootTemplateActions } from "./definitions/templates";
import { rootUserActions } from "./definitions/users";
export default [
@@ -18,4 +19,5 @@ export default [
...rootSettingsActions,
...rootDeveloperActions,
...rootTeamActions,
+ ...rootTemplateActions,
];
diff --git a/app/components/Notice.tsx b/app/components/Notice.tsx
index 6a2d804f3f..6f8f59be9e 100644
--- a/app/components/Notice.tsx
+++ b/app/components/Notice.tsx
@@ -8,10 +8,16 @@ type Props = {
children?: React.ReactNode;
icon?: JSX.Element;
description?: JSX.Element;
+ className?: string;
};
-const Notice: React.FC = ({ children, icon, description }: Props) => (
-
+const Notice: React.FC = ({
+ children,
+ icon,
+ description,
+ className,
+}: Props) => (
+
{icon}
diff --git a/app/components/Template/TemplateForm.tsx b/app/components/Template/TemplateForm.tsx
index c92f492f2e..a2cd1e2d61 100644
--- a/app/components/Template/TemplateForm.tsx
+++ b/app/components/Template/TemplateForm.tsx
@@ -1,18 +1,29 @@
+import { debounce } from "es-toolkit/compat";
import { observer } from "mobx-react";
import { InputIcon, ShapesIcon } from "outline-icons";
-import React, { useRef } from "react";
+import React, { useCallback, useEffect, useMemo, useRef } from "react";
import { Trans, useTranslation } from "react-i18next";
+import { Prompt } from "react-router-dom";
+import { toast } from "sonner";
import styled from "styled-components";
import type { ProsemirrorData } from "@shared/types";
+import { errToString } from "@shared/utils/error";
import type Template from "~/models/Template";
import Editor from "~/scenes/Document/components/Editor";
import { DocumentContextProvider } from "~/components/DocumentContext";
import LoadingIndicator from "~/components/LoadingIndicator";
import Notice from "~/components/Notice";
import useBoolean from "~/hooks/useBoolean";
+import useCurrentUser from "~/hooks/useCurrentUser";
+import useEventListener from "~/hooks/useEventListener";
import usePolicy from "~/hooks/usePolicy";
import useStores from "~/hooks/useStores";
+const AUTOSAVE_DELAY = 1000;
+
+/** The fields this form is able to edit. */
+type TemplateEdits = Pick;
+
export const TemplateForm = observer(function TemplateForm_({
handleSubmit,
template,
@@ -22,46 +33,141 @@ export const TemplateForm = observer(function TemplateForm_({
}) {
const { dialogs } = useStores();
const { t } = useTranslation();
+ const user = useCurrentUser();
const can = usePolicy(template);
- const dataRef = useRef(template.data);
+ const editsRef = useRef>({});
const ref = useRef(null);
const [isUploading, handleStartUpload, handleStopUpload] = useBoolean();
const readOnly = !can.update && !template.isNew;
+ const saveRef = useRef<() => Promise>(() => Promise.resolve());
+ const saveFailedRef = useRef(false);
+
+ const autosave = useMemo(
+ () => debounce(() => void saveRef.current(), AUTOSAVE_DELAY),
+ []
+ );
+
+ // The API response is applied back over the model, so anything edited while a
+ // request is in flight has to be re-applied once it lands.
+ const applyEdits = useCallback(() => {
+ Object.assign(template, editsRef.current);
+ }, [template]);
+
+ const save = useCallback(async () => {
+ if (template.isSaving) {
+ return;
+ }
+
+ applyEdits();
+ if (!template.isDirty()) {
+ return;
+ }
+
+ try {
+ await template.save();
+ saveFailedRef.current = false;
+ } catch (error) {
+ saveFailedRef.current = true;
+ toast.error(errToString(error));
+ return;
+ }
+
+ applyEdits();
+ if (template.isDirty()) {
+ autosave();
+ }
+ }, [template, applyEdits, autosave]);
+
+ useEffect(() => {
+ saveRef.current = save;
+ });
+
const handleChangeTitle = (title: string) => {
- template.title = title;
+ editsRef.current.title = title;
+ applyEdits();
+ autosave();
};
const handleChangeIcon = (icon: string, color: string) => {
- template.icon = icon;
- template.color = color;
+ editsRef.current.icon = icon;
+ editsRef.current.color = color;
+ applyEdits();
+ autosave();
};
const handleChange = (value: (asString: boolean) => ProsemirrorData) => {
- dataRef.current = value(false);
- template.data = dataRef.current;
+ editsRef.current.data = value(false);
+ applyEdits();
+ autosave();
};
- const handleSave = (options: { autosave?: boolean }) => {
- if (options.autosave) {
+ const handleSave = (options: { done?: boolean; autosave?: boolean }) => {
+ if (options.done) {
+ handleSubmit(template);
return;
}
- handleSubmit(template);
+
+ autosave.cancel();
+ void save();
};
const handleCancel = () => {
dialogs.closeAllModals();
};
+ const handleUnload = (event: BeforeUnloadEvent) => {
+ if (template.isDirty()) {
+ event.preventDefault();
+ event.returnValue = "";
+ }
+ };
+
+ // Changes are flushed on unmount, so navigation is only worth blocking when
+ // saving them has already failed.
+ const handleBlockNavigation = () =>
+ saveFailedRef.current && template.isDirty()
+ ? t(`Your changes couldn’t be saved.\nAre you sure you want to leave?`)
+ : true;
+
+ useEventListener("beforeunload", handleUnload);
+
+ // Flush anything the debounce hasn't caught yet, and clean up after a draft
+ // that was opened but never written to.
+ useEffect(
+ () => () => {
+ autosave.cancel();
+
+ if (readOnly) {
+ return;
+ }
+
+ applyEdits();
+
+ if (
+ template.isDraft &&
+ template.isEmpty &&
+ template.createdBy?.id === user.id
+ ) {
+ void template.delete();
+ } else if (template.isDirty()) {
+ void saveRef.current();
+ }
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ []
+ );
+
if (!template) {
return null;
}
return (
+
{isUploading && }
- }
description={
@@ -71,7 +177,7 @@ export const TemplateForm = observer(function TemplateForm_({
}
>
{t("You’re editing a template")}
-
+
template.isActive && !!template.data
+ const allTemplates = templatesStore.published.filter(
+ (template) => !!template.data
);
const hasTemplates = allTemplates.some(
(template) =>
@@ -100,7 +100,7 @@ function useTemplateMenuItem(): MenuItem | undefined {
keywords: "template",
children,
} satisfies MenuItem;
- }, [user, templatesStore.orderedData, collectionId, editor, t]);
+ }, [user, templatesStore.published, collectionId, editor, t]);
}
type Props = Omit &
diff --git a/app/hooks/useTemplateMenuActions.tsx b/app/hooks/useTemplateMenuActions.tsx
index 4e70857d73..097bfd126c 100644
--- a/app/hooks/useTemplateMenuActions.tsx
+++ b/app/hooks/useTemplateMenuActions.tsx
@@ -66,9 +66,7 @@ export function useTemplateMenuActions({
return [];
}
- const templates = templatesStore.orderedData.filter(
- (template) => template.isActive
- );
+ const templates = templatesStore.published;
const collectionTemplatesActions = templates
.filter(
diff --git a/app/hooks/useTemplateSettingsActions.tsx b/app/hooks/useTemplateSettingsActions.tsx
index 78b365ec90..1ca156379c 100644
--- a/app/hooks/useTemplateSettingsActions.tsx
+++ b/app/hooks/useTemplateSettingsActions.tsx
@@ -5,10 +5,10 @@ import type Template from "~/models/Template";
import { ActionSeparator, createAction } from "~/actions";
import {
copyTemplate,
- createDocumentFromTemplate,
deleteTemplate,
duplicateTemplate,
moveTemplate,
+ publishTemplate,
} from "~/actions/definitions/templates";
import { ActiveTemplateSection } from "~/actions/sections";
import usePolicy from "~/hooks/usePolicy";
@@ -40,10 +40,10 @@ export function useTemplateSettingsActions(
section: ActiveTemplateSection,
perform: () => onEdit?.(),
}),
+ publishTemplate,
duplicateTemplate,
moveTemplate,
ActionSeparator,
- createDocumentFromTemplate,
copyTemplate,
ActionSeparator,
deleteTemplate,
diff --git a/app/menus/TemplateMenu.tsx b/app/menus/TemplateMenu.tsx
index 19a4c7605e..1865e0e7a3 100644
--- a/app/menus/TemplateMenu.tsx
+++ b/app/menus/TemplateMenu.tsx
@@ -10,9 +10,11 @@ import { useTemplateSettingsActions } from "~/hooks/useTemplateSettingsActions";
type Props = {
template: Template;
onEdit?: () => void;
+ /** Whether to render the trigger as a neutral button with a border on hover */
+ neutral?: boolean;
};
-function TemplateMenu({ template, onEdit }: Props) {
+function TemplateMenu({ template, onEdit, neutral }: Props) {
const { t } = useTranslation();
const rootAction = useTemplateSettingsActions(template, onEdit);
@@ -23,7 +25,7 @@ function TemplateMenu({ template, onEdit }: Props) {
align="end"
ariaLabel={t("Template options")}
>
-
+
);
diff --git a/app/models/Template.test.ts b/app/models/Template.test.ts
new file mode 100644
index 0000000000..c60a6d5df0
--- /dev/null
+++ b/app/models/Template.test.ts
@@ -0,0 +1,65 @@
+import stores from "~/stores";
+import Template from "./Template";
+
+describe("Template model", () => {
+ const templates = stores.templates;
+
+ describe("isDraft", () => {
+ it("should be true when the template has not been published", () => {
+ const template = new Template(
+ { id: "123", title: "Untitled" },
+ templates
+ );
+ expect(template.isDraft).toBe(true);
+ });
+
+ it("should be false once the template has been published", () => {
+ const template = new Template(
+ {
+ id: "124",
+ title: "Untitled",
+ publishedAt: "2026-08-08T00:00:00.000Z",
+ },
+ templates
+ );
+ expect(template.isDraft).toBe(false);
+ });
+ });
+
+ describe("isEmpty", () => {
+ it("should be true without a title or content", () => {
+ const template = new Template({ id: "125", title: "" }, templates);
+ expect(template.isEmpty).toBe(true);
+ });
+
+ it("should be true when the title is only whitespace", () => {
+ const template = new Template({ id: "126", title: " " }, templates);
+ expect(template.isEmpty).toBe(true);
+ });
+
+ it("should be false with a title", () => {
+ const template = new Template({ id: "127", title: "Weekly" }, templates);
+ expect(template.isEmpty).toBe(false);
+ });
+
+ it("should be false with content", () => {
+ const template = new Template(
+ {
+ id: "128",
+ title: "",
+ data: {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "hello" }],
+ },
+ ],
+ },
+ },
+ templates
+ );
+ expect(template.isEmpty).toBe(false);
+ });
+ });
+});
diff --git a/app/models/Template.ts b/app/models/Template.ts
index a1d96bb2fe..b15bc6c178 100644
--- a/app/models/Template.ts
+++ b/app/models/Template.ts
@@ -2,6 +2,7 @@ import { addDays } from "date-fns";
import i18n from "i18next";
import { computed, observable } from "mobx";
import type { ProsemirrorData } from "@shared/types";
+import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
import { isRTL } from "@shared/utils/rtl";
import slugify from "@shared/utils/slugify";
import type TemplatesStore from "~/stores/TemplatesStore";
@@ -89,6 +90,21 @@ export default class Template extends ParanoidModel implements Searchable {
@observable
urlId: string;
+ /**
+ * The date the template was published, and so made available to other members
+ * of the workspace.
+ */
+ @observable
+ publishedAt: string | undefined;
+
+ /**
+ * Publishes the template, making it available to other members of the
+ * workspace.
+ *
+ * @returns a promise that resolves when the template has been published.
+ */
+ publish = () => this.save(undefined, { publish: true });
+
/**
* Returns the direction of the template text, either "rtl" or "ltr"
*/
@@ -124,11 +140,31 @@ export default class Template extends ParanoidModel implements Searchable {
return this.title === "";
}
+ /**
+ * Whether the template has neither a title nor any content.
+ */
+ @computed
+ get isEmpty(): boolean {
+ return (
+ !this.title?.trim() &&
+ (!this.data || ProsemirrorDataHelper.isEmpty(this.data))
+ );
+ }
+
@computed
get isWorkspaceTemplate(): boolean {
return !this.collectionId;
}
+ /**
+ * Whether the template is an unpublished draft, only visible to the user that
+ * created it.
+ */
+ @computed
+ get isDraft(): boolean {
+ return !this.publishedAt;
+ }
+
@computed
get permanentlyDeletedAt(): string | undefined {
if (!this.deletedAt) {
diff --git a/app/scenes/Settings/Template.tsx b/app/scenes/Settings/Template.tsx
index 009d22f471..b0dd9c1320 100644
--- a/app/scenes/Settings/Template.tsx
+++ b/app/scenes/Settings/Template.tsx
@@ -16,6 +16,7 @@ import Scene from "~/components/Scene";
import { TemplateForm } from "~/components/Template/TemplateForm";
import { createInternalLinkAction } from "~/actions";
import { NavigationSection } from "~/actions/sections";
+import { ActionContextProvider } from "~/hooks/useActionContext";
import useRequest from "~/hooks/useRequest";
import useStores from "~/hooks/useStores";
import TemplateMenu from "~/menus/TemplateMenu";
@@ -99,7 +100,7 @@ const TemplateSetting = observer(function Template_({ template }: Props) {
setSaving(true);
try {
- await template.save();
+ await (template.isDraft ? template.publish() : template.save());
history.push(settingsPath("templates"));
} catch (error) {
toast.error(errToString(error));
@@ -109,24 +110,26 @@ const TemplateSetting = observer(function Template_({ template }: Props) {
}, [template, t]);
return (
- }
- actions={
- <>
-
-
-
-
-
-
- >
- }
- >
-
-
+
+ }
+ actions={
+ <>
+
+
+
+
+
+
+ >
+ }
+ >
+
+
+
);
});
diff --git a/app/scenes/Settings/TemplateNew.tsx b/app/scenes/Settings/TemplateNew.tsx
index d154287218..6369a3debf 100644
--- a/app/scenes/Settings/TemplateNew.tsx
+++ b/app/scenes/Settings/TemplateNew.tsx
@@ -1,88 +1,43 @@
import { observer } from "mobx-react";
-import { ShapesIcon } from "outline-icons";
-import { useCallback, useMemo, useState } from "react";
+import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
-import { errToString } from "@shared/utils/error";
-import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
-import Template from "~/models/Template";
-import { Action } from "~/components/Actions";
-import Breadcrumb from "~/components/Breadcrumb";
-import Button from "~/components/Button";
-import CollectionIcon from "~/components/Icons/CollectionIcon";
+import PlaceholderDocument from "~/components/PlaceholderDocument";
import Scene from "~/components/Scene";
-import { TemplateForm } from "~/components/Template/TemplateForm";
-import { createInternalLinkAction } from "~/actions";
-import { NavigationSection } from "~/actions/sections";
import useQuery from "~/hooks/useQuery";
import useStores from "~/hooks/useStores";
-import { collectionPath, settingsPath } from "~/utils/routeHelpers";
+import { settingsPath } from "~/utils/routeHelpers";
import history from "~/utils/history";
function TemplateNewScene() {
const { t } = useTranslation();
- const { templates, collections } = useStores();
+ const { templates } = useStores();
const params = useQuery();
const collectionId = params.get("collectionId") || undefined;
- const collection = collectionId ? collections.get(collectionId) : undefined;
- const [template] = useState(
- () => new Template({ title: "", collectionId }, templates)
- );
- const [saving, setSaving] = useState(false);
-
- const breadcrumbActions = useMemo(
- () => [
- createInternalLinkAction({
- name: t("Templates"),
- section: NavigationSection,
- icon: ,
- to: settingsPath("templates"),
- }),
- ...(collection
- ? [
- createInternalLinkAction({
- name: collection.name,
- section: NavigationSection,
- icon: ,
- to: collectionPath(collection),
- }),
- ]
- : []),
- ],
- [t, collection]
- );
-
- const handleSubmit = useCallback(async () => {
- if (!template.data || ProsemirrorDataHelper.isEmpty(template.data)) {
- toast.message(t("A template must have content"));
- return;
+ useEffect(() => {
+ // The template is created up front, as an unpublished draft, so that
+ // anything written is persisted from the very first keystroke.
+ async function createTemplate() {
+ try {
+ const template = await templates.create(
+ { title: "", collectionId },
+ { publish: false }
+ );
+ history.replace(template.path);
+ } catch (_err) {
+ toast.error(t("Couldn’t create the template, try again?"));
+ history.replace(settingsPath("templates"));
+ }
}
- setSaving(true);
- try {
- await template.save();
- history.push(settingsPath("templates"));
- } catch (error) {
- toast.error(errToString(error));
- } finally {
- setSaving(false);
- }
- }, [template, t]);
+ void createTemplate();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
return (
- }
- actions={
-
-
-
- }
- >
-
+
+
);
}
diff --git a/app/scenes/Settings/components/TemplatesTable.tsx b/app/scenes/Settings/components/TemplatesTable.tsx
index 10e9234a1c..88fc512453 100644
--- a/app/scenes/Settings/components/TemplatesTable.tsx
+++ b/app/scenes/Settings/components/TemplatesTable.tsx
@@ -1,6 +1,6 @@
import { compact } from "es-toolkit/compat";
import { observer } from "mobx-react";
-import { DocumentIcon } from "outline-icons";
+import { ShapesIcon } from "outline-icons";
import React, { useCallback } from "react";
import { useTranslation } from "react-i18next";
import styled, { useTheme } from "styled-components";
@@ -8,7 +8,7 @@ import Flex from "@shared/components/Flex";
import Icon from "@shared/components/Icon";
import { hover } from "@shared/styles";
import type Template from "~/models/Template";
-import ButtonLink from "~/components/ButtonLink";
+import Badge from "~/components/Badge";
import { HEADER_HEIGHT } from "~/components/Header";
import CollectionIcon from "~/components/Icons/CollectionIcon";
import { ContextMenu } from "~/components/Menu/ContextMenu";
@@ -20,12 +20,14 @@ import { type Column as TableColumn } from "~/components/Table";
import { UserLabel } from "~/components/UserLabel";
import Text from "~/components/Text";
import Time from "~/components/Time";
+import Tooltip from "~/components/Tooltip";
import { ActionContextProvider } from "~/hooks/useActionContext";
import { useTemplateSettingsActions } from "~/hooks/useTemplateSettingsActions";
import TemplateMenu from "~/menus/TemplateMenu";
import { FILTER_HEIGHT } from "./StickyFilters";
import history from "~/utils/history";
import usePolicy from "~/hooks/usePolicy";
+import { Link } from "react-router-dom";
const ROW_HEIGHT = 50;
const STICKY_OFFSET = HEADER_HEIGHT + FILTER_HEIGHT;
@@ -80,9 +82,7 @@ export function TemplatesTable(props: Props) {
id: "title",
header: t("Title"),
accessor: (template) => template.titleWithDefault,
- component: (template) => (
-
- ),
+ component: (template) => ,
width: "4fr",
},
{
@@ -140,43 +140,41 @@ export function TemplatesTable(props: Props) {
);
}
-const TemplateLink = observer(
- ({
- template,
- onClick,
- }: {
- template: Template;
- onClick: (template: Template) => void;
- }) => {
- const theme = useTheme();
- const can = usePolicy(template);
- const content = (
-
- {template.icon ? (
-
- ) : (
-
- )}
- {can.update ? (
- {template.titleWithDefault}
- ) : (
- {template.titleWithDefault}
- )}
-
- );
+const TemplateLink = observer(({ template }: { template: Template }) => {
+ const theme = useTheme();
+ const { t } = useTranslation();
+ const can = usePolicy(template);
+ const content = (
+
+ {template.icon ? (
+
+ ) : (
+
+ )}
+ {can.update ? (
+ {template.titleWithDefault}
+ ) : (
+ {template.titleWithDefault}
+ )}
+ {template.isDraft && (
+
+ {t("Draft")}
+
+ )}
+
+ );
- if (!can.update) {
- return content;
- }
-
- return onClick(template)}>{content};
+ if (!can.update) {
+ return content;
}
-);
+
+ return {content};
+});
const Permission = observer(({ template }: { template: Template }) => {
const { t } = useTranslation();
diff --git a/app/stores/TemplatesStore.ts b/app/stores/TemplatesStore.ts
index 410d984719..94c65cdb71 100644
--- a/app/stores/TemplatesStore.ts
+++ b/app/stores/TemplatesStore.ts
@@ -12,9 +12,19 @@ export default class TemplatesStore extends Store {
super(rootStore, Template);
}
+ /**
+ * Templates that are published, and so available to insert into documents.
+ */
+ @computed
+ get published(): Template[] {
+ return this.orderedData.filter(
+ (template) => template.isActive && !template.isDraft
+ );
+ }
+
@computed
get alphabetical(): Template[] {
- return naturalSort(Array.from(this.data.values()), "title");
+ return naturalSort(this.published, "title");
}
@computed
diff --git a/server/models/Template.ts b/server/models/Template.ts
index a3a304ed6a..acfc5460ac 100644
--- a/server/models/Template.ts
+++ b/server/models/Template.ts
@@ -206,6 +206,16 @@ class Template extends ParanoidModel<
return !this.collectionId;
}
+ /**
+ * Returns whether this template is an unpublished draft, only visible to the
+ * user that created it.
+ *
+ * @returns boolean
+ */
+ get isDraft() {
+ return !this.publishedAt;
+ }
+
@BeforeValidate
static createUrlId(model: Template) {
return (model.urlId = model.urlId || generateUrlId());
diff --git a/server/policies/template.ts b/server/policies/template.ts
index b1d9b9020e..1228c3cdc3 100644
--- a/server/policies/template.ts
+++ b/server/policies/template.ts
@@ -14,6 +14,7 @@ allow(User, "updateTemplate", Team, (actor, team) =>
allow(User, "read", Template, (actor, template) =>
and(
isTeamModel(actor, template),
+ or(!template?.isDraft, template?.createdById === actor.id),
or(
and(!!template?.isWorkspaceTemplate, can(actor, "read", actor.team)),
can(actor, "readDocument", template?.collection)
diff --git a/server/routes/api/templates/schema.ts b/server/routes/api/templates/schema.ts
index 705e6ad93e..6c517eeac5 100644
--- a/server/routes/api/templates/schema.ts
+++ b/server/routes/api/templates/schema.ts
@@ -39,13 +39,16 @@ export const TemplatesCreateSchema = BaseSchema.extend({
body: z.object({
id: z.string().uuid().optional(),
collectionId: z.string().uuid().optional(),
- title: z.string().min(1).max(255),
- data: ProsemirrorSchema(),
+ title: z.string().max(255).optional(),
+ data: ProsemirrorSchema({ allowEmpty: true }).optional(),
icon: zodIconType().nullish(),
color: z
.string()
.regex(ValidateColor.regex, { message: ValidateColor.message })
.nullish(),
+
+ /** Whether the template is available to other members, defaults to true */
+ publish: z.boolean().default(true),
}),
});
@@ -83,7 +86,7 @@ export const TemplatesUpdateSchema = BaseSchema.extend({
body: z.object({
id: zodIdType(),
title: z.string().optional(),
- data: ProsemirrorSchema().optional(),
+ data: ProsemirrorSchema({ allowEmpty: true }).optional(),
icon: zodIconType().nullish(),
color: z
.string()
@@ -91,6 +94,9 @@ export const TemplatesUpdateSchema = BaseSchema.extend({
.nullish(),
fullWidth: z.boolean().optional(),
collectionId: z.string().uuid().nullish(),
+
+ /** Whether to make a draft template available to other members */
+ publish: z.boolean().optional(),
}),
});
diff --git a/server/routes/api/templates/templates.test.ts b/server/routes/api/templates/templates.test.ts
index 6cf74fc696..4aea2863c5 100644
--- a/server/routes/api/templates/templates.test.ts
+++ b/server/routes/api/templates/templates.test.ts
@@ -29,6 +29,39 @@ describe("#templates.list", () => {
expect(body.data[0].id).toEqual(template.id);
});
+ it("should list the user's own drafts", async () => {
+ const user = await buildUser();
+ const template = await buildTemplate({
+ userId: user.id,
+ teamId: user.teamId,
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.list", user);
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.length).toEqual(1);
+ expect(body.data[0].id).toEqual(template.id);
+ });
+
+ it("should not list drafts created by another user", async () => {
+ const user = await buildUser();
+ const other = await buildUser({ teamId: user.teamId });
+ await buildTemplate({
+ userId: other.id,
+ teamId: user.teamId,
+ collectionId: null,
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.list", user);
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.length).toEqual(0);
+ });
+
it("should return an empty document for templates without content", async () => {
const user = await buildUser();
await buildTemplate({
@@ -101,6 +134,60 @@ describe("#templates.list", () => {
});
});
+describe("#templates.create", () => {
+ it("should publish by default", async () => {
+ const admin = await buildAdmin();
+
+ const res = await server.post("/api/templates.create", admin, {
+ body: {
+ title: "My template",
+ data: {
+ type: "doc",
+ content: [
+ {
+ type: "paragraph",
+ content: [{ type: "text", text: "hello" }],
+ },
+ ],
+ },
+ },
+ });
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.publishedAt).toBeTruthy();
+ });
+
+ it("should not publish a template without content", async () => {
+ const admin = await buildAdmin();
+
+ const res = await server.post("/api/templates.create", admin, {
+ body: {
+ title: "My template",
+ data: ProsemirrorDataHelper.getEmpty(),
+ },
+ });
+
+ expect(res.status).toEqual(400);
+ });
+
+ it("should create an empty draft when publish is false", async () => {
+ const admin = await buildAdmin();
+
+ const res = await server.post("/api/templates.create", admin, {
+ body: {
+ title: "",
+ publish: false,
+ },
+ });
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.title).toEqual("");
+ expect(body.data.publishedAt).toEqual(null);
+ });
+});
+
describe("#templates.info", () => {
it("should return template data", async () => {
const user = await buildUser();
@@ -121,6 +208,44 @@ describe("#templates.info", () => {
expect(body.data.title).toEqual(template.title);
});
+ it("should return a draft to the user that created it", async () => {
+ const user = await buildUser();
+ const template = await buildTemplate({
+ userId: user.id,
+ teamId: user.teamId,
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.info", user, {
+ body: {
+ id: template.id,
+ },
+ });
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.id).toEqual(template.id);
+ });
+
+ it("should not return a draft created by another user", async () => {
+ const user = await buildUser();
+ const other = await buildUser({ teamId: user.teamId });
+ const template = await buildTemplate({
+ userId: other.id,
+ teamId: user.teamId,
+ collectionId: null,
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.info", user, {
+ body: {
+ id: template.id,
+ },
+ });
+
+ expect(res.status).toEqual(403);
+ });
+
it("should require authentication", async () => {
const res = await server.post("/api/templates.info");
expect(res.status).toEqual(401);
@@ -139,6 +264,66 @@ describe("#templates.info", () => {
});
describe("#templates.update", () => {
+ it("should accept an empty document while drafting", async () => {
+ const user = await buildUser();
+ const template = await buildTemplate({
+ userId: user.id,
+ teamId: user.teamId,
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.update", user, {
+ body: {
+ id: template.id,
+ title: "Still writing",
+ data: ProsemirrorDataHelper.getEmpty(),
+ },
+ });
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.title).toEqual("Still writing");
+ });
+
+ it("should not publish a draft without content", async () => {
+ const user = await buildUser();
+ const template = await buildTemplate({
+ userId: user.id,
+ teamId: user.teamId,
+ content: ProsemirrorDataHelper.getEmpty(),
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.update", user, {
+ body: {
+ id: template.id,
+ publish: true,
+ },
+ });
+
+ expect(res.status).toEqual(400);
+ });
+
+ it("should publish a draft when publish is true", async () => {
+ const user = await buildUser();
+ const template = await buildTemplate({
+ userId: user.id,
+ teamId: user.teamId,
+ publishedAt: null,
+ });
+
+ const res = await server.post("/api/templates.update", user, {
+ body: {
+ id: template.id,
+ publish: true,
+ },
+ });
+
+ const body = await res.json();
+ expect(res.status).toEqual(200);
+ expect(body.data.publishedAt).toBeTruthy();
+ });
+
it("should update template title", async () => {
const user = await buildUser();
const template = await buildTemplate({
diff --git a/server/routes/api/templates/templates.ts b/server/routes/api/templates/templates.ts
index 811faa9612..260351e3dd 100644
--- a/server/routes/api/templates/templates.ts
+++ b/server/routes/api/templates/templates.ts
@@ -1,6 +1,8 @@
import Router from "koa-router";
import type { WhereOptions } from "sequelize";
import { Op, Sequelize } from "sequelize";
+import { ProsemirrorDataHelper } from "@shared/utils/ProsemirrorDataHelper";
+import { ValidationError } from "@server/errors";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import { transaction } from "@server/middlewares/transaction";
@@ -23,12 +25,17 @@ router.post(
validate(T.TemplatesCreateSchema),
transaction(),
async (ctx: APIContext) => {
- const { id, title, data, icon, color, collectionId } = ctx.input.body;
+ const { id, title, data, icon, color, collectionId, publish } =
+ ctx.input.body;
const editorVersion = ctx.headers["x-editor-version"] as string | undefined;
const { transaction } = ctx.state;
const { user } = ctx.state.auth;
+ if (publish && (!data || ProsemirrorDataHelper.isEmpty(data))) {
+ throw ValidationError("A published template must have content");
+ }
+
let collection;
if (collectionId) {
collection = await Collection.findByPk(collectionId, {
@@ -42,12 +49,12 @@ router.post(
let template = await Template.createWithCtx(ctx, {
id,
- title,
+ title: title ?? "",
icon,
color,
- content: data,
+ content: data ?? null,
collectionId: collection?.id,
- publishedAt: new Date(),
+ publishedAt: publish ? new Date() : null,
createdById: user.id,
lastModifiedById: user.id,
teamId: user.teamId,
@@ -85,6 +92,19 @@ router.post(
[Op.eq]: null,
},
},
+ // drafts are only visible to the user that created them
+ {
+ [Op.or]: [
+ {
+ publishedAt: {
+ [Op.ne]: null,
+ },
+ },
+ {
+ createdById: user.id,
+ },
+ ],
+ },
],
};
@@ -259,7 +279,7 @@ router.post(
lastModifiedById: user.id,
teamId: user.teamId,
collectionId: targetCollectionId,
- publishedAt: new Date(),
+ publishedAt: original.isDraft ? null : new Date(),
content: original.content,
icon: original.icon,
color: original.color,
@@ -287,7 +307,7 @@ router.post(
transaction(),
async (ctx: APIContext) => {
const { transaction } = ctx.state;
- const { id, data, ...updatedFields } = ctx.input.body;
+ const { id, data, publish, ...updatedFields } = ctx.input.body;
const { user } = ctx.state.auth;
const template = await Template.findByPk(id, {
@@ -316,6 +336,16 @@ router.post(
template.content = data;
}
+ if (publish && template.isDraft) {
+ if (
+ !template.content ||
+ ProsemirrorDataHelper.isEmpty(template.content)
+ ) {
+ throw ValidationError("A published template must have content");
+ }
+ template.publishedAt = new Date();
+ }
+
await template.updateWithCtx(ctx, updatedFields);
ctx.body = {
diff --git a/server/test/factories.ts b/server/test/factories.ts
index 933a582254..2c4b252850 100644
--- a/server/test/factories.ts
+++ b/server/test/factories.ts
@@ -469,6 +469,7 @@ export async function buildTemplate(
lastModifiedById: overrides.userId,
createdById: overrides.userId,
editorVersion: "12.0.0",
+ publishedAt: new Date(),
...overrides,
},
{
diff --git a/server/tools/templates.ts b/server/tools/templates.ts
index 35558608db..0d2edef432 100644
--- a/server/tools/templates.ts
+++ b/server/tools/templates.ts
@@ -90,7 +90,16 @@ export function templateTools(server: McpServer, scopes: string[]) {
[Op.and]: WhereOptions[];
} = {
teamId: user.teamId,
- [Op.and]: [{ deletedAt: { [Op.eq]: null } }],
+ [Op.and]: [
+ { deletedAt: { [Op.eq]: null } },
+ // drafts are only visible to the user that created them
+ {
+ [Op.or]: [
+ { publishedAt: { [Op.ne]: null } },
+ { createdById: user.id },
+ ],
+ },
+ ],
};
if (collectionId) {
diff --git a/shared/i18n/locales/en_US/translation.json b/shared/i18n/locales/en_US/translation.json
index acb8053d63..8a278ebf2e 100644
--- a/shared/i18n/locales/en_US/translation.json
+++ b/shared/i18n/locales/en_US/translation.json
@@ -221,6 +221,8 @@
"template": "template",
"Template deleted": "Template deleted",
"Are you sure about that? Deleting the {{ templateName }} template is permanent.": "Are you sure about that? Deleting the {{ templateName }} template is permanent.",
+ "A template must have content": "A template must have content",
+ "Template published": "Template published",
"Move to workspace": "Move to workspace",
"Template moved": "Template moved",
"Couldn't move the template, try again?": "Couldn't move the template, try again?",
@@ -617,6 +619,7 @@
"Select a color": "Select a color",
"Select all": "Select all",
"Columns": "Columns",
+ "Your changes couldn’t be saved.\nAre you sure you want to leave?": "Your changes couldn’t be saved.\nAre you sure you want to leave?",
"Highlight some text and use the <1>1> control to add placeholders that can be filled out when creating new documents": "Highlight some text and use the <1>1> control to add placeholders that can be filled out when creating new documents",
"You’re editing a template": "You’re editing a template",
"Template created, go ahead and customize it": "Template created, go ahead and customize it",
@@ -1481,7 +1484,7 @@
"Sharing is currently disabled.": "Sharing is currently disabled.",
"You can globally enable and disable public document sharing in the security settings.": "You can globally enable and disable public document sharing in the security settings.",
"Documents that have been shared are listed below. Anyone that has the public link can access a read-only version of the document until the link has been revoked.": "Documents that have been shared are listed below. Anyone that has the public link can access a read-only version of the document until the link has been revoked.",
- "A template must have content": "A template must have content",
+ "Couldn’t create the template, try again?": "Couldn’t create the template, try again?",
"Could not load templates": "Could not load templates",
"Templates help your team create consistent and accurate documentation.": "Templates help your team create consistent and accurate documentation.",
"No templates have been created yet": "No templates have been created yet",