@foundrykit/history-plugin 0.2.0 → 0.2.1
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.
- package/README.md +2 -2
- package/dist/exports/client.js.map +1 -1
- package/dist/exports/rsc.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/timeline.js +1 -1
- package/dist/timeline.js.map +1 -1
- package/dist/views/TimelineView.d.ts +1 -1
- package/dist/views/TimelineView.js +1 -2
- package/dist/views/TimelineView.js.map +1 -1
- package/dist/views/VersionAuthor.d.ts +1 -1
- package/dist/views/VersionAuthor.js +0 -1
- package/dist/views/VersionAuthor.js.map +1 -1
- package/package.json +28 -44
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@ straight into Payload's compare view.
|
|
|
6
6
|
## Setup
|
|
7
7
|
|
|
8
8
|
```ts
|
|
9
|
-
import { historyPlugin } from '@foundrykit/history-plugin'
|
|
9
|
+
import { historyPlugin } from '@foundrykit/history-plugin';
|
|
10
10
|
|
|
11
11
|
export default buildConfig({
|
|
12
12
|
plugins: [
|
|
@@ -15,7 +15,7 @@ export default buildConfig({
|
|
|
15
15
|
// Or name them:
|
|
16
16
|
// historyPlugin({ collections: ['pages'], globals: ['settings'] }),
|
|
17
17
|
],
|
|
18
|
-
})
|
|
18
|
+
});
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
Run `payload generate:importmap` afterwards.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export {}
|
|
1
|
+
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["export {};\n"],"names":[],"mappings":"AAAA,WAAU"}
|
package/dist/exports/rsc.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { TimelineView } from '../views/TimelineView.js'
|
|
1
|
+
{"version":3,"sources":["../../src/exports/rsc.ts"],"sourcesContent":["export { TimelineView } from '../views/TimelineView.js';\nexport { VersionAuthor } from '../views/VersionAuthor.js';\n"],"names":["TimelineView","VersionAuthor"],"mappings":"AAAA,SAASA,YAAY,QAAQ,2BAA2B;AACxD,SAASC,aAAa,QAAQ,4BAA4B"}
|
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<NonNullable<CollectionConfig['admin']>['components']>['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: [({ req }) => (req.user?.collection === usersSlug ? req.user.id : null)],\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 = (kind: string, wanted: string[] | undefined, versioned: string[]) => {\n for (const slug of wanted ?? []) {\n if (!versioned.includes(slug)) {\n throw new Error(`history: ${kind} \"${slug}\" doesn't exist or has versions turned off`)\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 = (collection: CollectionConfig, usersSlug: string): 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.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) => payload.config.globals.find((g) => g.slug === global.slug)?.access.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) => (trackedGlobals.has(g.slug) ? trackGlobal(g, usersSlug) : g)),\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,gBAAe;AAE5C,SAASA,YAAY,QAAQ,gBAAe;AAS5C,MAAMC,WAAW;AACjB,MAAMC,iBAAiB;AAIvB;;;CAGC,GACD,MAAMC,eAAe,CAACC,QAA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AAIY,YAAYI,GAAGnD,aAAamD;QACxF;IACF,EAAC"}
|
|
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;g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word}${n === 1 ? '' : 's'}`;
|
|
|
61
61
|
for (const v of versions){
|
|
62
62
|
const group = groups.at(-1);
|
|
63
63
|
const head = group?.[0];
|
|
64
|
-
if (
|
|
64
|
+
if (group && head?.autosave && v.autosave && String(authorOf(head)) === String(authorOf(v))) {
|
|
65
65
|
group.push(v);
|
|
66
66
|
} else {
|
|
67
67
|
groups.push([
|
package/dist/timeline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/timeline.ts"],"sourcesContent":["import type { FlattenedField } from 'payload'
|
|
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,MAAM,IAAI,KAAK,KAAK;AAE/E,+EAA+E,GAC/E,OAAO,MAAME,gBAAgB,CAC3BC,QACAC,QACAC,QAEAF,OAAOG,OAAO,CAACC,CAAAA;QACb,IAAIrB,QAAQsB,GAAG,CAACD,MAAME,IAAI,GAAG;YAC3B,OAAO,EAAE;QACX;QACA,MAAMC,IAAIN,MAAM,CAACG,MAAME,IAAI,CAAC;QAC5B,MAAME,IAAIN,KAAK,CAACE,MAAME,IAAI,CAAC;QAC3B,IAAIG,KAAKC,SAAS,CAACH,KAAK,UAAUE,KAAKC,SAAS,CAACF,KAAK,OAAO;YAC3D,OAAO,EA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AQL,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,4 +1,4 @@
|
|
|
1
1
|
import type { DocumentViewServerProps } from 'payload';
|
|
2
2
|
import './index.scss';
|
|
3
3
|
/** Replaces Payload's versions table with a timeline: who, when, what kind of save, what changed. */
|
|
4
|
-
export declare const TimelineView: ({ initPageResult, searchParams }: DocumentViewServerProps) => Promise<import("react/jsx-runtime").JSX.Element>;
|
|
4
|
+
export declare const TimelineView: ({ initPageResult, searchParams, }: DocumentViewServerProps) => Promise<import("react/jsx-runtime").JSX.Element>;
|
|
@@ -2,7 +2,6 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
|
|
|
2
2
|
import { Gutter, Pill, SetDocumentStepNav } from '@payloadcms/ui';
|
|
3
3
|
import { notFound } from 'next/navigation.js';
|
|
4
4
|
import { formatAdminURL } from 'payload/shared';
|
|
5
|
-
import React from 'react';
|
|
6
5
|
import { buildTimeline } from '../timeline.js';
|
|
7
6
|
import './index.scss';
|
|
8
7
|
const PER_PAGE = 25;
|
|
@@ -99,7 +98,7 @@ const describe = (entry)=>{
|
|
|
99
98
|
const versions = docs.slice(0, PER_PAGE);
|
|
100
99
|
const hasMore = docs.length > PER_PAGE;
|
|
101
100
|
const entries = buildTimeline({
|
|
102
|
-
drafts: Boolean(entity.versions
|
|
101
|
+
drafts: Boolean(entity.versions?.drafts),
|
|
103
102
|
fields: entity.flattenedFields,
|
|
104
103
|
older: docs[PER_PAGE],
|
|
105
104
|
versions
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/views/TimelineView.tsx"],"sourcesContent":["import type { CollectionSlug, DocumentViewServerProps } from 'payload'\n\nimport { Gutter, Pill, SetDocumentStepNav } from '@payloadcms/ui'\nimport { notFound } from 'next/navigation.js'\nimport { formatAdminURL } from 'payload/shared'\nimport React from 'react'\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 ({ initPageResult, searchParams }: 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 && 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 = payload.collections[usersSlug]?.config.admin.useAsTitle ?? 'email'\n const authorIDs = [...new Set(entries.map((e) => e.author).filter((id) => id !== null))]\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> | 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 dateTime={entry.updatedAt} title={entry.updatedAt}>\n {timeAgo(entry.updatedAt, req.i18n.language)}\n </time>\n <Pill size=\"small\">\n {entry.count > 1 ? `${entry.count} autosaves` : 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 className=\"history__compare\" href={url(`${base}/${entry.id}`)}>\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","React","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":";AAEA,SAASA,MAAM,EAAEC,IAAI,EAAEC,kBAAkB,QAAQ,iBAAgB;AACjE,SAASC,QAAQ,QAAQ,qBAAoB;AAC7C,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,OAAOC,WAAW,QAAO;AAIzB,SAASC,aAAa,QAAQ,iBAAgB;AAC9C,OAAO,eAAc;AAErB,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,CAAC,CAACC,OAASA,IAAI,CAAC,EAAE,CAACC,WAAW,IACjCC,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,KAAK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EvE,IAAIyE,IAAI,CAACC,QAAQ;;sEAE7C,KAAC7H;4DAAKmC,MAAK;sEACRK,MAAMsF,KAAK,GAAG,IAAI,GAAGtF,MAAMsF,KAAK,CAAC,UAAU,CAAC,GAAGvH,WAAW,CAACiC,MAAMuF,IAAI,CAAC;;wDAExEvF,MAAMwF,MAAM,kBAAI,KAAChI;4DAAKmC,MAAK;sEAAQ;;;;8DAEtC,KAACmF;oDAAIP,WAAU;8DAAoBxE,SAASC;;;;sDAG9C,KAACwD;4CAAEe,WAAU;4CAAmBkB,MAAM7B,IAAI,GAAGD,KAAK,CAAC,EAAE3D,MAAMkD,EAAE,EAAE;sDAAG;;;mCAlBhClD,MAAMkD,EAAE;4BAuBhD;;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,EAAC"}
|
|
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,Q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
|
req: PayloadRequest;
|
|
10
10
|
};
|
|
11
11
|
/** Header action on a single version: who saved it. Payload's version view doesn't say. */
|
|
12
|
-
export declare const VersionAuthor: ({ collectionSlug, globalSlug, params, req }: Props) => Promise<import("react/jsx-runtime").JSX.Element | null>;
|
|
12
|
+
export declare const VersionAuthor: ({ collectionSlug, globalSlug, params, req, }: Props) => Promise<import("react/jsx-runtime").JSX.Element | null>;
|
|
13
13
|
export {};
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
import React from 'react';
|
|
3
2
|
import { AUTHOR_FIELD } from '../timeline.js';
|
|
4
3
|
import './index.scss';
|
|
5
4
|
/** Header action on a single version: who saved it. Payload's version view doesn't say. */ export const VersionAuthor = async ({ collectionSlug, globalSlug, params, req })=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/views/VersionAuthor.tsx"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload'
|
|
1
|
+
{"version":3,"sources":["../../src/views/VersionAuthor.tsx"],"sourcesContent":["import type { CollectionSlug, PayloadRequest } from 'payload';\n\nimport { AUTHOR_FIELD } from '../timeline.js';\nimport './index.scss';\n\ntype Props = {\n collectionSlug?: CollectionSlug;\n globalSlug?: string;\n params?: { segments?: string[] };\n req: PayloadRequest;\n};\n\n/** Header action on a single version: who saved it. Payload's version view doesn't say. */\nexport const VersionAuthor = async ({\n collectionSlug,\n globalSlug,\n params,\n req,\n}: Props) => {\n const id = params?.segments?.at(-1);\n if (!id || (!collectionSlug && !globalSlug)) {\n return null;\n }\n const { payload } = req;\n const query = {\n id,\n depth: 0,\n overrideAccess: false,\n req,\n user: req.user,\n } as const;\n const version = await (collectionSlug\n ? payload.findVersionByID({ ...query, collection: collectionSlug })\n : payload.findGlobalVersionByID({ ...query, slug: globalSlug! })\n ).catch(() => null);\n if (!version) {\n return null;\n }\n\n const authorID = (version.version as Record<string, unknown>)[AUTHOR_FIELD];\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 // Names only, so like the timeline this skips the users collection's read access.\n const author =\n authorID == null\n ? null\n : ((await payload\n .findByID({\n id: authorID as number | string,\n collection: usersSlug,\n depth: 0,\n overrideAccess: true,\n req,\n })\n .catch(() => null)) as null | Record<string, unknown>);\n const name = author\n ? String(author[titleField] || author.email || author.id)\n : authorID == null\n ? 'Unknown'\n : 'Deleted user';\n\n return (\n <span className='history__version-author'>\n Edited by <strong>{name}</strong>\n </span>\n );\n};\n"],"names":["AUTHOR_FIELD","VersionAuthor","collectionSlug","globalSlug","params","req","id","segments","at","payload","query","depth","overrideAccess","user","version","findVersionByID","collection","findGlobalVersionByID","slug","catch","authorID","usersSlug","config","admin","titleField","collections","useAsTitle","author","findByID","name","String","email","span","className","strong"],"mappings":";AAEA,SAASA,YAAY,QAAQ,iBAAiB;AAC9C,OAAO,eAAe;AAStB,yFAAyF,GACzF,OAAO,MAAMC,gBAAgB,OAAO,EAClCC,cAAc,EACdC,UAAU,EACVC,MAAM,EACNC,GAAG,EACG;IACN,MAAMC,KAAKF,QAAQG,UAAUC,GAAG,CAAC;IACjC,IAAI,CAACF,MAAO,CAACJ,kBAAkB,CAACC,YAAa;QAC3C,OAAO;IACT;IACA,MAAM,EAAEM,OAAO,EAAE,GAAGJ;IACpB,MAAMK,QAAQ;QACZJ;QACAK,OAAO;QACPC,gBAAgB;QAChBP;QACAQ,MAAMR,IAAIQ,IAAI;IAChB;IACA,MAAMC,UAAU,MAAM,AAACZ,CAAAA,iBACnBO,QAAQM,eAAe,CAAC;QAAE,GAAGL,KAAK;QAAEM,YAAYd;IAAe,KAC/DO,QAAQQ,qBAAqB,CAAC;QAAE,GAAGP,KAAK;QAAEQ,MAAMf;IAAY,EAAC,EAC/DgB,KAAK,CAAC,IAAM;IACd,IAAI,CAACL,SAAS;QACZ,OAAO;IACT;IAEA,MAAMM,WAAW,AAACN,QAAQA,OAAO,AAA4B,CAACd,aAAa;IAC3E,mHAAmH;IACnH,MAAMqB,YAAYZ,QAAQa,MAAM,CAACC,KAAK,CAACV,IAAI;IAC3C,MAAMW,aACJf,QAAQgB,WAAW,CAACJ,UAAU,EAAEC,OAAOC,MAAMG,cAAc;IAC7D,kFAAkF;IAClF,MAAMC,SACJP,YAAY,OACR,OACE,MAAMX,QACLmB,QAAQ,CAAC;QACRtB,IAAIc;QACJJ,YAAYK;QACZV,OAAO;QACPC,gBAAgB;QAChBP;IACF,GACCc,KAAK,CAAC,IAAM;IACrB,MAAMU,OAAOF,SACTG,OAAOH,MAAM,CAACH,WAAW,IAAIG,OAAOI,KAAK,IAAIJ,OAAOrB,EAAE,IACtDc,YAAY,OACV,YACA;IAEN,qBACE,MAACY;QAAKC,WAAU;;YAA0B;0BAC9B,KAACC;0BAAQL;;;;AAGzB,EAAE"}
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@foundrykit/history-plugin",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
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": {
|
|
7
7
|
"type": "git",
|
|
8
|
-
"url": "git+https://github.com/umi-labs/
|
|
8
|
+
"url": "git+https://github.com/umi-labs/foundry.git",
|
|
9
|
+
"directory": "packages/payload/history-plugin"
|
|
9
10
|
},
|
|
10
11
|
"type": "module",
|
|
11
12
|
"exports": {
|
|
@@ -30,37 +31,11 @@
|
|
|
30
31
|
"files": [
|
|
31
32
|
"dist"
|
|
32
33
|
],
|
|
33
|
-
"scripts": {
|
|
34
|
-
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
|
35
|
-
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths --ignore \"**/*.test.ts\"",
|
|
36
|
-
"build:types": "tsc --outDir dist --rootDir ./src",
|
|
37
|
-
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
38
|
-
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
|
|
39
|
-
"dev": "next dev dev --turbo",
|
|
40
|
-
"dev:generate-importmap": "pnpm dev:payload generate:importmap",
|
|
41
|
-
"dev:generate-types": "pnpm dev:payload generate:types",
|
|
42
|
-
"dev:payload": "cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload",
|
|
43
|
-
"generate:importmap": "pnpm dev:generate-importmap",
|
|
44
|
-
"generate:types": "pnpm dev:generate-types",
|
|
45
|
-
"lint": "eslint",
|
|
46
|
-
"lint:fix": "eslint ./src --fix",
|
|
47
|
-
"prepublishOnly": "pnpm build && node scripts/verify-pack.mjs",
|
|
48
|
-
"verify:pack": "node scripts/verify-pack.mjs",
|
|
49
|
-
"release": "release-it",
|
|
50
|
-
"release:dry": "release-it --dry-run",
|
|
51
|
-
"test": "pnpm test:unit && pnpm test:int && pnpm test:e2e",
|
|
52
|
-
"test:unit": "vitest run src",
|
|
53
|
-
"test:e2e": "playwright test",
|
|
54
|
-
"test:int": "vitest run dev/int.spec.ts"
|
|
55
|
-
},
|
|
56
34
|
"devDependencies": {
|
|
57
|
-
"@eslint/eslintrc": "^3.2.0",
|
|
58
35
|
"@payloadcms/db-mongodb": "3.84.1",
|
|
59
|
-
"@payloadcms/eslint-config": "3.28.0",
|
|
60
36
|
"@payloadcms/next": "3.84.1",
|
|
61
37
|
"@payloadcms/ui": "3.84.1",
|
|
62
38
|
"@playwright/test": "1.58.2",
|
|
63
|
-
"@release-it/conventional-changelog": "^11.0.0",
|
|
64
39
|
"@swc-node/register": "1.10.9",
|
|
65
40
|
"@swc/cli": "0.6.0",
|
|
66
41
|
"@types/node": "22.19.9",
|
|
@@ -68,21 +43,17 @@
|
|
|
68
43
|
"@types/react-dom": "19.2.3",
|
|
69
44
|
"copyfiles": "2.4.1",
|
|
70
45
|
"cross-env": "^7.0.3",
|
|
71
|
-
"eslint": "^9.23.0",
|
|
72
|
-
"eslint-config-next": "16.2.6",
|
|
73
46
|
"graphql": "^16.8.1",
|
|
74
47
|
"mongodb-memory-server": "10.1.4",
|
|
75
48
|
"next": "16.2.6",
|
|
76
49
|
"payload": "3.84.1",
|
|
77
|
-
"prettier": "^3.4.2",
|
|
78
50
|
"react": "19.2.6",
|
|
79
51
|
"react-dom": "19.2.6",
|
|
80
|
-
"release-it": "^20.0.1",
|
|
81
52
|
"rimraf": "3.0.2",
|
|
82
53
|
"sharp": "0.34.2",
|
|
83
|
-
"typescript": "5.
|
|
54
|
+
"typescript": "5.9.2",
|
|
84
55
|
"vite-tsconfig-paths": "6.0.5",
|
|
85
|
-
"vitest": "4.
|
|
56
|
+
"vitest": "4.1.10"
|
|
86
57
|
},
|
|
87
58
|
"peerDependencies": {
|
|
88
59
|
"@payloadcms/next": "^3.84.1",
|
|
@@ -92,18 +63,31 @@
|
|
|
92
63
|
"react": "^19"
|
|
93
64
|
},
|
|
94
65
|
"engines": {
|
|
95
|
-
"node": "
|
|
96
|
-
"pnpm": "^9 || ^10"
|
|
66
|
+
"node": ">=20.9.0"
|
|
97
67
|
},
|
|
98
68
|
"publishConfig": {
|
|
99
69
|
"access": "public"
|
|
100
70
|
},
|
|
101
|
-
"
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
"esbuild",
|
|
105
|
-
"unrs-resolver"
|
|
106
|
-
]
|
|
71
|
+
"homepage": "https://github.com/umi-labs/foundry/tree/prod/packages/payload/history-plugin#readme",
|
|
72
|
+
"bugs": {
|
|
73
|
+
"url": "https://github.com/umi-labs/foundry/issues"
|
|
107
74
|
},
|
|
108
|
-
"
|
|
109
|
-
|
|
75
|
+
"scripts": {
|
|
76
|
+
"build": "pnpm copyfiles && pnpm build:types && pnpm build:swc",
|
|
77
|
+
"build:swc": "swc ./src -d ./dist --config-file .swcrc --strip-leading-paths --ignore \"**/*.test.ts\"",
|
|
78
|
+
"build:types": "tsc --outDir dist --rootDir ./src",
|
|
79
|
+
"clean": "rimraf {dist,*.tsbuildinfo}",
|
|
80
|
+
"copyfiles": "copyfiles -u 1 \"src/**/*.{html,css,scss,ttf,woff,woff2,eot,svg,jpg,png,json}\" dist/",
|
|
81
|
+
"dev": "next dev dev --turbo",
|
|
82
|
+
"dev:generate-importmap": "pnpm dev:payload generate:importmap",
|
|
83
|
+
"dev:generate-types": "pnpm dev:payload generate:types",
|
|
84
|
+
"dev:payload": "cross-env PAYLOAD_CONFIG_PATH=./dev/payload.config.ts payload",
|
|
85
|
+
"generate:importmap": "pnpm dev:generate-importmap",
|
|
86
|
+
"generate:types": "pnpm dev:generate-types",
|
|
87
|
+
"verify:pack": "node scripts/verify-pack.mjs",
|
|
88
|
+
"test": "pnpm test:unit && pnpm test:int",
|
|
89
|
+
"test:unit": "vitest run src",
|
|
90
|
+
"test:e2e": "playwright test",
|
|
91
|
+
"test:int": "vitest run dev/int.spec.ts"
|
|
92
|
+
}
|
|
93
|
+
}
|