@lexibase/rdx-core 1.1.1 → 1.3.0

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.
@@ -0,0 +1,192 @@
1
+ // src/mdx/markdown-components.ts
2
+ import remarkDirective from "remark-directive";
3
+ function component(name, attributes, children, inline = false) {
4
+ return {
5
+ type: inline ? "mdxJsxTextElement" : "mdxJsxFlowElement",
6
+ name,
7
+ attributes: Object.entries(attributes).map(([name2, value]) => ({
8
+ type: "mdxJsxAttribute",
9
+ name: name2,
10
+ value
11
+ })),
12
+ children
13
+ };
14
+ }
15
+ function label(nodes) {
16
+ return nodes.map((node) => {
17
+ if (![
18
+ "text",
19
+ "inlineCode",
20
+ "emphasis",
21
+ "strong",
22
+ "delete",
23
+ "break"
24
+ ].includes(node.type)) {
25
+ throw new Error(
26
+ "[RDX] Component titles must contain text or inline Markdown formatting."
27
+ );
28
+ }
29
+ return node.type === "break" ? " " : node.children ? label(node.children) : node.value ?? "";
30
+ }).join("").trim();
31
+ }
32
+ function callout(node, source) {
33
+ if (node.type !== "blockquote") return;
34
+ const paragraph = node.children?.[0];
35
+ const first = paragraph?.children?.[0];
36
+ if (paragraph?.type !== "paragraph" || first?.type !== "text") return;
37
+ const match = /^\[!(NOTE|TIP|SUCCESS|WARNING|DANGER)\](?=[ \t\r\n]|$)[ \t]*/.exec(
38
+ first.value ?? ""
39
+ );
40
+ if (!match) return;
41
+ const offset = first.position?.start.offset;
42
+ if (offset === void 0 || !source.slice(offset).startsWith(`[!${match[1]}]`))
43
+ return;
44
+ const title = [];
45
+ const body = [];
46
+ let inBody = false;
47
+ for (const [index, child] of (paragraph.children ?? []).entries()) {
48
+ const current = index === 0 ? { ...child, value: child.value.slice(match[0].length) } : child;
49
+ if (!inBody && current.type === "break") {
50
+ inBody = true;
51
+ } else if (!inBody && current.type === "text" && current.value?.includes("\n")) {
52
+ const newline = current.value.indexOf("\n");
53
+ title.push({
54
+ ...current,
55
+ value: current.value.slice(0, newline).replace(/\r$/, "")
56
+ });
57
+ const rest = current.value.slice(newline + 1);
58
+ if (rest) body.push({ ...current, value: rest });
59
+ inBody = true;
60
+ } else if (inBody) body.push(current);
61
+ else title.push(current);
62
+ }
63
+ const heading = label(title);
64
+ return component(
65
+ "Callout",
66
+ {
67
+ variant: match[1].toLowerCase(),
68
+ ...heading ? { title: heading } : {}
69
+ },
70
+ [
71
+ ...body.length ? [{ type: "paragraph", children: body }] : [],
72
+ ...node.children?.slice(1) ?? []
73
+ ]
74
+ );
75
+ }
76
+ function container(node, source) {
77
+ const groups = [];
78
+ for (const child of node.children ?? []) {
79
+ if (child.type === "heading" && child.depth === 3) {
80
+ const children = [...child.children ?? []];
81
+ const marker = children.at(-1);
82
+ const beforeMarker = children.at(-2);
83
+ const disabled = node.name === "tabs" && marker?.type === "mdxTextExpression" && marker.value === "disabled" && source.slice(
84
+ marker.position?.start.offset,
85
+ marker.position?.end.offset
86
+ ) === "{disabled}" && (!beforeMarker || beforeMarker.type === "text" && /\s$/.test(beforeMarker.value ?? ""));
87
+ if (disabled) children.pop();
88
+ const title = label(children);
89
+ if (!title)
90
+ throw new Error(
91
+ `[RDX] :::${node.name} requires a nonempty ### title for each item.`
92
+ );
93
+ groups.push({ title, disabled, children: [] });
94
+ } else {
95
+ const group = groups.at(-1);
96
+ if (!group)
97
+ throw new Error(`[RDX] Start :::${node.name} items with ### Title.`);
98
+ group.children.push(child);
99
+ }
100
+ }
101
+ if (!groups.length)
102
+ throw new Error(
103
+ `[RDX] :::${node.name} requires at least one ### Title and its content.`
104
+ );
105
+ if (node.name === "tabs") {
106
+ const firstEnabled = groups.findIndex((group) => !group.disabled);
107
+ if (firstEnabled < 0)
108
+ throw new Error("[RDX] :::tabs requires at least one enabled tab.");
109
+ return component("Tabs", { defaultValue: `item-${firstEnabled + 1}` }, [
110
+ component(
111
+ "TabsList",
112
+ {},
113
+ groups.map(
114
+ (group, index) => component(
115
+ "TabsTrigger",
116
+ {
117
+ value: `item-${index + 1}`,
118
+ ...group.disabled ? { disabled: null } : {}
119
+ },
120
+ [{ type: "text", value: group.title }]
121
+ )
122
+ )
123
+ ),
124
+ // Disabled choices have no reachable panel; keep their content out of
125
+ // both rendering and the search index built from this same tree.
126
+ ...groups.flatMap(
127
+ (group, index) => group.disabled ? [] : [
128
+ component(
129
+ "TabsContent",
130
+ { value: `item-${index + 1}` },
131
+ group.children
132
+ )
133
+ ]
134
+ )
135
+ ]);
136
+ }
137
+ return component(
138
+ "Accordion",
139
+ {},
140
+ groups.map(
141
+ (group, index) => component("AccordionItem", { value: `item-${index + 1}` }, [
142
+ component("AccordionTrigger", {}, [
143
+ { type: "text", value: group.title }
144
+ ]),
145
+ component("AccordionContent", {}, group.children)
146
+ ])
147
+ )
148
+ );
149
+ }
150
+ function remarkDocumentationComponents() {
151
+ remarkDirective.call(this);
152
+ return (tree, file) => {
153
+ const source = String(file.value);
154
+ function transform(node) {
155
+ const alert = callout(node, source);
156
+ if (alert) return transform(alert);
157
+ if (["containerDirective", "leafDirective", "textDirective"].includes(
158
+ node.type
159
+ )) {
160
+ const known = ["tabs", "accordion", "kbd"].includes(node.name ?? "");
161
+ if (!known) {
162
+ const value = source.slice(
163
+ node.position?.start.offset,
164
+ node.position?.end.offset
165
+ );
166
+ return node.type === "textDirective" ? { type: "text", value } : { type: "paragraph", children: [{ type: "text", value }] };
167
+ }
168
+ if (Object.keys(node.attributes ?? {}).length)
169
+ throw new Error(`[RDX] :${node.name} does not accept attributes.`);
170
+ if (node.name === "kbd") {
171
+ if (node.type !== "textDirective")
172
+ throw new Error("[RDX] Write keyboard keys as :kbd[Ctrl].");
173
+ const key = label(node.children ?? []);
174
+ if (!key) throw new Error("[RDX] :kbd[...] requires a key name.");
175
+ return component("Kbd", {}, [{ type: "text", value: key }], true);
176
+ }
177
+ if (node.type !== "containerDirective")
178
+ throw new Error(
179
+ `[RDX] Write ${node.name} as a :::${node.name} block with ### item titles.`
180
+ );
181
+ return transform(container(node, source));
182
+ }
183
+ if (node.children) node.children = node.children.map(transform);
184
+ return node;
185
+ }
186
+ transform(tree);
187
+ };
188
+ }
189
+
190
+ export {
191
+ remarkDocumentationComponents
192
+ };
@@ -1,8 +1,14 @@
1
1
  export { D as DocumentLinkOptions, r as remarkDocumentLinks } from '../document-links-BtWSWs2x.js';
