Persist template drafts as they are written (#13357)

* fix: Warn before discarding unsaved template changes

Template content is only persisted when the form is explicitly submitted,
so navigating away or closing the tab silently lost everything typed.

Adds a navigation Prompt and a beforeunload handler to both template
scenes, and reverts the model on unmount so abandoned edits no longer
leak into other views rendering the same record.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: Persist templates from the first keystroke

New templates were held only in browser memory until Save was pressed, so
a refresh, crash, or stray navigation lost everything written.

Templates are now created up front as an unpublished draft and autosaved,
mirroring how documents behave. Drafts are visible only to their author
until published, and are cleaned up if abandoned while empty.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix: Preserve icon edits made during an in-flight template save

applyEdits only restored title and content, so an icon or color changed
while a save was in flight was overwritten by the response and never
re-saved.

Pending edits are now tracked as a single record covering every field the
form can change, rather than one ref per field.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feedback

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Tom MoorandClaude Opus 5 authored and GitHub committed 2026-08-09 00:09:20 +00:00
1 parent 77fcd895c4
commit e4d07b4f24
22 files changed
+640 -164

No files matched your search

+45 -1
View File
@@ -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: <PublishIcon />,
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: <CollectionIcon />,
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: <CopyIcon />,
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: <CaseSensitiveIcon />,
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: <CopyIcon />,
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,
];
+2
View File
@@ -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,
];
+8 -2
View File
@@ -8,10 +8,16 @@ type Props = {
children?: React.ReactNode;
icon?: JSX.Element;
description?: JSX.Element;
className?: string;
};
const Notice: React.FC<Props> = ({ children, icon, description }: Props) => (
<Container as="div">
const Notice: React.FC<Props> = ({
children,
icon,
description,
className,
}: Props) => (
<Container as="div" className={className}>
<Flex as="span" gap={8}>
{icon}
<span>
+124 -12
View File
@@ -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<Template, "title" | "data" | "icon" | "color">;
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<Partial<TemplateEdits>>({});
const ref = useRef(null);
const [isUploading, handleStartUpload, handleStopUpload] = useBoolean();
const readOnly = !can.update && !template.isNew;
const saveRef = useRef<() => Promise<void>>(() => 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 (
<DocumentContextProvider>
<Prompt message={handleBlockNavigation} />
<React.Suspense fallback={null}>
{isUploading && <LoadingIndicator />}
<Notice
<EditingNotice
icon={<ShapesIcon />}
description={
<Trans>
@@ -71,7 +177,7 @@ export const TemplateForm = observer(function TemplateForm_({
}
>
{t("You’re editing a template")}
</Notice>
</EditingNotice>
<Editor
id={template.id}
ref={ref}
@@ -96,6 +202,12 @@ export const TemplateForm = observer(function TemplateForm_({
);
});
const EditingNotice = styled(Notice)`
@media print {
display: none;
}
`;
const PlaceholderIcon = styled(InputIcon)`
position: relative;
top: 6px;
+3 -3
View File
@@ -33,8 +33,8 @@ function useTemplateMenuItem(): MenuItem | undefined {
return undefined;
}
const allTemplates = templatesStore.orderedData.filter(
(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<SuggestionsMenuProps, "renderMenuItem" | "items"> &
+1 -3
View File
@@ -66,9 +66,7 @@ export function useTemplateMenuActions({
return [];
}
const templates = templatesStore.orderedData.filter(
(template) => template.isActive
);
const templates = templatesStore.published;
const collectionTemplatesActions = templates
.filter(
+2 -2
View File
@@ -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,
+4 -2
View File
@@ -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")}
>
<OverflowMenuButton />
<OverflowMenuButton neutral={neutral} />
</DropdownMenu>
</ActionContextProvider>
);
+65
View File
@@ -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);
});
});
});
+36
View File
@@ -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) {
+22 -19
View File
@@ -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 (
<Scene
title={template.title}
left={<Breadcrumb actions={breadcrumbActions} />}
actions={
<>
<Action>
<Button onClick={handleSubmit} disabled={saving}>
{t("Save")}
</Button>
</Action>
<Action>
<TemplateMenu template={template} />
</Action>
</>
}
>
<TemplateForm template={template} handleSubmit={handleSubmit} />
</Scene>
<ActionContextProvider value={{ activeModels: [template] }}>
<Scene
title={template.title}
left={<Breadcrumb actions={breadcrumbActions} />}
actions={
<>
<Action>
<Button onClick={handleSubmit} disabled={saving}>
{template.isDraft ? t("Publish") : t("Done")}
</Button>
</Action>
<Action>
<TemplateMenu template={template} neutral />
</Action>
</>
}
>
<TemplateForm template={template} handleSubmit={handleSubmit} />
</Scene>
</ActionContextProvider>
);
});
+23 -68
View File
@@ -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: <ShapesIcon />,
to: settingsPath("templates"),
}),
...(collection
? [
createInternalLinkAction({
name: collection.name,
section: NavigationSection,
icon: <CollectionIcon collection={collection} />,
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 (
<Scene
title={t("New template")}
left={<Breadcrumb actions={breadcrumbActions} />}
actions={
<Action>
<Button onClick={handleSubmit} disabled={saving}>
{t("Save")}
</Button>
</Action>
}
>
<TemplateForm template={template} handleSubmit={handleSubmit} />
<Scene title={t("New template")}>
<PlaceholderDocument />
</Scene>
);
}
@@ -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) => (
<TemplateLink template={template} onClick={handleOpen} />
),
component: (template) => <TemplateLink template={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 = (
<Flex align="center" gap={4}>
{template.icon ? (
<Icon
value={template.icon}
initial={template.initial}
color={template.color || undefined}
size={24}
/>
) : (
<DocumentIcon size={24} color={theme.textSecondary} />
)}
{can.update ? (
<Title>{template.titleWithDefault}</Title>
) : (
<Text>{template.titleWithDefault}</Text>
)}
</Flex>
);
const TemplateLink = observer(({ template }: { template: Template }) => {
const theme = useTheme();
const { t } = useTranslation();
const can = usePolicy(template);
const content = (
<Flex align="center" gap={4}>
{template.icon ? (
<Icon
value={template.icon}
initial={template.initial}
color={template.color || undefined}
size={24}
/>
) : (
<ShapesIcon size={24} color={theme.textSecondary} />
)}
{can.update ? (
<Title>{template.titleWithDefault}</Title>
) : (
<Text>{template.titleWithDefault}</Text>
)}
{template.isDraft && (
<Tooltip content={t("Only visible to you")} placement="top">
<Badge>{t("Draft")}</Badge>
</Tooltip>
)}
</Flex>
);
if (!can.update) {
return content;
}
return <ButtonLink onClick={() => onClick(template)}>{content}</ButtonLink>;
if (!can.update) {
return content;
}
);
return <Link to={template.path}>{content}</Link>;
});
const Permission = observer(({ template }: { template: Template }) => {
const { t } = useTranslation();
+11 -1
View File
@@ -12,9 +12,19 @@ export default class TemplatesStore extends Store<Template> {
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
+10
View File
@@ -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());
+1
View File
@@ -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)
+9 -3
View File
@@ -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(),
}),
});
@@ -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({
+36 -6
View File
@@ -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<T.TemplatesCreateReq>) => {
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<T.TemplatesUpdateReq>) => {
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 = {
+1
View File
@@ -469,6 +469,7 @@ export async function buildTemplate(
lastModifiedById: overrides.userId,
createdById: overrides.userId,
editorVersion: "12.0.0",
publishedAt: new Date(),
...overrides,
},
{
+10 -1
View File
@@ -90,7 +90,16 @@ export function templateTools(server: McpServer, scopes: string[]) {
[Op.and]: WhereOptions<Template>[];
} = {
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) {
+4 -1
View File
@@ -221,6 +221,8 @@
"template": "template",
"Template deleted": "Template deleted",
"Are you sure about that? Deleting the <em>{{ templateName }}</em> template is permanent.": "Are you sure about that? Deleting the <em>{{ templateName }}</em> 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 <em>security settings</em>.": "You can globally enable and disable public document sharing in the <em>security settings</em>.",
"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",