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