Files
ipal-kit/src/modules/seo/buildManifest.ts
T

91 lines
2.7 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import { getDefaultLocale } from '../i18n/index.js'
type MediaLike =
| { height?: null | number; mimeType?: null | string; url?: null | string; width?: null | number }
| null
| undefined
type ManifestIcon = { sizes?: string; src: string; type?: string }
type Manifest = {
background_color?: string
display: 'standalone'
icons: ManifestIcon[]
name?: string
short_name?: string
start_url: string
theme_color?: string
}
type SettingsShape = {
backgroundColor?: null | string
favicon?: MediaLike
logo?: MediaLike
siteName?: null | string
themeColor?: null | string
}
/**
* Builds a Next Web App Manifest from SiteSettings — replaces the ~50 lines of
* icon/mimeType parsing copied into every project's manifest.ts. Values come
* from the panel; missing fields are omitted (no hardcoded client data).
*
* // app/manifest.ts
* import { createManifestHandler } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
* import { i18nConfig } from '@/i18n.config'
* export default createManifestHandler({ getCachedPayload, config: i18nConfig })
*/
export function createManifestHandler(opts: {
config: I18nConfig
getCachedPayload: () => Promise<BasePayload>
settingsSlug?: string
}): () => Promise<Manifest> {
return async () => {
const defaultLocale = getDefaultLocale(opts.config)
const payload = await opts.getCachedPayload()
const settings = (await payload
.findGlobal({
slug: (opts.settingsSlug ?? 'site-settings') as never,
depth: 1,
locale: defaultLocale as never,
})
.catch(() => null)) as null | SettingsShape
const start_url = `/${defaultLocale}`
if (!settings) {
return { display: 'standalone', icons: [], start_url }
}
const iconSource = settings.favicon ?? settings.logo
const icons: ManifestIcon[] = []
if (iconSource?.url) {
const type =
iconSource.mimeType ?? (iconSource.url.endsWith('.svg') ? 'image/svg+xml' : undefined)
const isSvg = type === 'image/svg+xml'
const size =
iconSource.width && iconSource.height
? `${iconSource.width}x${iconSource.height}`
: undefined
icons.push({
src: iconSource.url,
...(isSvg ? { sizes: 'any' } : size ? { sizes: size } : {}),
...(type ? { type } : {}),
})
}
return {
...(settings.siteName ? { name: settings.siteName, short_name: settings.siteName } : {}),
display: 'standalone',
start_url,
...(settings.backgroundColor ? { background_color: settings.backgroundColor } : {}),
...(settings.themeColor ? { theme_color: settings.themeColor } : {}),
icons,
}
}
}