/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ import './LinkPreview.css'; import * as React from 'react'; import { Suspense } from 'react'; // Cached responses or running request promises const PREVIEW_CACHE = {}; const URL_MATCHER = /((https?:\/\/(www\.)?)|(www\.))[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)/; function useSuspenseRequest(url: string) { let cached = PREVIEW_CACHE[url]; if (!url.match(URL_MATCHER)) { return { preview: null }; } if (!cached) { cached = PREVIEW_CACHE[url] = fetch( `/api/link-preview?url=${encodeURI(url)}` ) .then((response) => response.json()) .then((preview) => { PREVIEW_CACHE[url] = preview; return preview; }) .catch(() => { PREVIEW_CACHE[url] = { preview: null }; }); } if (cached instanceof Promise) { throw cached; } return cached; } function LinkPreviewContent({ url, }: Readonly<{ url: string; }>): JSX.Element { const { preview } = useSuspenseRequest(url); if (preview === null) { return null; } return (