social-embeds 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -169,19 +169,20 @@ A component checks an `embed` before using it: its `url` must be one `matchUrl`
169
169
 
170
170
  ## Shared props
171
171
 
172
- | Prop | Type | Default | Notes |
173
- | ------------- | ------------------------ | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
174
- | `url` | `string` | | Post URL. Platform components take `url` or `embed`; `<SocialEmbed>` takes `url` or `html`. |
175
- | `embed` | `ParsedEmbed` | | Platform components only. |
176
- | `html` | `string` | | `<SocialEmbed>` only. |
177
- | `width` | `number \| string` | `'100%'` | Wrapper width. |
178
- | `maxWidth` | `number` | per platform | The embed fills its container up to this width, in pixels. See [Platforms](#platforms). |
179
- | `height` | `number` | | Iframe-based embeds only (YouTube, TikTok, Facebook video embed code): a fixed height instead of the aspect ratio. The others size themselves. |
180
- | `placeholder` | `ReactNode` | a skeleton | Shown until the post has loaded. The default skeleton has a per-platform minimum height to limit layout shift. |
181
- | `lazy` | `boolean` | `true` | Load the embed only when it comes within 200 px of the viewport. |
182
- | `onLoad` | `() => void` | | Called once the platform has rendered the post (iframe embeds: when the iframe has loaded). |
183
- | `onError` | `(error: Error) => void` | | Called on invalid input, a script that fails to load, or a post that does not render. Components never throw. |
184
- | `...rest` | `ComponentProps<'div'>` | | Passed to the wrapper `div` (`className`, `style`, `data-*`, …). |
172
+ | Prop | Type | Default | Notes |
173
+ | ------------- | ------------------------ | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
174
+ | `url` | `string` | | Post URL. Platform components take `url` or `embed`; `<SocialEmbed>` takes `url` or `html`. |
175
+ | `embed` | `ParsedEmbed` | | Platform components only. |
176
+ | `html` | `string` | | `<SocialEmbed>` only. |
177
+ | `width` | `number \| string` | `'100%'` | Wrapper width. |
178
+ | `maxWidth` | `number` | per platform | The embed fills its container up to this width, in pixels. See [Platforms](#platforms). |
179
+ | `height` | `number` | | Iframe-based embeds only (YouTube, TikTok, Facebook video embed code): a fixed height instead of the aspect ratio. The others size themselves. |
180
+ | `maxHeight` | `number` | | Iframe-based embeds only: the embed is at most this tall, in pixels. It narrows to keep its aspect ratio, so a vertical video does not fill the column. |
181
+ | `placeholder` | `ReactNode` | a skeleton | Shown until the post has loaded. The default skeleton has a per-platform minimum height to limit layout shift. |
182
+ | `lazy` | `boolean` | `true` | Load the embed only when it comes within 200 px of the viewport. |
183
+ | `onLoad` | `() => void` | | Called once the platform has rendered the post (iframe embeds: when the iframe has loaded). |
184
+ | `onError` | `(error: Error) => void` | | Called on invalid input, a script that fails to load, or a post that does not render. Components never throw. |
185
+ | `...rest` | `ComponentProps<'div'>` | | Passed to the wrapper `div` (`className`, `style`, `data-*`, …). |
185
186
 
186
187
  Script-based embeds try to render three times, waiting 15 s each time, 1 s and then 2 s apart, before `onError` reports the failure.
187
188
 
@@ -223,6 +224,15 @@ The rules:
223
224
 
224
225
  - **Posts** always render through the SDK, including when the embed code is the `plugins/post.php` iframe. That iframe's height only fits the `width` it was made for, so it cannot be responsive; the SDK resizes the post itself. `show_text` and `width` from the iframe carry over; `height` is dropped.
225
226
  - **Video embed code** (the `plugins/video.php` iframe) renders as that iframe, in a box with its aspect ratio. No script.
227
+ - **Video embed code that shows the post text** (`show_text=true`, the Embed dialog's "Include full post") renders through the SDK, like a post. The text below the player has its own height at every width, so no aspect ratio fits the iframe, and its own height cuts the text off. `show_text`, `allowfullscreen`, `autoplay` and `show_captions` carry over, `width` and `height` are kept as the player's size, and `t` is dropped.
228
+ - **That code without its text**: pass `showText={false}` to `FacebookEmbed`. The player's size is known from the embed code, so it renders as the plain iframe again, in a box of the player's aspect ratio. No script, and `maxHeight` applies:
229
+
230
+ ```tsx
231
+ <FacebookEmbed embed={embed} showText={false} maxHeight={640} />
232
+ ```
233
+
234
+ A 9:16 reel is then at most 358×638 px, where the same code with its text is 550×1233 px in a 550 px column. Facebook has no option for a shorter text: it is shown in full or not at all.
235
+
226
236
  - **Video URLs** and `fb-video` SDK code render through the SDK, which knows the video's real size (videos are both 16:9 and vertical).
227
237
 
228
238
  URL shapes, each tested against Facebook's plugins on `www.facebook.com`, `facebook.com` and `m.facebook.com`:
@@ -302,7 +312,7 @@ The platform's class (`twitter-tweet`, `instagram-media`, `text-post-media`) is
302
312
  The host does nothing to make embeds responsive:
303
313
 
304
314
  - **Script-based embeds** (X, Instagram, Threads, Facebook SDK) get a wrapper of `width: 100%` (or `width`) and `max-width: {maxWidth}px`, and the platform widget fills it. Their height is the platform's own.
305
- - **Iframe embeds** get a wrapper with `aspect-ratio` taken from the embed code's `width` and `height` (16:9 without them; 9:16 for TikTok and YouTube Shorts URLs), and the iframe fills it. `height` replaces the aspect ratio with a fixed height.
315
+ - **Iframe embeds** get a wrapper with `aspect-ratio` taken from the embed code's `width` and `height` (16:9 without them; 9:16 for TikTok and YouTube Shorts URLs), and the iframe fills it. `height` replaces the aspect ratio with a fixed height. `maxHeight` keeps the aspect ratio and lowers the wrapper's `max-width` to the widest box that is at most that tall.
306
316
 
307
317
  ## License
308
318
 
@@ -12,16 +12,11 @@ type ParsedEmbed = {
12
12
  };
13
13
  fallbackHtml?: string;
14
14
  };
15
- /**
16
- * Recognises a post URL. The result has no fallback content, and options only for data the
17
- * URL itself carries (docs/decisions.md D13). Never throws.
18
- */
15
+ /** Never throws. Options hold only what the URL itself carries (docs/decisions.md D13). */
19
16
  declare function matchUrl(url: string): ParsedEmbed | null;
20
17
  /**
21
- * Recognises a platform's own embed code. The input must consist of exactly one embed
22
- * element plus, optionally, the platform's own `<script src>` tags, Facebook's empty
23
- * `<div id="fb-root">`, whitespace and comments. Anything else returns `null`
24
- * (docs/decisions.md D14). Never throws.
18
+ * Never throws. `null` unless the input is one embed element plus, at most, the platform's
19
+ * own scripts, `<div id="fb-root">`, whitespace and comments (docs/decisions.md D14).
25
20
  */
26
21
  declare function parseEmbed(html: string): ParsedEmbed | null;
27
22
  export { Platform as i, matchUrl as n, ParsedEmbed as r, parseEmbed as t };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,5 @@
1
- import { r as ParsedEmbed } from "./index-CGSxjvGN.js";
1
+ import { r as ParsedEmbed } from "./index-DCF8EEVz.js";
2
2
  import { ComponentProps, ReactNode } from "react";
3
- /** A platform component takes a post URL or an already-parsed embed (brief §5.2). */
4
3
  type EmbedSource = {
5
4
  url: string;
6
5
  embed?: never;
@@ -8,7 +7,6 @@ type EmbedSource = {
8
7
  embed: ParsedEmbed;
9
8
  url?: never;
10
9
  };
11
- /** Props every embed component shares (brief §6). */
12
10
  type SharedProps = Omit<ComponentProps<'div'>, 'children' | 'onLoad' | 'onError'> & {
13
11
  /** Wrapper width. Default `'100%'`. */
14
12
  width?: number | string;
@@ -23,14 +21,14 @@ type SharedProps = Omit<ComponentProps<'div'>, 'children' | 'onLoad' | 'onError'
23
21
  /** Fires on invalid input, script load failure or init timeout. */
24
22
  onError?: (error: Error) => void;
25
23
  };
26
- /** Iframe-based embeds (Group B) may also be given a fixed height. */
27
24
  type FrameProps = SharedProps & {
28
25
  /** A fixed height in pixels, instead of the embed's aspect ratio. */
29
26
  height?: number;
27
+ /** The embed is at most this tall, in pixels: it narrows to keep its aspect ratio. */
28
+ maxHeight?: number;
30
29
  };
31
30
  /**
32
- * The plugin attributes Facebook documents, plus the SDK locale. `data-width` and
33
- * `data-lazy` have no props, because `width` and `lazy` are the wrapper's
31
+ * `data-width` and `data-lazy` have no props, because `width` and `lazy` are the wrapper's
34
32
  * (docs/decisions.md D33).
35
33
  */
36
34
  type FacebookOptions = {
@@ -44,12 +42,8 @@ type FacebookOptions = {
44
42
  /** Video only. */
45
43
  showCaptions?: boolean;
46
44
  };
47
- /** `height` applies only to video embed code, which renders as an iframe. */
45
+ /** `height` and `maxHeight` apply only to a video that renders as an iframe. */
48
46
  type FacebookEmbedProps = EmbedSource & Omit<FrameProps, keyof FacebookOptions> & FacebookOptions;
49
- /**
50
- * Facebook rendering rules (brief §5.4): posts always through the SDK; video embed code as
51
- * the iframe that came in; video URLs through the SDK. The parser has set `variant`.
52
- */
53
47
  export declare function FacebookEmbed(props: FacebookEmbedProps): import("react").JSX.Element | null;
54
48
  type InstagramOptions = {
55
49
  /** Show the caption (`data-instgrm-captioned`). */
@@ -81,14 +75,11 @@ type TikTokOptions = {
81
75
  forceMuted?: boolean;
82
76
  };
83
77
  type TikTokEmbedProps = EmbedSource & Omit<FrameProps, keyof TikTokOptions> & TikTokOptions;
84
- /**
85
- * Every TikTok input renders the Embed Player iframe (docs/decisions.md D11). It is at
86
- * most 325px wide, the size of TikTok's own embed code (D40).
87
- */
78
+ /** At most 325px wide by default, the size of TikTok's own embed code (docs/decisions.md D40). */
88
79
  export declare function TikTokEmbed(props: TikTokEmbedProps): import("react").JSX.Element | null;
89
80
  /**
90
- * The embedded post attributes X documents. `data-width` has no prop, because `width` is
91
- * the wrapper's; the post fills the wrapper up to `maxWidth` (docs/decisions.md D33).
81
+ * `data-width` has no prop, because `width` is the wrapper's: the post fills the wrapper up
82
+ * to `maxWidth` (docs/decisions.md D33).
92
83
  */
93
84
  type XOptions = {
94
85
  theme?: 'light' | 'dark';
@@ -127,7 +118,6 @@ type YouTubeOptions = {
127
118
  };
128
119
  type YouTubeEmbedProps = EmbedSource & Omit<FrameProps, keyof YouTubeOptions> & YouTubeOptions;
129
120
  export declare function YouTubeEmbed(props: YouTubeEmbedProps): import("react").JSX.Element | null;
130
- /** Embed code or a post URL; never both (brief §5.2). */
131
121
  type SocialEmbedSource = {
132
122
  html: string;
133
123
  url?: never;
@@ -135,21 +125,14 @@ type SocialEmbedSource = {
135
125
  url: string;
136
126
  html?: never;
137
127
  };
138
- /**
139
- * Platform options come from the embed code. Div attributes that share a name with one
140
- * (`lang`, `color`, `rel`) are left out, because each platform reads that name its own way.
141
- */
142
128
  type PlatformOption = keyof XOptions | keyof InstagramOptions | keyof ThreadsOptions | keyof FacebookOptions | keyof TikTokOptions | keyof YouTubeOptions;
143
129
  type SocialEmbedProps = SocialEmbedSource & Omit<FrameProps, PlatformOption> & {
144
130
  /**
145
- * Called with the original string when `html` is not a recognised embed code
146
- * (brief §6.4). Without it, nothing is rendered and `onError` is called.
131
+ * Called with the original string when `html` is not a recognised embed code. Without
132
+ * it, nothing is rendered and `onError` is called.
147
133
  */
148
134
  fallback?: (html: string) => ReactNode;
149
135
  };
150
- /**
151
- * Recognises embed code or a post URL and renders the platform's component. `height`
152
- * reaches only the iframe-based embeds; the others size themselves (brief §6.1).
153
- */
154
- export declare function SocialEmbed(props: SocialEmbedProps): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | import("react").JSX.Element | null | undefined;
136
+ /** `height` and `maxHeight` reach only the iframe-based embeds: the others size themselves. */
137
+ export declare function SocialEmbed(props: SocialEmbedProps): string | number | bigint | boolean | import("react").JSX.Element | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | null | undefined;
155
138
  export type { EmbedSource, FacebookEmbedProps, FacebookOptions, FrameProps, InstagramEmbedProps, InstagramOptions, SharedProps, SocialEmbedProps, SocialEmbedSource, ThreadsEmbedProps, ThreadsOptions, TikTokEmbedProps, TikTokOptions, XEmbedProps, XOptions, YouTubeEmbedProps, YouTubeOptions };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { a as escapeAttribute, i as x$1, n as matchUrl, o as parseHtml, r as platforms, s as rebuild, t as parseEmbed } from "./parser-DVync2rz.js";
2
+ import { a as escapeAttribute, i as x$1, n as matchUrl, o as parseHtml, r as platforms, s as rebuild, t as parseEmbed } from "./parser-BrlUKvvo.js";
3
3
  import { useEffect, useMemo, useRef, useState } from "react";
4
4
  import { jsx, jsxs } from "react/jsx-runtime";
5
5
  // src/loader/load-script.ts
@@ -29,8 +29,9 @@ var LoadError = class extends Error {};
29
29
  async function add(script) {
30
30
  const ready = script.readyCallback?.();
31
31
  for (let attempt = 1;; attempt++) try {
32
- await insert(script);
33
- break;
32
+ const element = await insert(script);
33
+ if (attempt >= ATTEMPTS$1 || !script.skipped?.()) break;
34
+ element.remove();
34
35
  } catch (error) {
35
36
  if (!(error instanceof LoadError) || attempt >= ATTEMPTS$1) throw error;
36
37
  await delay(RETRY_DELAY_MS$1 * 2 ** (attempt - 1));
@@ -39,8 +40,8 @@ async function add(script) {
39
40
  }
40
41
  async function insert(script) {
41
42
  const restore = script.prepare?.();
43
+ const element = document.createElement("script");
42
44
  const loaded = new Promise((resolve, reject) => {
43
- const element = document.createElement("script");
44
45
  element.src = script.url;
45
46
  element.async = true;
46
47
  if (script.crossOrigin) element.crossOrigin = script.crossOrigin;
@@ -58,6 +59,7 @@ async function insert(script) {
58
59
  } finally {
59
60
  restore?.();
60
61
  }
62
+ return element;
61
63
  }
62
64
  function poll(script) {
63
65
  return new Promise((resolve, reject) => {
@@ -89,10 +91,7 @@ function delay(ms) {
89
91
  }
90
92
  // src/loader/platform-scripts.ts
91
93
  const globals$1 = () => window;
92
- /**
93
- * The SDK refuses to parse without a Graph API version. Social plugins render with old and
94
- * new versions alike; this is the one Meta's Embedded Posts documentation uses.
95
- */
94
+ /** The SDK refuses to parse without a Graph API version (docs/decisions.md D26). */
96
95
  const FACEBOOK_SDK_VERSION = "v26.0";
97
96
  const LOCALE = /^[a-z]{2,3}_[A-Z]{2}$/;
98
97
  /** Instagram and Threads share `instgrm.Embeds`; each registers its name when loaded. */
@@ -115,12 +114,6 @@ const x = {
115
114
  else resolve();
116
115
  })
117
116
  };
118
- /**
119
- * Instagram's and Threads' embed.js do nothing when a loaded Facebook SDK is on the page:
120
- * both start with `(window.FB && !window.FB.__buffer) || …`. The SDK's own stub carries
121
- * `__buffer` while the SDK loads, so a loaded SDK is marked the same way while the script
122
- * runs. Neither script reads `FB` anywhere else (docs/decisions.md D38).
123
- */
124
117
  function besideFacebookSdk() {
125
118
  const fb = globals$1().FB;
126
119
  if (!fb || fb.__buffer) return () => {};
@@ -129,24 +122,29 @@ function besideFacebookSdk() {
129
122
  delete fb.__buffer;
130
123
  };
131
124
  }
125
+ function skippedBesideFacebookSdk(name) {
126
+ const registered = embedSdkRegistered(name);
127
+ return () => {
128
+ const fb = globals$1().FB;
129
+ return !registered() && fb !== void 0 && !fb.__buffer;
130
+ };
131
+ }
132
132
  const instagram = {
133
133
  key: "instagram",
134
134
  url: "https://www.instagram.com/embed.js",
135
135
  isOwn: (src) => /^https?:\/\/www\.instagram\.com\/embed\.js(?:[?#]|$)/.test(src),
136
136
  isPresent: embedSdkRegistered("instagram"),
137
- prepare: besideFacebookSdk
137
+ prepare: besideFacebookSdk,
138
+ skipped: skippedBesideFacebookSdk("instagram")
138
139
  };
139
140
  const threads = {
140
141
  key: "threads",
141
142
  url: "https://www.threads.com/embed.js",
142
143
  isOwn: (src) => /^https?:\/\/www\.threads\.(?:com|net)\/embed\.js(?:[?#]|$)/.test(src),
143
144
  isPresent: embedSdkRegistered("threads"),
144
- prepare: besideFacebookSdk
145
+ prepare: besideFacebookSdk,
146
+ skipped: skippedBesideFacebookSdk("threads")
145
147
  };
146
- /**
147
- * `xfbml=0` stops the SDK from scanning the whole page; embeds are parsed explicitly. One
148
- * SDK serves the whole page, so the first locale requested wins.
149
- */
150
148
  function facebook(locale) {
151
149
  return {
152
150
  key: "facebook",
@@ -173,7 +171,6 @@ function loadPlatformScript(platform, { locale = "en_US" } = {}) {
173
171
  }
174
172
  // src/components/drivers.ts
175
173
  const globals = () => window;
176
- /** Calls `done` once `rendered(container)` holds, checking after every DOM change. */
177
174
  function watch(container, rendered, done) {
178
175
  if (rendered(container)) {
179
176
  done();
@@ -198,17 +195,10 @@ function watch(container, rendered, done) {
198
195
  observer.disconnect();
199
196
  };
200
197
  }
201
- /**
202
- * widgets.js and embed.js render every blockquote with their class anywhere in the page, on
203
- * load and on each call, so the components write the blockquote without it. The class is
204
- * added once, when this embed renders; a platform that has since replaced it with its own
205
- * (Threads' `text-post-media-registered`) keeps that (docs/decisions.md D39).
206
- */
207
198
  function reveal(container, className) {
208
199
  const blockquote = container.querySelector("blockquote");
209
200
  if (blockquote && !blockquote.hasAttribute("class")) blockquote.classList.add(className);
210
201
  }
211
- /** An iframe in `container` that the platform has given a height. */
212
202
  function hasSizedIframe(container) {
213
203
  return [...container.querySelectorAll("iframe")].some((iframe) => Number.parseFloat(iframe.style.height) > 0);
214
204
  }
@@ -285,11 +275,7 @@ function facebookDriver(locale) {
285
275
  }
286
276
  // src/components/hooks.ts
287
277
  const ROOT_MARGIN = "200px 0px";
288
- /**
289
- * Whether the element has come near the viewport. Always false on the server and in the
290
- * first client render, so server and client markup match; true right after mount when
291
- * `lazy` is off or IntersectionObserver is unavailable.
292
- */
278
+ /** False on the server and in the first client render, so the markup matches on hydration. */
293
279
  function useNearViewport(ref, lazy) {
294
280
  const [near, setNear] = useState(false);
295
281
  useEffect(() => {
@@ -326,23 +312,22 @@ const FILL = {
326
312
  position: "absolute",
327
313
  inset: 0
328
314
  };
329
- /**
330
- * Group B: a responsive wrapper whose aspect ratio comes from the input, with the
331
- * iframe filling it. The iframe is created on the client only, so its load event is
332
- * never missed before hydration; the placeholder covers the box until then.
333
- */
334
- function IframeEmbed({ src, title, allow, referrerPolicy, scrolling, ratio, size, width = "100%", maxWidth, height, placeholder, lazy = true, onLoad, style, ...rest }) {
315
+ function IframeEmbed({ src, title, allow, referrerPolicy, scrolling, ratio, size, width = "100%", maxWidth, height, maxHeight, placeholder, lazy = true, onLoad, style, ...rest }) {
335
316
  const frame = useRef(null);
336
317
  const near = useNearViewport(frame, lazy);
337
318
  const [loaded, setLoaded] = useState(false);
338
319
  const reported = useRef(false);
339
320
  const aspectWidth = size?.width ?? ratio.width;
340
321
  const aspectHeight = size?.height ?? ratio.height;
322
+ const widest = maxHeight === void 0 || height !== void 0 ? void 0 : Math.floor(maxHeight * aspectWidth / aspectHeight);
341
323
  const wrapper = {
342
324
  position: "relative",
343
325
  width,
344
- maxWidth,
345
- ...height === void 0 ? { aspectRatio: `${String(aspectWidth)} / ${String(aspectHeight)}` } : { height },
326
+ maxWidth: widest === void 0 || maxWidth !== void 0 && maxWidth < widest ? maxWidth : widest,
327
+ ...height === void 0 ? { aspectRatio: `${String(aspectWidth)} / ${String(aspectHeight)}` } : {
328
+ height,
329
+ maxHeight
330
+ },
346
331
  ...style
347
332
  };
348
333
  return /* @__PURE__ */ jsx("div", {
@@ -377,7 +362,6 @@ function IframeEmbed({ src, title, allow, referrerPolicy, scrolling, ratio, size
377
362
  })
378
363
  });
379
364
  }
380
- /** The default placeholder: a neutral box, readable on light and dark pages. */
381
365
  function Skeleton({ minHeight }) {
382
366
  return /* @__PURE__ */ jsx("div", {
383
367
  "aria-hidden": "true",
@@ -390,7 +374,6 @@ function Skeleton({ minHeight }) {
390
374
  });
391
375
  }
392
376
  // src/parser/verify.ts
393
- /** The kind and variant pairs the parser produces for each platform. */
394
377
  const SHAPES = {
395
378
  x: ["post sdk"],
396
379
  instagram: ["post sdk"],
@@ -404,16 +387,8 @@ const SHAPES = {
404
387
  youtube: ["video iframe"]
405
388
  };
406
389
  /**
407
- * Checks an embed handed to a component. It may not come from this parser: a host can build
408
- * one, or read one back from storage.
409
- *
410
- * - Its URL must be one `matchUrl` recognises for the same platform and id, and its kind
411
- * and variant a pair the parser produces, because components put the URL and id into
412
- * iframe sources and platform markup.
413
- * - Its `fallbackHtml` must be exactly what the platform's whitelist rebuilds, because
414
- * components write it into the page as HTML. For X it must also link to the same post,
415
- * because widgets.js renders the post the blockquote links to. Otherwise the fallback is
416
- * dropped.
390
+ * Security: the embed may be host-built, and its url, id and `fallbackHtml` are written
391
+ * into the page: only what this parser itself produces passes (docs/decisions.md D35).
417
392
  */
418
393
  function verifyEmbed(embed) {
419
394
  const matched = matchUrl(embed.url);
@@ -442,7 +417,6 @@ const NAMES = {
442
417
  tiktok: "TikTok",
443
418
  youtube: "YouTube"
444
419
  };
445
- /** The embed for `platform`, or a message saying why the input is not one. */
446
420
  function resolveEmbed(url, given, platform) {
447
421
  const embed = given ?? (url === void 0 ? null : matchUrl(url));
448
422
  if (!embed) return { error: `social-embeds: not a ${NAMES[platform]} post URL: ${String(url)}` };
@@ -451,17 +425,14 @@ function resolveEmbed(url, given, platform) {
451
425
  if (!verified) return { error: `social-embeds: the ${NAMES[platform]} embed's url and id do not match` };
452
426
  return { embed: verified };
453
427
  }
454
- /** Serialises query parameters; later entries replace earlier ones with the same name. */
428
+ /** Later entries replace earlier ones with the same name. */
455
429
  function query(...sources) {
456
430
  const params = /* @__PURE__ */ new Map();
457
431
  for (const source of sources) for (const [key, value] of source ?? []) params.set(key, String(value));
458
432
  const pairs = [...params].map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
459
433
  return pairs.length > 0 ? `?${pairs.join("&")}` : "";
460
434
  }
461
- /**
462
- * Maps option props to the platform's parameter names. Player parameters take 0 and 1,
463
- * so booleans become numbers; undefined props are left out.
464
- */
435
+ /** Player parameters take 0 and 1, so booleans become numbers. */
465
436
  function playerParams(props, names) {
466
437
  const params = [];
467
438
  for (const [prop, name] of Object.entries(names)) {
@@ -473,11 +444,6 @@ function playerParams(props, names) {
473
444
  }
474
445
  // src/components/facebook-video-iframe.tsx
475
446
  const ALLOW$2 = "autoplay; clipboard-write; encrypted-media; picture-in-picture; web-share";
476
- /**
477
- * Facebook video from embed code: the iframe that came in (brief §5.4), rebuilt from the
478
- * parsed href and parameters. Its content fills the iframe at any width, whatever its
479
- * `width` parameter says (docs/decisions.md D29). `FacebookEmbed` routes here.
480
- */
481
447
  function FacebookVideoIframe({ embed, ...frame }) {
482
448
  const params = Object.entries(embed.options).filter(([key]) => key !== "href");
483
449
  return /* @__PURE__ */ jsx(IframeEmbed, {
@@ -494,7 +460,7 @@ function FacebookVideoIframe({ embed, ...frame }) {
494
460
  });
495
461
  }
496
462
  // src/components/markup.ts
497
- /** `name="value"` pairs for defined values; `true` becomes a valueless attribute. */
463
+ /** `true` becomes a valueless attribute. */
498
464
  function attributes(entries) {
499
465
  let html = "";
500
466
  for (const [name, value] of Object.entries(entries)) {
@@ -503,10 +469,7 @@ function attributes(entries) {
503
469
  }
504
470
  return html;
505
471
  }
506
- /**
507
- * Options written as the platform's `data-*` attributes, in the given order. Booleans are
508
- * written as `"true"`/`"false"`, as platforms document them.
509
- */
472
+ /** Booleans are written as `"true"` and `"false"`, the way the platforms document them. */
510
473
  function dataAttributes(names, options) {
511
474
  const entries = {};
512
475
  for (const [key, name] of Object.entries(names)) {
@@ -531,11 +494,6 @@ const RETRY_DELAY_MS = 1e3;
531
494
  function toError(error) {
532
495
  return error instanceof Error ? error : new Error(String(error));
533
496
  }
534
- /**
535
- * Group A: the platform markup is written once into a container React never updates
536
- * again, so the platform script can replace it in place (brief §6.3). Callers key this
537
- * component by `markup`, so different markup gets a fresh container.
538
- */
539
497
  function ScriptEmbed({ driver, markup, hasFallback, minHeight, label, width = "100%", maxWidth, placeholder, lazy = true, onLoad, onError, style, ...rest }) {
540
498
  const container = useRef(null);
541
499
  const near = useNearViewport(container, lazy);
@@ -628,6 +586,12 @@ const ATTRIBUTES$1 = {
628
586
  autoplay: "data-autoplay",
629
587
  showCaptions: "data-show-captions"
630
588
  };
589
+ const PLAYER_PARAMETERS = {
590
+ showText: "show_text",
591
+ allowfullscreen: "allowfullscreen",
592
+ autoplay: "autoplay",
593
+ showCaptions: "show_captions"
594
+ };
631
595
  /** Embedded Posts: "Max. 750 pixel"; videos have no upper limit (docs/decisions.md D33). */
632
596
  const POST_MAX_WIDTH = 750;
633
597
  /** docs/decisions.md D34. */
@@ -635,18 +599,18 @@ const MIN_HEIGHT$3 = {
635
599
  post: 300,
636
600
  video: 200
637
601
  };
638
- /**
639
- * Facebook rendering rules (brief §5.4): posts always through the SDK; video embed code as
640
- * the iframe that came in; video URLs through the SDK. The parser has set `variant`.
641
- */
642
602
  function FacebookEmbed(props) {
643
- const { url, embed: given, onError, locale, showText, allowfullscreen, autoplay, showCaptions, height, ...shared } = props;
603
+ const { url, embed: given, onError, locale, showText, allowfullscreen, autoplay, showCaptions, height, maxHeight, ...shared } = props;
644
604
  const { embed, error } = resolveEmbed(url, given, "facebook");
645
605
  useReportError(error, onError);
646
606
  if (!embed) return null;
607
+ const frame = {
608
+ height,
609
+ maxHeight
610
+ };
647
611
  if (embed.variant === "iframe") return /* @__PURE__ */ jsx(FacebookVideoIframe, {
648
612
  ...shared,
649
- height,
613
+ ...frame,
650
614
  embed
651
615
  });
652
616
  const options = withProps(embed.options, {
@@ -655,6 +619,24 @@ function FacebookEmbed(props) {
655
619
  autoplay,
656
620
  showCaptions
657
621
  });
622
+ const { size } = embed;
623
+ if (embed.kind === "video" && options.showText === false && size?.width !== void 0 && size.height !== void 0) {
624
+ const parameters = {};
625
+ for (const [option, name] of Object.entries(PLAYER_PARAMETERS)) {
626
+ const value = options[option];
627
+ if (value !== void 0) parameters[name] = value;
628
+ }
629
+ parameters.width = size.width;
630
+ parameters.height = size.height;
631
+ return /* @__PURE__ */ jsx(FacebookVideoIframe, {
632
+ ...shared,
633
+ ...frame,
634
+ embed: {
635
+ ...embed,
636
+ options: parameters
637
+ }
638
+ });
639
+ }
658
640
  const sdkLocale = locale ?? (typeof options.locale === "string" ? options.locale : "en_US");
659
641
  const markup = `<div class="${embed.kind === "video" ? "fb-video" : "fb-post"}" data-href="${escapeAttribute(embed.url)}"${dataAttributes(ATTRIBUTES$1, options)}>${embed.fallbackHtml ?? ""}</div>`;
660
642
  return /* @__PURE__ */ jsx(ScriptEmbed, {
@@ -671,11 +653,6 @@ function FacebookEmbed(props) {
671
653
  // src/components/instagram-embed.tsx
672
654
  /** A photo post without caption at 375px, the smallest measured (docs/decisions.md D34). */
673
655
  const MIN_HEIGHT$2 = 680;
674
- /**
675
- * embed.js copies the blockquote's inline style onto its iframe and gives the iframe no
676
- * width of its own, so without this the post stays 326px wide. The value is the one in
677
- * Instagram's own embed code (docs/decisions.md D33).
678
- */
679
656
  const FLUID_WIDTH = "width:calc(100% - 2px)";
680
657
  function InstagramEmbed(props) {
681
658
  const { url, embed: given, onError, maxWidth = 540, captioned, ...shared } = props;
@@ -744,10 +721,7 @@ const PARAMS$1 = {
744
721
  forceMuted: "force_muted"
745
722
  };
746
723
  const ALLOW$1 = "accelerometer; autoplay; clipboard-write; encrypted-media; fullscreen; gyroscope; picture-in-picture; web-share";
747
- /**
748
- * Every TikTok input renders the Embed Player iframe (docs/decisions.md D11). It is at
749
- * most 325px wide, the size of TikTok's own embed code (D40).
750
- */
724
+ /** At most 325px wide by default, the size of TikTok's own embed code (docs/decisions.md D40). */
751
725
  function TikTokEmbed(props) {
752
726
  const { url, embed: given, onError, maxWidth = 325, controls, progressBar, playButton, volumeControl, fullscreenButton, timestamp, loop, autoplay, musicInfo, description, rel, nativeContextMenu, closedCaption, forceMuted, ...frame } = props;
753
727
  const { embed, error } = resolveEmbed(url, given, "tiktok");
@@ -890,12 +864,13 @@ function YouTubeEmbed(props) {
890
864
  });
891
865
  }
892
866
  // src/components/social-embed.tsx
893
- /**
894
- * Recognises embed code or a post URL and renders the platform's component. `height`
895
- * reaches only the iframe-based embeds; the others size themselves (brief §6.1).
896
- */
867
+ /** `height` and `maxHeight` reach only the iframe-based embeds: the others size themselves. */
897
868
  function SocialEmbed(props) {
898
- const { html, url, fallback, height, onError, ...shared } = props;
869
+ const { html, url, fallback, height, maxHeight, onError, ...shared } = props;
870
+ const frame = {
871
+ height,
872
+ maxHeight
873
+ };
899
874
  const embed = useMemo(() => html !== void 0 ? parseEmbed(html) : matchUrl(url), [html, url]);
900
875
  useReportError(embed === null && !(html !== void 0 && fallback) ? html !== void 0 ? "social-embeds: unrecognised embed code" : `social-embeds: not a supported post URL: ${url}` : void 0, onError);
901
876
  if (!embed) return html !== void 0 && fallback ? fallback(html) : null;
@@ -917,19 +892,19 @@ function SocialEmbed(props) {
917
892
  });
918
893
  case "facebook": return /* @__PURE__ */ jsx(FacebookEmbed, {
919
894
  ...shared,
920
- height,
895
+ ...frame,
921
896
  onError,
922
897
  embed
923
898
  });
924
899
  case "tiktok": return /* @__PURE__ */ jsx(TikTokEmbed, {
925
900
  ...shared,
926
- height,
901
+ ...frame,
927
902
  onError,
928
903
  embed
929
904
  });
930
905
  case "youtube": return /* @__PURE__ */ jsx(YouTubeEmbed, {
931
906
  ...shared,
932
- height,
907
+ ...frame,
933
908
  onError,
934
909
  embed
935
910
  });
@@ -28,7 +28,6 @@ const NAMED_ENTITIES = /* @__PURE__ */ new Map([
28
28
  ["apos", "'"],
29
29
  ["nbsp", "\xA0"]
30
30
  ]);
31
- /** Parses an HTML fragment into a node list, or `null` if it is not well-formed. */
32
31
  function parseHtml(input) {
33
32
  const root = {
34
33
  type: "element",
@@ -124,7 +123,7 @@ function decodeEntities(value) {
124
123
  function hasClass(element, name) {
125
124
  return (element.attrs.get("class") ?? "").split(/\s+/).includes(name);
126
125
  }
127
- /** All descendant elements in document order. */
126
+ /** In document order. */
128
127
  function descendants(nodes) {
129
128
  const found = [];
130
129
  for (const node of nodes) {
@@ -136,9 +135,8 @@ function descendants(nodes) {
136
135
  const URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "cite"]);
137
136
  const HTTP_URL = /^https?:\/\//i;
138
137
  /**
139
- * Rebuilds markup from whitelisted elements and attributes only. Elements not on the list
140
- * are dropped together with their content; `href` and `cite` must be http(s) URLs. Text is
141
- * copied as written: the tokenizer guarantees it contains no `<`, so it cannot open a tag.
138
+ * Security: the result reaches `dangerouslySetInnerHTML`. Elements off the list are dropped
139
+ * with their content, `href` and `cite` must be http(s) URLs, and text never holds a `<`.
142
140
  */
143
141
  function rebuild(nodes, whitelist) {
144
142
  let html = "";
@@ -169,7 +167,7 @@ function escapeAttribute(value) {
169
167
  }
170
168
  // src/parser/url.ts
171
169
  const URL_PATTERN = /^(?:https?:)?\/\/([^/?#\s@]+)((?:\/[^?#\s]*)?)(?:\?([^#\s]*))?(?:#\S*)?$/i;
172
- /** Splits an absolute or protocol-relative http(s) URL, or returns `null`. */
170
+ /** Absolute or protocol-relative http(s) URLs only. */
173
171
  function parseUrl(input) {
174
172
  const match = URL_PATTERN.exec(input.trim());
175
173
  if (!match) return null;
@@ -203,12 +201,11 @@ function coerce(value) {
203
201
  if (/^(?:0|[1-9]\d{0,14})$/.test(value)) return Number(value);
204
202
  return value;
205
203
  }
206
- /** Positive integer pixel size from an attribute or query value. */
207
204
  function pixels(value) {
208
205
  return value !== void 0 && /^[1-9]\d{0,5}$/.test(value) ? Number(value) : void 0;
209
206
  }
210
207
  // src/parser/platform.ts
211
- /** Reads options from attributes; the first attribute present for a key wins. */
208
+ /** The first attribute present for a key wins. */
212
209
  function attributeOptions(element, mapping, coerceValue) {
213
210
  const options = {};
214
211
  for (const [attribute, key] of mapping) {
@@ -264,6 +261,12 @@ const OPTION_ATTRIBUTES$2 = [
264
261
  ["data-autoplay", "autoplay"],
265
262
  ["data-show-captions", "showCaptions"]
266
263
  ];
264
+ const VIDEO_SDK_PARAMETERS = [
265
+ ["show_text", "showText"],
266
+ ["allowfullscreen", "allowfullscreen"],
267
+ ["autoplay", "autoplay"],
268
+ ["show_captions", "showCaptions"]
269
+ ];
267
270
  const PARSE_IGNORE = {
268
271
  name: "class",
269
272
  value: /^fb-xfbml-parse-ignore$/
@@ -368,7 +371,26 @@ const facebook = {
368
371
  if (width !== void 0) options.width = coerce(width);
369
372
  return embed(found, "post", "sdk", options);
370
373
  }
371
- if (src.path === "/plugins/video.php") return withSize(embed(found, "video", "iframe", Object.fromEntries([...src.query].filter(([key]) => key !== "href").map(([key, value]) => [key, coerce(value)]))), sizeOf(root));
374
+ if (src.path === "/plugins/video.php") {
375
+ const showText = coerce(src.query.get("show_text") ?? "");
376
+ if (showText === true || showText === 1) {
377
+ const options = {};
378
+ for (const [parameter, key] of VIDEO_SDK_PARAMETERS) {
379
+ const value = src.query.get(parameter);
380
+ if (value !== void 0) options[key] = coerce(value);
381
+ }
382
+ const width = pixels(src.query.get("width"));
383
+ const height = pixels(src.query.get("height"));
384
+ return withSize(embed(found, "video", "sdk", {
385
+ ...options,
386
+ showText: true
387
+ }), width === void 0 || height === void 0 ? void 0 : {
388
+ width,
389
+ height
390
+ });
391
+ }
392
+ return withSize(embed(found, "video", "iframe", Object.fromEntries([...src.query].filter(([key]) => key !== "href").map(([key, value]) => [key, coerce(value)]))), sizeOf(root));
393
+ }
372
394
  return null;
373
395
  },
374
396
  isOwnScript: (src) => SCRIPT$4.test(src),
@@ -398,10 +420,6 @@ const FALLBACK$2 = /* @__PURE__ */ new Map([
398
420
  ["a", ["href"]],
399
421
  ["p", []]
400
422
  ]);
401
- /**
402
- * embed.js serves only /p/, /reel/ and /tv/ permalinks; /reels/ and /{user}/… return 404
403
- * (docs/decisions.md D15), so the canonical URL drops the username and maps reels → reel.
404
- */
405
423
  function post$2(url) {
406
424
  if (!url || !HOSTS$3.has(url.host)) return null;
407
425
  const [, user, type, code] = POST_PATH$1.exec(url.path) ?? [];
@@ -495,7 +513,6 @@ const VIDEO_PATH = /^\/@([A-Za-z0-9._]{0,64})\/video\/(\d{1,25})\/?$/;
495
513
  const PLAYER_PATH = /^\/player\/v1\/(\d{1,25})\/?$/;
496
514
  const VIDEO_ID$1 = /^\d{1,25}$/;
497
515
  const SCRIPT$1 = /^(?:https?:)?\/\/www\.tiktok\.com\/embed\.js$/;
498
- /** `user` is unknown for player iframe input; TikTok serves `/@/video/{id}` for that case. */
499
516
  function video$1(id, user = "", options = {}) {
500
517
  return {
501
518
  platform: "tiktok",
@@ -687,10 +704,7 @@ const platforms = [
687
704
  }
688
705
  ];
689
706
  // src/parser/match-url.ts
690
- /**
691
- * Recognises a post URL. The result has no fallback content, and options only for data the
692
- * URL itself carries (docs/decisions.md D13). Never throws.
693
- */
707
+ /** Never throws. Options hold only what the URL itself carries (docs/decisions.md D13). */
694
708
  function matchUrl(url) {
695
709
  if (typeof url !== "string") return null;
696
710
  const parsed = parseUrl(url);
@@ -703,10 +717,8 @@ function matchUrl(url) {
703
717
  }
704
718
  // src/parser/parse-embed.ts
705
719
  /**
706
- * Recognises a platform's own embed code. The input must consist of exactly one embed
707
- * element plus, optionally, the platform's own `<script src>` tags, Facebook's empty
708
- * `<div id="fb-root">`, whitespace and comments. Anything else returns `null`
709
- * (docs/decisions.md D14). Never throws.
720
+ * Never throws. `null` unless the input is one embed element plus, at most, the platform's
721
+ * own scripts, `<div id="fb-root">`, whitespace and comments (docs/decisions.md D14).
710
722
  */
711
723
  function parseEmbed(html) {
712
724
  if (typeof html !== "string") return null;
package/dist/parser.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { i as Platform, n as matchUrl, r as ParsedEmbed, t as parseEmbed } from "./index-CGSxjvGN.js";
1
+ import { i as Platform, n as matchUrl, r as ParsedEmbed, t as parseEmbed } from "./index-DCF8EEVz.js";
2
2
  export { type ParsedEmbed, type Platform, matchUrl, parseEmbed };
package/dist/parser.js CHANGED
@@ -1 +1 @@
1
- export { n as matchUrl, t as parseEmbed } from "./parser-DVync2rz.js";
1
+ export { n as matchUrl, t as parseEmbed } from "./parser-BrlUKvvo.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "social-embeds",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Turn social media embed code or post URLs into working React components.",
5
5
  "license": "MIT",
6
6
  "author": "Atanas Mitrev",
@@ -47,10 +47,10 @@
47
47
  "publint": "0.3.25",
48
48
  "react": "19.3.1",
49
49
  "react-dom": "19.3.1",
50
- "tsdown": "0.23.4",
50
+ "tsdown": "0.23.7",
51
51
  "typescript": "6.0.3",
52
52
  "typescript-eslint": "8.72.1",
53
- "vite": "8.3.5",
53
+ "vite": "8.3.7",
54
54
  "vitest": "5.1.0"
55
55
  },
56
56
  "scripts": {