Skip to content

Instantly share code, notes, and snippets.

@DrMint
Last active October 25, 2024 10:59
Show Gist options
  • Save DrMint/b4a25460a2d3167acb37c13358898297 to your computer and use it in GitHub Desktop.
Save DrMint/b4a25460a2d3167acb37c13358898297 to your computer and use it in GitHub Desktop.
Grid View for Payload Uploads Collections
import { CollectionConfig } from "payload/types";
import { UploadsGridView } from "../../components/UploadsGridView/UploadsGridView";
export const Media: CollectionConfig = {
slug: "media",
admin: {
components: { views: { List: UploadsGridView } } // Set the List view to use the Grid view,
},
upload: {
staticURL: "/media",
staticDir: "media",
imageSizes: [
{
name: "thumbnail",
width: 400,
height: 300,
position: "centre",
},
{
name: "card",
width: 768,
height: 1024,
position: "centre",
},
],
adminThumbnail: "thumbnail", // This will be image size used in Grid view
mimeTypes: ["image/*"],
},
fields: [],
};
.grid {
margin-bottom: 25px;
> .grid__header {
margin-bottom: 15px;
display: flex;
gap: 1.5rem;
}
> .grid__cells {
display: grid;
grid-gap: 1rem;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
> .grid__cells__cell {
display: grid;
grid-template-rows: 1fr;
background-color: var(--theme-elevation-50);
border: 1px solid var(--theme-elevation-100);
position: relative;
> .grid__cells__cell__filename {
position: relative;
aspect-ratio: 1;
.thumbnail {
> img {
position: absolute;
inset: 0;
object-fit: contain;
background-size: 10% 10%;
background-image: radial-gradient(
circle,
var(--theme-elevation-100) 1px,
var(--theme-elevation-0) 1px
);
}
}
}
> .grid__cells__cell__selector {
position: absolute;
left: 0.75rem;
top: 0.75rem;
}
> .grid__cells__cell__info {
display: grid;
line-height: 1.5;
padding: 1rem;
gap: 0.5rem;
overflow-x: hidden;
> .grid__cells__cell__title {
font-weight: 600;
}
> .grid__cells__cell__others {
display: grid;
line-height: 1.5;
color: var(--theme-elevation-600);
width: 100%;
font-size: 90%;
}
}
}
}
}
import { useTableColumns } from "payload/dist/admin/components/elements/TableColumns";
import React, { Fragment } from "react";
import { Link } from "react-router-dom";
import "payload/dist/admin/components/elements/Table/index.scss";
import { Column } from "payload/dist/admin/components/elements/Table/types";
import Thumbnail from "payload/dist/admin/components/elements/Thumbnail";
import { SanitizedCollectionConfig } from "payload/types";
import './Grid.scss';
const baseClass = "grid";
type Props = {
data: any[];
collection: SanitizedCollectionConfig;
};
const fieldNames = {
filename: "filename",
select: "_select",
};
export const Grid: React.FC<Props> = ({ data, collection }) => {
const { columns: columnsFromContext } = useTableColumns();
const fields = columnsFromContext;
const otherFields = fields?.filter(
(col) => col.active && ![fieldNames.filename, fieldNames.select].includes(col.accessor)
);
const filenameField = fields.find((col) => col.accessor === fieldNames.filename);
const selectorField = fields.find((col) => col.accessor === fieldNames.select);
const headerColumns = fields
.sort((a, b) => {
const sortingValue = (value: Column) => {
switch (value.accessor) {
case fieldNames.select:
return 2;
case fieldNames.filename:
return 1;
default:
return 0;
}
};
return sortingValue(b) - sortingValue(a);
})
.filter(({ active, accessor }) => active || accessor === fieldNames.filename);
return (
<div className={baseClass}>
<div className={`${baseClass}__header`}>
{headerColumns.map((col, index) => (
<div key={index} id={`heading-${col.accessor}`}>
{col.components.Heading}
</div>
))}
</div>
<div className={`${baseClass}__cells`}>
{data &&
data.map((gridCell, cellIndex) => (
<div key={cellIndex} className={`${baseClass}__cells__cell`}>
{filenameField && (
<Link
className={`${baseClass}__cells__cell__filename`}
to={`${collection.slug}/${gridCell.id}`}>
<Thumbnail collection={collection} doc={gridCell} />
</Link>
)}
{selectorField && (
<div className={`${baseClass}__cells__cell__selector`}>
{selectorField.components.renderCell(gridCell, gridCell[selectorField.accessor])}
</div>
)}
<div className={`${baseClass}__cells__cell__info`}>
{filenameField && (
<Link
className={`${baseClass}__cells__cell__title`}
to={`${collection.slug}/${gridCell.id}`}>
{String(gridCell[filenameField.accessor])}
</Link>
)}
{otherFields.length > 0 && (
<div className={`${baseClass}__cells__cell__others`}>
{otherFields.map((col, colIndex) => (
<Fragment key={colIndex}>
{col.components.renderCell(gridCell, gridCell[col.accessor])}
</Fragment>
))}
</div>
)}
</div>
</div>
))}
</div>
</div>
);
};
export default Grid;
import { useWindowInfo } from "@faceless-ui/window-info";
import Button from "payload/dist/admin/components/elements/Button";
import DeleteMany from "payload/dist/admin/components/elements/DeleteMany";
import EditMany from "payload/dist/admin/components/elements/EditMany";
import Eyebrow from "payload/dist/admin/components/elements/Eyebrow";
import { Gutter } from "payload/dist/admin/components/elements/Gutter";
import ListControls from "payload/dist/admin/components/elements/ListControls";
import ListSelection from "payload/dist/admin/components/elements/ListSelection";
import Paginator from "payload/dist/admin/components/elements/Paginator";
import PerPage from "payload/dist/admin/components/elements/PerPage";
import Pill from "payload/dist/admin/components/elements/Pill";
import PublishMany from "payload/dist/admin/components/elements/PublishMany";
import { StaggeredShimmers } from "payload/dist/admin/components/elements/ShimmerEffect";
import UnpublishMany from "payload/dist/admin/components/elements/UnpublishMany";
import ViewDescription from "payload/dist/admin/components/elements/ViewDescription";
import Meta from "payload/dist/admin/components/utilities/Meta";
import { RelationshipProvider } from "payload/dist/admin/components/views/collections/List/RelationshipProvider";
import { SelectionProvider } from "payload/dist/admin/components/views/collections/List/SelectionProvider";
import { Props } from "payload/dist/admin/components/views/collections/List/types";
import formatFilesize from "payload/dist/uploads/formatFilesize";
import { getTranslation } from "payload/dist/utilities/getTranslation";
import React, { Fragment } from "react";
import { useTranslation } from "react-i18next";
import Grid from ".";
const baseClass = "collection-list";
export const UploadsGridView: React.ComponentType<Props> = (props) => {
const {
collection,
collection: {
labels: { singular: singularLabel, plural: pluralLabel },
admin: {
description,
components: { BeforeList, BeforeListTable, AfterListTable, AfterList } = {},
} = {},
},
data,
newDocumentURL,
limit,
hasCreatePermission,
disableEyebrow,
modifySearchParams,
handleSortChange,
handleWhereChange,
handlePageChange,
handlePerPageChange,
customHeader,
resetParams,
} = props;
const {
breakpoints: { s: smallBreak },
} = useWindowInfo();
const { t, i18n } = useTranslation("general");
let formattedDocs = data.docs || [];
if (collection.upload) {
formattedDocs = formattedDocs?.map((doc) => {
return {
...doc,
filesize: formatFilesize(doc.filesize),
};
});
}
return (
<div className={baseClass}>
{Array.isArray(BeforeList) &&
BeforeList.map((Component, i) => <Component key={i} {...props} />)}
<Meta title={getTranslation(collection.labels.plural, i18n)} />
<SelectionProvider docs={data.docs} totalDocs={data.totalDocs}>
{!disableEyebrow && <Eyebrow />}
<Gutter className={`${baseClass}__wrap`}>
<header className={`${baseClass}__header`}>
{customHeader && customHeader}
{!customHeader && (
<Fragment>
<h1>{getTranslation(pluralLabel, i18n)}</h1>
{hasCreatePermission && (
<Pill
to={newDocumentURL}
aria-label={t("createNewLabel", {
label: getTranslation(singularLabel, i18n),
})}>
{t("createNew")}
</Pill>
)}
{!smallBreak && (
<ListSelection label={getTranslation(collection.labels.plural, i18n)} />
)}
{description && (
<div className={`${baseClass}__sub-header`}>
<ViewDescription description={description} />
</div>
)}
</Fragment>
)}
</header>
<ListControls
collection={collection}
modifySearchQuery={modifySearchParams}
handleSortChange={handleSortChange}
handleWhereChange={handleWhereChange}
resetParams={resetParams}
/>
{Array.isArray(BeforeListTable) &&
BeforeListTable.map((Component, i) => <Component key={i} {...props} />)}
{!data.docs && (
<StaggeredShimmers
className={[`${baseClass}__shimmer`, `${baseClass}__shimmer--rows`].join(" ")}
count={6}
/>
)}
{data.docs && data.docs.length > 0 && (
<RelationshipProvider>
<Grid data={formattedDocs} collection={collection} />
</RelationshipProvider>
)}
{data.docs && data.docs.length === 0 && (
<div className={`${baseClass}__no-results`}>
<p>{t("noResults", { label: getTranslation(pluralLabel, i18n) })}</p>
{hasCreatePermission && newDocumentURL && (
<Button el="link" to={newDocumentURL}>
{t("createNewLabel", { label: getTranslation(singularLabel, i18n) })}
</Button>
)}
</div>
)}
{Array.isArray(AfterListTable) &&
AfterListTable.map((Component, i) => <Component key={i} {...props} />)}
<div className={`${baseClass}__page-controls`}>
<Paginator
limit={data.limit}
totalPages={data.totalPages}
page={data.page}
hasPrevPage={data.hasPrevPage}
hasNextPage={data.hasNextPage}
prevPage={data.prevPage ?? undefined}
nextPage={data.nextPage ?? undefined}
numberOfNeighbors={1}
disableHistoryChange={modifySearchParams === false}
onChange={handlePageChange}
/>
{data?.totalDocs > 0 && (
<Fragment>
<div className={`${baseClass}__page-info`}>
{data.page ?? 1 * data.limit - (data.limit - 1)}-
{data.totalPages > 1 && data.totalPages !== data.page
? data.limit * (data.page ?? 1)
: data.totalDocs}{" "}
{t("of")} {data.totalDocs}
</div>
<PerPage
limits={collection?.admin?.pagination?.limits}
limit={limit}
modifySearchParams={modifySearchParams}
handleChange={handlePerPageChange}
resetPage={data.totalDocs <= data.pagingCounter}
/>
<div className={`${baseClass}__list-selection`}>
{smallBreak && (
<Fragment>
<ListSelection label={getTranslation(collection.labels.plural, i18n)} />
<div className={`${baseClass}__list-selection-actions`}>
<EditMany collection={collection} resetParams={resetParams} />
<PublishMany collection={collection} resetParams={resetParams} />
<UnpublishMany collection={collection} resetParams={resetParams} />
<DeleteMany collection={collection} resetParams={resetParams} />
</div>
</Fragment>
)}
</div>
</Fragment>
)}
</div>
</Gutter>
</SelectionProvider>
{Array.isArray(AfterList) &&
AfterList.map((Component, i) => <Component key={i} {...props} />)}
</div>
);
};
@DrMint
Copy link
Author

DrMint commented Aug 19, 2023

Grid View for Payload Uploads Collections

Before (default List View)

Screenshot 2023-08-19 at 15-22-20 Weapons Thumbnails - Accord’s Library

After (this Grid View)

Screenshot 2023-08-19 at 15-21-06 Weapons Thumbnails - Accord’s Library

Caveats

  • In the view, the button to select which information to display is still called "Columns". I preferred to keep it this way so that no additional localization is necessary. Also in this column selection, enabling or disabled File Name will have no effect, the column is displayed regardless. I did it this way because, without it, this Grid view doesn't make much sense.
  • The layout can rather easily break if a Column value is very long. Only enable Column that make sense for a Grid view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment