@foundrykit/history-plugin 0.2.1 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ import type { Config } from 'payload';
2
+ /**
3
+ * Records this plugin as active in `config.custom.foundrykit.activePlugins`, the list
4
+ * `@foundrykit/guides-plugin` sends to the guides hub so the site gets this plugin's guides.
5
+ * Only call it on the enabled path: installed-but-disabled doesn't count.
6
+ *
7
+ * Every FoundryKit Payload plugin carries its own copy of this file (it's too small for a package);
8
+ * keep them identical.
9
+ */
10
+ export declare const recordActivePlugin: (config: Config, name: string) => Config;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Records this plugin as active in `config.custom.foundrykit.activePlugins`, the list
3
+ * `@foundrykit/guides-plugin` sends to the guides hub so the site gets this plugin's guides.
4
+ * Only call it on the enabled path: installed-but-disabled doesn't count.
5
+ *
6
+ * Every FoundryKit Payload plugin carries its own copy of this file (it's too small for a package);
7
+ * keep them identical.
8
+ */ export const recordActivePlugin = (config, name)=>{
9
+ const foundrykit = config.custom?.foundrykit ?? {};
10
+ return {
11
+ ...config,
12
+ custom: {
13
+ ...config.custom,
14
+ foundrykit: {
15
+ ...foundrykit,
16
+ activePlugins: [
17
+ ...new Set([
18
+ ...foundrykit.activePlugins ?? [],
19
+ name
20
+ ])
21
+ ]
22
+ }
23
+ }
24
+ };
25
+ };
26
+
27
+ //# sourceMappingURL=activePlugins.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activePlugins.ts"],"sourcesContent":["import type { Config } from 'payload';\n\n/**\n * Records this plugin as active in `config.custom.foundrykit.activePlugins`, the list\n * `@foundrykit/guides-plugin` sends to the guides hub so the site gets this plugin's guides.\n * Only call it on the enabled path: installed-but-disabled doesn't count.\n *\n * Every FoundryKit Payload plugin carries its own copy of this file (it's too small for a package);\n * keep them identical.\n */\nexport const recordActivePlugin = (config: Config, name: string): Config => {\n const foundrykit = (config.custom?.foundrykit ?? {}) as {\n activePlugins?: string[];\n };\n return {\n ...config,\n custom: {\n ...config.custom,\n foundrykit: {\n ...foundrykit,\n activePlugins: [\n ...new Set([...(foundrykit.activePlugins ?? []), name]),\n ],\n },\n },\n };\n};\n"],"names":["recordActivePlugin","config","name","foundrykit","custom","activePlugins","Set"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,qBAAqB,CAACC,QAAgBC;IACjD,MAAMC,aAAcF,OAAOG,MAAM,EAAED,cAAc,CAAC;IAGlD,OAAO;QACL,GAAGF,MAAM;QACTG,QAAQ;YACN,GAAGH,OAAOG,MAAM;YAChBD,YAAY;gBACV,GAAGA,UAAU;gBACbE,eAAe;uBACV,IAAIC,IAAI;2BAAKH,WAAWE,aAAa,IAAI,EAAE;wBAAGH;qBAAK;iBACvD;YACH;QACF;IACF;AACF,EAAE"}
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { recordActivePlugin } from './activePlugins.js';
1
2
  import { AUTHOR_FIELD } from './timeline.js';
2
3
  export { AUTHOR_FIELD } from './timeline.js';
3
4
  const TIMELINE = '@foundrykit/history-plugin/rsc#TimelineView';
@@ -128,11 +129,11 @@ export const historyPlugin = (options = {})=>(config)=>{
128
129
  const globals = config.globals ?? [];
129
130
  const trackedCollections = checkTracked('collection', options.collections, collections.filter((c)=>c.versions).map((c)=>c.slug));
130
131
  const trackedGlobals = checkTracked('global', options.globals, globals.filter((g)=>g.versions).map((g)=>g.slug));
131
- return {
132
+ return recordActivePlugin({
132
133
  ...config,
133
134
  collections: collections.map((c)=>trackedCollections.has(c.slug) ? trackCollection(c, usersSlug) : c),
134
135
  globals: globals.map((g)=>trackedGlobals.has(g.slug) ? trackGlobal(g, usersSlug) : g)
135
- };
136
+ }, '@foundrykit/history-plugin');
136
137
  };
137
138
 
138
139
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Access,\n AccessArgs,\n CollectionConfig,\n CollectionSlug,\n Config,\n Field,\n GlobalConfig,\n Payload,\n Where,\n} from 'payload';\n\nimport { AUTHOR_FIELD } from './timeline.js';\n\nexport { AUTHOR_FIELD } from './timeline.js';\n\nexport type HistoryPluginConfig = {\n /** Collections to track. Defaults to every collection with versions. */\n collections?: string[];\n /** Globals to track. Defaults to every global with versions. */\n globals?: string[];\n};\n\nconst TIMELINE = '@foundrykit/history-plugin/rsc#TimelineView';\nconst VERSION_AUTHOR = '@foundrykit/history-plugin/rsc#VersionAuthor';\n\ntype Views = NonNullable<\n NonNullable<CollectionConfig['admin']>['components']\n>['views'];\n\n/**\n * Uses the timeline as the versions tab, unless the site already replaced it, and names the\n * author on a single version. Actions alone don't replace Payload's version view.\n */\nconst withTimeline = (views: Views): Views => ({\n ...views,\n edit: {\n ...views?.edit,\n version: {\n ...views?.edit?.version,\n actions: [...(views?.edit?.version?.actions ?? []), VERSION_AUTHOR],\n },\n versions: views?.edit?.versions ?? { Component: TIMELINE },\n } as NonNullable<Views>['edit'],\n});\n\nconst authorField = (usersSlug: string): Field => ({\n name: AUTHOR_FIELD,\n type: 'relationship',\n // Staff only. A site's own server-side reads (Local API, overrideAccess) skip field access, so\n // maxDepth keeps it an id there: populated, it would put a staff user's email into any page\n // data that reaches the browser.\n access: { read: ({ req }) => Boolean(req.user) },\n admin: { position: 'sidebar', readOnly: true },\n hooks: {\n // Always the person saving, whatever was sent. Saves with no admin user (scripts, the\n // public site) record no author.\n beforeChange: [\n ({ req }) => (req.user?.collection === usersSlug ? req.user.id : null),\n ],\n },\n label: 'Last edited by',\n maxDepth: 0,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n relationTo: usersSlug as CollectionSlug,\n});\n\n/**\n * Version history needs a login and the entity's own read access. Payload's default only needs\n * a login, so a site gating reads (for example with the permissions plugin) would leak history.\n * The entity's read access is looked up at request time, so plugin order doesn't matter.\n */\n/** Rewrites a read query on documents into the same query on their versions. */\nconst toVersionsWhere = (where: Where): Where =>\n Object.fromEntries(\n Object.entries(where).map(([key, value]) =>\n key === 'and' || key === 'or'\n ? [key, (value as Where[]).map(toVersionsWhere)]\n : [key === 'id' ? 'parent' : `version.${key}`, value]\n )\n );\n\nconst readVersions =\n (getRead: (payload: Payload) => Access | undefined): Access =>\n async (args: AccessArgs) => {\n if (!args.req.user) {\n return false;\n }\n const read = getRead(args.req.payload);\n const result = read ? await read(args) : true;\n // A query limits which documents can be read, so it limits which versions can be read too.\n return typeof result === 'boolean' ? result : toVersionsWhere(result);\n };\n\nconst checkTracked = (\n kind: string,\n wanted: string[] | undefined,\n versioned: string[]\n) => {\n for (const slug of wanted ?? []) {\n if (!versioned.includes(slug)) {\n throw new Error(\n `history: ${kind} \"${slug}\" doesn't exist or has versions turned off`\n );\n }\n }\n return new Set(wanted ?? versioned);\n};\n\nconst checkNoAuthorField = (slug: string, fields: Field[]) => {\n if (fields.some(field => 'name' in field && field.name === AUTHOR_FIELD)) {\n throw new Error(`history: \"${slug}\" already has a \"${AUTHOR_FIELD}\" field`);\n }\n};\n\nconst trackCollection = (\n collection: CollectionConfig,\n usersSlug: string\n): CollectionConfig => {\n checkNoAuthorField(collection.slug, collection.fields);\n return {\n ...collection,\n access: {\n ...collection.access,\n readVersions:\n collection.access?.readVersions ??\n readVersions(\n payload =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n payload.collections[collection.slug as CollectionSlug]?.config\n .access.read\n ),\n },\n admin: {\n ...collection.admin,\n components: {\n ...collection.admin?.components,\n views: withTimeline(collection.admin?.components?.views),\n },\n },\n fields: [...collection.fields, authorField(usersSlug)],\n };\n};\n\nconst trackGlobal = (global: GlobalConfig, usersSlug: string): GlobalConfig => {\n checkNoAuthorField(global.slug, global.fields);\n return {\n ...global,\n access: {\n ...global.access,\n readVersions:\n global.access?.readVersions ??\n readVersions(\n payload =>\n payload.config.globals.find(g => g.slug === global.slug)?.access\n .read\n ),\n },\n admin: {\n ...global.admin,\n components: {\n ...global.admin?.components,\n views: withTimeline(global.admin?.components?.views),\n },\n },\n fields: [...global.fields, authorField(usersSlug)],\n };\n};\n\nexport const historyPlugin =\n (options: HistoryPluginConfig = {}) =>\n (config: Config): Config => {\n const usersSlug = config.admin?.user ?? 'users';\n const collections = config.collections ?? [];\n const globals = config.globals ?? [];\n\n const trackedCollections = checkTracked(\n 'collection',\n options.collections,\n collections.filter(c => c.versions).map(c => c.slug)\n );\n const trackedGlobals = checkTracked(\n 'global',\n options.globals,\n globals.filter(g => g.versions).map(g => g.slug)\n );\n\n return {\n ...config,\n collections: collections.map(c =>\n trackedCollections.has(c.slug) ? trackCollection(c, usersSlug) : c\n ),\n globals: globals.map(g =>\n trackedGlobals.has(g.slug) ? trackGlobal(g, usersSlug) : g\n ),\n };\n };\n"],"names":["AUTHOR_FIELD","TIMELINE","VERSION_AUTHOR","withTimeline","views","edit","version","actions","versions","Component","authorField","usersSlug","name","type","access","read","req","Boolean","user","admin","position","readOnly","hooks","beforeChange","collection","id","label","maxDepth","relationTo","toVersionsWhere","where","Object","fromEntries","entries","map","key","value","readVersions","getRead","args","payload","result","checkTracked","kind","wanted","versioned","slug","includes","Error","Set","checkNoAuthorField","fields","some","field","trackCollection","collections","config","components","trackGlobal","global","globals","find","g","historyPlugin","options","trackedCollections","filter","c","trackedGlobals","has"],"mappings":"AAYA,SAASA,YAAY,QAAQ,gBAAgB;AAE7C,SAASA,YAAY,QAAQ,gBAAgB;AAS7C,MAAMC,WAAW;AACjB,MAAMC,iBAAiB;AAMvB;;;CAGC,GACD,MAAMC,eAAe,CAACC,QAAyB,CAAA;QAC7C,GAAGA,KAAK;QACRC,MAAM;YACJ,GAAGD,OAAOC,IAAI;YACdC,SAAS;gBACP,GAAGF,OAAOC,MAAMC,OAAO;gBACvBC,SAAS;uBAAKH,OAAOC,MAAMC,SAASC,WAAW,EAAE;oBAAGL;iBAAe;YACrE;YACAM,UAAUJ,OAAOC,MA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GAAGhC,OACvDC;QAEX;QACAI,OAAO;YACL,GAAGwC,OAAOxC,KAAK;YACfsC,YAAY;gBACV,GAAGE,OAAOxC,KAAK,EAAEsC,UAAU;gBAC3BrD,OAAOD,aAAawD,OAAOxC,KAAK,EAAEsC,YAAYrD;YAChD;QACF;QACA+C,QAAQ;eAAIQ,OAAOR,MAAM;YAAEzC,YAAYC;SAAW;IACpD;AACF;AAEA,OAAO,MAAMoD,gBACX,CAACC,UAA+B,CAAC,CAAC,GAClC,CAACR;QACC,MAAM7C,YAAY6C,OAAOrC,KAAK,EAAED,QAAQ;QACxC,MAAMqC,cAAcC,OAAOD,WAAW,IAAI,EAAE;QAC5C,MAAMK,UAAUJ,OAAOI,OAAO,IAAI,EAAE;QAEpC,MAAMK,qBAAqBvB,aACzB,cACAsB,QAAQT,WAAW,EACnBA,YAAYW,MAAM,CAACC,CAAAA,IAAKA,EAAE3D,QAAQ,EAAE0B,GAAG,CAACiC,CAAAA,IAAKA,EAAErB,IAAI;QAErD,MAAMsB,iBAAiB1B,aACrB,UACAsB,QAAQJ,OAAO,EACfA,QAAQM,MAAM,CAACJ,CAAAA,IAAKA,EAAEtD,QAAQ,EAAE0B,GAAG,CAAC4B,CAAAA,IAAKA,EAAEhB,IAAI;QAGjD,OAAO;YACL,GAAGU,MAAM;YACTD,aAAaA,YAAYrB,GAAG,CAACiC,CAAAA,IAC3BF,mBAAmBI,GAAG,CAACF,EAAErB,IAAI,IAAIQ,gBAAgBa,GAAGxD,aAAawD;YAEnEP,SAASA,QAAQ1B,GAAG,CAAC4B,CAAAA,IACnBM,eAAeC,GAAG,CAACP,EAAEhB,IAAI,IAAIY,YAAYI,GAAGnD,aAAamD;QAE7D;IACF,EAAE"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import type {\n Access,\n AccessArgs,\n CollectionConfig,\n CollectionSlug,\n Config,\n Field,\n GlobalConfig,\n Payload,\n Where,\n} from 'payload';\nimport { recordActivePlugin } from './activePlugins.js';\nimport { AUTHOR_FIELD } from './timeline.js';\n\nexport { AUTHOR_FIELD } from './timeline.js';\n\nexport type HistoryPluginConfig = {\n /** Collections to track. Defaults to every collection with versions. */\n collections?: string[];\n /** Globals to track. Defaults to every global with versions. */\n globals?: string[];\n};\n\nconst TIMELINE = '@foundrykit/history-plugin/rsc#TimelineView';\nconst VERSION_AUTHOR = '@foundrykit/history-plugin/rsc#VersionAuthor';\n\ntype Views = NonNullable<\n NonNullable<CollectionConfig['admin']>['components']\n>['views'];\n\n/**\n * Uses the timeline as the versions tab, unless the site already replaced it, and names the\n * author on a single version. Actions alone don't replace Payload's version view.\n */\nconst withTimeline = (views: Views): Views => ({\n ...views,\n edit: {\n ...views?.edit,\n version: {\n ...views?.edit?.version,\n actions: [...(views?.edit?.version?.actions ?? []), VERSION_AUTHOR],\n },\n versions: views?.edit?.versions ?? { Component: TIMELINE },\n } as NonNullable<Views>['edit'],\n});\n\nconst authorField = (usersSlug: string): Field => ({\n name: AUTHOR_FIELD,\n type: 'relationship',\n // Staff only. A site's own server-side reads (Local API, overrideAccess) skip field access, so\n // maxDepth keeps it an id there: populated, it would put a staff user's email into any page\n // data that reaches the browser.\n access: { read: ({ req }) => Boolean(req.user) },\n admin: { position: 'sidebar', readOnly: true },\n hooks: {\n // Always the person saving, whatever was sent. Saves with no admin user (scripts, the\n // public site) record no author.\n beforeChange: [\n ({ req }) => (req.user?.collection === usersSlug ? req.user.id : null),\n ],\n },\n label: 'Last edited by',\n maxDepth: 0,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n relationTo: usersSlug as CollectionSlug,\n});\n\n/**\n * Version history needs a login and the entity's own read access. Payload's default only needs\n * a login, so a site gating reads (for example with the permissions plugin) would leak history.\n * The entity's read access is looked up at request time, so plugin order doesn't matter.\n */\n/** Rewrites a read query on documents into the same query on their versions. */\nconst toVersionsWhere = (where: Where): Where =>\n Object.fromEntries(\n Object.entries(where).map(([key, value]) =>\n key === 'and' || key === 'or'\n ? [key, (value as Where[]).map(toVersionsWhere)]\n : [key === 'id' ? 'parent' : `version.${key}`, value]\n )\n );\n\nconst readVersions =\n (getRead: (payload: Payload) => Access | undefined): Access =>\n async (args: AccessArgs) => {\n if (!args.req.user) {\n return false;\n }\n const read = getRead(args.req.payload);\n const result = read ? await read(args) : true;\n // A query limits which documents can be read, so it limits which versions can be read too.\n return typeof result === 'boolean' ? result : toVersionsWhere(result);\n };\n\nconst checkTracked = (\n kind: string,\n wanted: string[] | undefined,\n versioned: string[]\n) => {\n for (const slug of wanted ?? []) {\n if (!versioned.includes(slug)) {\n throw new Error(\n `history: ${kind} \"${slug}\" doesn't exist or has versions turned off`\n );\n }\n }\n return new Set(wanted ?? versioned);\n};\n\nconst checkNoAuthorField = (slug: string, fields: Field[]) => {\n if (fields.some(field => 'name' in field && field.name === AUTHOR_FIELD)) {\n throw new Error(`history: \"${slug}\" already has a \"${AUTHOR_FIELD}\" field`);\n }\n};\n\nconst trackCollection = (\n collection: CollectionConfig,\n usersSlug: string\n): CollectionConfig => {\n checkNoAuthorField(collection.slug, collection.fields);\n return {\n ...collection,\n access: {\n ...collection.access,\n readVersions:\n collection.access?.readVersions ??\n readVersions(\n payload =>\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n payload.collections[collection.slug as CollectionSlug]?.config\n .access.read\n ),\n },\n admin: {\n ...collection.admin,\n components: {\n ...collection.admin?.components,\n views: withTimeline(collection.admin?.components?.views),\n },\n },\n fields: [...collection.fields, authorField(usersSlug)],\n };\n};\n\nconst trackGlobal = (global: GlobalConfig, usersSlug: string): GlobalConfig => {\n checkNoAuthorField(global.slug, global.fields);\n return {\n ...global,\n access: {\n ...global.access,\n readVersions:\n global.access?.readVersions ??\n readVersions(\n payload =>\n payload.config.globals.find(g => g.slug === global.slug)?.access\n .read\n ),\n },\n admin: {\n ...global.admin,\n components: {\n ...global.admin?.components,\n views: withTimeline(global.admin?.components?.views),\n },\n },\n fields: [...global.fields, authorField(usersSlug)],\n };\n};\n\nexport const historyPlugin =\n (options: HistoryPluginConfig = {}) =>\n (config: Config): Config => {\n const usersSlug = config.admin?.user ?? 'users';\n const collections = config.collections ?? [];\n const globals = config.globals ?? [];\n\n const trackedCollections = checkTracked(\n 'collection',\n options.collections,\n collections.filter(c => c.versions).map(c => c.slug)\n );\n const trackedGlobals = checkTracked(\n 'global',\n options.globals,\n globals.filter(g => g.versions).map(g => g.slug)\n );\n\n return recordActivePlugin(\n {\n ...config,\n collections: collections.map(c =>\n trackedCollections.has(c.slug) ? trackCollection(c, usersSlug) : c\n ),\n globals: globals.map(g =>\n trackedGlobals.has(g.slug) ? trackGlobal(g, usersSlug) : g\n ),\n },\n '@foundrykit/history-plugin'\n );\n };\n"],"names":["recordActivePlugin","AUTHOR_FIELD","TIMELINE","VERSION_AUTHOR","withTimeline","views","edit","version","actions","versions","Component","authorField","usersSlug","name","type","access","read","req","Boolean","user","admin","position","readOnly","hooks","beforeChange","collection","id","label","maxDepth","relationTo","toVersionsWhere","where","Object","fromEntries","entries","map","key","value","readVersions","getRead","args","payload","result","checkTracked","kind","wanted","versioned","slug","includes","Error","Set","checkNoAuthorField","fields","some","field","trackCollection","collections","config","components","trackGlobal","global","globals","find","g","historyPlugin","options","trackedCollections","filter","c","trackedGlobals","has"],"mappings":"AAWA,SAASA,kBAAkB,QAAQ,qBAAqB;AACxD,SAASC,YAAY,QAAQ,gBAAgB;AAE7C,SAASA,YAAY,QAAQ,gBAAgB;AAS7C,MAAMC,WAAW;AACjB,MAAMC,iBAAiB;AAMvB;;;CAGC,GACD,MAAMC,eAAe,CAACC,QAAyB,CAAA;QAC7C,GAAGA,KAAK;QACRC,MAAM;YACJ,GAAGD,OAAOC,IAAI;YACdC,SAAS;gBACP,GAAGF,OAAOC,MAAMC,OAAO;gBACvBC,SAAS;uBAAKH,OAAOC,MAAMC,SAASC,WAAW,EAAE;oBAAGL;iBAAe;YACrE;YACAM,UAAUJ,OAAOC,MAAMG,YAAY;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vDC;QAEX;QACAI,OAAO;YACL,GAAGwC,OAAOxC,KAAK;YACfsC,YAAY;gBACV,GAAGE,OAAOxC,KAAK,EAAEsC,UAAU;gBAC3BrD,OAAOD,aAAawD,OAAOxC,KAAK,EAAEsC,YAAYrD;YAChD;QACF;QACA+C,QAAQ;eAAIQ,OAAOR,MAAM;YAAEzC,YAAYC;SAAW;IACpD;AACF;AAEA,OAAO,MAAMoD,gBACX,CAACC,UAA+B,CAAC,CAAC,GAClC,CAACR;QACC,MAAM7C,YAAY6C,OAAOrC,KAAK,EAAED,QAAQ;QACxC,MAAMqC,cAAcC,OAAOD,WAAW,IAAI,EAAE;QAC5C,MAAMK,UAAUJ,OAAOI,OAAO,IAAI,EAAE;QAEpC,MAAMK,qBAAqBvB,aACzB,cACAsB,QAAQT,WAAW,EACnBA,YAAYW,MAAM,CAACC,CAAAA,IAAKA,EAAE3D,QAAQ,EAAE0B,GAAG,CAACiC,CAAAA,IAAKA,EAAErB,IAAI;QAErD,MAAMsB,iBAAiB1B,aACrB,UACAsB,QAAQJ,OAAO,EACfA,QAAQM,MAAM,CAACJ,CAAAA,IAAKA,EAAEtD,QAAQ,EAAE0B,GAAG,CAAC4B,CAAAA,IAAKA,EAAEhB,IAAI;QAGjD,OAAO/C,mBACL;YACE,GAAGyD,MAAM;YACTD,aAAaA,YAAYrB,GAAG,CAACiC,CAAAA,IAC3BF,mBAAmBI,GAAG,CAACF,EAAErB,IAAI,IAAIQ,gBAAgBa,GAAGxD,aAAawD;YAEnEP,SAASA,QAAQ1B,GAAG,CAAC4B,CAAAA,IACnBM,eAAeC,GAAG,CAACP,EAAEhB,IAAI,IAAIY,YAAYI,GAAGnD,aAAamD;QAE7D,GACA;IAEJ,EAAE"}
@@ -22,6 +22,8 @@ export type Entry = {
22
22
  id: ID;
23
23
  kind: Kind;
24
24
  latest: boolean;
25
+ /** This save moved the document to the trash, or brought it back. */
26
+ trash: 'restored' | 'trashed' | null;
25
27
  updatedAt: string;
26
28
  };
27
29
  /** Labels for the top-level fields that differ between two version snapshots. */
package/dist/timeline.js CHANGED
@@ -3,6 +3,8 @@ export const AUTHOR_FIELD = 'updatedBy';
3
3
  '_status',
4
4
  AUTHOR_FIELD,
5
5
  'createdAt',
6
+ // Trashing and restoring are told apart below (`trash`), not listed as a changed field.
7
+ 'deletedAt',
6
8
  'id',
7
9
  'updatedAt'
8
10
  ]);
