import React, { FC } from 'react';
import HTMLReactParser, { domToReact } from 'html-react-parser';
import Head from 'next/head';
import { FontFaceGenerator, Meta, Project, FontVault } from '@cntrl-site/sdk';
interface Props {
project: Project;
meta: Meta;
slug?: string;
siteUrl?: string;
fontsVault: FontVault[];
}
export const CNTRLHead: FC = ({ meta, project, slug, siteUrl, fontsVault }) => {
const canonicalUrl = buildCanonicalUrl(siteUrl ?? project.primaryDomain, slug);
const googleFonts: ReturnType = HTMLReactParser(project.fonts.google);
const adobeFonts: ReturnType = HTMLReactParser(project.fonts.adobe);
const parsedFonts = {
...(typeof googleFonts === 'object' ? googleFonts : {}),
...(typeof adobeFonts === 'object' ? adobeFonts : {})
};
const customFonts = project.fonts.custom;
const htmlHead = HTMLReactParser(project.html.head);
const ffGenerator = new FontFaceGenerator([...fontsVault, ...customFonts]);
const links = Object.values(parsedFonts as ReturnType).map((value) => {
if (!value) return null;
const rel = value?.rel || value.props?.rel;
const href = value?.href || value.props?.href;
if (!rel || !href) return null;
return (
);
});
return (
{meta.title}
{canonicalUrl && }
{canonicalUrl && }
{links}
{htmlHead}
);
};
function buildCanonicalUrl(host: string | null | undefined, slug: string | undefined): string | null {
if (!host) return null;
if (slug === undefined) return null;
const base = parseAsUrl(host);
if (!base) return null;
if (!base.pathname.endsWith('/')) base.pathname += '/';
const relative = stripSlashes(slug);
const target = relative ? new URL(`${relative}/`, base) : base;
target.search = '';
target.hash = '';
return target.toString();
}
function parseAsUrl(input: string): URL | null {
return tryParseUrl(input) ?? tryParseUrl(`https://${input}`);
}
function tryParseUrl(input: string): URL | null {
try {
return new URL(input);
} catch {
return null;
}
}
function stripSlashes(value: string): string {
let start = 0;
let end = value.length;
while (start < end && value[start] === '/') start += 1;
while (end > start && value[end - 1] === '/') end -= 1;
return value.slice(start, end);
}