2
2
  export { default as rehypeDocumentationHeadings } from 'rehype-slug';
3
3
  import rehypeShiki from '@shikijs/rehype';
4
+ import remarkDirective from 'remark-directive';
4
5
 
5
6
  /** shadcn's Shiki/GitHub palette, applied to MDX on the server. */
6
7
  declare function rehypeDocumentationCode(this: ThisParameterType<typeof rehypeShiki>): ReturnType<typeof rehypeShiki>;
7
8
 
8
- export { rehypeDocumentationCode };
9
+ /** Markdown authoring adapters for the shared shadcn/Base UI components. */
10
+ declare function remarkDocumentationComponents(this: ThisParameterType<typeof remarkDirective>): (tree: unknown, file: {
11
+ value: unknown;
12
+ }) => void;
13
+
14
+ export { rehypeDocumentationCode, remarkDocumentationComponents };
package/dist/mdx/index.js CHANGED
@@ -1,14 +1,132 @@
1
1
  import {
2
2
  remarkDocumentLinks
3
3
  } from "../chunk-Z6GCGXVC.js";
4
+ import {
5
+ remarkDocumentationComponents
6
+ } from "../chunk-H2E5IS4E.js";
4
7
 
5
8
  // src/mdx/index.ts
6
9
  import { default as default2 } from "rehype-slug";
7
10
 
8
11
  // src/mdx/code-highlighting.ts
9
12
  import rehypeShiki from "@shikijs/rehype";
13
+
14
+ // src/mdx/folder-tree.ts
15
+ var branch = /^([ \t|│]*)(\|-|\|_|├──|└──)(?:[ \t]+(.*))?$/;
16
+ var guide = /^[ \t|│]*[|│][ \t|│]*$/;
17
+ function explicitTree(source) {
18
+ const lines = source.split(/\r?\n/);
19
+ if (!lines.some((line) => branch.test(line) || guide.test(line))) return;
20
+ return lines.map((line) => {
21
+ const match = line.match(branch);
22
+ if (match) {
23
+ const prefix = match[1].replaceAll("|", "\u2502").replaceAll(" ", " ");
24
+ const connector = match[2] === "|-" ? "\u251C\u2500\u2500" : match[2] === "|_" ? "\u2514\u2500\u2500" : match[2];
25
+ return `${prefix}${connector}${match[3] ? " " + match[3].trimEnd() : ""}`;
26
+ }
27
+ return guide.test(line) ? line.replaceAll("|", "\u2502").replaceAll(" ", " ") : line.trimEnd();
28
+ }).join("\n");
29
+ }
30
+ function formatFolderTree(source) {
31
+ const diagram = explicitTree(source);
32
+ if (diagram !== void 0) return diagram;
33
+ const roots = [];
34
+ const parents = [];
35
+ for (const [index, line] of source.split(/\r?\n/).entries()) {
36
+ if (!line.trim()) continue;
37
+ const indentation = line.match(/^[ \t]*/)?.[0].replaceAll(" ", " ") ?? "";
38
+ const depth = indentation.length / 2;
39
+ if (!Number.isInteger(depth) || depth > parents.length)
40
+ throw new Error(
41
+ `Invalid folder fence at line ${index + 1}: use two spaces per level without skipping levels.`
42
+ );
43
+ const parent = parents[depth - 1];
44
+ if (parent && !parent.name.endsWith("/"))
45
+ throw new Error(
46
+ `Invalid folder fence at line ${index + 1}: parent folders must end with /.`
47
+ );
48
+ const entry = { name: line.trim(), children: [] };
49
+ const siblings = parent ? parent.children : roots;
50
+ siblings.push(entry);
51
+ parents.length = depth;
52
+ parents.push(entry);
53
+ }
54
+ const lines = [];
55
+ function draw(entries, prefix, root = false) {
56
+ entries.forEach((entry, index) => {
57
+ const last = index === entries.length - 1;
58
+ lines.push(
59
+ root ? entry.name : `${prefix}${last ? "\u2514\u2500\u2500 " : "\u251C\u2500\u2500 "}${entry.name}`
60
+ );
61
+ draw(entry.children, root ? "" : prefix + (last ? " " : "\u2502 "));
62
+ });
63
+ }
64
+ draw(roots, "", true);
65
+ return lines.join("\n") + (source.endsWith("\n") ? "\n" : "");
66
+ }
67
+
68
+ // src/mdx/code-highlighting.ts
69
+ function codeOptions(meta) {
70
+ const properties = {};
71
+ if (typeof meta !== "string") return properties;
72
+ const attributes = /(?:^|\s)([\w-]+)(?:=(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^\s"']+)))?(?=\s|$)/g;
73
+ for (const match of meta.matchAll(attributes)) {
74
+ const value = (match[2] ?? match[3] ?? match[4])?.replace(/\\(["'\\])/g, "$1").trim();
75
+ if (match[1] === "title" && value) properties["data-rdx-code-title"] = value;
76
+ if (match[1] === "lineNumbers") {
77
+ if (value !== void 0)
78
+ throw new Error(
79
+ "Invalid code fence metadata: lineNumbers must be a flag without a value."
80
+ );
81
+ properties["data-rdx-code-line-numbers"] = "true";
82
+ }
83
+ if (match[1] === "startLine") {
84
+ if (!value || !/^\d+$/.test(value) || !Number.isSafeInteger(Number(value)) || Number(value) < 1)
85
+ throw new Error(
86
+ "Invalid code fence metadata: startLine must be a positive safe integer."
87
+ );
88
+ properties["data-rdx-code-start-line"] = String(Number(value));
89
+ }
90
+ }
91
+ return properties;
92
+ }
93
+ function prepareCodeBlocks(node) {
94
+ const code = node.tagName === "pre" ? node.children?.[0] : void 0;
95
+ const data = code?.data;
96
+ const meta = data && typeof data === "object" && "meta" in data ? data.meta : void 0;
97
+ if (code)
98
+ node.properties = {
99
+ ...node.properties,
100
+ ...codeOptions(meta ?? code.properties?.metastring)
101
+ };
102
+ const classes = code?.properties?.className;
103
+ if (code && Array.isArray(classes) && classes.some((name) => /^language-mermaid$/i.test(String(name)))) {
104
+ node.properties = { ...node.properties, "data-rdx-code-mode": "mermaid" };
105
+ code.properties.className = classes.filter(
106
+ (name) => !/^language-mermaid$/i.test(String(name))
107
+ );
108
+ return;
109
+ }
110
+ if (code && Array.isArray(classes) && classes.some((name) => /^language-folder$/i.test(String(name)))) {
111
+ node.properties = { ...node.properties, "data-rdx-code-mode": "folder" };
112
+ code.properties.className = classes.filter(
113
+ (name) => !/^language-folder$/i.test(String(name))
114
+ );
115
+ code.children = [
116
+ {
117
+ type: "text",
118
+ value: formatFolderTree(
119
+ code.children?.map((child) => child.value ?? "").join("") ?? ""
120
+ )
121
+ }
122
+ ];
123
+ return;
124
+ }
125
+ node.children?.forEach(prepareCodeBlocks);
126
+ }
10
127
  function rehypeDocumentationCode() {
11
- return rehypeShiki.call(this, {
128
+ const diffVariants = /* @__PURE__ */ new WeakMap();
129
+ const highlight = rehypeShiki.call(this, {
12
130
  themes: { light: "github-light", dark: "github-dark" },
13
131
  defaultColor: false,
14
132
  addLanguageClass: true,
@@ -18,11 +136,49 @@ function rehypeDocumentationCode() {
18
136
  fallbackLanguage: "text",
19
137
  // The copy button must retain MDX's original trailing newline.
20
138
  stripEndNewline: false,
21
- inline: false
139
+ inline: false,
140
+ transformers: [
141
+ {
142
+ name: "rdx:diff-lines",
143
+ pre(node) {
144
+ Object.assign(node.properties, codeOptions(this.options.meta?.__raw));
145
+ if (this.options.lang === "diff")
146
+ node.properties["data-rdx-code-mode"] = "diff";
147
+ },
148
+ preprocess(code) {
149
+ if (this.options.lang === "diff") {
150
+ let inHunk = false;
151
+ diffVariants.set(
152
+ this.meta,
153
+ code.split("\n").map((text) => {
154
+ if (text.startsWith("diff --git ")) inHunk = false;
155
+ if (text.startsWith("@@")) {
156
+ inHunk = true;
157
+ return "hunk";
158
+ }
159
+ if (!inHunk && /^(\+\+\+|---)(?:\s|$)/.test(text))
160
+ return "default";
161
+ return text.startsWith("+") ? "added" : text.startsWith("-") ? "removed" : "default";
162
+ })
163
+ );
164
+ }
165
+ },
166
+ line(node, line) {
167
+ if (this.options.lang !== "diff") return;
168
+ node.properties["data-rdx-line-variant"] = diffVariants.get(this.meta)?.[line - 1] ?? "default";
169
+ }
170
+ }
171
+ ]
22
172
  });
173
+ if (typeof highlight !== "function") return highlight;
174
+ return (tree, ...args) => {
175
+ prepareCodeBlocks(tree);
176
+ return highlight(tree, ...args);
177
+ };
23
178
  }
24
179
  export {
25
180
  rehypeDocumentationCode,
26
181
  default2 as rehypeDocumentationHeadings,
27
- remarkDocumentLinks
182
+ remarkDocumentLinks,
183
+ remarkDocumentationComponents
28
184
  };
@@ -1,10 +1,14 @@
1
+ import {
2
+ remarkDocumentationComponents
3
+ } from "../chunk-H2E5IS4E.js";
4
+
1
5
  // src/search/index.ts
2
6
  import GithubSlugger from "github-slugger";
3
7
  import remarkGfm from "remark-gfm";
4
8
  import remarkMdx from "remark-mdx";
5
9
  import remarkParse from "remark-parse";
6
10
  import { unified } from "unified";
7
- var parser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx);
11
+ var parser = unified().use(remarkParse).use(remarkGfm).use(remarkMdx).use(remarkDocumentationComponents);
8
12
  function text(node) {
9
13
  if (node.type === "break") return " ";
10
14
  if (["mdxjsEsm", "mdxFlowExpression", "mdxTextExpression", "html"].includes(
@@ -66,6 +70,12 @@ function buildSearchIndex(documents) {
66
70
  if (node.name && ["script", "style", "svg"].includes(node.name.toLowerCase()))
67
71
  return;
68
72
  const nestedInteractive = interactive || node.name === "TabsContent" || node.name === "AccordionContent";
73
+ if (node.name === "Callout") {
74
+ const title = node.attributes?.find(
75
+ (attribute) => attribute.type === "mdxJsxAttribute" && attribute.name === "title"
76
+ )?.value;
77
+ if (typeof title === "string") current.text += ` ${title}`;
78
+ }
69
79
  node.children?.forEach((child) => visit2(child, nestedInteractive));
70
80
  } else {
71
81
  current.text += ` ${text(node)}`;
@@ -74,7 +84,9 @@ function buildSearchIndex(documents) {
74
84
  var visit = visit2;
75
85
  const firstEntry = entries.length;
76
86
  const slugger = new GithubSlugger();
77
- const tree = parser.parse(document.content);
87
+ const tree = parser.runSync(parser.parse(document.content), {
88
+ value: document.content
89
+ });
78
90
  let current = {
79
91
  href: document.href,
80
92
  title: document.title,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lexibase/rdx-core",
3
- "version": "1.1.1",
3
+ "version": "1.3.0",
4
4
  "description": "Content indexing and document utilities for RDX documentation projects.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -41,21 +41,22 @@
41
41
  },
42
42
  "homepage": "https://github.com/lexibase/rdx#readme",
43
43
  "dependencies": {
44
+ "@shikijs/rehype": "^4.5.0",
44
45
  "github-slugger": "^2.0.0",
46
+ "gray-matter": "^4.0.3",
47
+ "rehype-slug": "^6.0.0",
48
+ "remark-directive": "4.0.0",
49
+ "remark-gfm": "^4.0.1",
45
50
  "remark-mdx": "^3.1.1",
46
51
  "remark-parse": "^11.0.0",
47
- "remark-gfm": "^4.0.1",
48
52
  "unified": "^11.0.5",
49
- "@shikijs/rehype": "^4.5.0",
50
- "gray-matter": "^4.0.3",
51
- "rehype-slug": "^6.0.0",
52
53
  "@lexibase/rdx-types": "1.1.1"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@types/node": "^22.15.3",
56
57
  "@types/react": "19.3.0",
57
- "@rdx/typescript-config": "1.0.0",
58
- "@rdx/eslint-config": "1.0.0"
58
+ "@rdx/eslint-config": "1.0.0",
59
+ "@rdx/typescript-config": "1.0.0"
59
60
  },
60
61
  "engines": {
61
62
  "node": "^22.18.0 || ^24.11.0"