@@ -51,6 +53,11 @@ const plural = (n, word)=>`${n} ${word}${n === 1 ? '' : 's'}`;
51
53
  label
52
54
  ];
53
55
  });
56
+ const trashMove = (previous, newest)=>{
57
+ const was = Boolean(previous?.version.deletedAt);
58
+ const is = Boolean(newest.version.deletedAt);
59
+ return is && !was ? 'trashed' : was && !is ? 'restored' : null;
60
+ };
54
61
  /**
55
62
  * Turns versions (newest first) into timeline entries. `older` is the version just before the
56
63
  * last one on this page, used to work out what that one changed.
@@ -84,6 +91,7 @@ const plural = (n, word)=>`${n} ${word}${n === 1 ? '' : 's'}`;
84
91
  first: !previous,
85
92
  kind: kindOf(newest, drafts),
86
93
  latest: Boolean(newest.latest),
94
+ trash: trashMove(previous, newest),
87
95
  updatedAt: newest.updatedAt
88
96
  };
89
97
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/timeline.ts"],"sourcesContent":["import type { FlattenedField } from 'payload';\n\nexport const AUTHOR_FIELD = 'updatedBy';\n\n/** Bookkeeping fields every version has; they never count as a change. */\nconst IGNORED = new Set([\n '_status',\n AUTHOR_FIELD,\n 'createdAt',\n 'id',\n 'updatedAt',\n]);\n\ntype ID = number | string;\n\nexport type RawVersion = {\n autosave?: boolean;\n id: ID;\n latest?: boolean;\n updatedAt: string;\n version: Record<string, unknown>;\n};\n\nexport type Kind = 'autosave' | 'draft' | 'published' | 'saved';\n\nexport type Entry = {\n author: ID | null;\n /** One label per changed field, e.g. \"Title\" or \"Layout (+2 blocks)\". */\n changes: string[];\n /** How many versions were merged into this entry (consecutive autosaves). */\n count: number;\n /** The first version saved when the document was created. */\n created: boolean;\n /** The oldest version there is, which has no earlier one to compare with. */\n first: boolean;\n id: ID;\n kind: Kind;\n latest: boolean;\n updatedAt: string;\n};\n\nconst kindOf = (v: RawVersion, drafts: boolean): Kind => {\n if (v.autosave) {\n return 'autosave';\n }\n if (!drafts) {\n return 'saved';\n }\n return v.version._status === 'published' ? 'published' : 'draft';\n};\n\n/**\n * Whether the first version is the document's creation. A document that existed before versions\n * were turned on gets its first version on a later save, which isn't its creation.\n */\nconst isCreation = (v: RawVersion) => {\n const createdAt = v.version.createdAt;\n return (\n typeof createdAt !== 'string' ||\n Date.parse(v.updatedAt) - Date.parse(createdAt) < 60_000\n );\n};\n\nconst plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;\n\n/** Labels for the top-level fields that differ between two version snapshots. */\nexport const changedFields = (\n fields: FlattenedField[],\n before: Record<string, unknown>,\n after: Record<string, unknown>\n): string[] =>\n fields.flatMap(field => {\n if (IGNORED.has(field.name)) {\n return [];\n }\n const a = before[field.name];\n const b = after[field.name];\n if (JSON.stringify(a ?? null) === JSON.stringify(b ?? null)) {\n return [];\n }\n const label = typeof field.label === 'string' ? field.label : field.name;\n if (\n (field.type === 'blocks' || field.type === 'array') &&\n Array.isArray(b)\n ) {\n const diff = b.length - (Array.isArray(a) ? a.length : 0);\n const unit = field.type === 'blocks' ? 'block' : 'row';\n if (diff > 0) {\n return [`${label} (+${plural(diff, unit)})`];\n }\n if (diff < 0) {\n return [`${label} (−${plural(-diff, unit)})`];\n }\n }\n return [label];\n });\n\n/**\n * Turns versions (newest first) into timeline entries. `older` is the version just before the\n * last one on this page, used to work out what that one changed.\n */\nexport const buildTimeline = ({\n drafts,\n fields,\n older,\n versions,\n}: {\n drafts: boolean;\n fields: FlattenedField[];\n older?: RawVersion;\n versions: RawVersion[];\n}): Entry[] => {\n const authorOf = (v: RawVersion) =>\n (v.version[AUTHOR_FIELD] as ID | null | undefined) ?? null;\n\n // A run of autosaves by one person reads as one edit, so group them first.\n const groups: RawVersion[][] = [];\n for (const v of versions) {\n const group = groups.at(-1);\n const head = group?.[0];\n if (\n group &&\n head?.autosave &&\n v.autosave &&\n String(authorOf(head)) === String(authorOf(v))\n ) {\n group.push(v);\n } else {\n groups.push([v]);\n }\n }\n\n let seen = 0;\n return groups.map(group => {\n seen += group.length;\n const newest = group[0];\n // What the whole group changed: compare the newest with the version before the oldest.\n const previous = versions[seen] ?? older;\n return {\n id: newest.id,\n author: authorOf(newest),\n changes: previous\n ? changedFields(fields, previous.version, newest.version)\n : [],\n count: group.length,\n created: !previous && isCreation(newest),\n first: !previous,\n kind: kindOf(newest, drafts),\n latest: Boolean(newest.latest),\n updatedAt: newest.updatedAt,\n };\n });\n};\n"],"names":["AUTHOR_FIELD","IGNORED","Set","kindOf","v","drafts","autosave","version","_status","isCreation","createdAt","Date","parse","updatedAt","plural","n","word","changedFields","fields","before","after","flatMap","field","has","name","a","b","JSON","stringify","label","type","Array","isArray","diff","length","unit","buildTimeline","older","versions","authorOf","groups","group","at","head","String","push","seen","map","newest","previous","id","author","changes","count","created","first","kind","latest","Boolean"],"mappings":"AAEA,OAAO,MAAMA,eAAe,YAAY;AAExC,wEAAwE,GACxE,MAAMC,UAAU,IAAIC,IAAI;IACtB;IACAF;IACA;IACA;IACA;CACD;AA8BD,MAAMG,SAAS,CAACC,GAAeC;IAC7B,IAAID,EAAEE,QAAQ,EAAE;QACd,OAAO;IACT;IACA,IAAI,CAACD,QAAQ;QACX,OAAO;IACT;IACA,OAAOD,EAAEG,OAAO,CAACC,OAAO,KAAK,cAAc,cAAc;AAC3D;AAEA;;;CAGC,GACD,MAAMC,aAAa,CAACL;IAClB,MAAMM,YAAYN,EAAEG,OAAO,CAACG,SAAS;IACrC,OACE,OAAOA,cAAc,YACrBC,KAAKC,KAAK,CAACR,EAAES,SAAS,IAAIF,KAAKC,KAAK,CAACF,aAAa;AAEtD;AAEA,MAAMI,SAAS,CAACC,GAAWC,OAAiB,GAAGD,EAAE,CAAC,EAAEC,OAAOD,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MwC,SAAyB,EAAE;IACjC,KAAK,MAAMpC,KAAKkC,SAAU;QACxB,MAAMG,QAAQD,OAAOE,EAAE,CAAC,CAAC;QACzB,MAAMC,OAAOF,OAAO,CAAC,EAAE;QACvB,IACEA,SACAE,MAAMrC,YACNF,EAAEE,QAAQ,IACVsC,OAAOL,SAASI,WAAWC,OAAOL,SAASnC,KAC3C;YACAqC,MAAMI,IAAI,CAACzC;QACb,OAAO;YACLoC,OAAOK,IAAI,CAAC;gBAACzC;aAAE;QACjB;IACF;IAEA,IAAI0C,OAAO;IACX,OAAON,OAAOO,GAAG,CAACN,CAAAA;QAChBK,QAAQL,MAAMP,MAAM;QACpB,MAAMc,SAASP,KAAK,CAAC,EAAE;QACvB,uFAAuF;QACvF,MAAMQ,WAAWX,QAAQ,CAACQ,KAAK,IAAIT;QACnC,OAAO;YACLa,IAAIF,OAAOE,EAAE;YACbC,QAAQZ,SAASS;YACjBI,SAASH,WACLhC,cAAcC,QAAQ+B,SAAS1C,OAAO,EAAEyC,OAAOzC,OAAO,IACtD,EAAE;YACN8C,OAAOZ,MAAMP,MAAM;YACnBoB,SAAS,CAACL,YAAYxC,WAAWuC;YACjCO,OAAO,CAACN;YACRO,MAAMrD,OAAO6C,QAAQ3C;YACrBoD,QAAQC,QAAQV,OAAOS,MAAM;YAC7B5C,WAAWmC,OAAOnC,SAAS;QAC7B;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../src/timeline.ts"],"sourcesContent":["import type { FlattenedField } from 'payload';\n\nexport const AUTHOR_FIELD = 'updatedBy';\n\n/** Bookkeeping fields every version has; they never count as a change. */\nconst IGNORED = new Set([\n '_status',\n AUTHOR_FIELD,\n 'createdAt',\n // Trashing and restoring are told apart below (`trash`), not listed as a changed field.\n 'deletedAt',\n 'id',\n 'updatedAt',\n]);\n\ntype ID = number | string;\n\nexport type RawVersion = {\n autosave?: boolean;\n id: ID;\n latest?: boolean;\n updatedAt: string;\n version: Record<string, unknown>;\n};\n\nexport type Kind = 'autosave' | 'draft' | 'published' | 'saved';\n\nexport type Entry = {\n author: ID | null;\n /** One label per changed field, e.g. \"Title\" or \"Layout (+2 blocks)\". */\n changes: string[];\n /** How many versions were merged into this entry (consecutive autosaves). */\n count: number;\n /** The first version saved when the document was created. */\n created: boolean;\n /** The oldest version there is, which has no earlier one to compare with. */\n first: boolean;\n id: ID;\n kind: Kind;\n latest: boolean;\n /** This save moved the document to the trash, or brought it back. */\n trash: 'restored' | 'trashed' | null;\n updatedAt: string;\n};\n\nconst kindOf = (v: RawVersion, drafts: boolean): Kind => {\n if (v.autosave) {\n return 'autosave';\n }\n if (!drafts) {\n return 'saved';\n }\n return v.version._status === 'published' ? 'published' : 'draft';\n};\n\n/**\n * Whether the first version is the document's creation. A document that existed before versions\n * were turned on gets its first version on a later save, which isn't its creation.\n */\nconst isCreation = (v: RawVersion) => {\n const createdAt = v.version.createdAt;\n return (\n typeof createdAt !== 'string' ||\n Date.parse(v.updatedAt) - Date.parse(createdAt) < 60_000\n );\n};\n\nconst plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;\n\n/** Labels for the top-level fields that differ between two version snapshots. */\nexport const changedFields = (\n fields: FlattenedField[],\n before: Record<string, unknown>,\n after: Record<string, unknown>\n): string[] =>\n fields.flatMap(field => {\n if (IGNORED.has(field.name)) {\n return [];\n }\n const a = before[field.name];\n const b = after[field.name];\n if (JSON.stringify(a ?? null) === JSON.stringify(b ?? null)) {\n return [];\n }\n const label = typeof field.label === 'string' ? field.label : field.name;\n if (\n (field.type === 'blocks' || field.type === 'array') &&\n Array.isArray(b)\n ) {\n const diff = b.length - (Array.isArray(a) ? a.length : 0);\n const unit = field.type === 'blocks' ? 'block' : 'row';\n if (diff > 0) {\n return [`${label} (+${plural(diff, unit)})`];\n }\n if (diff < 0) {\n return [`${label} (−${plural(-diff, unit)})`];\n }\n }\n return [label];\n });\n\nconst trashMove = (previous: RawVersion | undefined, newest: RawVersion) => {\n const was = Boolean(previous?.version.deletedAt);\n const is = Boolean(newest.version.deletedAt);\n return is && !was ? 'trashed' : was && !is ? 'restored' : null;\n};\n\n/**\n * Turns versions (newest first) into timeline entries. `older` is the version just before the\n * last one on this page, used to work out what that one changed.\n */\nexport const buildTimeline = ({\n drafts,\n fields,\n older,\n versions,\n}: {\n drafts: boolean;\n fields: FlattenedField[];\n older?: RawVersion;\n versions: RawVersion[];\n}): Entry[] => {\n const authorOf = (v: RawVersion) =>\n (v.version[AUTHOR_FIELD] as ID | null | undefined) ?? null;\n\n // A run of autosaves by one person reads as one edit, so group them first.\n const groups: RawVersion[][] = [];\n for (const v of versions) {\n const group = groups.at(-1);\n const head = group?.[0];\n if (\n group &&\n head?.autosave &&\n v.autosave &&\n String(authorOf(head)) === String(authorOf(v))\n ) {\n group.push(v);\n } else {\n groups.push([v]);\n }\n }\n\n let seen = 0;\n return groups.map(group => {\n seen += group.length;\n const newest = group[0];\n // What the whole group changed: compare the newest with the version before the oldest.\n const previous = versions[seen] ?? older;\n return {\n id: newest.id,\n author: authorOf(newest),\n changes: previous\n ? changedFields(fields, previous.version, newest.version)\n : [],\n count: group.length,\n created: !previous && isCreation(newest),\n first: !previous,\n kind: kindOf(newest, drafts),\n latest: Boolean(newest.latest),\n trash: trashMove(previous, newest),\n updatedAt: newest.updatedAt,\n };\n });\n};\n"],"names":["AUTHOR_FIELD","IGNORED","Set","kindOf","v","drafts","autosave","version","_status","isCreation","createdAt","Date","parse","updatedAt","plural","n","word","changedFields","fields","before","after","flatMap","field","has","name","a","b","JSON","stringify","label","type","Array","isArray","diff","length","unit","trashMove","previous","newest","was","Boolean","deletedAt","is","buildTimeline","older","versions","authorOf","groups","group","at","head","String","push","seen","map","id","author","changes","count","created","first","kind","latest","trash"],"mappings":"AAEA,OAAO,MAAMA,eAAe,YAAY;AAExC,wEAAwE,GACxE,MAAMC,UAAU,IAAIC,IAAI;IACtB;IACAF;IACA;IACA,wFAAwF;IACxF;IACA;IACA;CACD;AAgCD,MAAMG,SAAS,CAACC,G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,SAAS9B,OAAO,EAAE+B,OAAO/B,OAAO,IACtD,EAAE;YACNmD,OAAOV,MAAMd,MAAM;YACnByB,SAAS,CAACtB,YAAY5B,WAAW6B;YACjCsB,OAAO,CAACvB;YACRwB,MAAM1D,OAAOmC,QAAQjC;YACrByD,QAAQtB,QAAQF,OAAOwB,MAAM;YAC7BC,OAAO3B,UAAUC,UAAUC;YAC3BzB,WAAWyB,OAAOzB,SAAS;QAC7B;IACF;AACF,EAAE"}
@@ -50,6 +50,20 @@ const timeAgo = (iso, locale)=>{
50
50
  }
51
51
  return format.format(0, 'minute');
52
52
  };
