@asteroidcms/core-utils 0.1.2 → 0.1.4

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/index.js CHANGED
@@ -1,23 +1,8 @@
1
- import { createContext, useContext, useMemo, useRef, useEffect, createElement } from 'react';
2
- import { ApolloProvider, useQuery, useMutation } from '@apollo/client/react';
3
1
  import { HttpLink, ApolloClient, InMemoryCache, ApolloLink, gql, CombinedGraphQLErrors, CombinedProtocolErrors } from '@apollo/client';
4
2
  import { SetContextLink } from '@apollo/client/link/context';
5
3
  import { ErrorLink } from '@apollo/client/link/error';
6
- import { jsx } from 'react/jsx-runtime';
7
- import hljs from 'highlight.js/lib/common';
8
- import 'highlight.js/styles/tokyo-night-dark.css';
9
4
 
10
- // src/provider/AsteroidCMSProvider.tsx
11
- var AsteroidCMSContext = createContext(null);
12
- function useAsteroidCMSConfig() {
13
- const ctx = useContext(AsteroidCMSContext);
14
- if (!ctx) {
15
- throw new Error(
16
- "useAsteroidCMSConfig must be used inside <AsteroidCMSProvider>. Wrap your app with <AsteroidCMSProvider cmsUrl=... apiKey=... />."
17
- );
18
- }
19
- return ctx;
20
- }
5
+ // src/apollo/createApolloClient.ts
21
6
  function createErrorLink(onError) {
22
7
  return new ErrorLink(({ error }) => {
23
8
  if (!onError) return;
@@ -77,234 +62,6 @@ function createApolloClient(config) {
77
62
  ...config.apolloOptions
78
63
  });
79
64
  }
80
- function AsteroidCMSProvider({ children, ...config }) {
81
- const resolved = useMemo(() => resolveConfig(config), [
82
- config.cmsUrl,
83
- config.apiKey,
84
- config.graphqlPath,
85
- config.mediaPath,
86
- config.headers,
87
- config.onError
88
- ]);
89
- const client = useMemo(
90
- () => createApolloClient(config),
91
- // The client is intentionally rebuilt only when the identity-shaping props change.
92
- [
93
- config.client,
94
- resolved.cmsUrl,
95
- resolved.apiKey,
96
- resolved.graphqlPath,
97
- config.cacheConfig,
98
- config.apolloOptions
99
- ]
100
- );
101
- return /* @__PURE__ */ jsx(AsteroidCMSContext.Provider, { value: resolved, children: /* @__PURE__ */ jsx(ApolloProvider, { client, children }) });
102
- }
103
- function useCmsContent({
104
- schema_slug,
105
- entrySlug,
106
- select = [],
107
- fullData = false,
108
- limit,
109
- offset,
110
- status = "PUBLISHED",
111
- filter,
112
- search,
113
- variables = {}
114
- }) {
115
- const isSingle = !!entrySlug;
116
- const buildSelection2 = (items = []) => {
117
- const lines = [];
118
- items.forEach((item) => {
119
- if (typeof item === "string") {
120
- lines.push(`${item}: dataField(slug: "${item}")`);
121
- } else if ("field" in item && typeof item.field === "string") {
122
- if (!("select" in item)) {
123
- const alias2 = item.as || item.field;
124
- lines.push(`${alias2}: dataField(slug: "${item.field}")`);
125
- return;
126
- }
127
- const alias = item.as || item.field;
128
- const resolver = item.single ? "expandedReferenceObject" : "expandedReference";
129
- const subSelection = item.select?.length ? buildSelection2(item.select) : "data { ... }";
130
- lines.push(`
131
- ${alias}: ${resolver}(slug: "${item.field}") {
132
- ${subSelection}
133
- }
134
- `);
135
- }
136
- });
137
- return lines.join("\n ").trim();
138
- };
139
- const selectionParts = [];
140
- if (fullData) selectionParts.push("data");
141
- if (select.length > 0) {
142
- const userSelection = buildSelection2(select);
143
- if (userSelection) selectionParts.push(userSelection);
144
- }
145
- const selection = selectionParts.join("\n ").trim() || "id";
146
- const queryVariables = {
147
- schema_slug,
148
- ...entrySlug && { slug: entrySlug },
149
- ...variables
150
- };
151
- const fieldArgParts = ["schema_slug: $schema_slug"];
152
- if (!isSingle) {
153
- if (typeof limit === "number" && limit >= 0) {
154
- fieldArgParts.push("limit: $limit");
155
- queryVariables.limit = limit;
156
- }
157
- if (typeof offset === "number" && offset >= 0) {
158
- fieldArgParts.push("offset: $offset");
159
- queryVariables.offset = offset;
160
- }
161
- if (status) {
162
- fieldArgParts.push("status: $status");
163
- queryVariables.status = status;
164
- }
165
- const hasSearch = Array.isArray(search) && search.length > 0;
166
- const hasFilter = filter && typeof filter === "object" && Object.keys(filter).length > 0;
167
- if (hasSearch || hasFilter) {
168
- const mergedFilter = hasFilter ? { ...filter } : {};
169
- if (hasSearch) {
170
- for (const condition of search) {
171
- mergedFilter[condition.field] = {
172
- regex: true,
173
- value: condition.value,
174
- mode: condition.mode ?? "i"
175
- };
176
- }
177
- }
178
- fieldArgParts.push("data: $filter");
179
- queryVariables.filter = mergedFilter;
180
- }
181
- }
182
- const varDecls = ["$schema_slug: String!"];
183
- if ("limit" in queryVariables) varDecls.push("$limit: Float");
184
- if ("offset" in queryVariables) varDecls.push("$offset: Float");
185
- if ("status" in queryVariables) varDecls.push("$status: ContentStatus");
186
- if ("filter" in queryVariables) varDecls.push("$filter: JSONObject");
187
- const varBlock = varDecls.length > 0 ? `(
188
- ${varDecls.join("\n ")}
189
- )` : "";
190
- const contentFieldArgs = fieldArgParts.join(", ");
191
- const queryStr = isSingle ? `
192
- query Get${schema_slug}Entry($schema_slug: String!, $slug: String!) {
193
- entry: contentEntry(schema_slug: $schema_slug, slug: $slug) {
194
- ${selection}
195
- }
196
- }
197
- ` : `
198
- query Get${schema_slug}Entries${varBlock} {
199
- entries: contentEntries(${contentFieldArgs}) {
200
- ${selection}
201
- }
202
- }
203
- `;
204
- const GET_CONTENT = gql(queryStr);
205
- const { loading, error, data, ...rest } = useQuery(GET_CONTENT, {
206
- variables: queryVariables,
207
- skip: !schema_slug || isSingle && !entrySlug
208
- });
209
- const typed = data;
210
- const result = isSingle ? typed?.entry : typed?.entries;
211
- return {
212
- loading,
213
- error,
214
- data: result,
215
- ...rest
216
- };
217
- }
218
- function useCmsMutate({
219
- schema_slug,
220
- select = [],
221
- fullData = false,
222
- mutationType = "create",
223
- entryId,
224
- variables: inputVariables = {}
225
- }) {
226
- const buildSelection2 = (items = []) => {
227
- const lines = [];
228
- for (const item of items) {
229
- if (typeof item === "string") {
230
- lines.push(`${item}: dataField(slug: "${item}")`);
231
- continue;
232
- }
233
- const { field, as, single, select: subSelect } = item;
234
- const alias = as || field;
235
- if (!subSelect?.length) {
236
- lines.push(`${alias}: dataField(slug: "${field}")`);
237
- continue;
238
- }
239
- const resolver = single ? "expandedReferenceObject" : "expandedReference";
240
- const sub = buildSelection2(subSelect) || "id slug";
241
- lines.push(`
242
- ${alias}: ${resolver}(slug: "${field}") {
243
- id
244
- slug
245
- ${sub}
246
- }
247
- `);
248
- }
249
- return lines.join("\n ").trim();
250
- };
251
- const userSelection = buildSelection2(select);
252
- let selection = fullData ? "data" : "";
253
- if (userSelection) {
254
- selection = selection ? `${selection}
255
- ${userSelection}` : userSelection;
256
- }
257
- if (!selection) {
258
- selection = "id slug status version created_at updated_at";
259
- }
260
- const operation = mutationType;
261
- const mutationName = `${operation}ContentEntry`;
262
- const varDecls = ["$schema_slug: String!"];
263
- const callArgs = ["schema_slug: $schema_slug"];
264
- if (operation === "create" || operation === "update") {
265
- varDecls.unshift("$data: JSONObject!");
266
- callArgs.unshift("data: $data");
267
- }
268
- if (operation === "update" || operation === "delete") {
269
- varDecls.push("$id: ID!");
270
- callArgs.push("id: $id");
271
- }
272
- const returnFields = selection.includes("data") ? selection : `${selection}
273
- data`;
274
- const MUTATION = gql`
275
- mutation ${mutationName}(${varDecls.join(", ")}) {
276
- result: ${mutationName}(${callArgs.join(", ")}) {
277
- id
278
- status
279
- version
280
- created_at
281
- updated_at
282
- schema {
283
- id
284
- slug
285
- }
286
- ${returnFields}
287
- }
288
- }
289
- `;
290
- const mutationVariables = {
291
- schema_slug,
292
- ...operation === "update" || operation === "delete" ? { id: entryId } : {},
293
- ...inputVariables
294
- };
295
- if ((operation === "update" || operation === "delete") && !entryId) {
296
- console.warn(`useCmsMutate: entryId is required for ${operation}`);
297
- }
298
- const [mutateFn, mutationResult] = useMutation(MUTATION, {
299
- variables: mutationVariables
300
- });
301
- const resultData = mutationResult.data?.result;
302
- return {
303
- mutate: mutateFn,
304
- ...mutationResult,
305
- data: resultData
306
- };
307
- }
308
65
  function buildSelection(items = []) {
309
66
  const lines = [];
310
67
  items.forEach((item) => {
@@ -436,10 +193,6 @@ function cmsImage(id, options) {
436
193
  const path = (options.mediaPath ?? "/media/canonical").replace(/^\/?/, "/");
437
194
  return `${base}${path}/${id}`;
438
195
  }
439
- function useCmsImage() {
440
- const { cmsUrl, mediaPath } = useAsteroidCMSConfig();
441
- return (id) => cmsImage(id, { cmsUrl, mediaPath });
442
- }
443
196
 
444
197
  // src/utils/getContentReadTime.ts
445
198
  function getContentReadTime(content, options = {}) {
@@ -571,7 +324,36 @@ function parseRichText(html, options = {}) {
571
324
  working = upgradeStandaloneImages(working);
572
325
  working = upgradeAuthoredBlockquotes(working);
573
326
  working = flattenTableCellParagraphs(working);
574
- return sanitizeAndStyle(working, options);
327
+ working = sanitizeAndStyle(working, options);
328
+ if (options.autoHeadingIds !== false) {
329
+ working = injectHeadingIds(working);
330
+ }
331
+ return working;
332
+ }
333
+ function injectHeadingIds(html) {
334
+ const used = /* @__PURE__ */ new Map();
335
+ const existingRe = /<h[1-6]\b[^>]*\bid\s*=\s*("([^"]*)"|'([^']*)'|(\S+))/gi;
336
+ let em;
337
+ while ((em = existingRe.exec(html)) !== null) {
338
+ const id = em[2] ?? em[3] ?? em[4] ?? "";
339
+ if (id) used.set(id, (used.get(id) ?? 0) + 1);
340
+ }
341
+ return html.replace(
342
+ /<(h[1-6])\b([^>]*)>([\s\S]*?)<\/\1>/gi,
343
+ (full, tag, attrs, inner) => {
344
+ if (/\bid\s*=/i.test(attrs)) return full;
345
+ const text = inner.replace(/<[^>]+>/g, " ").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, " ").trim();
346
+ if (!text) return full;
347
+ const base = slugifyHeading(text) || tag;
348
+ const n = used.get(base) ?? 0;
349
+ used.set(base, n + 1);
350
+ const id = n === 0 ? base : `${base}-${n}`;
351
+ return `<${tag}${attrs} id="${id}">${inner}</${tag}>`;
352
+ }
353
+ );
354
+ }
355
+ function slugifyHeading(text) {
356
+ return text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
575
357
  }
576
358
  function flattenTableCellParagraphs(html) {
577
359
  return html.replace(
@@ -1113,495 +895,79 @@ function sanitizeAndStyle(html, options) {
1113
895
  return out.join("");
1114
896
  }
1115
897
 
1116
- // src/components/RichTextContent.tsx
1117
- var DEFAULT_CLASS_MAP = {
1118
- variants: {
1119
- "figure:pullquote": "relative my-8",
1120
- "blockquote:pullquote": "relative italic text-lg leading-snug tracking-[-0.01em] sm:text-xl",
1121
- "figcaption:pullquote": "mt-4 pt-3 border-t border-current/15 not-italic text-xs uppercase tracking-[0.14em] opacity-80",
1122
- "span:quote-open": "mr-1 font-serif text-[1.4em] leading-none align-[-0.15em] opacity-60 select-none",
1123
- "span:quote-close": "ml-1 font-serif text-[1.4em] leading-none align-[-0.15em] opacity-60 select-none",
1124
- "span:author": "ml-1 font-semibold not-italic tracking-[0.16em] text-current"
1125
- }
1126
- };
1127
- function mergeClassMap(defaults, user) {
1128
- if (!user) return defaults;
1129
- return {
1130
- ...defaults,
1131
- ...user,
1132
- variants: { ...defaults.variants, ...user.variants }
1133
- };
1134
- }
1135
- var COPY_ICON_SVG = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`;
1136
- var CHECK_ICON_SVG = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg>`;
1137
- var ATTRIBUTION_RE = /^(?:[—–-]+|--)\s+\S/;
1138
- function isAttributionEl(el) {
1139
- if (!el) return false;
1140
- if (el.getAttribute("data-variant") === "attribution") return true;
1141
- return ATTRIBUTION_RE.test((el.textContent ?? "").trim());
1142
- }
1143
- function findQuoteBody(bq) {
1144
- const children = Array.from(bq.children);
1145
- if (children.length === 0) return { first: null, last: null };
1146
- let lastIdx = children.length - 1;
1147
- while (lastIdx >= 0 && isAttributionEl(children[lastIdx])) lastIdx--;
1148
- if (lastIdx < 0) return { first: null, last: null };
1149
- return { first: children[0], last: children[lastIdx] };
1150
- }
1151
- function enhanceBlockquotes(root) {
1152
- const quotes = root.querySelectorAll("blockquote");
1153
- quotes.forEach((bq) => {
1154
- if (bq.dataset.rtQuoted === "1") return;
1155
- if (bq.closest('figure[data-variant="pullquote"]')) return;
1156
- bq.dataset.rtQuoted = "1";
1157
- const { first, last } = findQuoteBody(bq);
1158
- if (!first || !last) return;
1159
- const open = document.createElement("span");
1160
- open.className = "rt-quote-open";
1161
- open.setAttribute("aria-hidden", "true");
1162
- open.textContent = "\u201C";
1163
- const close = document.createElement("span");
1164
- close.className = "rt-quote-close";
1165
- close.setAttribute("aria-hidden", "true");
1166
- close.textContent = "\u201D";
1167
- first.prepend(open);
1168
- last.append(close);
1169
- });
1170
- }
1171
- function escapeHtml2(s) {
1172
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
1173
- }
1174
- function preserveSpaces(html) {
1175
- return html.replace(/ {2,}/g, (m) => "&nbsp;".repeat(m.length));
1176
- }
1177
- function highlightSource(src, lang) {
1178
- if (lang && hljs.getLanguage(lang)) {
1179
- try {
1180
- return hljs.highlight(src, { language: lang, ignoreIllegals: true }).value;
1181
- } catch {
1182
- }
1183
- }
1184
- return escapeHtml2(src);
1185
- }
1186
- function highlightLine(line, lang) {
1187
- if (!line) return "";
1188
- return preserveSpaces(highlightSource(line, lang));
1189
- }
1190
- function highlightCodeBlock(pre) {
1191
- const lang = pre.dataset.language;
1192
- if (!lang) return;
1193
- const code = pre.querySelector("code");
1194
- if (!code) return;
1195
- if (code.dataset.rtHighlighted === "1") return;
1196
- const source = code.textContent ?? "";
1197
- code.innerHTML = highlightSource(source, lang);
1198
- code.classList.add("hljs");
1199
- code.dataset.rtHighlighted = "1";
1200
- }
1201
- var DIFF_SEPARATOR_RE = /\n?@@---@@\n?/;
1202
- function diffLines(a, b) {
1203
- const n = a.length;
1204
- const m = b.length;
1205
- const dp = Array.from(
1206
- { length: n + 1 },
1207
- () => new Array(m + 1).fill(0)
1208
- );
1209
- for (let i2 = 1; i2 <= n; i2++) {
1210
- for (let j2 = 1; j2 <= m; j2++) {
1211
- dp[i2][j2] = a[i2 - 1] === b[j2 - 1] ? dp[i2 - 1][j2 - 1] + 1 : Math.max(dp[i2 - 1][j2], dp[i2][j2 - 1]);
1212
- }
1213
- }
1214
- const ops = [];
1215
- let i = n;
1216
- let j = m;
1217
- while (i > 0 && j > 0) {
1218
- if (a[i - 1] === b[j - 1]) {
1219
- ops.unshift({ t: "eq", line: a[i - 1] });
1220
- i--;
1221
- j--;
1222
- } else if (dp[i - 1][j] >= dp[i][j - 1]) {
1223
- ops.unshift({ t: "rem", line: a[i - 1] });
1224
- i--;
898
+ // src/utils/extractHeadings.ts
899
+ var DEFAULT_LEVELS = [2, 3];
900
+ function slugify(text) {
901
+ return text.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
902
+ }
903
+ function decodeBasicEntities(s) {
904
+ return s.replace(/&nbsp;/g, " ").replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'");
905
+ }
906
+ function stripTags(s) {
907
+ return decodeBasicEntities(s.replace(/<[^>]+>/g, " ")).replace(/\s+/g, " ").trim();
908
+ }
909
+ function uniqueId(base, used) {
910
+ const seed = base || "section";
911
+ const n = used.get(seed) ?? 0;
912
+ used.set(seed, n + 1);
913
+ return n === 0 ? seed : `${seed}-${n}`;
914
+ }
915
+ function extractHeadingsFromHtml(html, options = {}) {
916
+ if (!html) return [];
917
+ const levels = options.levels ?? DEFAULT_LEVELS;
918
+ const slug = options.slugify ?? slugify;
919
+ const used = /* @__PURE__ */ new Map();
920
+ const out = [];
921
+ const re = /<h([1-6])\b([^>]*)>([\s\S]*?)<\/h\1>/gi;
922
+ let m;
923
+ let i = 0;
924
+ while ((m = re.exec(html)) !== null) {
925
+ const level = Number(m[1]);
926
+ if (!levels.includes(level)) continue;
927
+ const attrs = m[2] ?? "";
928
+ const inner = m[3] ?? "";
929
+ const text = stripTags(inner);
930
+ if (!text) continue;
931
+ const explicitIdMatch = attrs.match(/\bid\s*=\s*("([^"]*)"|'([^']*)'|(\S+))/i);
932
+ let id;
933
+ if (explicitIdMatch) {
934
+ id = explicitIdMatch[2] ?? explicitIdMatch[3] ?? explicitIdMatch[4] ?? "";
935
+ if (id) used.set(id, (used.get(id) ?? 0) + 1);
1225
936
  } else {
1226
- ops.unshift({ t: "add", line: b[j - 1] });
1227
- j--;
1228
- }
1229
- }
1230
- while (i > 0) ops.unshift({ t: "rem", line: a[--i] });
1231
- while (j > 0) ops.unshift({ t: "add", line: b[--j] });
1232
- return ops;
1233
- }
1234
- function renderDiff(before, after, lang) {
1235
- const ops = diffLines(before.split("\n"), after.split("\n"));
1236
- const rows = [];
1237
- let aNo = 0;
1238
- let bNo = 0;
1239
- let k = 0;
1240
- while (k < ops.length) {
1241
- const op = ops[k];
1242
- if (op.t === "eq") {
1243
- aNo++;
1244
- bNo++;
1245
- rows.push({
1246
- left: { n: aNo, line: op.line, cls: "" },
1247
- right: { n: bNo, line: op.line, cls: "" }
1248
- });
1249
- k++;
1250
- continue;
1251
- }
1252
- const rems = [];
1253
- while (k < ops.length && ops[k].t === "rem") {
1254
- rems.push(ops[k].line);
1255
- k++;
1256
- }
1257
- const adds = [];
1258
- while (k < ops.length && ops[k].t === "add") {
1259
- adds.push(ops[k].line);
1260
- k++;
1261
- }
1262
- const len = Math.max(rems.length, adds.length);
1263
- for (let x = 0; x < len; x++) {
1264
- const remLine = x < rems.length ? rems[x] : null;
1265
- const addLine = x < adds.length ? adds[x] : null;
1266
- rows.push({
1267
- left: {
1268
- n: remLine !== null ? ++aNo : null,
1269
- line: remLine,
1270
- cls: remLine !== null ? "rt-diff-rem" : "rt-diff-empty"
1271
- },
1272
- right: {
1273
- n: addLine !== null ? ++bNo : null,
1274
- line: addLine,
1275
- cls: addLine !== null ? "rt-diff-add" : "rt-diff-empty"
1276
- }
1277
- });
937
+ id = uniqueId(slug(text, i), used);
1278
938
  }
939
+ out.push({ id, text, level });
940
+ i++;
1279
941
  }
1280
- const cell = (c, side) => {
1281
- const sign = side === "l" ? "-" : "+";
1282
- const showSign = c.cls === "rt-diff-rem" || c.cls === "rt-diff-add";
1283
- return `<td class="rt-diff-num">${c.n ?? ""}</td><td class="rt-diff-sign">${showSign ? sign : ""}</td><td class="rt-diff-line ${c.cls}">${c.line === null ? "" : highlightLine(c.line, lang) || "&nbsp;"}</td>`;
1284
- };
1285
- const body = rows.map((r) => `<tr>${cell(r.left, "l")}${cell(r.right, "r")}</tr>`).join("");
1286
- return `<table class="rt-diff-table"><tbody>${body}</tbody></table>`;
1287
- }
1288
- function makeCopyButton(getText, opts = {}) {
1289
- const btn = document.createElement("button");
1290
- btn.type = "button";
1291
- btn.className = opts.className ?? "rt-codeblock__copy";
1292
- btn.setAttribute("aria-label", opts.label ?? "Copy code");
1293
- btn.innerHTML = COPY_ICON_SVG;
1294
- btn.addEventListener("click", async () => {
1295
- try {
1296
- await navigator.clipboard.writeText(getText());
1297
- btn.innerHTML = CHECK_ICON_SVG;
1298
- btn.classList.add("is-copied");
1299
- window.setTimeout(() => {
1300
- btn.innerHTML = COPY_ICON_SVG;
1301
- btn.classList.remove("is-copied");
1302
- }, 1500);
1303
- } catch {
1304
- }
1305
- });
1306
- return btn;
1307
- }
1308
- function buildCodeBlockLabel(pre) {
1309
- const filename = pre.dataset.filename;
1310
- if (!filename) return null;
1311
- const tag = document.createElement("span");
1312
- tag.className = "rt-codeblock__label";
1313
- const file = document.createElement("span");
1314
- file.className = "rt-codeblock__filename rt-codeblock__language";
1315
- file.textContent = filename;
1316
- tag.appendChild(file);
1317
- return tag;
942
+ return out;
1318
943
  }
1319
- function enhanceCodeBlocks(root) {
1320
- const blocks = root.querySelectorAll("pre");
1321
- blocks.forEach((pre) => {
1322
- if (pre.dataset.rtEnhanced === "1") return;
1323
- pre.dataset.rtEnhanced = "1";
1324
- pre.classList.add("rt-codeblock");
1325
- const variant = pre.dataset.variant;
1326
- if (variant === "diff") {
1327
- const codeEl = pre.querySelector("code");
1328
- const src = codeEl?.textContent ?? "";
1329
- const [beforeSrc = "", afterSrc = ""] = src.split(DIFF_SEPARATOR_RE);
1330
- pre.innerHTML = renderDiff(beforeSrc, afterSrc, pre.dataset.language);
1331
- const bar = document.createElement("div");
1332
- bar.className = "rt-diff-copy-bar";
1333
- const leftHalf = document.createElement("div");
1334
- leftHalf.className = "rt-diff-copy-half";
1335
- leftHalf.appendChild(
1336
- makeCopyButton(() => beforeSrc, {
1337
- className: "rt-diff-copy",
1338
- label: "Copy before"
1339
- })
1340
- );
1341
- const rightHalf = document.createElement("div");
1342
- rightHalf.className = "rt-diff-copy-half";
1343
- rightHalf.appendChild(
1344
- makeCopyButton(() => afterSrc, {
1345
- className: "rt-diff-copy",
1346
- label: "Copy after"
1347
- })
1348
- );
1349
- bar.appendChild(leftHalf);
1350
- bar.appendChild(rightHalf);
1351
- pre.prepend(bar);
1352
- const label2 = buildCodeBlockLabel(pre);
1353
- if (label2) pre.prepend(label2);
1354
- return;
1355
- }
1356
- if (variant === "terminal") {
1357
- pre.classList.add("rt-terminal");
1358
- const codeEl = pre.querySelector("code");
1359
- const source = codeEl?.textContent ?? "";
1360
- if (codeEl) {
1361
- const lang = pre.dataset.language || "sh";
1362
- const lines = source.split("\n");
1363
- codeEl.innerHTML = lines.map(
1364
- (line) => `<span class="rt-term-line"><span class="rt-term-prompt" aria-hidden="true">$</span> ${highlightLine(line, lang) || "&nbsp;"}</span>`
1365
- ).join("");
1366
- }
1367
- pre.appendChild(makeCopyButton(() => source, { label: "Copy commands" }));
1368
- return;
1369
- }
1370
- const label = buildCodeBlockLabel(pre);
1371
- if (label) pre.prepend(label);
1372
- pre.appendChild(
1373
- makeCopyButton(
1374
- () => pre.querySelector("code")?.textContent ?? pre.innerText
1375
- )
1376
- );
1377
- highlightCodeBlock(pre);
944
+ function extractHeadingsFromElement(root, options = {}) {
945
+ const levels = options.levels ?? DEFAULT_LEVELS;
946
+ const slug = options.slugify ?? slugify;
947
+ const selector = levels.map((l) => `h${l}`).join(",");
948
+ const nodes = root.querySelectorAll(selector);
949
+ const used = /* @__PURE__ */ new Map();
950
+ nodes.forEach((n) => {
951
+ if (n.id) used.set(n.id, (used.get(n.id) ?? 0) + 1);
1378
952
  });
1379
- }
1380
- var CODEBLOCK_STYLE = `
1381
- .rt-codeblock { position: relative; }
1382
- .rt-codeblock[data-filename]:not([data-filename=""]) { padding-top: 2rem; }
1383
- .rt-codeblock__label {
1384
- position: absolute; top: 0.45rem; left: 0.85rem;
1385
- display: inline-flex; align-items: center; gap: 0.5rem;
1386
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
1387
- pointer-events: none;
1388
- }
1389
- .rt-codeblock__filename {
1390
- font-size: 0.72rem; letter-spacing: 0.02em;
1391
- color: #d1d5db;
1392
- }
1393
- .rt-codeblock__sep {
1394
- color: #6b7280;
1395
- font-size: 0.72rem;
1396
- }
1397
- .rt-codeblock__language {
1398
- font-size: 0.6rem; letter-spacing: 0.08em;
1399
- text-transform: lowercase;
1400
- color: #9ca3af;
1401
- padding: 0.05rem 0.35rem;
1402
- border: 1px solid rgba(255,255,255,0.12);
1403
- border-radius: 0.25rem;
1404
- }
1405
- .rt-codeblock__copy {
1406
- position: absolute; top: 0.4rem; right: 0.4rem;
1407
- display: inline-flex; align-items: center; justify-content: center;
1408
- width: 1.75rem; height: 1.75rem; padding: 0;
1409
- border: 1px solid rgba(255,255,255,0.08);
1410
- border-radius: 0.375rem;
1411
- background: rgba(255,255,255,0.04);
1412
- color: #d1d5db;
1413
- cursor: pointer;
1414
- opacity: 0; transition: opacity 120ms ease, background 120ms ease, color 120ms ease;
1415
- }
1416
- .rt-codeblock:hover .rt-codeblock__copy,
1417
- .rt-codeblock:focus-within .rt-codeblock__copy { opacity: 1; }
1418
- .rt-codeblock__copy:hover { background: rgba(255,255,255,0.1); color: #fff; }
1419
- .rt-codeblock__copy.is-copied { color: #34d399; opacity: 1; }
1420
- @media (hover: none) { .rt-codeblock__copy { opacity: 1; } }
1421
- .rt-quote-open, .rt-quote-close {
1422
- font-family: Georgia, "Times New Roman", serif;
1423
- font-size: 1.4em;
1424
- line-height: 0;
1425
- vertical-align: -0.15em;
1426
- opacity: 0.6;
1427
- user-select: none;
1428
- }
1429
- .rt-quote-open { margin-right: 0.15em; }
1430
- .rt-quote-close { margin-left: 0.15em; }
1431
- /* highlight.js theme handles .hljs-* color classes; we only override the
1432
- default .hljs background so the per-block chrome (dark bg, terminal,
1433
- diff red/green rows) wins. */
1434
- .rt-codeblock .hljs,
1435
- .rt-codeblock code.hljs { background: transparent; padding: 0; }
1436
-
1437
- /* Terminal variant ------------------------------------------------------- */
1438
- .rt-codeblock.rt-terminal,
1439
- .rt-codeblock[data-variant="terminal"] {
1440
- position: relative;
1441
- padding-top: 2.25rem;
1442
- background: #0b0b0d;
1443
- border: 1px solid rgba(255,255,255,0.08);
1444
- border-radius: 0.65rem;
1445
- box-shadow: 0 1px 0 rgba(255,255,255,0.04) inset,
1446
- 0 10px 30px -10px rgba(0,0,0,0.6);
1447
- }
1448
- .rt-codeblock.rt-terminal::before,
1449
- .rt-codeblock[data-variant="terminal"]::before {
1450
- content: "";
1451
- position: absolute; top: 0; left: 0; right: 0; height: 1.75rem;
1452
- background: linear-gradient(#1a1a1d, #141417);
1453
- border-bottom: 1px solid rgba(255,255,255,0.06);
1454
- border-radius: 0.65rem 0.65rem 0 0;
1455
- }
1456
- .rt-codeblock.rt-terminal::after,
1457
- .rt-codeblock[data-variant="terminal"]::after {
1458
- content: "";
1459
- position: absolute; top: 0.55rem; left: 0.75rem;
1460
- width: 0.65rem; height: 0.65rem; border-radius: 50%;
1461
- background: #ff5f57;
1462
- box-shadow:
1463
- 1.1rem 0 0 0 #febc2e,
1464
- 2.2rem 0 0 0 #28c840;
1465
- }
1466
- .rt-codeblock.rt-terminal code,
1467
- .rt-codeblock[data-variant="terminal"] code {
1468
- color: #d4d4d8;
1469
- display: block;
1470
- }
1471
- .rt-term-line { display: block; white-space: pre-wrap; }
1472
- .rt-term-prompt {
1473
- color: #28c840;
1474
- font-weight: 600;
1475
- margin-right: 0.35em;
1476
- user-select: none;
1477
- }
1478
-
1479
- /* Diff variant ----------------------------------------------------------- */
1480
- .rt-codeblock[data-variant="diff"] {
1481
- padding: 0;
1482
- overflow: hidden;
1483
- background: #0b0b0d;
1484
- border: 1px solid rgba(255,255,255,0.08);
1485
- }
1486
- .rt-codeblock[data-variant="diff"][data-filename]:not([data-filename=""]) {
1487
- padding-top: 2rem;
1488
- }
1489
- .rt-diff-table {
1490
- width: 100%;
1491
- border-collapse: collapse;
1492
- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
1493
- font-size: 0.78rem;
1494
- line-height: 1.55;
1495
- color: #e5e7eb;
1496
- table-layout: fixed;
1497
- }
1498
- .rt-diff-table colgroup { display: none; }
1499
- .rt-diff-table td {
1500
- padding: 0 0.5rem;
1501
- vertical-align: top;
1502
- white-space: pre-wrap;
1503
- word-break: break-word;
1504
- }
1505
- .rt-diff-table td.rt-diff-num {
1506
- width: 2.25rem;
1507
- text-align: right;
1508
- color: rgba(156,163,175,0.55);
1509
- user-select: none;
1510
- background: rgba(255,255,255,0.02);
1511
- }
1512
- .rt-diff-table td.rt-diff-sign {
1513
- width: 0.85rem;
1514
- text-align: center;
1515
- user-select: none;
1516
- color: rgba(255,255,255,0.45);
1517
- }
1518
- .rt-diff-table td.rt-diff-line.rt-diff-rem {
1519
- background: rgba(248,113,113,0.12);
1520
- color: #fecaca;
1521
- }
1522
- .rt-diff-table tr:has(td.rt-diff-rem) td.rt-diff-sign:first-of-type {
1523
- color: #f87171;
1524
- }
1525
- .rt-diff-table td.rt-diff-line.rt-diff-add {
1526
- background: rgba(74,222,128,0.12);
1527
- color: #bbf7d0;
1528
- }
1529
- .rt-diff-table tr:has(td.rt-diff-add) td.rt-diff-sign + td + td + td.rt-diff-sign {
1530
- color: #4ade80;
1531
- }
1532
- .rt-diff-table td.rt-diff-line.rt-diff-empty {
1533
- background: rgba(255,255,255,0.025);
1534
- }
1535
- .rt-diff-table tr td:nth-child(4) { border-left: 1px solid rgba(255,255,255,0.06); }
1536
- .rt-diff-copy-bar {
1537
- position: absolute; top: 0.4rem; left: 0; right: 0; z-index: 2;
1538
- display: grid; grid-template-columns: 1fr 1fr;
1539
- pointer-events: none;
1540
- }
1541
- .rt-diff-copy-half {
1542
- display: flex;
1543
- justify-content: flex-end;
1544
- padding-right: 0.4rem;
1545
- }
1546
- .rt-diff-copy {
1547
- pointer-events: auto;
1548
- display: inline-flex; align-items: center; justify-content: center;
1549
- width: 1.6rem; height: 1.6rem; padding: 0;
1550
- border: 1px solid rgba(255,255,255,0.1);
1551
- border-radius: 0.375rem;
1552
- background: rgba(20,20,23,0.85);
1553
- color: #d1d5db;
1554
- cursor: pointer;
1555
- opacity: 0; transition: opacity 120ms ease, background 120ms ease, color 120ms ease;
1556
- }
1557
- .rt-codeblock[data-variant="diff"]:hover .rt-diff-copy,
1558
- .rt-codeblock[data-variant="diff"]:focus-within .rt-diff-copy { opacity: 1; }
1559
- .rt-diff-copy:hover { background: rgba(0,0,0,0.92); color: #fff; }
1560
- .rt-diff-copy.is-copied { color: #34d399; opacity: 1; }
1561
- @media (hover: none) { .rt-diff-copy { opacity: 1; } }
1562
- `;
1563
- var styleInjected = false;
1564
- function ensureCodeBlockStyles() {
1565
- if (styleInjected || typeof document === "undefined") return;
1566
- if (document.getElementById("rt-codeblock-style")) {
1567
- styleInjected = true;
1568
- return;
1569
- }
1570
- const tag = document.createElement("style");
1571
- tag.id = "rt-codeblock-style";
1572
- tag.textContent = CODEBLOCK_STYLE;
1573
- document.head.appendChild(tag);
1574
- styleInjected = true;
1575
- }
1576
- function RichTextContent({
1577
- html,
1578
- classMap,
1579
- as = "div",
1580
- className
1581
- }) {
1582
- const merged = useMemo(
1583
- () => mergeClassMap(DEFAULT_CLASS_MAP, classMap),
1584
- [classMap]
1585
- );
1586
- const safe = useMemo(
1587
- () => parseRichText(html, { classMap: merged }),
1588
- [html, merged]
1589
- );
1590
- const ref = useRef(null);
1591
- useEffect(() => {
1592
- ensureCodeBlockStyles();
1593
- if (ref.current) {
1594
- enhanceCodeBlocks(ref.current);
1595
- enhanceBlockquotes(ref.current);
1596
- }
1597
- }, [safe]);
1598
- return createElement(as, {
1599
- ref,
1600
- className,
1601
- dangerouslySetInnerHTML: { __html: safe }
953
+ const out = [];
954
+ let i = 0;
955
+ nodes.forEach((node) => {
956
+ const level = Number(node.tagName.slice(1));
957
+ const text = (node.textContent ?? "").replace(/\s+/g, " ").trim();
958
+ if (!text) return;
959
+ if (!node.id) {
960
+ node.id = uniqueId(slug(text, i), used);
961
+ }
962
+ if (options.scrollMarginTop != null) {
963
+ node.style.scrollMarginTop = `${options.scrollMarginTop}px`;
964
+ }
965
+ out.push({ id: node.id, text, level });
966
+ i++;
1602
967
  });
968
+ return out;
1603
969
  }
1604
970
 
1605
- export { AsteroidCMSProvider, RichTextContent, buildCmsQuery, cmsImage, createApolloClient, fetchCmsContent, getContentReadTime, parseRichText, removeEmptyParagraphs, useAsteroidCMSConfig, useCmsContent, useCmsImage, useCmsMutate };
971
+ export { buildCmsQuery, cmsImage, createApolloClient, extractHeadingsFromElement, extractHeadingsFromHtml, fetchCmsContent, getContentReadTime, parseRichText, removeEmptyParagraphs, slugify };
1606
972
  //# sourceMappingURL=index.js.map
1607
973
  //# sourceMappingURL=index.js.map