Skip to content

Commit

Permalink
fix static paths for mdx and list pages
Browse files Browse the repository at this point in the history
  • Loading branch information
nemanjam committed Jul 12, 2024
1 parent 0d7aaf7 commit d99f826
Show file tree
Hide file tree
Showing 9 changed files with 63 additions and 19 deletions.
3 changes: 3 additions & 0 deletions docs/working-notes/todo3.md
Original file line number Diff line number Diff line change
Expand Up @@ -396,5 +396,8 @@ satori can define og image with html, astro-canvas limited
satori understands only react jsx, not solid-js
solid-js style prop dash case 'border-radius': '3px'
use satori vercel playground for design og image and research examples
og image getStaticPath paths
handle long site url in og template
add random hero images for mdx and list pages, and maybe random gradient, handle longer domain in new row
```

3 changes: 3 additions & 0 deletions src/constants/metadata.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CONFIG } from '@/config';

import type { Metadata } from '@/types/common';
import type { ValueUnion } from '@/types/utils';

// can't import getDefaultOpenGraphImagePath here, circular dependency

Expand Down Expand Up @@ -57,3 +58,5 @@ export const OG_IMAGE_PREFIXES = {
OG_PAGES: 'pages',
OG_LISTS: 'lists',
} as const;

export type OgImagePrefixType = ValueUnion<typeof OG_IMAGE_PREFIXES>;
5 changes: 4 additions & 1 deletion src/layouts/Page.astro
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@ const { title, description } = content;
const { pathname } = Astro.url;
// og image for metadata, only call in layouts
const path = `/pages${pathname}`;
//! important: fix home page path '/' for og image here, not in getStaticPathsv or getOpenGraphImagePath()
const path = ['', '/'].includes(pathname) ? '/pages/index' : `/pages${pathname}`;
const image = getOpenGraphImagePath(path);
const metadata = { title, description, image };
Expand Down
3 changes: 1 addition & 2 deletions src/libs/api/open-graph/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ export const getPages = async () => {
allProjects.map((project) => [`${OG_IMAGE_PREFIXES.OG_PROJECTS}/${project.slug}`, project.data])
);

// const pages = { ...posts, ...projects, ...mdxPages, ...listPages };
const pages = { ...posts, ...projects };
const pages = { ...posts, ...projects, ...mdxPages, ...listPages };

return pages;
};
9 changes: 6 additions & 3 deletions src/libs/api/open-graph/template-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ export interface TemplateProps {

const templateHtml = ({ title, heroImageUrl, avatarImageUrl, siteUrl }: TemplateProps) => html`
<div class="flex p-8 h-full" style="background: linear-gradient(to right, #D1D5DB, #F3F4F6)">
<div class="flex w-full flex-row gap-6 justify-between text-slate-900">
<div class="flex w-full flex-row justify-between text-slate-900">
<!-- left column -->
<div class="w-[550px] flex flex-col gap-4 justify-between">
<div class="flex text-6xl font-semibold">${title}</div>
<div class="w-[550px] flex flex-col justify-between mr-6">
<!-- title -->
<div class="flex text-6xl font-semibold mb-4">${title}</div>
<!-- avatar and site -->
<div class="flex items-center">
<img
src=${avatarImageUrl}
Expand Down
2 changes: 1 addition & 1 deletion src/pages/api/open-graph/[...route].png.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const getStaticPaths = async () => {

// object to array of tuples
const paths = Object.entries(pages).map(([path, page]) => ({
params: { route: path },
params: { route: path }, // home page '/' path fixed to '/page/index/ in src/layouts/Page.astro
props: { page },
}));

Expand Down
5 changes: 5 additions & 0 deletions src/types/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,8 @@
* Unused, use ComponentProps<typeof SomeComponent> instead.
*/
export type InferProps<T> = T extends (props: infer P) => JSX.Element ? P : never;

/**
* Extracts the union type of values from a constant object.
*/
export type ValueUnion<T extends Record<PropertyKey, unknown>> = T[keyof T];
50 changes: 38 additions & 12 deletions src/utils/open-graph-image.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import { OG_IMAGE_PREFIXES } from '@/constants/metadata';
import { ROUTES } from '@/constants/routes';
import { removeLeadingAndTrailingSlashes } from '@/utils/paths';
import { removeFirstPathSegment, removeLeadingAndTrailingSlashes } from '@/utils/paths';

import type { OgImagePrefixType } from '@/constants/metadata';

/*--------------------- getOpenGraphImagePath -------------------*/

const { OG_PAGES } = OG_IMAGE_PREFIXES;
export const getOpenGraphImagePath = (path: string): string => {
// only to throw for invalid path
const _prefix = getPagePrefix(path);

const homePageOgImage = `${ROUTES.API.OG_IMAGES}${OG_PAGES}.png`;
const _404PageOgImage = `${ROUTES.API.OG_IMAGES}${OG_PAGES}404.png`;
const trimmedPath = removeLeadingAndTrailingSlashes(path);

export const getOpenGraphImagePath = (path: string): string => {
const imagePath = `${ROUTES.API.OG_IMAGES}${trimmedPath}.png`;

return imagePath;
};

export const getPagePrefix = (path: string): OgImagePrefixType => {
const trimmedPath = removeLeadingAndTrailingSlashes(path);
let prefix = trimmedPath.split('/')[0];

Expand All @@ -19,15 +27,33 @@ export const getOpenGraphImagePath = (path: string): string => {
const prefixes = Object.values(OG_IMAGE_PREFIXES) as string[];

if (!prefixes.includes(prefix)) {
console.error(`Unknown path prefix requested: ${prefix}`);
return _404PageOgImage;
const message = `Unknown path prefix requested: ${prefix}`;
console.error(message);
throw new Error(message);
}

// prevents recursion on 404
// if (prefix === 'pages' && !isKnownRoute(trimmedPath)) return _404PageOgImage; // about -> pages/about
if (trimmedPath === '') return homePageOgImage;
return prefix as OgImagePrefixType;
};

const imagePath = `${ROUTES.API.OG_IMAGES}${trimmedPath}.png`;
/** not needed function, wrong */
export const getPathForGetStaticPaths = (path: string): string => {
const prefix = getPagePrefix(path);

return imagePath;
let staticPath: string;

switch (prefix) {
case OG_IMAGE_PREFIXES.OG_BLOG:
case OG_IMAGE_PREFIXES.OG_PROJECTS:
staticPath = path;
break;
case OG_IMAGE_PREFIXES.OG_PAGES:
case OG_IMAGE_PREFIXES.OG_LISTS:
staticPath = removeFirstPathSegment(path);
break;

default:
throw new Error(`Unknown static path prefix requested: ${prefix}`);
}

return staticPath;
};
2 changes: 2 additions & 0 deletions src/utils/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export const removeTrailingSlash = (path: string) => path.replace(/\/+$/g, '');

export const removeLeadingAndTrailingSlashes = (path: string) => path.replace(/^\/+|\/+$/g, '');

export const removeFirstPathSegment = (path: string) => path.split('/').slice(1).join('/');

/*----------------------------- detect unknown routes ---------------------------*/

// maybe remove
Expand Down

0 comments on commit d99f826

Please sign in to comment.