53
+ const dayAndTime = (iso, locale)=>{
54
+ const date = new Date(iso);
55
+ return {
56
+ day: date.toLocaleDateString(locale, {
57
+ day: 'numeric',
58
+ month: 'short',
59
+ year: 'numeric'
60
+ }),
61
+ time: date.toLocaleTimeString(locale, {
62
+ hour: '2-digit',
63
+ minute: '2-digit'
64
+ })
65
+ };
66
+ };
53
67
  const describe = (entry)=>{
54
68
  if (entry.created) {
55
69
  return 'Created';
@@ -85,6 +99,8 @@ const describe = (entry)=>{
85
99
  const result = collectionConfig ? await payload.findVersions({
86
100
  ...query,
87
101
  collection: collectionConfig.slug,
102
+ // Include the versions saved while it was in the trash, so moving it there and back shows.
103
+ trash: true,
88
104
  where: {
89
105
  parent: {
90
106
  equals: docID
@@ -155,35 +171,71 @@ const describe = (entry)=>{
155
171
  className: "history__list",
156
172
  children: entries.map((entry)=>{
157
173
  const name = nameOf(entry.author);
174
+ const { day, time } = dayAndTime(entry.updatedAt, req.i18n.language);
175
+ const kind = entry.trash === 'trashed' ? 'Moved to trash' : entry.trash === 'restored' ? 'Restored from trash' : entry.count > 1 ? `${entry.count} autosaves` : KIND_LABELS[entry.kind];
158
176
  return /*#__PURE__*/ _jsxs("li", {
159
- className: "history__entry",
177
+ className: [
178
+ 'history__entry',
179
+ entry.latest && 'history__entry--latest'
180
+ ].filter(Boolean).join(' '),
160
181
  children: [
182
+ /*#__PURE__*/ _jsx("div", {
183
+ className: "history__when",
184
+ children: /*#__PURE__*/ _jsxs("time", {
185
+ dateTime: entry.updatedAt,
186
+ title: new Date(entry.updatedAt).toLocaleString(req.i18n.language, {
187
+ dateStyle: 'full',
188
+ timeStyle: 'short'
189
+ }),
190
+ children: [
191
+ /*#__PURE__*/ _jsx("span", {
192
+ className: "history__day",
193
+ children: day
194
+ }),
195
+ /*#__PURE__*/ _jsx("span", {
196
+ className: "history__time",
197
+ children: time
198
+ }),
199
+ /*#__PURE__*/ _jsx("span", {
200
+ className: "history__ago",
201
+ children: timeAgo(entry.updatedAt, req.i18n.language)
202
+ })
203
+ ]
204
+ })
205
+ }),
161
206
  /*#__PURE__*/ _jsx("span", {
162
207
  "aria-hidden": true,
163
- className: "history__avatar",
164
- children: initials(name)
208
+ className: "history__dot"
165
209
  }),
166
210
  /*#__PURE__*/ _jsxs("div", {
167
211
  className: "history__body",
168
212
  children: [
169
213
  /*#__PURE__*/ _jsxs("div", {
170
- className: "history__meta",
214
+ className: "history__title",
171
215
  children: [
172
- /*#__PURE__*/ _jsx("strong", {
173
- children: name
216
+ /*#__PURE__*/ _jsx("span", {
217
+ "aria-hidden": true,
218
+ className: "history__avatar",
219
+ children: initials(name)
174
220
  }),
175
- /*#__PURE__*/ _jsx("time", {
176
- dateTime: entry.updatedAt,
177
- title: entry.updatedAt,
178
- children: timeAgo(entry.updatedAt, req.i18n.language)
179
- }),
180
- /*#__PURE__*/ _jsx(Pill, {
181
- size: "small",
182
- children: entry.count > 1 ? `${entry.count} autosaves` : KIND_LABELS[entry.kind]
221
+ /*#__PURE__*/ _jsxs("span", {
222
+ className: "history__who",
223
+ children: [
224
+ kind,
225
+ " by ",
226
+ /*#__PURE__*/ _jsx("strong", {
227
+ children: name
228
+ })
229
+ ]
183
230
  }),
184
231
  entry.latest && /*#__PURE__*/ _jsx(Pill, {
185
232
  size: "small",
186
233
  children: "Latest"
234
+ }),
235
+ /*#__PURE__*/ _jsx("a", {
236
+ className: "history__compare",
237
+ href: url(`${base}/${entry.id}`),
238
+ children: "View changes →"
187
239
  })
188
240
  ]
189
241
  }),
@@ -192,11 +244,6 @@ const describe = (entry)=>{
192
244
  children: describe(entry)
193
245
  })
194
246
  ]
195
- }),
196
- /*#__PURE__*/ _jsx("a", {
197
- className: "history__compare",
198
- href: url(`${base}/${entry.id}`),
199
- children: "View"
200
247
  })
201
248
  ]
202
249
  }, entry.id);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/views/TimelineView.tsx"],"sourcesContent":["import { Gutter, Pill, SetDocumentStepNav } from '@payloadcms/ui';\nimport { notFound } from 'next/navigation.js';\nimport type { CollectionSlug, DocumentViewServerProps } from 'payload';\nimport { formatAdminURL } from 'payload/shared';\n\nimport type { Entry, Kind, RawVersion } from '../timeline.js';\n\nimport { buildTimeline } from '../timeline.js';\nimport './index.scss';\n\nconst PER_PAGE = 25;\n\nconst KIND_LABELS: Record<Kind, string> = {\n autosave: 'Autosave',\n draft: 'Draft',\n published: 'Published',\n saved: 'Saved',\n};\n\nconst initials = (label: string) =>\n label\n .split(/[\\s@.]+/)\n .filter(Boolean)\n .slice(0, 2)\n .map(part => part[0].toUpperCase())\n .join('');\n\nconst UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 365 * 24 * 3600],\n ['month', 30 * 24 * 3600],\n ['week', 7 * 24 * 3600],\n ['day', 24 * 3600],\n ['hour', 3600],\n ['minute', 60],\n];\n\nconst timeAgo = (iso: string, locale: string) => {\n const seconds = (Date.parse(iso) - Date.now()) / 1000;\n const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n for (const [unit, size] of UNITS) {\n if (Math.abs(seconds) >= size) {\n return format.format(Math.round(seconds / size), unit);\n }\n }\n return format.format(0, 'minute');\n};\n\nconst describe = (entry: Entry) => {\n if (entry.created) {\n return 'Created';\n }\n if (entry.first) {\n return 'First recorded version';\n }\n if (!entry.changes.length) {\n return 'No content changes';\n }\n return `Changed ${entry.changes.join(', ')}`;\n};\n\n/** Replaces Payload's versions table with a timeline: who, when, what kind of save, what changed. */\nexport const TimelineView = async ({\n initPageResult,\n searchParams,\n}: DocumentViewServerProps) => {\n const { collectionConfig, docID, globalConfig, req } = initPageResult;\n const { payload, user } = req;\n const entity = collectionConfig ?? globalConfig;\n if (!entity) {\n return notFound();\n }\n const page = Math.max(1, Number(searchParams?.page) || 1);\n\n // One extra version, so the last entry on the page can be compared with the one before it.\n // ponytail: offset paging by over-fetching; fine for hundreds of versions, switch to a\n // cursor on updatedAt if documents get thousands.\n const skip = (page - 1) * PER_PAGE;\n const query = {\n depth: 0,\n limit: skip + PER_PAGE + 1,\n overrideAccess: false,\n req,\n sort: '-updatedAt',\n user,\n } as const;\n const result = collectionConfig\n ? await payload.findVersions({\n ...query,\n collection: collectionConfig.slug,\n where: { parent: { equals: docID } },\n })\n : await payload.findGlobalVersions({ ...query, slug: globalConfig!.slug });\n const docs = (result.docs as unknown as RawVersion[]).slice(skip);\n const versions = docs.slice(0, PER_PAGE);\n const hasMore = docs.length > PER_PAGE;\n\n const entries = buildTimeline({\n drafts: Boolean(entity.versions?.drafts),\n fields: entity.flattenedFields,\n older: docs[PER_PAGE],\n versions,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n const usersSlug = payload.config.admin.user as CollectionSlug;\n const titleField =\n payload.collections[usersSlug]?.config.admin.useAsTitle ?? 'email';\n const authorIDs = [\n ...new Set(entries.map(e => e.author).filter(id => id !== null)),\n ];\n const authors = authorIDs.length\n ? (\n await payload.find({\n collection: usersSlug,\n depth: 0,\n limit: authorIDs.length,\n overrideAccess: true,\n pagination: false,\n req,\n where: { id: { in: authorIDs } },\n })\n ).docs\n : [];\n const nameOf = (id: Entry['author']) => {\n const author = authors.find(a => String(a.id) === String(id)) as\n | Record<string, unknown>\n | undefined;\n if (!author) {\n return id === null ? 'Unknown' : 'Deleted user';\n }\n return String(author[titleField] || author.email || author.id);\n };\n\n const base: `/${string}` = collectionConfig\n ? `/collections/${collectionConfig.slug}/${docID}/versions`\n : `/globals/${globalConfig!.slug}/versions`;\n const url = (path: `/${string}`) =>\n formatAdminURL({ adminRoute: payload.config.routes.admin, path });\n const label = collectionConfig\n ? typeof collectionConfig.labels.plural === 'string'\n ? collectionConfig.labels.plural\n : collectionConfig.slug\n : typeof globalConfig!.label === 'string'\n ? globalConfig!.label\n : globalConfig!.slug;\n\n return (\n <>\n <SetDocumentStepNav\n collectionSlug={collectionConfig?.slug}\n globalSlug={globalConfig?.slug}\n id={docID}\n pluralLabel={label}\n useAsTitle={collectionConfig?.admin.useAsTitle ?? globalConfig?.slug}\n view='Versions'\n />\n <main className='history'>\n <Gutter>\n {entries.length === 0 ? (\n <p>No versions yet.</p>\n ) : (\n <ol className='history__list'>\n {entries.map(entry => {\n const name = nameOf(entry.author);\n return (\n <li className='history__entry' key={entry.id}>\n <span aria-hidden className='history__avatar'>\n {initials(name)}\n </span>\n <div className='history__body'>\n <div className='history__meta'>\n <strong>{name}</strong>\n <time\n dateTime={entry.updatedAt}\n title={entry.updatedAt}\n >\n {timeAgo(entry.updatedAt, req.i18n.language)}\n </time>\n <Pill size='small'>\n {entry.count > 1\n ? `${entry.count} autosaves`\n : KIND_LABELS[entry.kind]}\n </Pill>\n {entry.latest && <Pill size='small'>Latest</Pill>}\n </div>\n <div className='history__changes'>{describe(entry)}</div>\n </div>\n {/* A plain link: Payload's client-side Link didn't navigate from this view. */}\n <a\n className='history__compare'\n href={url(`${base}/${entry.id}`)}\n >\n View\n </a>\n </li>\n );\n })}\n </ol>\n )}\n {(page > 1 || hasMore) && (\n <nav className='history__pages'>\n {page > 1 && <a href={`?page=${page - 1}`}>Newer</a>}\n {hasMore && <a href={`?page=${page + 1}`}>Older</a>}\n </nav>\n )}\n </Gutter>\n </main>\n </>\n );\n};\n"],"names":["Gutter","Pill","SetDocumentStepNav","notFound","formatAdminURL","buildTimeline","PER_PAGE","KIND_LABELS","autosave","draft","published","saved","initials","label","split","filter","Boolean","slice","map","part","toUpperCase","join","UNITS","timeAgo","iso","locale","seconds","Date","parse","now","format","Intl","RelativeTimeFormat","numeric","unit","size","Math","abs","round","describe","entry","created","first","changes","length","TimelineView","initPageResult","searchParams","collectionConfig","docID","globalConfig","req","payload","user","entity","page","max","Number","skip","query","depth","limit","overrideAccess","sort","result","findVersions","collection","slug","where","parent","equals","findGlobalVersions","docs","versions","hasMore","entries","drafts","fields","flattenedFields","older","usersSlug","config","admin","titleField","collections","useAsTitle","authorIDs","Set","e","author","id","authors","find","pagination","in","nameOf","a","String","email","base","url","path","adminRoute","routes","labels","plural","collectionSlug","globalSlug","pluralLabel","view","main","className","p","ol","name","li","span","aria-hidden","div","strong","time","dateTime","updatedAt","title","i18n","language","count","kind","latest","href","nav"],"mappings":";AAAA,SAASA,MAAM,EAAEC,IAAI,EAAEC,kBAAkB,QAAQ,iBAAiB;AAClE,SAASC,QAAQ,QAAQ,qBAAqB;AAE9C,SAASC,cAAc,QAAQ,iBAAiB;AAIhD,SAASC,aAAa,QAAQ,iBAAiB;AAC/C,OAAO,eAAe;AAEtB,MAAMC,WAAW;AAEjB,MAAMC,cAAoC;IACxCC,UAAU;IACVC,OAAO;IACPC,WAAW;IACXC,OAAO;AACT;AAEA,MAAMC,WAAW,CAACC,QAChBA,MACGC,KAAK,CAAC,WACNC,MAAM,CAACC,SACPC,KAAK,CAAC,GAAG,GACTC,GAAG,CAACC,CAAAA,OAAQA,IAAI,CAAC,EAAE,CAACC,WAAW,IAC/BC,IAAI,CAAC;AAEV,MAAMC,QAAiD;IACrD;QAAC;QAAQ,MAAM,KAAK;KAAK;IACzB;QAAC;QAAS,KAAK,KAAK;KAAK;IACzB;QAAC;QAAQ,IAAI,KAAK;KAAK;IACvB;QAAC;QAAO,KAAK;KAAK;IAClB;QAAC;QAAQ;KAAK;IACd;QAAC;QAAU;KAAG;CACf;AAED,MAAMC,UAAU,CAACC,KAAaC;IAC5B,MAAMC,UAAU,AAACC,CAAAA,KAAKC,KAAK,CAAC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;sEAErBnG,QAAQiB,MAAMkF,SAAS,EAAEvE,IAAIyE,IAAI,CAACC,QAAQ;;sEAE7C,KAAC5H;4DAAKkC,MAAK;sEACRK,MAAMsF,KAAK,GAAG,IACX,GAAGtF,MAAMsF,KAAK,CAAC,UAAU,CAAC,GAC1BvH,WAAW,CAACiC,MAAMuF,IAAI,CAAC;;wDAE5BvF,MAAMwF,MAAM,kBAAI,KAAC/H;4DAAKkC,MAAK;sEAAQ;;;;8DAEtC,KAACmF;oDAAIP,WAAU;8DAAoBxE,SAASC;;;;sDAG9C,KAACwD;4CACCe,WAAU;4CACVkB,MAAM7B,IAAI,GAAGD,KAAK,CAAC,EAAE3D,MAAMkD,EAAE,EAAE;sDAChC;;;mCA1BiClD,MAAMkD,EAAE;4BA+BhD;;wBAGFnC,CAAAA,OAAO,KAAKmB,OAAM,mBAClB,MAACwD;4BAAInB,WAAU;;gCACZxD,OAAO,mBAAK,KAACyC;oCAAEiC,MAAM,CAAC,MAAM,EAAE1E,OAAO,GAAG;8CAAE;;gCAC1CmB,yBAAW,KAACsB;oCAAEiC,MAAM,CAAC,MAAM,EAAE1E,OAAO,GAAG;8CAAE;;;;;;;;;AAOxD,EAAE"}
1
+ {"version":3,"sources":["../../src/views/TimelineView.tsx"],"sourcesContent":["import { Gutter, Pill, SetDocumentStepNav } from '@payloadcms/ui';\nimport { notFound } from 'next/navigation.js';\nimport type { CollectionSlug, DocumentViewServerProps } from 'payload';\nimport { formatAdminURL } from 'payload/shared';\n\nimport type { Entry, Kind, RawVersion } from '../timeline.js';\n\nimport { buildTimeline } from '../timeline.js';\nimport './index.scss';\n\nconst PER_PAGE = 25;\n\nconst KIND_LABELS: Record<Kind, string> = {\n autosave: 'Autosave',\n draft: 'Draft',\n published: 'Published',\n saved: 'Saved',\n};\n\nconst initials = (label: string) =>\n label\n .split(/[\\s@.]+/)\n .filter(Boolean)\n .slice(0, 2)\n .map(part => part[0].toUpperCase())\n .join('');\n\nconst UNITS: [Intl.RelativeTimeFormatUnit, number][] = [\n ['year', 365 * 24 * 3600],\n ['month', 30 * 24 * 3600],\n ['week', 7 * 24 * 3600],\n ['day', 24 * 3600],\n ['hour', 3600],\n ['minute', 60],\n];\n\nconst timeAgo = (iso: string, locale: string) => {\n const seconds = (Date.parse(iso) - Date.now()) / 1000;\n const format = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });\n for (const [unit, size] of UNITS) {\n if (Math.abs(seconds) >= size) {\n return format.format(Math.round(seconds / size), unit);\n }\n }\n return format.format(0, 'minute');\n};\n\nconst dayAndTime = (iso: string, locale: string) => {\n const date = new Date(iso);\n return {\n day: date.toLocaleDateString(locale, {\n day: 'numeric',\n month: 'short',\n year: 'numeric',\n }),\n time: date.toLocaleTimeString(locale, {\n hour: '2-digit',\n minute: '2-digit',\n }),\n };\n};\n\nconst describe = (entry: Entry) => {\n if (entry.created) {\n return 'Created';\n }\n if (entry.first) {\n return 'First recorded version';\n }\n if (!entry.changes.length) {\n return 'No content changes';\n }\n return `Changed ${entry.changes.join(', ')}`;\n};\n\n/** Replaces Payload's versions table with a timeline: who, when, what kind of save, what changed. */\nexport const TimelineView = async ({\n initPageResult,\n searchParams,\n}: DocumentViewServerProps) => {\n const { collectionConfig, docID, globalConfig, req } = initPageResult;\n const { payload, user } = req;\n const entity = collectionConfig ?? globalConfig;\n if (!entity) {\n return notFound();\n }\n const page = Math.max(1, Number(searchParams?.page) || 1);\n\n // One extra version, so the last entry on the page can be compared with the one before it.\n // ponytail: offset paging by over-fetching; fine for hundreds of versions, switch to a\n // cursor on updatedAt if documents get thousands.\n const skip = (page - 1) * PER_PAGE;\n const query = {\n depth: 0,\n limit: skip + PER_PAGE + 1,\n overrideAccess: false,\n req,\n sort: '-updatedAt',\n user,\n } as const;\n const result = collectionConfig\n ? await payload.findVersions({\n ...query,\n collection: collectionConfig.slug,\n // Include the versions saved while it was in the trash, so moving it there and back shows.\n trash: true,\n where: { parent: { equals: docID } },\n })\n : await payload.findGlobalVersions({ ...query, slug: globalConfig!.slug });\n const docs = (result.docs as unknown as RawVersion[]).slice(skip);\n const versions = docs.slice(0, PER_PAGE);\n const hasMore = docs.length > PER_PAGE;\n\n const entries = buildTimeline({\n drafts: Boolean(entity.versions?.drafts),\n fields: entity.flattenedFields,\n older: docs[PER_PAGE],\n versions,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion -- a union once a site generates types\n const usersSlug = payload.config.admin.user as CollectionSlug;\n const titleField =\n payload.collections[usersSlug]?.config.admin.useAsTitle ?? 'email';\n const authorIDs = [\n ...new Set(entries.map(e => e.author).filter(id => id !== null)),\n ];\n const authors = authorIDs.length\n ? (\n await payload.find({\n collection: usersSlug,\n depth: 0,\n limit: authorIDs.length,\n overrideAccess: true,\n pagination: false,\n req,\n where: { id: { in: authorIDs } },\n })\n ).docs\n : [];\n const nameOf = (id: Entry['author']) => {\n const author = authors.find(a => String(a.id) === String(id)) as\n | Record<string, unknown>\n | undefined;\n if (!author) {\n return id === null ? 'Unknown' : 'Deleted user';\n }\n return String(author[titleField] || author.email || author.id);\n };\n\n const base: `/${string}` = collectionConfig\n ? `/collections/${collectionConfig.slug}/${docID}/versions`\n : `/globals/${globalConfig!.slug}/versions`;\n const url = (path: `/${string}`) =>\n formatAdminURL({ adminRoute: payload.config.routes.admin, path });\n const label = collectionConfig\n ? typeof collectionConfig.labels.plural === 'string'\n ? collectionConfig.labels.plural\n : collectionConfig.slug\n : typeof globalConfig!.label === 'string'\n ? globalConfig!.label\n : globalConfig!.slug;\n\n return (\n <>\n <SetDocumentStepNav\n collectionSlug={collectionConfig?.slug}\n globalSlug={globalConfig?.slug}\n id={docID}\n pluralLabel={label}\n useAsTitle={collectionConfig?.admin.useAsTitle ?? globalConfig?.slug}\n view='Versions'\n />\n <main className='history'>\n <Gutter>\n {entries.length === 0 ? (\n <p>No versions yet.</p>\n ) : (\n <ol className='history__list'>\n {entries.map(entry => {\n const name = nameOf(entry.author);\n const { day, time } = dayAndTime(\n entry.updatedAt,\n req.i18n.language\n );\n const kind =\n entry.trash === 'trashed'\n ? 'Moved to trash'\n : entry.trash === 'restored'\n ? 'Restored from trash'\n : entry.count > 1\n ? `${entry.count} autosaves`\n : KIND_LABELS[entry.kind];\n return (\n <li\n className={[\n 'history__entry',\n entry.latest && 'history__entry--latest',\n ]\n .filter(Boolean)\n .join(' ')}\n key={entry.id}\n >\n <div className='history__when'>\n <time\n dateTime={entry.updatedAt}\n title={new Date(entry.updatedAt).toLocaleString(\n req.i18n.language,\n { dateStyle: 'full', timeStyle: 'short' }\n )}\n >\n <span className='history__day'>{day}</span>\n <span className='history__time'>{time}</span>\n <span className='history__ago'>\n {timeAgo(entry.updatedAt, req.i18n.language)}\n </span>\n </time>\n </div>\n <span aria-hidden className='history__dot' />\n <div className='history__body'>\n <div className='history__title'>\n <span aria-hidden className='history__avatar'>\n {initials(name)}\n </span>\n <span className='history__who'>\n {kind} by <strong>{name}</strong>\n </span>\n {entry.latest && <Pill size='small'>Latest</Pill>}\n {/* A plain link: Payload's client-side Link didn't navigate from this view. */}\n <a\n className='history__compare'\n href={url(`${base}/${entry.id}`)}\n >\n View changes →\n </a>\n </div>\n <div className='history__changes'>{describe(entry)}</div>\n </div>\n </li>\n );\n })}\n </ol>\n )}\n {(page > 1 || hasMore) && (\n <nav className='history__pages'>\n {page > 1 && <a href={`?page=${page - 1}`}>Newer</a>}\n {hasMore && <a href={`?page=${page + 1}`}>Older</a>}\n </nav>\n )}\n </Gutter>\n </main>\n </>\n );\n};\n"],"names":["Gutter","Pill","SetDocumentStepNav","notFound","formatAdminURL","buildTimeline","PER_PAGE","KIND_LABELS","autosave","draft","published","saved","initials","label","split","filter","Boolean","slice","map","part","toUpperCase","join","UNITS","timeAgo","iso","locale","seconds","Date","parse","now","format","Intl","RelativeTimeFormat","numeric","unit","size","Math","abs","round","dayAndTime","date","day","toLocaleDateString","month","year","time","toLocaleTimeString","hour","minute","describe","entry","created","first","changes","length","TimelineView","initPageResult","searchParams","collectionConfig","docID","globalConfig","req","payload","user","entity","page","max","Number","skip","query","depth","limit","overrideAccess","sort","result","findVersions","collection","slug","trash","where","parent","equals","findGlobalVersions","docs","versions","hasMore","entries","drafts","fields","flattenedFields","older","usersSlug","config","admin","titleField","collections","useAsTitle","authorIDs","Set","e","author","id","authors","find","pagination","in","nameOf","a","String","email","base","url","path","adminRoute","routes","labels","plural","collectionSlug","globalSlug","pluralLabel","view","main","className","p","ol","name","updatedAt","i18n","language","kind","count","li","latest","div","dateTime","title","toLocaleString","dateStyle","timeStyle","span","aria-hidden","strong","href","nav"],"mappings":";AAAA,SAASA,MAAM,EAAEC,IAAI,EAAEC,kBAAkB,QAAQ,iBAAiB;AAClE,SAASC,QAAQ,QAAQ,qBAAqB;AAE9C,SAASC,cAAc,QAAQ,iBAAiB;AAIhD,SAASC,aAAa,QAAQ,iBAAiB;AAC/C,OAAO,eAAe;AAEtB,MAAMC,WAAW;AAEjB,MAAMC,cAAoC;IACxCC,UAAU;IACVC,OAAO;IACPC,WAAW;IACXC,OAAO;AACT;AAEA,MAAMC,WAAW,CAACC,QAChBA,MACGC,KAAK,CAAC,WACNC,MAAM,CAACC,SACPC,KAAK,CAAC,GAAG,GACTC,GAAG,CAACC,CAAAA,OAAQA,IAAI,CAAC,EAAE,CAACC,WAAW,IAC/BC,IAAI,CAAC;AAEV,MAAMC,QAAiD;IACrD;QAAC;QAAQ,MAAM,KAAK;KAAK;IACzB;QAAC;QAAS,KAAK,KAAK;KAAK;IACzB;QAAC;QAAQ,IAAI,KAAK;KAAK;IACvB;QAAC;QAAO,KAAK;KAAK;IAClB;QAAC;QAAQ;KAAK;IACd;QAAC;QAAU;KAAG;CACf;AAED,MAAMC,UAAU,CAACC,KAAaC;IAC5B,MAAMC,UAAU,AAACC,CAAAA,KAAKC,KAAK,CAACJ,OAAOG,KAAKE,GAAG,EAAC,IAAK;IACjD,MAAMC,SAAS,IAAIC,KAAKC,kBAAkB,CAACP,QAAQ;QAAEQ,SAAS;IAAO;IACrE,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CnB;;wBAGFpC,CAAAA,OAAO,KAAKoB,OAAM,mBAClB,MAAC0D;4BAAIrB,WAAU;;gCACZzD,OAAO,mBAAK,KAAC0C;oCAAEmC,MAAM,CAAC,MAAM,EAAE7E,OAAO,GAAG;8CAAE;;gCAC1CoB,yBAAW,KAACsB;oCAAEmC,MAAM,CAAC,MAAM,EAAE7E,OAAO,GAAG;8CAAE;;;;;;;;;AAOxD,EAAE"}
@@ -4,56 +4,125 @@
4
4
  padding-bottom: calc(var(--base) * 4);
5
5
  }
6
6
 
7
+ // A vertical timeline: when on the left, a line with a dot per save, what happened on the right.
7
8
  .history__list {
8
9
  list-style: none;
9
- margin: 0;
10
+ margin: calc(var(--base) * 0.5) 0 0;
10
11
  padding: 0;
11
12
  }
12
13
 
13
14
  .history__entry {
14
- align-items: center;
15
- border-bottom: 1px solid var(--theme-elevation-100);
16
- display: flex;
17
- gap: var(--base);
18
- padding: calc(var(--base) * 0.75) 0;
15
+ column-gap: calc(var(--base) * 1.25);
16
+ display: grid;
17
+ grid-template-columns: 9rem 0.75rem minmax(0, 1fr);
18
+ padding-bottom: var(--base);
19
+ position: relative;
20
+
21
+ // The line, from this dot down to the next one.
22
+ &::before {
23
+ background: var(--theme-elevation-150);
24
+ bottom: 0;
25
+ content: "";
26
+ left: calc(9rem + var(--base) * 1.25 + 0.375rem - 1px);
27
+ position: absolute;
28
+ top: 1.25rem;
29
+ width: 2px;
30
+ }
31
+
32
+ &:last-child::before {
33
+ display: none;
34
+ }
19
35
  }
20
36
 
21
- .history__avatar {
22
- align-items: center;
23
- background: var(--theme-elevation-150);
37
+ .history__when {
38
+ padding-top: 0.75rem;
39
+ text-align: right;
40
+
41
+ time {
42
+ display: flex;
43
+ flex-direction: column;
44
+ gap: 0.125rem;
45
+ }
46
+ }
47
+
48
+ .history__day {
49
+ font-weight: 600;
50
+ }
51
+
52
+ .history__time,
53
+ .history__ago {
54
+ color: var(--theme-elevation-500);
55
+ font-size: 0.85em;
56
+ }
57
+
58
+ .history__dot {
59
+ background: var(--theme-bg);
60
+ border: 2px solid var(--theme-elevation-400);
24
61
  border-radius: 50%;
25
- display: inline-flex;
26
- flex-shrink: 0;
27
- font-size: 0.75em;
28
- height: 32px;
29
- justify-content: center;
30
- width: 32px;
62
+ height: 0.75rem;
63
+ margin-top: 1rem;
64
+ position: relative;
65
+ width: 0.75rem;
66
+ z-index: 1;
67
+
68
+ .history__entry--latest & {
69
+ background: var(--theme-success-500);
70
+ border-color: var(--theme-success-500);
71
+ }
31
72
  }
32
73
 
33
74
  .history__body {
34
- flex: 1;
75
+ background: var(--theme-elevation-50);
76
+ border: 1px solid var(--theme-elevation-100);
77
+ border-radius: var(--style-radius-m);
78
+ display: flex;
79
+ flex-direction: column;
80
+ gap: calc(var(--base) * 0.25);
35
81
  min-width: 0;
82
+ padding: calc(var(--base) * 0.75) var(--base);
83
+
84
+ .history__entry--latest & {
85
+ border-color: var(--theme-success-250);
86
+ }
36
87
  }
37
88
 
38
- .history__meta {
39
- align-items: center;
89
+ .history__title {
90
+ align-items: flex-start;
40
91
  display: flex;
41
- flex-wrap: wrap;
92
+ font-size: 1.1em;
42
93
  gap: calc(var(--base) * 0.5);
94
+ }
43
95
 
44
- time {
45
- color: var(--theme-elevation-500);
46
- }
96
+ // Long names (often an email) wrap beside the avatar instead of pushing it onto its own line.
97
+ .history__who {
98
+ min-width: 0;
99
+ overflow-wrap: anywhere;
100
+ padding-top: 0.0625rem;
101
+ }
102
+
103
+ .history__avatar {
104
+ align-items: center;
105
+ background: var(--theme-elevation-150);
106
+ border-radius: 50%;
107
+ display: inline-flex;
108
+ flex-shrink: 0;
109
+ font-size: 0.65em;
110
+ margin-top: 0.125rem;
111
+ height: 1.5rem;
112
+ justify-content: center;
113
+ width: 1.5rem;
47
114
  }
48
115
 
49
116
  .history__changes {
50
117
  color: var(--theme-elevation-600);
51
- margin-top: calc(var(--base) * 0.25);
52
118
  overflow-wrap: anywhere;
53
119
  }
54
120
 
55
121
  .history__compare {
56
122
  flex-shrink: 0;
123
+ font-size: 0.9em;
124
+ margin-left: auto;
125
+ white-space: nowrap;
57
126
  }
58
127
 
59
128
  .history__pages {
@@ -66,3 +135,29 @@
66
135
  color: var(--theme-elevation-600);
67
136
  white-space: nowrap;
68
137
  }
138
+
139
+ @media (max-width: 40rem) {
140
+ .history__entry {
141
+ grid-template-columns: 0.75rem minmax(0, 1fr);
142
+
143
+ &::before {
144
+ left: calc(0.375rem - 1px);
145
+ }
146
+ }
147
+
148
+ .history__when {
149
+ grid-column: 2;
150
+ grid-row: 2;
151
+ text-align: left;
152
+
153
+ time {
154
+ flex-direction: row;
155
+ gap: 0.5rem;
156
+ }
157
+ }
158
+
159
+ .history__dot {
160
+ grid-column: 1;
161
+ grid-row: 1;
162
+ }
163
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/history-plugin",
3
- "version": "0.2.1",
3
+ "version": "0.2.3",
4
4
  "description": "Version history for Payload CMS 3: who made each version, a timeline of changes and a clearer compare view",
5
5
  "license": "MIT",
6
6
  "repository": {