@asteroidcms/core-utils 0.1.5 → 0.1.7

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/dist/client.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { PropsWithChildren, ReactNode, RefObject } from 'react';
2
+ import * as react from 'react';
3
+ import { PropsWithChildren, ReactNode } from 'react';
3
4
  import * as _apollo_client from '@apollo/client';
4
5
  import { InMemoryCacheConfig, ApolloClientOptions, ApolloClient } from '@apollo/client';
5
6
  import { useMutation } from '@apollo/client/react';
@@ -224,8 +225,8 @@ interface RichTextContentProps {
224
225
  */
225
226
  onReady?: (root: HTMLElement) => void;
226
227
  /**
227
- * Optional ref to the wrapper element. Useful for hooks like
228
- * `useTableOfContents` that need a stable reference to the rendered tree.
228
+ * Optional ref to the wrapper element. Useful for consumers that need a
229
+ * stable reference to the rendered tree (e.g. scroll observers, ToC hooks).
229
230
  */
230
231
  contentRef?: React.MutableRefObject<HTMLElement | null>;
231
232
  /**
@@ -254,7 +255,7 @@ interface RichTextContentProps {
254
255
  */
255
256
  calloutIcons?: Partial<Record<string, ReactNode>>;
256
257
  }
257
- declare function RichTextContent({ html, classMap, as, className, onReady, contentRef, calloutIcons, }: RichTextContentProps): react_jsx_runtime.JSX.Element;
258
+ declare const RichTextContent: react.NamedExoticComponent<RichTextContentProps>;
258
259
 
259
260
  /**
260
261
  * Heading extraction helpers used to build tables of contents (ToC) from
@@ -293,42 +294,4 @@ declare function extractHeadingsFromElement(root: HTMLElement, options?: Extract
293
294
  scrollMarginTop?: number;
294
295
  }): ExtractedHeading[];
295
296
 
296
- interface UseTableOfContentsOptions {
297
- /** Heading levels to include. Defaults to `[2, 3]`. */
298
- levels?: ReadonlyArray<HeadingLevel>;
299
- /**
300
- * Re-collect headings whenever this value changes. Pass the article slug
301
- * (or any stable identifier) so swapping content rebuilds the ToC.
302
- */
303
- contentKey?: string | number | null;
304
- /** Pixels to subtract from heading scroll-into-view target. Default 24. */
305
- scrollMarginTop?: number;
306
- /**
307
- * Distance from the top of the viewport (in px) at which a heading becomes
308
- * "active". A heading is considered active once its top edge has scrolled
309
- * past this line. Default `96` — works well with a sticky header that
310
- * stands ~60–80px tall.
311
- */
312
- activationOffset?: number;
313
- }
314
- interface UseTableOfContentsResult {
315
- items: ExtractedHeading[];
316
- activeId: string;
317
- }
318
- /**
319
- * Build a table of contents from a rendered element and track which
320
- * heading is currently in view via IntersectionObserver. Resilient to
321
- * content swaps when `contentKey` is provided.
322
- *
323
- * Usage:
324
- * ```tsx
325
- * const ref = useRef<HTMLDivElement>(null);
326
- * const { items, activeId } = useTableOfContents(ref, {
327
- * contentKey: article.slug,
328
- * levels: [2, 3],
329
- * });
330
- * ```
331
- */
332
- declare function useTableOfContents(ref: RefObject<HTMLElement | null>, options?: UseTableOfContentsOptions): UseTableOfContentsResult;
333
-
334
- export { AsteroidCMSProvider, type AsteroidCMSProviderProps, type ExtractHeadingsOptions, type ExtractedHeading, type HeadingLevel, RichTextContent, type UseCmsContentOptions, type UseCmsMutateOptions, type UseTableOfContentsOptions, type UseTableOfContentsResult, extractHeadingsFromElement, extractHeadingsFromHtml, slugify, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate, useTableOfContents };
297
+ export { AsteroidCMSProvider, type AsteroidCMSProviderProps, type ExtractHeadingsOptions, type ExtractedHeading, type HeadingLevel, RichTextContent, type UseCmsContentOptions, type UseCmsMutateOptions, extractHeadingsFromElement, extractHeadingsFromHtml, slugify, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate };
package/dist/client.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { PropsWithChildren, ReactNode, RefObject } from 'react';
2
+ import * as react from 'react';
3
+ import { PropsWithChildren, ReactNode } from 'react';
3
4
  import * as _apollo_client from '@apollo/client';
