Last active
March 23, 2024 04:07
-
-
Save huijiewei/ae8fba5e66e789d33ee42936888d44e2 to your computer and use it in GitHub Desktop.
This function is designed to merge metadata from Remix routes, eliminating duplicates and optimizing titles
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import type { LoaderFunction, MetaFunction } from "@remix-run/node"; | |
| import type { ServerRuntimeMetaDescriptor } from "@remix-run/server-runtime"; | |
| export const mergeMeta = < | |
| Loader extends LoaderFunction | unknown = unknown, | |
| ParentsLoaders extends Record<string, LoaderFunction | unknown> = Record<string, unknown>, | |
| >( | |
| metaFn: MetaFunction<Loader, ParentsLoaders>, | |
| titleJoin: string = " - ", | |
| ): MetaFunction<Loader, ParentsLoaders> => { | |
| return (arg) => { | |
| const leafMeta = metaFn(arg); | |
| const mergedMeta = arg.matches.reduceRight((acc, match) => { | |
| for (const parentMeta of match.meta) { | |
| const index = acc.findIndex((meta) => { | |
| if ("name" in meta && "name" in parentMeta) { | |
| return meta.name === parentMeta.name; | |
| } | |
| if ("property" in meta && "property" in parentMeta) { | |
| return meta.property === parentMeta.property; | |
| } | |
| if ("title" in meta && "title" in parentMeta) { | |
| return meta.title === parentMeta.title; | |
| } | |
| return false; | |
| }); | |
| if (index == -1) { | |
| acc.push(parentMeta); | |
| } | |
| } | |
| return acc; | |
| }, leafMeta); | |
| const titles: string[] = []; | |
| const result: ServerRuntimeMetaDescriptor[] = []; | |
| for (const meta of mergedMeta) { | |
| if ("title" in meta) { | |
| if (typeof meta.title === "string" && meta.title.length > 0) { | |
| titles.push(...meta.title.split(titleJoin)); | |
| } | |
| } else { | |
| result.push(meta); | |
| } | |
| } | |
| result.unshift({ title: [...new Set(titles)].join(titleJoin) }); | |
| return result; | |
| }; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { mergeMeta } from "./mergeMeta"; | |
| export const meta = mergeMeta(({ data }) => { | |
| return [{ title: data.project.name }]; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment