Skip to content

Commit

Permalink
preview fixes and localization support
Browse files Browse the repository at this point in the history
  • Loading branch information
kahlstrm committed Jan 30, 2024
1 parent 7747b4e commit 8938a8d
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 57 deletions.
11 changes: 7 additions & 4 deletions apps/cms/src/collections/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@ import { generatePreviewUrl } from "../preview";
import { getLocale } from "../util";

const formatPath: FieldHook<Page> = async ({ data, req }) => {
const locale = getLocale(req) ?? "fi";
if (data) {
if (data.topic && data.slug) {
const topic = await req.payload.findByID({
collection: "topics",
id: data.topic.value as string,
locale: req.locale,
locale,
});
return `/${topic.slug}/${data.slug}`;
return `/${locale}/${topic.slug}/${data.slug}`;
} else if (data.slug) {
return `/${data.slug}`;
return `/${locale}/${data.slug}`;
}
}
};
Expand All @@ -28,7 +29,9 @@ export const Pages: CollectionConfig = {
useAsTitle: "title",
defaultColumns: ["path", "title"],
listSearchableFields: ["path", "title"],
preview: generatePreviewUrl<Page>((doc) => doc.path ?? "/"),
preview: generatePreviewUrl<Page>((doc) => {
return doc.path ?? "/";
}),
},
access: {
read: publishedAndVisibleOrSignedIn,
Expand Down
2 changes: 1 addition & 1 deletion apps/cms/src/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@ import type { GeneratePreviewURL } from "payload/config";
export const generatePreviewUrl =
<T>(getUrl: (doc: T) => string): GeneratePreviewURL =>
(doc) =>
`${process.env.PUBLIC_FRONTEND_URL}/next_api/preview?url=${getUrl(doc as T)}`;
`/next_api/preview?url=${getUrl(doc as T)}`;
1 change: 0 additions & 1 deletion apps/web/src/app/[lang]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ export default async function RootLayout({
children: React.ReactNode;
} & LayoutProps) {
const dictionary = await getDictionary(lang);

return (
<html lang={lang}>
<body className={cn(inter.variable, robotoMono.variable, "font-sans")}>
Expand Down
29 changes: 19 additions & 10 deletions apps/web/src/components/admin-bar-client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,28 @@ export function AdminBarClient({
collection?: string;
}) {
const exitPreview = async () => {
await fetch("/api/exit-preview");
await fetch("/next_api/exit-preview");
window.location.reload();
};

return (
<PayloadAdminBar
className="bottom-0"
cmsURL={process.env.PUBLIC_SERVER_URL ?? window.location.origin}
collection={collection}
id={id}
onPreviewExit={void exitPreview}
preview={isPreviewMode}
style={{ top: "auto" }}
/>
<>
{isPreviewMode ? (
<div className="top-30 fixed z-20 w-full bg-red-500 p-2 text-center text-white">
This is a draft preview
</div>
) : null}
<PayloadAdminBar
className="bottom-0"
cmsURL={process.env.PUBLIC_SERVER_URL ?? window.location.origin}
collection={collection}
id={id}
onPreviewExit={() => void exitPreview()} // has to be likes this, otherwise it doesn't run for some reason :shrug:
preview={isPreviewMode}
style={{
top: "auto",
}}
/>
</>
);
}
7 changes: 2 additions & 5 deletions apps/web/src/components/footer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { RenderIcon } from "@tietokilta/ui";
import Image from "next/image";
import Link from "next/link";
import { fetchFooter } from "../../lib/api/footer";
import { cn, localisePath } from "../../lib/utils";
import { cn } from "../../lib/utils";

export async function Footer({ locale }: { locale: string }) {
const footer = await fetchFooter(locale)({});
Expand Down Expand Up @@ -65,10 +65,7 @@ export async function Footer({ locale }: { locale: string }) {
href={
"url" in link
? link.url ?? "#broken"
: localisePath(
(link.page as Page).path ?? "#broken",
locale,
)
: (link.page as Page).path ?? "#broken"
}
>
<RenderIcon className="h-6 w-6" name={link.icon} />
Expand Down
20 changes: 5 additions & 15 deletions apps/web/src/components/main-nav/link-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
import NextLink, { type LinkProps } from "next/link";
import { usePathname } from "next/navigation";
import type { HTMLProps } from "react";
import { localisePath } from "../../lib/utils";

function Link({
href,
Expand All @@ -37,16 +36,13 @@ function Link({

function NavigationLink({
pageOrTopic,
locale,
}: {
pageOrTopic: MainNavigationItem[number];
locale: string;
}) {
if (pageOrTopic.type === "page") {
const localisedPath = localisePath(
(pageOrTopic.pageConfig?.page as Page | undefined)?.path ?? "#broken",
locale,
);
const localisedPath =
(pageOrTopic.pageConfig?.page as Page | undefined)?.path ?? "#broken";

return (
<Link className={navigationMenuTriggerStyle()} href={localisedPath}>
{(pageOrTopic.pageConfig?.page as Page).title}
Expand Down Expand Up @@ -74,12 +70,7 @@ function NavigationLink({
className="mb-2 w-full border-b-0 pb-0 pl-0"
variant="link"
>
<Link
href={localisePath(
(page as Page).path ?? "#broken",
locale,
)}
>
<Link href={(page as Page).path ?? "#broken"}>
{(page as Page).title}
</Link>
</Button>
Expand Down Expand Up @@ -114,13 +105,12 @@ function NavigationLink({

export const LinkList = ({
links,
locale,
}: {
links: MainNavigationItem;
locale: string;
}) =>
links.map((pageOrTopic) => (
<NavigationMenuItem key={pageOrTopic.id}>
<NavigationLink locale={locale} pageOrTopic={pageOrTopic} />
<NavigationLink pageOrTopic={pageOrTopic} />
</NavigationMenuItem>
));
21 changes: 4 additions & 17 deletions apps/web/src/components/mobile-nav/link-list.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ import NextLink, { type LinkProps } from "next/link";
import { usePathname } from "next/navigation";
import type { HTMLProps } from "react";
import type { Dictionary } from "../../lib/dictionaries";
import { localisePath } from "../../lib/utils";

function Link({
href,
Expand All @@ -43,7 +42,6 @@ function Link({

function NavigationLink({
pageOrTopic,
locale,
dict,
}: {
pageOrTopic: MainNavigationItem[number];
Expand All @@ -54,15 +52,12 @@ function NavigationLink({
};
}) {
if (pageOrTopic.type === "page") {
const localisedPath = localisePath(
(pageOrTopic.pageConfig?.page as Page).path ?? "#broken",
locale,
);
const path = (pageOrTopic.pageConfig?.page as Page).path ?? "#broken";

return (
<Link
className="underline-offset-2 hover:underline aria-[current='page']:underline"
href={localisedPath}
href={path}
>
<span>{(pageOrTopic.pageConfig?.page as Page).title}</span>
</Link>
Expand Down Expand Up @@ -93,12 +88,7 @@ function NavigationLink({
className="w-full border-b-0 pl-0"
variant="link"
>
<Link
href={localisePath(
(page as Page).path ?? "#broken",
locale,
)}
>
<Link href={(page as Page).path ?? "#broken"}>
{(page as Page).title}
</Link>
</Button>
Expand Down Expand Up @@ -175,10 +165,7 @@ export function LinkList({
href={
"url" in link
? link.url ?? "#broken"
: localisePath(
(link.page as Page).path ?? "#broken",
locale,
)
: (link.page as Page).path ?? "#broken"
}
>
<RenderIcon className="h-6 w-6" name={link.icon} />
Expand Down
9 changes: 8 additions & 1 deletion apps/web/src/lib/api/fetcher.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import stringify from "json-stable-stringify";
import type { RequestCookie } from "next/dist/compiled/@edge-runtime/cookies";
import { stringify as qsStringify } from "qs";
import { draftMode, cookies } from "next/headers";

export const fetcher =
<Request, Response>(
Expand All @@ -14,7 +15,6 @@ export const fetcher =
async (req: Request): Promise<Response | undefined | null> => {
let payloadToken: RequestCookie | undefined;

const { draftMode, cookies } = await import("next/headers");
const { isEnabled: isDraftMode } = draftMode();

if (isDraftMode) {
Expand Down Expand Up @@ -81,6 +81,13 @@ export const getGlobal = <Response>(path: string, locale: string) =>
fetcher<Record<string, never>, Response>(
() => `getGlobal_${path}?locale=${locale}`,
async (_, draft, fetchOptions): Promise<Response | undefined> => {
const fetchUrl = `${process.env.PUBLIC_SERVER_URL}${path}?${qsStringify({
locale,
depth: 10, // TODO: remove this when we have a better way to handle depth for example with GraphQL
// Needs to be bigger than 1 to get media / images
...(draft ? { draft: "true" } : {}),
}).toString()}`;
console.log("fetchUrl", fetchUrl);
const result = await fetch(
`${process.env.PUBLIC_SERVER_URL}${path}?${qsStringify({
locale,
Expand Down
3 changes: 0 additions & 3 deletions apps/web/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ import { twMerge } from "tailwind-merge";

export const cn = (...inputs: ClassValue[]): string => twMerge(clsx(inputs));

export const localisePath = (path: string, locale: string) =>
`/${locale}${path}` as const;

export const jsxToTextContent = (element: JSX.Element | undefined): string => {
if (!element) return "";

Expand Down

0 comments on commit 8938a8d

Please sign in to comment.