feat: add login and logout event, clean up collection page styles (#798)

This commit is contained in:
Daniel Lautzenheiser
2023-05-11 18:52:06 -04:00
committed by GitHub
parent a66068ca03
commit 80a5e11722
33 changed files with 952 additions and 2887 deletions

View File

@ -387,6 +387,28 @@ collections:
- label: Description
name: description
widget: text
- name: list_with_object_child
label: List With Object Child
widget: list
fields:
- label: Name
name: name
widget: string
hint: First and Last
- label: Description
name: description
widget: text
- label: Object
name: object
widget: object
fields:
- label: Name
name: name
widget: string
hint: First and Last
- label: Description
name: description
widget: text
- name: string_list
label: String List
widget: list

View File

@ -184,16 +184,15 @@
var slug = dateString + '-post-number-' + i + '.md';
window.repoFiles._posts[slug] = {
content:
'---\ntitle: "This is post # ' +
i +
`\"\ndraft: ${i % 2 === 0}` +
'\nimage: /assets/uploads/lobby.jpg' +
'\ndate: ' +
dateString +
'T00:00:00.000Z\n---\n# The post is number ' +
i +
`\n\n![Static CMS](https://raw.githubusercontent.com/StaticJsCMS/static-cms/main/static-cms-logo.png)
content: `---
title: "This is post # ${i}"
draft: ${i % 2 === 0}
image: /assets/uploads/lobby.jpg
date: ${dateString}T00:00:00.000Z
---
# The post is number ${i}
![Static CMS](https://raw.githubusercontent.com/StaticJsCMS/static-cms/main/static-cms-logo.png)
# Awesome Editor!

View File

@ -11,15 +11,31 @@ const PostPreview = ({ entry, widgetFor }) => {
);
};
const PostPreviewCard = ({ entry, theme, hasLocalBackup }) => {
const PostPreviewCard = ({ entry, theme, hasLocalBackup, widgetFor }) => {
const date = new Date(entry.data.date);
const month = date.getMonth() + 1;
const day = date.getDate();
const image = entry.data.image;
return h(
'div',
{ style: { width: '100%' } },
h('div', {
style: {
width: '100%',
borderTopLeftRadius: '8px',
borderTopRightRadius: '8px',
overflow: 'hidden',
height: '140px',
backgroundSize: 'cover',
backgroundRepat: 'no-repeat',
backgroundPosition: 'center',
objectFit: 'cover',
backgroundImage: `url('${image}')`,
},
}),
h(
'div',
{ style: { padding: '16px', width: '100%' } },
@ -52,7 +68,6 @@ const PostPreviewCard = ({ entry, theme, hasLocalBackup }) => {
fontSize: '14px',
fontWeight: 700,
color: 'rgb(107, 114, 128)',
fontSize: '14px',
lineHeight: '18px',
},
},
@ -93,7 +108,7 @@ const PostPreviewCard = ({ entry, theme, hasLocalBackup }) => {
justifyContent: 'center',
textAlign: 'center',
},
title: 'Has local backup'
title: 'Has local backup',
},
'i',
)
@ -151,6 +166,8 @@ const PostDraftFieldPreview = ({ value }) => {
cursor: 'pointer',
borderRadius: '4px',
fontSize: '14px',
lineHeight: '16px',
height: '20px',
},
},
value === true ? 'Draft' : 'Published',
@ -226,7 +243,7 @@ const CustomPage = () => {
};
CMS.registerPreviewTemplate('posts', PostPreview);
CMS.registerPreviewCard('posts', PostPreviewCard);
CMS.registerPreviewCard('posts', PostPreviewCard, () => 240);
CMS.registerFieldPreview('posts', 'date', PostDateFieldPreview);
CMS.registerFieldPreview('posts', 'draft', PostDraftFieldPreview);
CMS.registerPreviewTemplate('general', GeneralPreview);

View File

@ -150,15 +150,6 @@ export default class BitbucketBackend implements BackendClass {
return AuthenticationPage;
}
setUser(user: { token: string }) {
this.token = user.token;
this.api = new API({
requestFunction: this.apiRequestFunction,
branch: this.branch,
repo: this.repo,
});
}
requestFunction = async (req: ApiRequest) => {
const token = await this.getToken();
const authorizedRequest = unsentRequest.withHeaders({ Authorization: `Bearer ${token}` }, req);

View File

@ -1,5 +1,5 @@
import { createTheme, ThemeProvider } from '@mui/material/styles';
import React, { useCallback, useEffect, useMemo } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { translate } from 'react-polyglot';
import { connect } from 'react-redux';
import {
@ -185,6 +185,17 @@ const App = ({
}
}, [dispatch]);
const [prevUser, setPrevUser] = useState(user);
useEffect(() => {
if (!prevUser && user) {
invokeEvent('login', {
login: user.login,
name: user.name ?? '',
});
}
setPrevUser(user);
}, [prevUser, user]);
const content = useMemo(() => {
if (!user) {
return authenticationPage;

View File

@ -13,7 +13,7 @@ const MultiSearchCollectionPage: FC = () => {
const filterTerm = params['*'];
return (
<MainView breadcrumbs={[{ name: 'Search' }]} showQuickCreate showLeftNav>
<MainView breadcrumbs={[{ name: 'Search' }]} showQuickCreate showLeftNav noScroll noMargin>
<CollectionView
name={name}
searchTerm={searchTerm}
@ -42,7 +42,7 @@ const SingleCollectionPage: FC<SingleCollectionPageProps> = ({
const breadcrumbs = useBreadcrumbs(collection, filterTerm);
return (
<MainView breadcrumbs={breadcrumbs} showQuickCreate showLeftNav noScroll>
<MainView breadcrumbs={breadcrumbs} showQuickCreate showLeftNav noScroll noMargin>
<CollectionView
name={name}
searchTerm={searchTerm}

View File

@ -196,7 +196,7 @@ const CollectionView = ({
const collectionDescription = collection?.description;
return (
<div className="flex flex-col h-full">
<div className="flex flex-col h-full px-5 pt-4">
<div className="flex items-center mb-4">
{isSearchResults ? (
<>

View File

@ -79,7 +79,10 @@ const EntryCard: FC<TranslatedProps<EntryCardProps>> = ({
[collection, entry.slug],
);
const PreviewCardComponent = useMemo(() => getPreviewCard(templateName) ?? null, [templateName]);
const PreviewCardComponent = useMemo(
() => getPreviewCard(templateName)?.component ?? null,
[templateName],
);
const theme = useAppSelector(selectTheme);

View File

@ -152,16 +152,18 @@ const EntryListing: FC<TranslatedProps<EntryListingProps>> = ({
if (viewStyle === VIEW_STYLE_TABLE) {
return (
<EntryListingTable
key="table"
entryData={entryData}
isSingleCollectionInList={isSingleCollectionInList}
summaryFieldHeaders={summaryFieldHeaders}
loadNext={handleLoadMore}
canLoadMore={Boolean(hasMore && handleLoadMore)}
isLoadingEntries={isLoadingEntries}
t={t}
/>
<div className="pb-3 overflow-hidden">
<EntryListingTable
key="table"
entryData={entryData}
isSingleCollectionInList={isSingleCollectionInList}
summaryFieldHeaders={summaryFieldHeaders}
loadNext={handleLoadMore}
canLoadMore={Boolean(hasMore && handleLoadMore)}
isLoadingEntries={isLoadingEntries}
t={t}
/>
</div>
);
}

View File

@ -1,14 +1,17 @@
import React, { useCallback, useMemo, useState } from 'react';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import AutoSizer from 'react-virtualized-auto-sizer';
import { VariableSizeGrid as Grid } from 'react-window';
import {
MEDIA_CARD_HEIGHT,
MEDIA_CARD_MARGIN,
MEDIA_CARD_WIDTH,
MEDIA_LIBRARY_PADDING,
} from '@staticcms/core/constants/mediaLibrary';
COLLECTION_CARD_HEIGHT,
COLLECTION_CARD_HEIGHT_WITHOUT_IMAGE,
COLLECTION_CARD_MARGIN,
COLLECTION_CARD_WIDTH,
} from '@staticcms/core/constants/views';
import { getPreviewCard } from '@staticcms/core/lib/registry';
import classNames from '@staticcms/core/lib/util/classNames.util';
import { selectTemplateName } from '@staticcms/core/lib/util/collection.util';
import { isNotNullish } from '@staticcms/core/lib/util/null.util';
import EntryCard from './EntryCard';
import type { CollectionEntryData } from '@staticcms/core/interface';
@ -40,7 +43,7 @@ const CardWrapper = ({
parseFloat(
`${
typeof style.left === 'number'
? style.left ?? MEDIA_CARD_MARGIN * columnIndex
? style.left ?? COLLECTION_CARD_MARGIN * columnIndex
: style.left
}`,
),
@ -66,8 +69,8 @@ const CardWrapper = ({
top,
width: style.width,
height: style.height,
paddingRight: `${columnIndex + 1 === columnCount ? 0 : MEDIA_CARD_MARGIN}px`,
paddingBottom: `${MEDIA_CARD_MARGIN}px`,
paddingRight: `${columnIndex + 1 === columnCount ? 0 : COLLECTION_CARD_MARGIN}px`,
paddingBottom: `${COLLECTION_CARD_MARGIN}px`,
}}
>
<EntryCard
@ -93,14 +96,51 @@ const EntryListingCardGrid: FC<EntryListingCardGridProps> = ({
setVersion(oldVersion => oldVersion + 1);
}, []);
const getHeightFn = useCallback((data: CollectionEntryData) => {
const templateName = selectTemplateName(data.collection, data.entry.slug);
return getPreviewCard(templateName)?.getHeight ?? null;
}, []);
const getDefaultHeight = useCallback((data?: CollectionEntryData) => {
return isNotNullish(data?.imageFieldName)
? COLLECTION_CARD_HEIGHT
: COLLECTION_CARD_HEIGHT_WITHOUT_IMAGE;
}, []);
const [prevCardHeights, setPrevCardHeight] = useState<number[]>([]);
const cardHeights: number[] = useMemo(() => {
const newCardHeights = [...prevCardHeights];
const startIndex = newCardHeights.length;
const endIndex = entryData.length;
for (let i = startIndex; i < endIndex; i++) {
const data = entryData[i];
const getHeight = getHeightFn(data);
if (getHeight) {
newCardHeights.push(getHeight({ collection: data.collection, entry: data.entry }));
continue;
}
newCardHeights.push(getDefaultHeight(data));
}
return newCardHeights;
}, [entryData, getDefaultHeight, getHeightFn, prevCardHeights]);
useEffect(() => {
if (cardHeights.length !== prevCardHeights.length) {
setPrevCardHeight(cardHeights);
}
}, [cardHeights, prevCardHeights.length]);
return (
<div className="relative w-full h-full">
<AutoSizer onResize={handleResize}>
{({ height = 0, width = 0 }) => {
const columnWidthWithGutter = MEDIA_CARD_WIDTH + MEDIA_CARD_MARGIN;
const rowHeightWithGutter = MEDIA_CARD_HEIGHT + MEDIA_CARD_MARGIN;
const columnWidthWithGutter = COLLECTION_CARD_WIDTH + COLLECTION_CARD_MARGIN;
const columnCount = Math.floor(width / columnWidthWithGutter);
const nonGutterSpace = (width - MEDIA_CARD_MARGIN * columnCount) / width;
const nonGutterSpace = (width - COLLECTION_CARD_MARGIN * columnCount) / width;
const columnWidth = (1 / columnCount) * nonGutterSpace;
const rowCount = Math.ceil(entryData.length / columnCount);
@ -123,12 +163,15 @@ const EntryListingCardGrid: FC<EntryListingCardGridProps> = ({
columnWidth={index =>
index + 1 === columnCount
? width * columnWidth
: width * columnWidth + MEDIA_CARD_MARGIN
: width * columnWidth + COLLECTION_CARD_MARGIN
}
rowCount={rowCount}
rowHeight={() => rowHeightWithGutter}
rowHeight={index =>
(cardHeights.length > index ? cardHeights[index] : getDefaultHeight()) +
COLLECTION_CARD_MARGIN
}
width={width}
height={height - MEDIA_LIBRARY_PADDING}
height={height}
itemData={
{
entryData,
@ -146,6 +189,7 @@ const EntryListingCardGrid: FC<EntryListingCardGridProps> = ({
`,
)}
style={{ position: 'unset' }}
overscanRowCount={5}
>
{CardWrapper}
</Grid>

View File

@ -58,7 +58,7 @@ const EntryListingGrid: FC<EntryListingGridProps> = ({
return (
<div className="relative h-full overflow-hidden">
<div ref={gridContainerRef} className="relative h-full overflow-auto styled-scrollbars">
<div ref={gridContainerRef} className="relative h-full overflow-hidden">
<EntryListingCardGrid
key="grid"
entryData={entryData}

View File

@ -69,8 +69,28 @@ const EntryListingTable: FC<EntryListingTableProps> = ({
}, [clientHeight, fetchMoreOnBottomReached, scrollHeight, scrollTop]);
return (
<div className="relative h-full overflow-hidden">
<div ref={tableContainerRef} className="relative h-full overflow-auto styled-scrollbars">
<div
className="
relative
max-h-full
h-full
overflow-hidden
p-1.5
bg-white
dark:bg-slate-800
rounded-xl
"
>
<div
ref={tableContainerRef}
className="
relative
h-full
overflow-auto
styled-scrollbars
styled-scrollbars-secondary
"
>
<Table
columns={
!isSingleCollectionInList

View File

@ -22,6 +22,7 @@ const Card = ({ children, className }: CardProps) => {
dark:border-gray-700/40
flex
flex-col
h-full
`,
className,
)}

View File

@ -11,18 +11,17 @@ interface TableCellProps {
const TableCell = ({ columns, children }: TableCellProps) => {
return (
<div className="shadow-md">
<div
className="
shadow-md
z-[2]
"
>
<table className="w-full text-sm text-left text-gray-500 dark:text-gray-300">
<thead className="text-xs">
<tr>
{columns.map((column, index) => (
<TableHeaderCell
key={index}
isFirst={index === 0}
isLast={index + 1 === columns.length}
>
{column}
</TableHeaderCell>
<TableHeaderCell key={index}>{column}</TableHeaderCell>
))}
</tr>
</thead>

View File

@ -38,12 +38,21 @@ const TableCell = ({ children, emphasis = false, to, shrink = false }: TableCell
<td
className={classNames(
!to ? 'px-4 py-3' : 'p-0',
'text-gray-500 dark:text-gray-300',
`
text-gray-500
dark:text-gray-300
`,
emphasis && 'font-medium text-gray-900 whitespace-nowrap dark:text-white',
shrink && 'w-0',
)}
>
{content}
<div
className="
h-[44px]
"
>
{content}
</div>
</td>
);
};

View File

@ -7,37 +7,36 @@ import type { ReactNode } from 'react';
interface TableHeaderCellProps {
children: ReactNode;
isFirst: boolean;
isLast: boolean;
}
const TableHeaderCell = ({ children, isFirst, isLast }: TableHeaderCellProps) => {
const TableHeaderCell = ({ children }: TableHeaderCellProps) => {
return (
<th
scope="col"
className="
text-gray-500
bg-slate-50
dark:text-gray-400
dark:bg-slate-900
sticky
top-0
p-0
"
className={classNames(
`
font-bold
sticky
top-0
border-0
p-0
`,
)}
>
<div
className={classNames(
`
bg-gray-100
border-slate-200
dark:bg-slate-700
dark:border-gray-700
px-4
py-3
`,
isFirst && 'rounded-tl-lg',
isLast && 'rounded-tr-lg',
)}
className="
px-4
py-3
text-gray-900
border-gray-100
border-b
bg-white
dark:text-white
dark:border-gray-700
dark:bg-slate-800
shadow-sm
text-[14px]
"
>
{typeof children === 'string' && isEmpty(children) ? <>&nbsp;</> : children}
</div>

View File

@ -14,11 +14,14 @@ const TableRow = ({ children, className }: TableRowProps) => {
<tr
className={classNames(
`
border-b
border-t
first:border-t-0
border-gray-100
dark:border-gray-700
bg-white
hover:bg-slate-50
dark:bg-slate-800
dark:border-gray-700
dark:hover:bg-slate-700
`,
className,
)}

View File

@ -2,3 +2,9 @@ export const VIEW_STYLE_TABLE = 'table';
export const VIEW_STYLE_GRID = 'grid';
export type ViewStyle = typeof VIEW_STYLE_TABLE | typeof VIEW_STYLE_GRID;
export const COLLECTION_CARD_WIDTH = 240;
export const COLLECTION_CARD_HEIGHT = 204;
export const COLLECTION_CARD_IMAGE_HEIGHT = 140;
export const COLLECTION_CARD_HEIGHT_WITHOUT_IMAGE = 64;
export const COLLECTION_CARD_MARGIN = 10;

View File

@ -887,9 +887,14 @@ export interface BackendInitializer<EF extends BaseField = UnknownField> {
init: (config: Config<EF>, options: BackendInitializerOptions) => BackendClass;
}
export interface AuthorData {
login: string | undefined;
name: string;
}
export interface EventData {
entry: Entry;
author: { login: string | undefined; name: string };
author: AuthorData;
}
export type PreSaveEventHandler<O extends Record<string, unknown> = Record<string, unknown>> = (
@ -906,10 +911,21 @@ export type MountedEventHandler<O extends Record<string, unknown> = Record<strin
options: O,
) => void | Promise<void>;
export type LoginEventHandler<O extends Record<string, unknown> = Record<string, unknown>> = (
data: AuthorData,
options: O,
) => void | Promise<void>;
export type LogoutEventHandler<O extends Record<string, unknown> = Record<string, unknown>> = (
options: O,
) => void | Promise<void>;
export type EventHandlers<O extends Record<string, unknown> = Record<string, unknown>> = {
preSave: PreSaveEventHandler<O>;
postSave: PostSaveEventHandler<O>;
mounted: MountedEventHandler<O>;
login: LoginEventHandler<O>;
logout: LogoutEventHandler<O>;
};
export interface EventListener<

View File

@ -96,6 +96,10 @@ export function slugFormatter<EF extends BaseField = UnknownField>(
entryData: EntryData,
slugConfig?: Slug,
): string {
if (!('fields' in collection)) {
return '';
}
const slugTemplate = collection.slug || '{{slug}}';
const identifierField = selectIdentifier(collection);
@ -152,12 +156,12 @@ export function summaryFormatter<EF extends BaseField>(
export function folderFormatter<EF extends BaseField>(
folderTemplate: string,
entry: Entry | null | undefined,
collection: Collection<EF>,
collection: Collection<EF> | undefined,
defaultFolder: string,
folderKey: string,
slugConfig?: Slug,
) {
if (!entry || !entry.data) {
if (!entry || !entry.data || !collection) {
return folderTemplate;
}

View File

@ -2,10 +2,12 @@ import { oneLine } from 'common-tags';
import type {
AdditionalLink,
AuthorData,
BackendClass,
BackendInitializer,
BackendInitializerOptions,
BaseField,
Collection,
Config,
CustomIcon,
Entry,
@ -14,6 +16,8 @@ import type {
EventListener,
FieldPreviewComponent,
LocalePhrasesRoot,
LoginEventHandler,
LogoutEventHandler,
MountedEventHandler,
ObjectValue,
PostSaveEventHandler,
@ -30,13 +34,15 @@ import type {
WidgetValueSerializer,
} from '../interface';
export const allowedEvents = ['mounted', 'preSave', 'postSave'] as const;
export const allowedEvents = ['mounted', 'login', 'logout', 'preSave', 'postSave'] as const;
export type AllowedEvent = (typeof allowedEvents)[number];
type EventHandlerRegistry = {
preSave: { handler: PreSaveEventHandler; options: Record<string, unknown> }[];
postSave: { handler: PostSaveEventHandler; options: Record<string, unknown> }[];
mounted: { handler: MountedEventHandler; options: Record<string, unknown> }[];
login: { handler: LoginEventHandler; options: Record<string, unknown> }[];
logout: { handler: LogoutEventHandler; options: Record<string, unknown> }[];
};
const eventHandlers = allowedEvents.reduce((acc, e) => {
@ -44,10 +50,15 @@ const eventHandlers = allowedEvents.reduce((acc, e) => {
return acc;
}, {} as EventHandlerRegistry);
interface CardPreviews {
component: TemplatePreviewCardComponent<ObjectValue>;
getHeight?: (data: { collection: Collection; entry: Entry }) => number;
}
interface Registry {
backends: Record<string, BackendInitializer>;
templates: Record<string, TemplatePreviewComponent<ObjectValue>>;
cards: Record<string, TemplatePreviewCardComponent<ObjectValue>>;
cards: Record<string, CardPreviews>;
fieldPreviews: Record<string, Record<string, FieldPreviewComponent>>;
widgets: Record<string, Widget>;
icons: Record<string, CustomIcon>;
@ -145,11 +156,15 @@ export function getPreviewTemplate(name: string): TemplatePreviewComponent<Objec
export function registerPreviewCard<T, EF extends BaseField = UnknownField>(
name: string,
component: TemplatePreviewCardComponent<T, EF>,
getHeight?: () => number,
) {
registry.cards[name] = component as TemplatePreviewCardComponent<ObjectValue>;
registry.cards[name] = {
component: component as TemplatePreviewCardComponent<ObjectValue>,
getHeight,
};
}
export function getPreviewCard(name: string): TemplatePreviewCardComponent<ObjectValue> | null {
export function getPreviewCard(name: string): CardPreviews | null {
return registry.cards[name] ?? null;
}
@ -336,19 +351,27 @@ export function registerEventListener<
>({ name, handler }: EventListener<E, O>, options?: O) {
validateEventName(name);
registry.eventHandlers[name].push({
handler: handler as MountedEventHandler & PreSaveEventHandler & PostSaveEventHandler,
handler: handler as MountedEventHandler &
LoginEventHandler &
PreSaveEventHandler &
PostSaveEventHandler,
options: options ?? {},
});
}
export async function invokeEvent(name: 'login', data: AuthorData): Promise<void>;
export async function invokeEvent(name: 'logout'): Promise<void>;
export async function invokeEvent(name: 'preSave', data: EventData): Promise<EntryData>;
export async function invokeEvent(name: 'postSave', data: EventData): Promise<void>;
export async function invokeEvent(name: 'mounted'): Promise<void>;
export async function invokeEvent(name: AllowedEvent, data?: EventData): Promise<void | EntryData> {
export async function invokeEvent(
name: AllowedEvent,
data?: EventData | AuthorData,
): Promise<void | EntryData> {
validateEventName(name);
if (name === 'mounted') {
console.info('[StaticCMS] Firing mounted event');
if (name === 'mounted' || name === 'logout') {
console.info(`[StaticCMS] Firing ${name} event`);
const handlers = registry.eventHandlers[name];
for (const { handler, options } of handlers) {
handler(options);
@ -357,11 +380,21 @@ export async function invokeEvent(name: AllowedEvent, data?: EventData): Promise
return;
}
if (name === 'login') {
console.info('[StaticCMS] Firing login event', data);
const handlers = registry.eventHandlers[name];
for (const { handler, options } of handlers) {
handler(data as AuthorData, options);
}
return;
}
if (name === 'postSave') {
console.info(`[StaticCMS] Firing post save event`, data);
const handlers = registry.eventHandlers[name];
for (const { handler, options } of handlers) {
handler(data!, options);
handler(data as EventData, options);
}
return;
@ -371,7 +404,7 @@ export async function invokeEvent(name: AllowedEvent, data?: EventData): Promise
console.info(`[StaticCMS] Firing pre save event`, data);
let _data = { ...data! };
let _data = { ...(data as EventData) };
for (const { handler, options } of handlers) {
const result = await handler(_data, options);
if (_data !== undefined && result !== undefined) {

View File

@ -360,7 +360,7 @@
}
.dark .styled-scrollbars.styled-scrollbars-secondary {
--scrollbar-foreground: rgba(47, 64, 93, 0.8);
--scrollbar-foreground: rgba(47, 64, 84, 0.8);
--scrollbar-background: rgb(30 41 59);
}
@ -383,3 +383,28 @@
/* Background */
background: var(--scrollbar-background);
}
table {
tbody {
tr {
&:last-child {
border-bottom-right-radius: 8px;
border-bottom-left-radius: 8px;
td {
&:first-child {
& > div {
border-bottom-left-radius: 8px;
}
}
&:last-child {
& > div {
border-bottom-right-radius: 8px;
}
}
}
}
}
}
}

View File

@ -60,7 +60,6 @@ const ObjectControl: FC<WidgetControlProps<ObjectValue, ObjectField>> = ({
parentHidden={hidden}
locale={locale}
i18n={i18n}
forList={forList}
forSingleList={forSingleList}
/>
);