UNPKG

@wordpress/block-library

Version:
35 lines (34 loc) • 1.37 kB
import { useSelect } from "@wordpress/data"; import { store } from "@wordpress/core-data"; // packages/block-library/src/utils/use-resolved-url.ts /** * Resolves a link against a base URL, the way a browser resolves an `href`. * * @param url The link, as stored in a block's attributes. * @param baseUrl The URL that relative links and hash links resolve against. * @return The absolute URL, or `undefined` when the link can't be resolved, * such as a relative link with no base URL. */ function getResolvedUrl(url, baseUrl) { if (!url) return; try { return new URL(url, baseUrl).href; } catch { return; } } /** * Resolves a link against the site's home URL. A page-relative link, such as * `#faq` or `./about`, depends on the page it's rendered on, which a block * doesn't know, so the home page stands in for it. * * @param url The link, as stored in a block's attributes. * @return The absolute URL, or `undefined` when the link can't be resolved. */ function useResolvedUrl(url) { const needsBaseUrl = !!url && getResolvedUrl(url) === void 0; const homeUrl = useSelect((select) => needsBaseUrl ? select(store).getEntityRecord("root", "__unstableBase")?.home : void 0, [needsBaseUrl]); return getResolvedUrl(url, homeUrl && homeUrl.replace(/\/?$/, "/")); } export { getResolvedUrl, useResolvedUrl }; //# sourceMappingURL=use-resolved-url.mjs.map