4
5
  import { InMemoryCacheConfig, ApolloClientOptions, ApolloClient } from '@apollo/client';
5
6
  import { useMutation } from '@apollo/client/react';
@@ -224,8 +225,8 @@ interface RichTextContentProps {
224
225
  */
225
226
  onReady?: (root: HTMLElement) => void;
226
227
  /**
227
- * Optional ref to the wrapper element. Useful for hooks like
228
- * `useTableOfContents` that need a stable reference to the rendered tree.
228
+ * Optional ref to the wrapper element. Useful for consumers that need a
229
+ * stable reference to the rendered tree (e.g. scroll observers, ToC hooks).
229
230
  */
230
231
  contentRef?: React.MutableRefObject<HTMLElement | null>;
231
232
  /**
@@ -254,7 +255,7 @@ interface RichTextContentProps {
254
255
  */
255
256
  calloutIcons?: Partial<Record<string, ReactNode>>;
256
257
  }
257
- declare function RichTextContent({ html, classMap, as, className, onReady, contentRef, calloutIcons, }: RichTextContentProps): react_jsx_runtime.JSX.Element;
258
+ declare const RichTextContent: react.NamedExoticComponent<RichTextContentProps>;
258
259
 
259
260
  /**
260
261
  * Heading extraction helpers used to build tables of contents (ToC) from
@@ -293,42 +294,4 @@ declare function extractHeadingsFromElement(root: HTMLElement, options?: Extract
293
294
  scrollMarginTop?: number;
294
295
  }): ExtractedHeading[];
295
296
 
296
- interface UseTableOfContentsOptions {
297
- /** Heading levels to include. Defaults to `[2, 3]`. */
298
- levels?: ReadonlyArray<HeadingLevel>;
299
- /**
300
- * Re-collect headings whenever this value changes. Pass the article slug
301
- * (or any stable identifier) so swapping content rebuilds the ToC.
302
- */
303
- contentKey?: string | number | null;
304
- /** Pixels to subtract from heading scroll-into-view target. Default 24. */
305
- scrollMarginTop?: number;
306
- /**
307
- * Distance from the top of the viewport (in px) at which a heading becomes
308
- * "active". A heading is considered active once its top edge has scrolled
309
- * past this line. Default `96` — works well with a sticky header that
310
- * stands ~60–80px tall.
311
- */
312
- activationOffset?: number;
313
- }
314
- interface UseTableOfContentsResult {
315
- items: ExtractedHeading[];
316
- activeId: string;
317
- }
318
- /**
319
- * Build a table of contents from a rendered element and track which
320
- * heading is currently in view via IntersectionObserver. Resilient to
321
- * content swaps when `contentKey` is provided.
322
- *
323
- * Usage:
324
- * ```tsx
325
- * const ref = useRef<HTMLDivElement>(null);
326
- * const { items, activeId } = useTableOfContents(ref, {
327
- * contentKey: article.slug,
328
- * levels: [2, 3],
329
- * });
330
- * ```
331
- */
332
- declare function useTableOfContents(ref: RefObject<HTMLElement | null>, options?: UseTableOfContentsOptions): UseTableOfContentsResult;
333
-
334
- export { AsteroidCMSProvider, type AsteroidCMSProviderProps, type ExtractHeadingsOptions, type ExtractedHeading, type HeadingLevel, RichTextContent, type UseCmsContentOptions, type UseCmsMutateOptions, type UseTableOfContentsOptions, type UseTableOfContentsResult, extractHeadingsFromElement, extractHeadingsFromHtml, slugify, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate, useTableOfContents };
297
+ export { AsteroidCMSProvider, type AsteroidCMSProviderProps, type ExtractHeadingsOptions, type ExtractedHeading, type HeadingLevel, RichTextContent, type UseCmsContentOptions, type UseCmsMutateOptions, extractHeadingsFromElement, extractHeadingsFromHtml, slugify, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate };
package/dist/client.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
- import { createContext, useContext, useMemo, useRef, useState, useEffect, Fragment, createElement } from 'react';
2
+ import { createContext, memo, useMemo, useRef, useState, useLayoutEffect, Fragment, createElement, useContext } from 'react';
3
3
  import { ApolloProvider, useQuery, useMutation } from '@apollo/client/react';
4
4
  import { gql, HttpLink, ApolloClient, InMemoryCache, ApolloLink, CombinedGraphQLErrors, CombinedProtocolErrors } from '@apollo/client';
5
5
  import { SetContextLink } from '@apollo/client/link/context';
