shelving
Version:
Toolkit for using data in JavaScript.
36 lines (35 loc) • 1.61 kB
JavaScript
import { createContext, use } from "react";
import { RequiredError } from "../../error/RequiredError.js";
import { getURIParams } from "../../util/uri.js";
import { matchURLPrefix } from "../../util/url.js";
import { mergeMeta } from "../util/meta.js";
/** Context to store the `Config` object. */
export const MetaContext = createContext({});
MetaContext.displayName = "MetaContext";
/**
* Use the current meta context in a component.
*
* @param meta A set of new possible meta data to combine into the current meta context.
*/
export function requireMeta(meta) {
const current = use(MetaContext);
return meta ? mergeMeta(current, meta) : current;
}
/**
* Use the current meta context in a component with some additional URL helpers.
*
* @param meta A set of new possible meta data to combine into the current meta context.
* @returns A `Meta` object with a defined `url` object, and `path` and `params` properties combined in.
* @throws {RequiredError} if the current meta has no `url`
* @throws {RequiredError} if the current meta `url` does not match the origin of the current meta `root`
*/
export function requireMetaURL(meta, caller = requireMetaURL) {
const { url, root, ...combined } = requireMeta(meta);
if (!url)
throw new RequiredError("Meta URL is required", { received: url, caller });
const path = matchURLPrefix(url, root, caller);
if (!path)
throw new RequiredError("Meta URL and meta root must share an origin", { url, root, caller });
const params = getURIParams(url, caller);
return { ...combined, url, root, path, params };
}