diff --git a/app/utils/remix.test.ts b/app/utils/remix.test.ts new file mode 100644 index 000000000..0292caba3 --- /dev/null +++ b/app/utils/remix.test.ts @@ -0,0 +1,41 @@ +import type { Location } from "react-router"; +import { describe, expect, it } from "vitest"; +import { metaTags } from "./remix"; +import { COMMON_PREVIEW_IMAGE } from "./urls"; + +const location = { pathname: "/to/1/brackets" } as Location; + +const contentOf = (tags: ReturnType, property: string) => + tags.find((tag) => "property" in tag && tag.property === property)?.content; + +describe("metaTags()", () => { + it("uses the common preview image when no image given", () => { + const tags = metaTags({ title: "sendou.ink", location }); + + expect(contentOf(tags, "og:image")).toBe(COMMON_PREVIEW_IMAGE); + }); + + it("uses the given image url", () => { + const tags = metaTags({ + title: "sendou.ink", + location, + image: { url: "https://cdn.example.com/img/preview.png" }, + }); + + expect(contentOf(tags, "og:image")).toBe( + "https://cdn.example.com/img/preview.png", + ); + }); + + it("resolves og:url from the location pathname", () => { + const tags = metaTags({ title: "sendou.ink", location }); + + expect(contentOf(tags, "og:url")).toBe("https://sendou.ink/to/1/brackets"); + }); + + it("prefers the url override over the location pathname", () => { + const tags = metaTags({ title: "sendou.ink", location, url: "/to/1" }); + + expect(contentOf(tags, "og:url")).toBe("https://sendou.ink/to/1"); + }); +}); diff --git a/app/utils/remix.ts b/app/utils/remix.ts index a0b595f7f..76ce6d0f1 100644 --- a/app/utils/remix.ts +++ b/app/utils/remix.ts @@ -28,6 +28,7 @@ interface OpenGraphArgs { /** Optionally override location pathname. */ url?: string; image?: { + /** Absolute URL of the image. */ url: string; dimensions?: { width: number; @@ -80,21 +81,11 @@ export function metaTags(args: OpenGraphArgs) { }, { property: "og:url", - content: `${ROOT_URL}${args.location.pathname}`, + content: `${ROOT_URL}${args.url ?? args.location.pathname}`, }, { property: "og:image", - content: (() => { - if (args.image?.url.startsWith("http")) { - return args.image.url; - } - - if (args.image) { - return `${ROOT_URL}${args.image.url}`; - } - - return `${ROOT_URL}${COMMON_PREVIEW_IMAGE}`; - })(), + content: args.image?.url ?? COMMON_PREVIEW_IMAGE, }, ].filter((val) => val !== null);