6
6
  import { ErrorLink } from '@apollo/client/link/error';
7
- import { jsx, jsxs } from 'react/jsx-runtime';
7
+ import { jsxs, jsx } from 'react/jsx-runtime';
8
8
  import { createPortal } from 'react-dom';
9
9
  import hljs from 'highlight.js/lib/common';
10
10
 
@@ -1044,37 +1044,38 @@ function isIconEnabled(el) {
1044
1044
  if (v === null) return false;
1045
1045
  return v !== "false" && v !== "0";
1046
1046
  }
1047
- function enhanceCallouts(root) {
1047
+ function enhanceCallouts(root, calloutIcons) {
1048
1048
  const callouts = root.querySelectorAll("aside[data-callout]");
1049
1049
  callouts.forEach((el) => {
1050
- if (el.dataset.rtCalloutEnhanced === "1") return;
1051
- el.dataset.rtCalloutEnhanced = "1";
1052
- if (!isIconEnabled(el)) return;
1053
1050
  if (el.querySelector(":scope > .rt-callout-icon")) return;
1051
+ if (!isIconEnabled(el)) return;
1054
1052
  const variant = calloutVariantOf(el);
1055
1053
  const icon = document.createElement("span");
1056
1054
  icon.className = "rt-callout-icon";
1057
1055
  icon.dataset.variant = variant;
1058
1056
  icon.setAttribute("aria-hidden", "true");
1057
+ if (!calloutIcons || !(variant in calloutIcons)) {
1058
+ icon.innerHTML = CALLOUT_ICON_SVG[variant] ?? CALLOUT_ICON_SVG.default;
1059
+ }
1059
1060
  el.prepend(icon);
1060
1061
  });
1062
+ if (!calloutIcons) return [];
1061
1063
  const chips = [];
1062
1064
  root.querySelectorAll(
1063
1065
  "aside[data-callout] > .rt-callout-icon"
1064
1066
  ).forEach((chip) => {
1065
- chips.push({
1066
- el: chip,
1067
- variant: chip.dataset.variant || (chip.parentElement?.getAttribute("data-variant") ?? "default")
1068
- });
1067
+ const variant = chip.dataset.variant || (chip.parentElement?.getAttribute("data-variant") ?? "default");
1068
+ if (variant in calloutIcons) {
1069
+ chips.push({ el: chip, variant });
1070
+ }
1069
1071
  });
1070
1072
  return chips;
1071
1073
  }
1072
1074
  function enhanceBlockquotes(root) {
1073
1075
  const quotes = root.querySelectorAll("blockquote");
1074
1076
  quotes.forEach((bq) => {
1075
- if (bq.dataset.rtQuoted === "1") return;
1077
+ if (bq.querySelector(":scope > .rt-quote-open")) return;
1076
1078
  if (bq.closest('figure[data-variant="pullquote"]')) return;
1077
- bq.dataset.rtQuoted = "1";
1078
1079
  const { first, last } = findQuoteBody(bq);
1079
1080
  if (!first || !last) return;
1080
1081
  const open = document.createElement("span");
@@ -1113,11 +1114,10 @@ function highlightCodeBlock(pre) {
1113
1114
  if (!lang) return;
1114
1115
  const code = pre.querySelector("code");
1115
1116
  if (!code) return;
1116
- if (code.dataset.rtHighlighted === "1") return;
1117
+ if (code.classList.contains("hljs")) return;
1117
1118
  const source = code.textContent ?? "";
1118
1119
  code.innerHTML = highlightSource(source, lang);
1119
1120
  code.classList.add("hljs");
1120
- code.dataset.rtHighlighted = "1";
1121
1121
  }
1122
1122
  var DIFF_SEPARATOR_RE = /\n?@@---@@\n?/;
1123
1123
  function diffLines(a, b) {
@@ -1240,8 +1240,7 @@ function buildCodeBlockLabel(pre) {
1240
1240
  function enhanceCodeBlocks(root) {
1241
1241
  const blocks = root.querySelectorAll("pre");
1242
1242
  blocks.forEach((pre) => {
1243
- if (pre.dataset.rtEnhanced === "1") return;
1244
- pre.dataset.rtEnhanced = "1";
1243
+ if (pre.classList.contains("rt-codeblock")) return;
1245
1244
  pre.classList.add("rt-codeblock");
1246
1245
  const variant = pre.dataset.variant;
1247
1246
  if (variant === "diff") {
@@ -1585,7 +1584,7 @@ function BuiltinCalloutIcon({ variant }) {
1585
1584
  const html = CALLOUT_ICON_SVG[variant] ?? CALLOUT_ICON_SVG.default;
1586
1585
  return /* @__PURE__ */ jsx("span", { dangerouslySetInnerHTML: { __html: html } });
1587
1586
  }
1588
- function RichTextContent({
1587
+ var RichTextContent = memo(function RichTextContent2({
1589
1588
  html,
1590
1589
  classMap,
1591
1590
  as = "div",
@@ -1603,49 +1602,58 @@ function RichTextContent({
1603
1602
  [html, merged]
1604
1603
  );
1605
1604
  const ref = useRef(null);
1606
- const [chips, setChips] = useState([]);
1607
- useEffect(() => {
1605
+ const prevSafe = useRef("");
1606
+ const chipsRef = useRef([]);
1607
+ const onReadyRef = useRef(onReady);
1608
+ onReadyRef.current = onReady;
1609
+ const contentRefStable = useRef(contentRef);
1610
+ contentRefStable.current = contentRef;
1611
+ const calloutIconsRef = useRef(calloutIcons);
1612
+ calloutIconsRef.current = calloutIcons;
1613
+ const [renderKey, setRenderKey] = useState(0);
1614
+ useLayoutEffect(() => {
1608
1615
  ensureCodeBlockStyles();
1609
1616
  const root = ref.current;
1610
1617
  if (!root) return;
1611
- if (contentRef) contentRef.current = root;
1612
- const apply = () => {
1613
- mo.disconnect();
1614
- enhanceCodeBlocks(root);
1615
- enhanceBlockquotes(root);
1616
- const nextChips = enhanceCallouts(root);
1617
- setChips((prev) => calloutChipsEqual(prev, nextChips) ? prev : nextChips);
1618
- onReady?.(root);
1619
- mo.observe(root, { childList: true, subtree: true });
1620
- };
1621
- let raf = 0;
1622
- const mo = new MutationObserver(() => {
1623
- if (raf) return;
1624
- raf = requestAnimationFrame(() => {
1625
- raf = 0;
1626
- apply();
1627
- });
1628
- });
1629
- apply();
1630
- return () => {
1631
- mo.disconnect();
1632
- if (raf) cancelAnimationFrame(raf);
1633
- };
1634
- }, [safe, onReady, contentRef]);
1618
+ if (contentRefStable.current) contentRefStable.current.current = root;
1619
+ if (prevSafe.current === safe) return;
1620
+ prevSafe.current = safe;
1621
+ root.innerHTML = safe;
1622
+ enhanceCodeBlocks(root);
1623
+ enhanceBlockquotes(root);
1624
+ const nextChips = enhanceCallouts(root, calloutIconsRef.current);
1625
+ if (!calloutChipsEqual(chipsRef.current, nextChips)) {
1626
+ chipsRef.current = nextChips;
1627
+ if (nextChips.length > 0) setRenderKey((n) => n + 1);
1628
+ }
1629
+ onReadyRef.current?.(root);
1630
+ }, [safe]);
1635
1631
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1636
1632
  createElement(as, {
1637
1633
  ref,
1638
- className,
1639
- dangerouslySetInnerHTML: { __html: safe }
1634
+ className
1640
1635
  }),
1641
- chips.map(
1636
+ chipsRef.current.map(
1642
1637
  (chip, i) => createPortal(
1643
- calloutIcons && chip.variant in calloutIcons ? calloutIcons[chip.variant] : /* @__PURE__ */ jsx(BuiltinCalloutIcon, { variant: chip.variant }),
1638
+ calloutIconsRef.current && chip.variant in calloutIconsRef.current ? calloutIconsRef.current[chip.variant] : /* @__PURE__ */ jsx(BuiltinCalloutIcon, { variant: chip.variant }),
1644
1639
  chip.el,
1645
1640
  `${chip.variant}:${i}`
1646
1641
  )
1647
1642
  )
1648
1643
  ] });
1644
+ }, richTextPropsEqual);
1645
+ function richTextPropsEqual(prev, next) {
1646
+ if (prev.html !== next.html) return false;
1647
+ if (prev.classMap !== next.classMap) return false;
1648
+ if (prev.as !== next.as) return false;
1649
+ if (prev.className !== next.className) return false;
1650
+ const prevKeys = prev.calloutIcons ? Object.keys(prev.calloutIcons) : [];
1651
+ const nextKeys = next.calloutIcons ? Object.keys(next.calloutIcons) : [];
1652
+ if (prevKeys.length !== nextKeys.length) return false;
1653
+ for (const k of nextKeys) {
1654
+ if (!prevKeys.includes(k)) return false;
1655
+ }
1656
+ return true;
1649
1657
  }
1650
1658
 
1651
1659
  // src/utils/extractHeadings.ts
@@ -1721,97 +1729,6 @@ function extractHeadingsFromElement(root, options = {}) {
1721
1729
  return out;
1722
1730
  }
1723
1731
 
1724
- // src/hooks/useTableOfContents.tsx
1725
- function useTableOfContents(ref, options = {}) {
1726
- const {
1727
- levels,
1728
- contentKey = null,
1729
- scrollMarginTop = 24,
1730
- activationOffset = 96
1731
- } = options;
1732
- const [items, setItems] = useState([]);
1733
- const [activeId, setActiveId] = useState("");
1734
- useEffect(() => {
1735
- const root = ref.current;
1736
- if (!root) {
1737
- setItems([]);
1738
- setActiveId("");
1739
- return;
1740
- }
1741
- let raf = 0;
1742
- const collect = () => {
1743
- const next = extractHeadingsFromElement(root, {
1744
- levels,
1745
- scrollMarginTop
1746
- });
1747
- setItems(next);
1748
- setActiveId(
1749
- (prev) => next.some((h) => h.id === prev) ? prev : next[0]?.id ?? ""
1750
- );
1751
- };
1752
- raf = requestAnimationFrame(collect);
1753
- const mo = new MutationObserver(() => {
1754
- if (raf) cancelAnimationFrame(raf);
1755
- raf = requestAnimationFrame(collect);
1756
- });
1757
- mo.observe(root, { childList: true, subtree: true, characterData: true });
1758
- return () => {
1759
- mo.disconnect();
1760
- if (raf) cancelAnimationFrame(raf);
1761
- };
1762
- }, [ref, contentKey, levels, scrollMarginTop]);
1763
- useEffect(() => {
1764
- if (items.length === 0) return;
1765
- const targets = items.map((it) => document.getElementById(it.id)).filter((el) => el !== null);
1766
- if (targets.length === 0) return;
1767
- let raf = 0;
1768
- const compute = () => {
1769
- raf = 0;
1770
- let activeIdx = 0;
1771
- for (let i = 0; i < items.length; i++) {
1772
- const el = document.getElementById(items[i].id);
1773
- if (!el) continue;
1774
- if (el.getBoundingClientRect().top - activationOffset <= 0) {
1775
- activeIdx = i;
1776
- } else {
1777
- break;
1778
- }
1779
- }
1780
- const scroller = document.scrollingElement || document.documentElement;
1781
- const scrollY = window.scrollY;
1782
- const viewportH = window.innerHeight;
1783
- const atBottom = scrollY + viewportH >= scroller.scrollHeight - 2;
1784
- if (atBottom) {
1785
- for (let i = items.length - 1; i > activeIdx; i--) {
1786
- const el = document.getElementById(items[i].id);
1787
- if (el && el.getBoundingClientRect().top < viewportH) {
1788
- activeIdx = i;
1789
- break;
1790
- }
1791
- }
1792
- }
1793
- setActiveId(items[activeIdx].id);
1794
- };
1795
- const schedule = () => {
1796
- if (raf) return;
1797
- raf = requestAnimationFrame(compute);
1798
- };
1799
- const io = new IntersectionObserver(schedule, {
1800
- rootMargin: `-${activationOffset}px 0px -${Math.max(0, window.innerHeight - activationOffset - 1)}px 0px`,
1801
- threshold: 0
1802
- });
1803
- targets.forEach((t) => io.observe(t));
1804
- window.addEventListener("resize", schedule, { passive: true });
1805
- compute();
1806
- return () => {
1807
- io.disconnect();
1808
- window.removeEventListener("resize", schedule);
1809
- if (raf) cancelAnimationFrame(raf);
1810
- };
1811
- }, [items, activationOffset]);
1812
- return { items, activeId };
1813
- }
1814
-
1815
- export { AsteroidCMSProvider, RichTextContent, extractHeadingsFromElement, extractHeadingsFromHtml, slugify, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate, useTableOfContents };
1732
+ export { AsteroidCMSProvider, RichTextContent, extractHeadingsFromElement, extractHeadingsFromHtml, slugify, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate };
1816
1733
  //# sourceMappingURL=client.js.map
1817
1734
  //# sourceMappingURL=client.js.map