@ai-matrx/print 0.5.9 → 0.6.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.
package/dist/markdown.js CHANGED
@@ -753,6 +753,257 @@ var MARKDOWN_DOCUMENT_CSS = `/*
753
753
  }
754
754
  `;
755
755
  var MARKDOWN_ARTICLE_CSS = `*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}body{font-family:Georgia,'Times New Roman',serif;font-size:11pt;line-height:1.7;color:var(--matrx-print-fg, #1a1a1a);background:var(--matrx-print-bg, #fff);max-width:780px;margin:0 auto;padding:32px 40px}.print-actions{display:flex;gap:10px;margin-bottom:28px;padding-bottom:20px;border-bottom:2px solid var(--matrx-print-border, #e5e7eb)}.print-btn{display:inline-flex;align-items:center;gap:6px;padding:8px 20px;border-radius:8px;font-size:13px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;cursor:pointer;border:none;font-weight:600;transition:opacity .15s}.print-btn:hover{opacity:.85}.print-btn-primary{background:var(--matrx-print-accent, #2563eb);color:var(--matrx-print-bg, #fff)}.print-btn-secondary{background:var(--matrx-print-surface-sunken, #f3f4f6);color:var(--matrx-print-fg-muted, #374151);border:1px solid var(--matrx-print-border-muted, #d1d5db)}h1,h2,h3,h4,h5,h6{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Helvetica Neue',sans-serif;font-weight:700;line-height:1.3;color:var(--matrx-print-heading, #111827);margin-top:1.6em;margin-bottom:.5em;page-break-after:avoid}h1{font-size:24pt;border-bottom:2px solid var(--matrx-print-border, #e5e7eb);padding-bottom:.3em;margin-top:0}h2{font-size:18pt;border-bottom:1px solid var(--matrx-print-border, #e5e7eb);padding-bottom:.2em}h3{font-size:14pt}p{margin-bottom:.9em;orphans:3;widows:3}a{color:var(--matrx-print-accent, #2563eb);text-decoration:underline;word-break:break-word}ul,ol{margin:.6em 0 .9em 0;padding-left:1.8em}li{margin-bottom:.3em;page-break-inside:avoid}blockquote{margin:1em 0;padding:.7em 1em .7em 1.2em;border-left:4px solid var(--matrx-print-quote-border, #6366f1);background:var(--matrx-print-quote-bg, #f5f3ff);border-radius:0 6px 6px 0;color:var(--matrx-print-fg-muted, #374151);font-style:italic;page-break-inside:avoid}.inline-code{font-family:'JetBrains Mono','Fira Code',monospace;font-size:9.5pt;background:var(--matrx-print-code-bg, #f1f5f9);color:var(--matrx-print-ink, #0f172a);padding:1px 5px;border-radius:4px;border:1px solid var(--matrx-print-line, #e2e8f0)}.code-block-wrapper{position:relative;margin:1em 0 1.2em;border-radius:8px;overflow:hidden;border:1px solid var(--matrx-print-line, #e2e8f0);page-break-inside:avoid}.code-lang{display:block;font-family:-apple-system,sans-serif;font-size:9pt;font-weight:600;color:var(--matrx-print-fg-subtle, #64748b);background:var(--matrx-print-surface, #f8fafc);padding:4px 12px;border-bottom:1px solid var(--matrx-print-line, #e2e8f0);text-transform:uppercase;letter-spacing:.05em}.code-block{margin:0;padding:14px 16px;background:var(--matrx-print-ink, #0f172a);color:var(--matrx-print-line, #e2e8f0);font-family:'JetBrains Mono',monospace;font-size:9pt;line-height:1.6;overflow-x:auto;white-space:pre;tab-size:2}.print-table{width:100%;border-collapse:collapse;margin:1em 0 1.2em;font-size:10pt;page-break-inside:avoid}.print-table th{background:var(--matrx-print-table-head-bg, #1e293b);color:var(--matrx-print-surface, #f8fafc);font-family:-apple-system,sans-serif;font-weight:600;font-size:9.5pt;text-align:left;padding:8px 12px;border:1px solid var(--matrx-print-table-head-border, #334155)}.print-table td{padding:7px 12px;border:1px solid var(--matrx-print-line, #e2e8f0);vertical-align:top}.print-table tr:nth-child(even) td{background:var(--matrx-print-surface, #f8fafc)}hr{border:none;border-top:2px solid var(--matrx-print-border, #e5e7eb);margin:1.5em 0}.print-figure{margin:1em 0 1.2em;page-break-inside:avoid}.print-image{display:block;max-width:100%;height:auto;margin:0 auto;border-radius:6px}.print-figure figcaption{margin-top:.4em;text-align:center;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif;font-size:9.5pt;color:var(--matrx-print-fg-subtle, #64748b)}@media print{body{max-width:100%;padding:0;font-size:10.5pt}.print-actions{display:none!important}.code-block,.print-table th,blockquote{color-adjust:exact;-webkit-print-color-adjust:exact;print-color-adjust:exact}a[href]::after{content:" ("attr(href)")";font-size:9pt;color:var(--matrx-print-fg-subtle, #64748b)}a[href^="#"]::after,a[href^="javascript:"]::after{content:""}h1,h2,h3{page-break-after:avoid}pre,blockquote,table{page-break-inside:avoid}}`;
756
+ var MARKDOWN_SHARED_CSS = `
757
+ .matrx-page-break {
758
+ position: relative;
759
+ clear: both;
760
+ height: 0;
761
+ margin: 2.75rem 0;
762
+ border: 0;
763
+ border-top: 2px dashed var(--matrx-print-border-muted, #d1d5db);
764
+ }
765
+ .matrx-page-break::after {
766
+ content: attr(data-label);
767
+ position: absolute;
768
+ left: 50%;
769
+ top: 0;
770
+ transform: translate(-50%, -50%);
771
+ padding: 0 0.75rem;
772
+ background: var(--matrx-print-bg, #ffffff);
773
+ color: var(--matrx-print-fg-subtle, #6b7280);
774
+ font: 600 10px/1.6 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
775
+ letter-spacing: 0.08em;
776
+ text-transform: uppercase;
777
+ white-space: nowrap;
778
+ }
779
+
780
+ .matrx-artifact {
781
+ margin: 1.25em 0;
782
+ border: 1px solid var(--matrx-print-border, #e5e7eb);
783
+ border-radius: 8px;
784
+ overflow: hidden;
785
+ }
786
+ .matrx-artifact-header {
787
+ display: flex;
788
+ align-items: baseline;
789
+ gap: 0.6em;
790
+ padding: 0.45em 0.9em;
791
+ background: var(--matrx-print-surface, #f8fafc);
792
+ border-bottom: 1px solid var(--matrx-print-border, #e5e7eb);
793
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
794
+ }
795
+ .matrx-artifact-kind {
796
+ font-size: 0.72em;
797
+ font-weight: 700;
798
+ letter-spacing: 0.06em;
799
+ text-transform: uppercase;
800
+ color: var(--matrx-print-accent, #2563eb);
801
+ }
802
+ .matrx-artifact-title {
803
+ font-weight: 600;
804
+ color: var(--matrx-print-fg, #1a1a1a);
805
+ }
806
+ .matrx-artifact-body {
807
+ padding: 0.8em 0.9em;
808
+ }
809
+ .matrx-artifact-body > :first-child {
810
+ margin-top: 0;
811
+ }
812
+ .matrx-artifact-body > :last-child {
813
+ margin-bottom: 0;
814
+ }
815
+ .matrx-artifact-empty {
816
+ margin: 0;
817
+ font-style: italic;
818
+ color: var(--matrx-print-fg-subtle, #6b7280);
819
+ }
820
+
821
+ li.matrx-task-item {
822
+ list-style: none;
823
+ }
824
+ .matrx-task-box {
825
+ position: relative;
826
+ display: inline-block;
827
+ width: 0.9em;
828
+ height: 0.9em;
829
+ margin: 0 0.5em 0 -1.35em;
830
+ border: 1.5px solid var(--matrx-print-fg-muted, #4a4a4a);
831
+ border-radius: 3px;
832
+ vertical-align: -0.1em;
833
+ }
834
+ .matrx-task-box.is-checked::after {
835
+ content: "\\2713";
836
+ position: absolute;
837
+ inset: 0;
838
+ font-size: 0.8em;
839
+ font-weight: 700;
840
+ line-height: 1.1em;
841
+ text-align: center;
842
+ color: var(--matrx-print-fg, #1a1a1a);
843
+ }
844
+
845
+ :is(.matrx-content-container, .content) del {
846
+ color: var(--matrx-print-fg-muted, #4a4a4a);
847
+ text-decoration: line-through;
848
+ }
849
+ :is(.matrx-content-container, .content) hr.matrx-hr-accent {
850
+ height: 2px;
851
+ margin: 1.75em 0;
852
+ border: 0;
853
+ border-radius: 2px;
854
+ background: var(--matrx-print-accent, #2563eb);
855
+ opacity: 0.6;
856
+ }
857
+ :is(.matrx-content-container, .content) hr.matrx-hr-heavy {
858
+ height: 4px;
859
+ margin: 2.25em 0;
860
+ border: 0;
861
+ border-radius: 4px;
862
+ background: var(--matrx-print-accent, #2563eb);
863
+ }
864
+
865
+ .matrx-flashcards-print {
866
+ margin: 1em 0 1.2em;
867
+ }
868
+ .matrx-fc {
869
+ display: grid;
870
+ grid-template-columns: 1fr 1fr;
871
+ margin-bottom: 0.5em;
872
+ border: 1px solid var(--matrx-print-border, #e5e7eb);
873
+ border-radius: 6px;
874
+ }
875
+ .matrx-fc-front,
876
+ .matrx-fc-back {
877
+ padding: 0.6em 0.8em;
878
+ }
879
+ .matrx-fc-front {
880
+ font-weight: 600;
881
+ border-right: 1px dashed var(--matrx-print-border-muted, #d1d5db);
882
+ }
883
+ .matrx-fc-num {
884
+ display: inline-block;
885
+ min-width: 1.6em;
886
+ font-size: 0.85em;
887
+ color: var(--matrx-print-fg-subtle, #6b7280);
888
+ }
889
+
890
+ @media print {
891
+ .matrx-page-break {
892
+ margin: 0;
893
+ border: 0;
894
+ break-after: page;
895
+ page-break-after: always;
896
+ }
897
+ .matrx-page-break::after {
898
+ content: none;
899
+ }
900
+ .matrx-page-break + * {
901
+ margin-top: 0;
902
+ }
903
+
904
+ /* Scoped to the rendered markdown (.matrx-content-container = document
905
+ skin, .content = print window) so a host page that carries this sheet
906
+ \u2014 a WordPress theme \u2014 keeps its own print rules everywhere else. */
907
+
908
+ /* Long tables flow across pages: the header row repeats, rows never split. */
909
+ :is(.matrx-content-container, .content) thead {
910
+ display: table-header-group;
911
+ }
912
+ :is(.matrx-content-container, .content) :is(tr, img, figure),
913
+ .matrx-fc,
914
+ .matrx-task-item {
915
+ break-inside: avoid;
916
+ page-break-inside: avoid;
917
+ }
918
+ :is(.matrx-content-container, .content) :is(h1, h2, h3, h4, h5, h6),
919
+ .matrx-artifact-header {
920
+ break-after: avoid;
921
+ page-break-after: avoid;
922
+ break-inside: avoid;
923
+ }
924
+
925
+ /* Paper cannot scroll: long code lines wrap instead of being cut off. */
926
+ :is(.matrx-content-container, .content) :is(pre, pre code) {
927
+ white-space: pre-wrap !important;
928
+ overflow-wrap: anywhere;
929
+ overflow: visible !important;
930
+ }
931
+ .code-block-wrapper,
932
+ .matrx-artifact {
933
+ overflow: visible;
934
+ }
935
+ :is(.matrx-content-container, .content) img {
936
+ max-width: 100% !important;
937
+ }
938
+
939
+ .matrx-artifact-header,
940
+ .matrx-task-box {
941
+ -webkit-print-color-adjust: exact;
942
+ print-color-adjust: exact;
943
+ }
944
+
945
+ a.matrx-link[href^="http"]::after {
946
+ content: " (" attr(href) ")";
947
+ font-size: 0.85em;
948
+ color: var(--matrx-print-fg-subtle, #6b7280);
949
+ overflow-wrap: anywhere;
950
+ }
951
+ }
952
+ `;
953
+ var MARKDOWN_PAGE_CSS = `
954
+ @page {
955
+ margin: 0.6in 0.65in 0.7in;
956
+ @bottom-center {
957
+ content: counter(page) " / " counter(pages);
958
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
959
+ font-size: 8pt;
960
+ color: var(--matrx-print-fg-subtle, #6b7280);
961
+ }
962
+ }
963
+ `;
964
+ var MARKDOWN_PAGE_PLAIN_CSS = `
965
+ @page {
966
+ margin: 0.6in 0.65in 0.7in;
967
+ }
968
+ `;
969
+
970
+ // src/directives.ts
971
+ var PAGE_BREAK_MARKDOWN = "<!-- pagebreak -->";
972
+ var PAGE_BREAK_CLASS = "matrx-page-break";
973
+ var PAGE_BREAK_LABEL = "Page break";
974
+ var COMMENT_FORM = /^<!--\s*(?:page[\s_-]?break|new[\s_-]?page)\s*-->$/i;
975
+ var LATEX_FORM = /^\\(?:pagebreak|newpage|clearpage)\s*(?:\{\s*\})?$/i;
976
+ var DIV_FORM = /^<div\b([^>]*)>\s*<\/div>$|^<div\b([^>]*)\/>$/i;
977
+ var DIV_BREAK_ATTR = /(?:page-break-(?:after|before)\s*:\s*always|break-(?:after|before)\s*:\s*page|class\s*=\s*["'](?:[^"']*\s)?page-?break(?:\s[^"']*)?["'])/i;
978
+ function isPageBreakLine(line) {
979
+ const t = line.trim();
980
+ if (t.length < 8 || t.length > 200) return false;
981
+ if (COMMENT_FORM.test(t) || LATEX_FORM.test(t)) return true;
982
+ const div = DIV_FORM.exec(t);
983
+ if (!div) return false;
984
+ return DIV_BREAK_ATTR.test(div[1] ?? div[2] ?? "");
985
+ }
986
+ function splitAtPageBreaks(markdown) {
987
+ const lines = markdown.split(/\r?\n/);
988
+ const pieces = [];
989
+ let current = [];
990
+ let fence = null;
991
+ for (const line of lines) {
992
+ const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line);
993
+ if (fenceMatch) {
994
+ const marker = fenceMatch[1];
995
+ if (fence === null) fence = marker;
996
+ else if (marker[0] === fence[0] && marker.length >= fence.length) fence = null;
997
+ } else if (fence === null && isPageBreakLine(line)) {
998
+ if (current.join("\n").trim()) pieces.push(current.join("\n"));
999
+ current = [];
1000
+ continue;
1001
+ }
1002
+ current.push(line);
1003
+ }
1004
+ if (current.join("\n").trim() || pieces.length === 0) pieces.push(current.join("\n"));
1005
+ return pieces;
1006
+ }
756
1007
 
757
1008
  // src/markdown.ts
758
1009
  function removeThinkingContent(content) {
@@ -765,80 +1016,166 @@ function hasThinkingContent(content) {
765
1016
  if (!content) return false;
766
1017
  return /<thinking>|<think>|<reasoning>/i.test(content);
767
1018
  }
768
- function convertMarkdownTables(html) {
769
- const tableRegex = /^(\|.*\|)\s*\n(\|[-\s:|]*\|)\s*\n((?:\|.*\|\s*\n?)*)/gm;
770
- return html.replace(
771
- tableRegex,
772
- (_match, headerRow, _separatorRow, bodyRows) => {
773
- const headers = headerRow.split("|").map((cell) => cell.trim()).filter((cell) => cell !== "");
774
- const rows = bodyRows.trim().split("\n").filter((row) => row.trim()).map(
775
- (row) => row.split("|").map((cell) => cell.trim()).filter((cell) => cell !== "")
776
- );
777
- let tableHtml = '<table class="matrx-table">\n';
778
- if (headers.length > 0) {
779
- tableHtml += '<thead class="matrx-table-head">\n<tr class="matrx-table-row">\n';
780
- for (const header of headers) {
781
- tableHtml += `<th class="matrx-table-header">${header}</th>
782
- `;
783
- }
784
- tableHtml += "</tr>\n</thead>\n";
785
- }
786
- if (rows.length > 0) {
787
- tableHtml += '<tbody class="matrx-table-body">\n';
788
- for (const row of rows) {
789
- if (row.length === 0) continue;
790
- tableHtml += '<tr class="matrx-table-row">\n';
791
- for (const cell of row) {
792
- tableHtml += `<td class="matrx-table-cell">${cell}</td>
793
- `;
794
- }
795
- tableHtml += "</tr>\n";
796
- }
797
- tableHtml += "</tbody>\n";
798
- }
799
- return `${tableHtml}</table>
800
- `;
1019
+ var TOKEN_OPEN = "\uE000";
1020
+ var TOKEN_CLOSE = "\uE001";
1021
+ var BLOCK_TOKEN = (i) => `${TOKEN_OPEN}B${i}${TOKEN_CLOSE}`;
1022
+ var INLINE_TOKEN = (i) => `${TOKEN_OPEN}I${i}${TOKEN_CLOSE}`;
1023
+ var TOKEN_RE = /\uE000([BI])(\d+)\uE001/g;
1024
+ var PARAGRAPH_WRAPPED_BLOCK_RE = /<p[^>]*>\s*(\uE000B\d+\uE001)\s*<\/p>/g;
1025
+ var Stash = class {
1026
+ items = [];
1027
+ block(html) {
1028
+ return BLOCK_TOKEN(this.items.push(html) - 1);
1029
+ }
1030
+ inline(html) {
1031
+ return INLINE_TOKEN(this.items.push(html) - 1);
1032
+ }
1033
+ restore(html) {
1034
+ let out = html;
1035
+ for (let pass = 0; pass < 8 && out.includes(TOKEN_OPEN); pass++) {
1036
+ out = out.replace(PARAGRAPH_WRAPPED_BLOCK_RE, "$1").replace(TOKEN_RE, (_m, _k, i) => this.items[Number(i)] ?? "");
801
1037
  }
802
- );
1038
+ return out;
1039
+ }
1040
+ };
1041
+ var DOCUMENT_GRAMMAR = {
1042
+ skin: "document",
1043
+ table: "matrx-table",
1044
+ thead: "matrx-table-head",
1045
+ tbody: "matrx-table-body",
1046
+ tr: "matrx-table-row",
1047
+ th: "matrx-table-header",
1048
+ td: "matrx-table-cell",
1049
+ ul: "matrx-list matrx-bullet-list",
1050
+ ol: "matrx-list matrx-numbered-list",
1051
+ ulNested: "matrx-list matrx-bullet-list matrx-nested-list",
1052
+ olNested: "matrx-list matrx-numbered-list matrx-nested-list",
1053
+ li: "matrx-list-item",
1054
+ hr: "matrx-hr",
1055
+ del: "matrx-del",
1056
+ strong: "matrx-strong",
1057
+ em: "matrx-em",
1058
+ inlineCode: "matrx-inline-code"
1059
+ };
1060
+ var ARTICLE_GRAMMAR = {
1061
+ skin: "article",
1062
+ table: "print-table",
1063
+ thead: "",
1064
+ tbody: "",
1065
+ tr: "",
1066
+ th: "",
1067
+ td: "",
1068
+ ul: "",
1069
+ ol: "",
1070
+ ulNested: "",
1071
+ olNested: "",
1072
+ li: "",
1073
+ hr: "",
1074
+ del: "",
1075
+ strong: "",
1076
+ em: "",
1077
+ inlineCode: "inline-code"
1078
+ };
1079
+ var cls = (...names) => {
1080
+ const joined = names.filter(Boolean).join(" ");
1081
+ return joined ? ` class="${joined}"` : "";
1082
+ };
1083
+ var PAGE_BREAK_HTML = `<div class="${PAGE_BREAK_CLASS}" role="separator" aria-label="${PAGE_BREAK_LABEL}" data-label="${PAGE_BREAK_LABEL}"></div>`;
1084
+ function codeBlockHtml(g, code, language) {
1085
+ const body = escapeHtml2(code.replace(/\n$/, ""));
1086
+ const lang = language.trim();
1087
+ if (g.skin === "article") {
1088
+ const label = lang ? `<span class="code-lang">${escapeHtml2(lang)}</span>` : "";
1089
+ return `<div class="code-block-wrapper">${label}<pre class="code-block"><code>${body}</code></pre></div>`;
1090
+ }
1091
+ const dataLang = lang ? ` data-language="${escapeHtml2(lang)}"` : "";
1092
+ return `<pre class="matrx-code-block"${dataLang}><code class="matrx-code">${body}</code></pre>`;
1093
+ }
1094
+ var CODE_ARTIFACT_LANGUAGE = {
1095
+ html: "html",
1096
+ react: "tsx",
1097
+ svg: "svg",
1098
+ mermaid: "mermaid",
1099
+ diff: "diff",
1100
+ iframe: "html",
1101
+ code: ""
1102
+ };
1103
+ var ARTIFACT_TYPE_LABEL = {
1104
+ html: "HTML",
1105
+ svg: "SVG",
1106
+ react: "React",
1107
+ iframe: "Embed"
1108
+ };
1109
+ function parseTagAttributes(tag) {
1110
+ const attrs = {};
1111
+ for (const m of tag.matchAll(/([a-zA-Z_][\w-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
1112
+ attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? "";
1113
+ }
1114
+ return attrs;
1115
+ }
1116
+ function artifactLabel(type) {
1117
+ if (!type) return "Artifact";
1118
+ return ARTIFACT_TYPE_LABEL[type] ?? type.replace(/[-_]+/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
1119
+ }
1120
+ function looksLikeJson(body) {
1121
+ const t = body.trim();
1122
+ if (!/^[[{]/.test(t)) return false;
1123
+ try {
1124
+ JSON.parse(t);
1125
+ return true;
1126
+ } catch {
1127
+ return false;
1128
+ }
803
1129
  }
804
- function markdownToHtml(markdown, options = {}) {
805
- const notice = options.onNotice;
806
- if (!markdown) {
807
- notice?.({
808
- code: "empty-output",
809
- message: "markdownToHtml received an empty string.",
810
- remedy: "Check the content is loaded before converting; nothing was rendered."
811
- });
812
- return "";
1130
+ function artifactHtml(g, attrs, body, ctx) {
1131
+ const type = (attrs.type ?? "").toLowerCase();
1132
+ const title = attrs.title?.trim() ?? "";
1133
+ const header = `<div class="matrx-artifact-header"><span class="matrx-artifact-kind">${escapeHtml2(
1134
+ artifactLabel(type)
1135
+ )}</span>${title ? `<span class="matrx-artifact-title">${escapeHtml2(title)}</span>` : ""}</div>`;
1136
+ let inner;
1137
+ const trimmed = (body ?? "").replace(/^\n+|\n+$/g, "");
1138
+ if (body === null || !trimmed.trim()) {
1139
+ inner = `<p class="matrx-artifact-empty">Saved artifact \u2014 open it in AI Matrx to view its content.</p>`;
1140
+ } else if (/^\s*(`{3,}|~{3,})/.test(trimmed)) {
1141
+ inner = convertBody(g.skin, trimmed, ctx);
1142
+ } else if (type in CODE_ARTIFACT_LANGUAGE) {
1143
+ inner = codeBlockHtml(g, trimmed, CODE_ARTIFACT_LANGUAGE[type] || attrs.language || attrs.lang || "");
1144
+ } else if (looksLikeJson(trimmed)) {
1145
+ inner = codeBlockHtml(g, JSON.stringify(JSON.parse(trimmed), null, 2), "json");
1146
+ } else {
1147
+ inner = convertBody(g.skin, trimmed, ctx);
813
1148
  }
814
- const startWrapper = '<div class="matrx-content-container">';
815
- const endWrapper = "</div>";
816
- let html = options.includeThinking ? markdown : removeThinkingContent(markdown);
817
- const flashcardPlaceholders = [];
818
- let flashcardIndex = 0;
819
- let globalCardIndex = 0;
820
- html = html.replace(
821
- /<flashcards>([\s\S]*?)<\/flashcards>/gi,
822
- (_match, content) => {
823
- const cards = content.split(/\n*---\n*/g).map((card) => card.trim()).filter((card) => card.length > 0);
824
- if (cards.length === 0) return "";
825
- let flashcardsHtml = '<div class="matrx-flashcards-container">\n';
826
- for (const card of cards) {
827
- const frontMatch = card.match(/Front:\s*(.+?)(?=\n|$)/i);
828
- const backMatch = card.match(/Back:\s*([\s\S]+?)$/i);
829
- const front = frontMatch?.[1]?.trim();
830
- const back = backMatch?.[1]?.trim();
831
- if (!front || !back) {
832
- notice?.({
833
- code: "flashcard-malformed",
834
- message: `A flashcard was skipped: it is missing a ${front ? "Back:" : "Front:"} line.`,
835
- remedy: 'Every card inside <flashcards> needs both "Front: \u2026" and "Back: \u2026", separated from the next card by ---.'
836
- });
837
- continue;
838
- }
839
- globalCardIndex++;
840
- const cardId = `card${globalCardIndex}`;
841
- flashcardsHtml += ` <div class="matrx-flashcard">
1149
+ return `<section class="matrx-artifact" data-artifact-type="${escapeHtml2(type || "artifact")}">${header}<div class="matrx-artifact-body">${inner}</div></section>`;
1150
+ }
1151
+ function parseFlashcards(content, notice) {
1152
+ const cards = [];
1153
+ for (const card of content.split(/\n*---\n*/g).map((c) => c.trim()).filter(Boolean)) {
1154
+ const front = card.match(/Front:\s*(.+?)(?=\n|$)/i)?.[1]?.trim();
1155
+ const back = card.match(/Back:\s*([\s\S]+?)$/i)?.[1]?.trim();
1156
+ if (!front || !back) {
1157
+ notice?.({
1158
+ code: "flashcard-malformed",
1159
+ message: `A flashcard was skipped: it is missing a ${front ? "Back:" : "Front:"} line.`,
1160
+ remedy: 'Every card inside <flashcards> needs both "Front: \u2026" and "Back: \u2026", separated from the next card by ---.'
1161
+ });
1162
+ continue;
1163
+ }
1164
+ cards.push({ front, back });
1165
+ }
1166
+ return cards;
1167
+ }
1168
+ function flashcardsHtml(g, cards, ctx) {
1169
+ if (g.skin === "article") {
1170
+ return `<div class="matrx-flashcards-print">${cards.map(
1171
+ (c, i) => `<div class="matrx-fc"><div class="matrx-fc-front"><span class="matrx-fc-num">${i + 1}</span>${c.front}</div><div class="matrx-fc-back">${c.back}</div></div>`
1172
+ ).join("")}</div>`;
1173
+ }
1174
+ let out = '<div class="matrx-flashcards-container">\n';
1175
+ for (const { front, back } of cards) {
1176
+ ctx.cardIndex++;
1177
+ const cardId = `card${ctx.cardIndex}`;
1178
+ out += ` <div class="matrx-flashcard">
842
1179
  <input type="checkbox" class="matrx-flashcard-input" id="${cardId}">
843
1180
  <label for="${cardId}" class="matrx-flashcard-label"></label>
844
1181
  <div class="matrx-flashcard-inner">
@@ -858,154 +1195,318 @@ function markdownToHtml(markdown, options = {}) {
858
1195
  </div>
859
1196
 
860
1197
  `;
1198
+ }
1199
+ return `${out}</div>
1200
+ `;
1201
+ }
1202
+ var FENCE_OPEN = /^(\s*)(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/;
1203
+ function protectRegions(markdown, g, stash, ctx) {
1204
+ const lines = markdown.split(/\r?\n/);
1205
+ const out = [];
1206
+ for (let i = 0; i < lines.length; i++) {
1207
+ const line = lines[i];
1208
+ const fence = FENCE_OPEN.exec(line);
1209
+ if (fence) {
1210
+ const marker = fence[2];
1211
+ const code = [];
1212
+ let j = i + 1;
1213
+ for (; j < lines.length; j++) {
1214
+ const close = /^\s*(`{3,}|~{3,})\s*$/.exec(lines[j]);
1215
+ if (close && close[1][0] === marker[0] && close[1].length >= marker.length) break;
1216
+ code.push(lines[j]);
861
1217
  }
862
- flashcardsHtml += "</div>\n";
863
- const placeholder = `\u03A9FLASHCARD\u03A9${flashcardIndex}\u03A9FLASHCARD\u03A9`;
864
- flashcardPlaceholders.push({ placeholder, html: flashcardsHtml });
865
- flashcardIndex++;
866
- return placeholder;
1218
+ const indent = fence[1].length;
1219
+ const dedented = code.map((l) => l.slice(Math.min(indent, l.length - l.trimStart().length)));
1220
+ out.push(stash.block(codeBlockHtml(g, dedented.join("\n"), fence[3] ?? "")));
1221
+ i = j;
1222
+ continue;
1223
+ }
1224
+ if (isPageBreakLine(line)) {
1225
+ out.push(stash.block(PAGE_BREAK_HTML));
1226
+ continue;
867
1227
  }
1228
+ const open = /^\s*<artifact\b((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>(.*)$/i.exec(line);
1229
+ if (open) {
1230
+ const attrs = parseTagAttributes(open[1] ?? "");
1231
+ if (open[2] === "/") {
1232
+ out.push(stash.block(artifactHtml(g, attrs, null, ctx)));
1233
+ if (open[3]?.trim()) out.push(open[3]);
1234
+ continue;
1235
+ }
1236
+ const bodyLines = [];
1237
+ let rest = open[3] ?? "";
1238
+ let after = "";
1239
+ let j = i;
1240
+ let inFence = null;
1241
+ for (; ; ) {
1242
+ const closeAt = inFence ? -1 : rest.search(/<\/artifact\s*>/i);
1243
+ if (closeAt >= 0) {
1244
+ bodyLines.push(rest.slice(0, closeAt));
1245
+ after = rest.slice(closeAt).replace(/^<\/artifact\s*>/i, "");
1246
+ break;
1247
+ }
1248
+ bodyLines.push(rest);
1249
+ const f = /^\s*(`{3,}|~{3,})/.exec(rest);
1250
+ if (f) {
1251
+ const m = f[1];
1252
+ if (inFence === null) inFence = m;
1253
+ else if (m[0] === inFence[0] && m.length >= inFence.length) inFence = null;
1254
+ }
1255
+ j++;
1256
+ if (j >= lines.length) break;
1257
+ rest = lines[j];
1258
+ }
1259
+ const html = ctx.depth >= 3 ? codeBlockHtml(g, bodyLines.join("\n"), "") : artifactHtml(g, attrs, bodyLines.join("\n"), { ...ctx, depth: ctx.depth + 1 });
1260
+ out.push(stash.block(html));
1261
+ if (after.trim()) out.push(after);
1262
+ i = j;
1263
+ continue;
1264
+ }
1265
+ out.push(line);
1266
+ }
1267
+ let text = out.join("\n");
1268
+ text = text.replace(
1269
+ /`([^`\n]+)`/g,
1270
+ (_m, code) => stash.inline(`<code${cls(g.inlineCode)}>${escapeHtml2(code)}</code>`)
868
1271
  );
869
- html = html.replace(/^[-]{3,}$/gm, '<hr class="matrx-hr">');
870
- html = html.replace(/^[*]{3,}$/gm, '<hr class="matrx-hr">');
871
- const imagePlaceholders = [];
872
- let imageIndex = 0;
873
- html = html.replace(
874
- /!\[([^\]]*)\]\(([^)]+)\)/g,
875
- (_match, altText, url) => {
876
- const placeholder = `\u03A9IMAGE\u03A9${imageIndex}\u03A9IMAGE\u03A9`;
877
- imagePlaceholders.push({
878
- placeholder,
879
- html: `<img class="matrx-image" src="${url}" alt="${altText}" />`
880
- });
881
- imageIndex++;
882
- return placeholder;
1272
+ text = text.replace(/<!--[\s\S]*?-->/g, "");
1273
+ const before = text;
1274
+ for (let pass = 0; pass < 8; pass++) {
1275
+ const next = text.replace(/<(script|style|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "").replace(/<\/?(?:script|style|head|html|body)\b[^>]*>/gi, "").replace(/<!DOCTYPE[^>]*>/gi, "");
1276
+ if (next === text) break;
1277
+ text = next;
1278
+ }
1279
+ text = sanitizeRawTags(text);
1280
+ if (text !== before && !ctx.strippedAnnounced) {
1281
+ ctx.strippedAnnounced = true;
1282
+ ctx.options.onNotice?.({
1283
+ code: "html-stripped",
1284
+ message: "Unsafe or page-level markup (a <script>, <style>, <head>, an <html>/<body> shell, an on\u2026 event handler, or a javascript: URL) was removed from the rendered copy.",
1285
+ remedy: 'To show a full HTML page, put it in an ```html fence or an <artifact type="html"> block \u2014 it is printed as its source.'
1286
+ });
1287
+ }
1288
+ text = text.replace(/<flashcards>([\s\S]*?)<\/flashcards>/gi, (_m, content) => {
1289
+ const cards = parseFlashcards(content, ctx.options.onNotice);
1290
+ return cards.length ? `
1291
+ ${stash.block(flashcardsHtml(g, cards, ctx))}
1292
+ ` : "";
1293
+ });
1294
+ return text;
1295
+ }
1296
+ var URL_ATTRS = /* @__PURE__ */ new Set(["href", "src", "action", "formaction", "xlink:href", "poster", "background"]);
1297
+ function decodeForSchemeCheck(value) {
1298
+ return value.replace(/&#x([0-9a-f]+);?/gi, (_m, h) => String.fromCharCode(parseInt(h, 16))).replace(/&#(\d+);?/g, (_m, d) => String.fromCharCode(Number(d))).replace(/&colon;/gi, ":").replace(/[\u0000-\u0020]+/g, "").toLowerCase();
1299
+ }
1300
+ function sanitizeRawTags(text) {
1301
+ return text.replace(
1302
+ /<([a-zA-Z][\w:-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>/g,
1303
+ (whole, tag, rawAttrs) => {
1304
+ if (!/[=\s]/.test(rawAttrs)) return whole;
1305
+ let changed = false;
1306
+ const attrs = rawAttrs.replace(
1307
+ /(\s+)([^\s"'=<>/]+)(\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g,
1308
+ (m, _sp, name, _eq, dq, sq, bare) => {
1309
+ const lower = name.toLowerCase();
1310
+ if (lower.startsWith("on") || lower === "srcdoc") {
1311
+ changed = true;
1312
+ return "";
1313
+ }
1314
+ if (URL_ATTRS.has(lower)) {
1315
+ const value = decodeForSchemeCheck(dq ?? sq ?? bare ?? "");
1316
+ if (/^(?:javascript|vbscript):|^data:text\/html/.test(value)) {
1317
+ changed = true;
1318
+ return ` ${name}="#"`;
1319
+ }
1320
+ }
1321
+ return m;
1322
+ }
1323
+ );
1324
+ return changed ? `<${tag}${attrs}>` : whole;
883
1325
  }
884
1326
  );
885
- const linkPlaceholders = [];
886
- let linkIndex = 0;
887
- html = html.replace(
888
- /\[([^\]]+)\]\(([^)]+)\)/g,
889
- (_match, linkText, url) => {
890
- const placeholder = `\u03A9LINK\u03A9${linkIndex}\u03A9LINK\u03A9`;
891
- linkPlaceholders.push({
892
- placeholder,
893
- html: `<a class="matrx-link" href="${url}">${linkText}</a>`
1327
+ }
1328
+ function safeUrl(url) {
1329
+ const u = url.trim();
1330
+ if (/^(?:javascript|vbscript):|^data:text\/html/.test(decodeForSchemeCheck(u))) return "#";
1331
+ return u.replace(/"/g, "%22");
1332
+ }
1333
+ function convertEmphasis(html, g) {
1334
+ const strong = `<strong${cls(g.strong)}>`;
1335
+ const em = `<em${cls(g.em)}>`;
1336
+ return html.replace(/\*\*\*(?!\s)(.+?)(?<!\s)\*\*\*/g, `${strong}${em}$1</em></strong>`).replace(/\*\*(?!\s)(.+?)(?<!\s)\*\*/g, `${strong}$1</strong>`).replace(/(?<![\w*])\*(?![\s*])(.+?)(?<![\s*])\*(?![\w*])/g, `${em}$1</em>`).replace(/(?<![\w_])___(?!\s)(.+?)(?<!\s)___(?![\w_])/g, `${strong}${em}$1</em></strong>`).replace(/(?<![\w_])__(?!\s)(.+?)(?<!\s)__(?![\w_])/g, `${strong}$1</strong>`).replace(/(?<![\w_])_(?![\s_])(.+?)(?<![\s_])_(?![\w_])/g, `${em}$1</em>`).replace(/~~(?!\s)(.+?)(?<!\s)~~/g, `<del${cls(g.del)}>$1</del>`);
1337
+ }
1338
+ var LINK_URL = String.raw`((?:[^()\s]|\([^()\s]*\))+)(?:\s+"[^"]*")?`;
1339
+ var IMAGE_RE = new RegExp(String.raw`!\[([^\]]*)\]\(` + LINK_URL + String.raw`\)`, "g");
1340
+ var LINK_RE = new RegExp(String.raw`\[([^\]]+)\]\(` + LINK_URL + String.raw`\)`, "g");
1341
+ function convertRules(html, g) {
1342
+ return html.replace(/^\s{0,3}#\s*={3,}\s*$/gm, `<hr${cls(g.hr, "matrx-hr-heavy")}>`).replace(/^\s{0,3}\*(?:\s*\*){2,}\s*$/gm, `<hr${cls(g.hr, "matrx-hr-accent")}>`).replace(/^\s{0,3}(?:-\s*){3,}$/gm, `<hr${cls(g.hr)}>`).replace(/^\s{0,3}(?:_\s*){3,}$/gm, `<hr${cls(g.hr)}>`);
1343
+ }
1344
+ function splitTableRow(row) {
1345
+ let r = row.trim();
1346
+ if (r.startsWith("|")) r = r.slice(1);
1347
+ if (r.endsWith("|") && !r.endsWith("\\|")) r = r.slice(0, -1);
1348
+ return r.split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
1349
+ }
1350
+ function cellAlign(separator) {
1351
+ const s = separator.trim();
1352
+ const left = s.startsWith(":");
1353
+ const right = s.endsWith(":");
1354
+ if (left && right) return ' style="text-align:center"';
1355
+ if (right) return ' style="text-align:right"';
1356
+ return "";
1357
+ }
1358
+ function convertTables(html, g) {
1359
+ const tableRegex = /^(\|.*\|)\s*\n(\|[-\s:|]*\|)\s*\n((?:\|.*\|\s*\n?)*)/gm;
1360
+ return html.replace(
1361
+ tableRegex,
1362
+ (_m, headerRow, separatorRow, bodyRows) => {
1363
+ const headers = splitTableRow(headerRow);
1364
+ const aligns = splitTableRow(separatorRow).map(cellAlign);
1365
+ const rows = bodyRows.trim().split("\n").filter((r) => r.trim()).map(splitTableRow);
1366
+ let t = `<table${cls(g.table)}>
1367
+ <thead${cls(g.thead)}>
1368
+ <tr${cls(g.tr)}>
1369
+ `;
1370
+ headers.forEach((h, i) => {
1371
+ t += `<th${cls(g.th)}${aligns[i] ?? ""}>${h}</th>
1372
+ `;
894
1373
  });
895
- linkIndex++;
896
- return placeholder;
1374
+ t += "</tr>\n</thead>\n";
1375
+ if (rows.length > 0) {
1376
+ t += `<tbody${cls(g.tbody)}>
1377
+ `;
1378
+ for (const row of rows) {
1379
+ t += `<tr${cls(g.tr)}>
1380
+ `;
1381
+ row.forEach((c, i) => {
1382
+ t += `<td${cls(g.td)}${aligns[i] ?? ""}>${c}</td>
1383
+ `;
1384
+ });
1385
+ t += "</tr>\n";
1386
+ }
1387
+ t += "</tbody>\n";
1388
+ }
1389
+ return `${t}</table>
1390
+ `;
897
1391
  }
898
1392
  );
899
- html = html.replace(/^# (.+)$/gm, '<h1 class="matrx-h1">$1</h1>').replace(/^## (.+)$/gm, '<h2 class="matrx-h2">$1</h2>').replace(/^### (.+)$/gm, '<h3 class="matrx-h3">$1</h3>').replace(/^#### (.+)$/gm, '<h4 class="matrx-h4">$1</h4>').replace(/^##### (.+)$/gm, '<h5 class="matrx-h5">$1</h5>').replace(/^###### (.+)$/gm, '<h6 class="matrx-h6">$1</h6>');
900
- html = html.replace(/\*\*(.+?)\*\*/g, '<strong class="matrx-strong">$1</strong>').replace(/\*(.+?)\*/g, '<em class="matrx-em">$1</em>').replace(/__(.+?)__/g, '<strong class="matrx-strong">$1</strong>').replace(/_(.+?)_/g, '<em class="matrx-em">$1</em>');
1393
+ }
1394
+ function convertLists(html, g) {
901
1395
  const lines = html.split("\n");
902
- let processedHtml = "";
1396
+ let processed = "";
903
1397
  const listStack = [];
904
1398
  let lastListItem = "";
1399
+ const li = `<li${cls(g.li)}>`;
905
1400
  const top = () => listStack[listStack.length - 1];
906
- const closeDeeperThan = (indent) => {
907
- while (listStack.length > 0 && top().indent > indent) {
908
- if (lastListItem) {
909
- processedHtml += "</li>\n";
910
- lastListItem = "";
911
- }
912
- const closing = listStack.pop();
913
- if (!closing) break;
914
- processedHtml += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
915
- if (listStack.length > 0) processedHtml += "</li>\n";
1401
+ const openTag = (type, nested) => type === "ol" ? `<ol${cls(nested ? g.olNested : g.ol)}>
1402
+ ` : `<ul${cls(nested ? g.ulNested : g.ul)}>
1403
+ `;
1404
+ const popOne = () => {
1405
+ if (lastListItem) {
1406
+ processed += "</li>\n";
1407
+ lastListItem = "";
916
1408
  }
1409
+ const closing = listStack.pop();
1410
+ if (!closing) return;
1411
+ processed += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
1412
+ if (listStack.length > 0) processed += "</li>\n";
1413
+ };
1414
+ const closeDeeperThan = (indent) => {
1415
+ while (listStack.length > 0 && top().indent > indent) popOne();
917
1416
  };
918
1417
  for (const line of lines) {
919
- const numberedMatch = line.match(/^(\s*)(\d+)\.\s+(.+)$/);
920
- if (numberedMatch) {
921
- const indent = (numberedMatch[1] ?? "").length;
922
- const content = numberedMatch[3] ?? "";
1418
+ const numbered = line.match(/^(\s*)(\d+)[.)]\s+(.+)$/);
1419
+ const bullet = numbered ? null : line.match(/^(\s*)[*\-+]\s+(.+)$/);
1420
+ if (numbered || bullet) {
1421
+ const type = numbered ? "ol" : "ul";
1422
+ const indent = (numbered ?? bullet)[1]?.length ?? 0;
1423
+ const content = (numbered ? numbered[3] : bullet[2]) ?? "";
923
1424
  const current = top();
924
1425
  if (current && indent > current.indent) {
925
- processedHtml += '\n<ol class="matrx-list matrx-numbered-list matrx-nested-list">\n';
926
- listStack.push({ type: "ol", indent });
927
- processedHtml += `<li class="matrx-list-item">${content}`;
928
- lastListItem = "ol";
1426
+ processed += `
1427
+ ${openTag(type, true)}`;
1428
+ listStack.push({ type, indent });
929
1429
  } else {
930
1430
  closeDeeperThan(indent);
931
- if (lastListItem && top()?.indent === indent) processedHtml += "</li>\n";
1431
+ if (lastListItem && top()?.indent === indent) processed += "</li>\n";
932
1432
  const now = top();
933
- if (!now || now.indent !== indent || now.type !== "ol") {
934
- processedHtml += '<ol class="matrx-list matrx-numbered-list">\n';
935
- listStack.push({ type: "ol", indent });
1433
+ if (now && now.indent === indent && now.type !== type) {
1434
+ const closing = listStack.pop();
1435
+ processed += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
936
1436
  }
937
- processedHtml += `<li class="matrx-list-item">${content}`;
938
- lastListItem = "ol";
939
- }
940
- continue;
941
- }
942
- const bulletMatch = line.match(/^(\s*)[*\-+]\s+(.+)$/);
943
- if (bulletMatch) {
944
- const indent = (bulletMatch[1] ?? "").length;
945
- const content = bulletMatch[2] ?? "";
946
- const current = top();
947
- if (current && indent > current.indent) {
948
- processedHtml += '\n<ul class="matrx-list matrx-bullet-list matrx-nested-list">\n';
949
- listStack.push({ type: "ul", indent });
950
- processedHtml += `<li class="matrx-list-item">${content}`;
951
- lastListItem = "ul";
952
- } else {
953
- closeDeeperThan(indent);
954
- if (lastListItem && top()?.indent === indent) processedHtml += "</li>\n";
955
- const now = top();
956
- if (!now || now.indent !== indent || now.type !== "ul") {
957
- processedHtml += '<ul class="matrx-list matrx-bullet-list">\n';
958
- listStack.push({ type: "ul", indent });
1437
+ const after = top();
1438
+ if (!after || after.indent !== indent || after.type !== type) {
1439
+ processed += openTag(type, listStack.length > 0);
1440
+ listStack.push({ type, indent });
959
1441
  }
960
- processedHtml += `<li class="matrx-list-item">${content}`;
961
- lastListItem = "ul";
962
1442
  }
1443
+ processed += `${li}${content}`;
1444
+ lastListItem = type;
963
1445
  continue;
964
1446
  }
965
1447
  if (line.trim() !== "") {
966
- while (listStack.length > 0) {
967
- if (lastListItem) {
968
- processedHtml += "</li>\n";
969
- lastListItem = "";
970
- }
971
- const closing = listStack.pop();
972
- if (!closing) break;
973
- processedHtml += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
974
- if (listStack.length > 0) processedHtml += "</li>\n";
975
- }
1448
+ while (listStack.length > 0) popOne();
976
1449
  }
977
- processedHtml += `${line}
1450
+ processed += `${line}
978
1451
  `;
979
1452
  }
980
- while (listStack.length > 0) {
981
- if (lastListItem) {
982
- processedHtml += "</li>\n";
983
- lastListItem = "";
984
- }
985
- const closing = listStack.pop();
986
- if (!closing) break;
987
- processedHtml += closing.type === "ol" ? "</ol>\n" : "</ul>\n";
988
- if (listStack.length > 0) processedHtml += "</li>\n";
1453
+ while (listStack.length > 0) popOne();
1454
+ return processed.replace(
1455
+ /<li( class="([^"]*)")?>\s*\[([ xX])\]\s+/g,
1456
+ (_m, _c, classes, mark) => `<li${cls(classes ?? "", "matrx-task-item")}><span class="matrx-task-box${mark === " " ? "" : " is-checked"}" aria-hidden="true"></span>`
1457
+ );
1458
+ }
1459
+ function convertBody(skin, markdown, ctx) {
1460
+ return skin === "article" ? articleBody(markdown, ctx) : documentBody(markdown, ctx);
1461
+ }
1462
+ function scrubTokens(markdown) {
1463
+ return markdown.replace(/[\uE000\uE001]/g, "");
1464
+ }
1465
+ function newContext(options) {
1466
+ return { options, depth: 0, cardIndex: 0, strippedAnnounced: false };
1467
+ }
1468
+ function markdownToHtml(markdown, options = {}) {
1469
+ if (!markdown) {
1470
+ options.onNotice?.({
1471
+ code: "empty-output",
1472
+ message: "markdownToHtml received an empty string.",
1473
+ remedy: "Check the content is loaded before converting; nothing was rendered."
1474
+ });
1475
+ return "";
989
1476
  }
990
- html = processedHtml;
991
- html = html.replace(/^> (.+)$/gm, '<blockquote class="matrx-blockquote">$1</blockquote>');
1477
+ const source = scrubTokens(options.includeThinking ? markdown : removeThinkingContent(markdown));
1478
+ return `<div class="matrx-content-container">${documentBody(source, newContext(options))}</div>`;
1479
+ }
1480
+ function documentBody(markdown, ctx) {
1481
+ const g = DOCUMENT_GRAMMAR;
1482
+ const stash = new Stash();
1483
+ let html = protectRegions(markdown, g, stash, ctx);
1484
+ html = convertRules(html, g);
992
1485
  html = html.replace(
993
- /```([^`]+)```/gs,
994
- '<pre class="matrx-code-block"><code class="matrx-code">$1</code></pre>'
1486
+ IMAGE_RE,
1487
+ (_m, alt, url) => stash.block(`<img class="matrx-image" src="${safeUrl(url)}" alt="${escapeHtml2(alt)}" />`)
995
1488
  );
996
- html = html.replace(/`([^`]+)`/g, '<code class="matrx-inline-code">$1</code>');
997
- html = convertMarkdownTables(html);
998
- html = html.replace(/<table>/g, '<table class="matrx-table">').replace(/<thead>/g, '<thead class="matrx-table-head">').replace(/<tbody>/g, '<tbody class="matrx-table-body">').replace(/<tr>/g, '<tr class="matrx-table-row">').replace(/<th>/g, '<th class="matrx-table-header">').replace(/<td>/g, '<td class="matrx-table-cell">');
999
- html = html.replace(/<img([^>]*)>/g, '<img class="matrx-image"$1>');
1000
- html = html.replace(/<div(?!\s+class="matrx-)([^>]*)>/g, '<div class="matrx-div"$1>');
1001
- html = html.replace(/<span([^>]*)>/g, '<span class="matrx-span"$1>');
1002
- html = html.replace(/^([^<\n].+)$/gm, '<p class="matrx-paragraph">$1</p>');
1003
1489
  html = html.replace(
1004
- /<\/p>\s*<p class="matrx-paragraph">/g,
1005
- '</p><p class="matrx-paragraph">'
1490
+ LINK_RE,
1491
+ (_m, text, url) => stash.inline(`<a class="matrx-link" href="${safeUrl(url)}">${convertEmphasis(text, g)}</a>`)
1006
1492
  );
1493
+ html = html.replace(/^# (.+)$/gm, '<h1 class="matrx-h1">$1</h1>').replace(/^## (.+)$/gm, '<h2 class="matrx-h2">$1</h2>').replace(/^### (.+)$/gm, '<h3 class="matrx-h3">$1</h3>').replace(/^#### (.+)$/gm, '<h4 class="matrx-h4">$1</h4>').replace(/^##### (.+)$/gm, '<h5 class="matrx-h5">$1</h5>').replace(/^###### (.+)$/gm, '<h6 class="matrx-h6">$1</h6>');
1494
+ html = convertLists(html, g);
1495
+ html = convertEmphasis(html, g);
1496
+ html = html.replace(/^> ?(.+)$/gm, '<blockquote class="matrx-blockquote">$1</blockquote>');
1497
+ html = convertTables(html, g);
1498
+ html = html.replace(/<table>/g, '<table class="matrx-table">').replace(/<thead>/g, '<thead class="matrx-table-head">').replace(/<tbody>/g, '<tbody class="matrx-table-body">').replace(/<tr>/g, '<tr class="matrx-table-row">').replace(/<th>/g, '<th class="matrx-table-header">').replace(/<td>/g, '<td class="matrx-table-cell">');
1499
+ html = html.replace(/<img(?![^>]*class=)([^>]*)>/g, '<img class="matrx-image"$1>');
1500
+ html = html.replace(/<div\b([^>]*)>/g, (m, attrs) => {
1501
+ if (/\bclass="matrx-/.test(attrs)) return m;
1502
+ if (/\bclass="/.test(attrs)) return `<div${attrs.replace(/\bclass="/, 'class="matrx-div ')}>`;
1503
+ return `<div class="matrx-div"${attrs}>`;
1504
+ });
1505
+ html = html.replace(/<span(?![^>]*class=)([^>]*)>/g, '<span class="matrx-span"$1>');
1506
+ html = html.replace(/^([^<\n].+)$/gm, '<p class="matrx-paragraph">$1</p>');
1507
+ html = html.replace(/<\/p>\s*<p class="matrx-paragraph">/g, '</p><p class="matrx-paragraph">');
1007
1508
  html = html.replace(
1008
- /(<h1 class="matrx-h1">[\s\S]*?<\/h1>\s*)<p class="matrx-paragraph">([\s\S]*?)<\/p>/g,
1509
+ /(<h1 class="matrx-h1">[\s\S]*?<\/h1>\s*)<p class="matrx-paragraph">((?:(?!\uE000B)[\s\S])*?)<\/p>/g,
1009
1510
  '$1<p class="matrx-intro">$2</p>'
1010
1511
  );
1011
1512
  html = html.replace(
@@ -1032,42 +1533,7 @@ function markdownToHtml(markdown, options = {}) {
1032
1533
  /(<div class="matrx-faq-answer">)<p class="matrx-paragraph">([\s\S]*?)<\/p>(<\/div>)/g,
1033
1534
  "$1$2$3"
1034
1535
  );
1035
- for (const { placeholder, html: imageHtml } of imagePlaceholders) {
1036
- if (html.includes(placeholder)) html = html.replaceAll(placeholder, imageHtml);
1037
- }
1038
- html = html.replace(/<p class="matrx-paragraph">\s*(<img[^>]*>)\s*<\/p>/g, "$1");
1039
- for (const { placeholder, html: linkHtml } of linkPlaceholders) {
1040
- if (html.includes(placeholder)) html = html.replaceAll(placeholder, linkHtml);
1041
- }
1042
- for (const { placeholder, html: cardHtml } of flashcardPlaceholders) {
1043
- if (html.includes(placeholder)) html = html.replaceAll(placeholder, cardHtml);
1044
- }
1045
- return startWrapper + html + endWrapper;
1046
- }
1047
- function convertArticleTables(html) {
1048
- const tableRegex = /^(\|.*\|)\s*\n(\|[-\s:|]*\|)\s*\n((?:\|.*\|\s*\n?)*)/gm;
1049
- return html.replace(
1050
- tableRegex,
1051
- (_match, headerRow, _sep, bodyRows) => {
1052
- const headers = headerRow.split("|").map((c) => c.trim()).filter((c) => c !== "");
1053
- const rows = bodyRows.trim().split("\n").filter((r) => r.trim()).map(
1054
- (r) => r.split("|").map((c) => c.trim()).filter((c) => c !== "")
1055
- );
1056
- let t = '<table class="print-table">\n';
1057
- if (headers.length) {
1058
- t += `<thead><tr>${headers.map((h) => `<th>${h}</th>`).join("")}</tr></thead>
1059
- `;
1060
- }
1061
- if (rows.length) {
1062
- t += `<tbody>${rows.map(
1063
- (r) => r.length ? `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>` : ""
1064
- ).join("\n")}</tbody>
1065
- `;
1066
- }
1067
- return `${t}</table>
1068
- `;
1069
- }
1070
- );
1536
+ return stash.restore(html);
1071
1537
  }
1072
1538
  function markdownToArticleHtml(markdown, options = {}) {
1073
1539
  if (!markdown) {
@@ -1078,117 +1544,38 @@ function markdownToArticleHtml(markdown, options = {}) {
1078
1544
  });
1079
1545
  return "";
1080
1546
  }
1081
- let html = options.includeThinking ? markdown : removeThinkingContent(markdown);
1082
- html = convertArticleTables(html);
1083
- const codeBlockPlaceholders = [];
1084
- let codeIdx = 0;
1547
+ const source = scrubTokens(options.includeThinking ? markdown : removeThinkingContent(markdown));
1548
+ return articleBody(source, newContext(options));
1549
+ }
1550
+ function articleBody(markdown, ctx) {
1551
+ const g = ARTICLE_GRAMMAR;
1552
+ const stash = new Stash();
1553
+ let html = protectRegions(markdown, g, stash, ctx);
1554
+ html = convertTables(html, g);
1555
+ html = convertRules(html, g);
1085
1556
  html = html.replace(
1086
- /```(\w*)\n?([\s\S]*?)```/g,
1087
- (_m, lang, code) => {
1088
- const ph = `\u03A9CODEBLOCK\u03A9${codeIdx}\u03A9CODEBLOCK\u03A9`;
1089
- const langLabel = lang ? `<span class="code-lang">${lang}</span>` : "";
1090
- codeBlockPlaceholders.push({
1091
- placeholder: ph,
1092
- html: `<div class="code-block-wrapper">${langLabel}<pre class="code-block"><code>${escapeHtml2(
1093
- code.trim()
1094
- )}</code></pre></div>`
1095
- });
1096
- codeIdx++;
1097
- return ph;
1098
- }
1557
+ IMAGE_RE,
1558
+ (_m, alt, url) => stash.block(
1559
+ `<figure class="print-figure"><img class="print-image" src="${safeUrl(url)}" alt="${escapeHtml2(alt)}" />${alt ? `<figcaption>${escapeHtml2(alt)}</figcaption>` : ""}</figure>`
1560
+ )
1099
1561
  );
1100
- const imagePlaceholders = [];
1101
- let imageIdx = 0;
1102
1562
  html = html.replace(
1103
- /!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g,
1104
- (_m, alt, url) => {
1105
- const ph = `\u03A9IMAGE\u03A9${imageIdx}\u03A9IMAGE\u03A9`;
1106
- imagePlaceholders.push({
1107
- placeholder: ph,
1108
- html: `<figure class="print-figure"><img class="print-image" src="${url}" alt="${escapeHtml2(alt)}" />${alt ? `<figcaption>${escapeHtml2(alt)}</figcaption>` : ""}</figure>`
1109
- });
1110
- imageIdx++;
1111
- return ph;
1112
- }
1113
- );
1114
- const linkPlaceholders = [];
1115
- let linkIdx = 0;
1116
- html = html.replace(
1117
- /\[([^\]]+)\]\(([^)]+)\)/g,
1118
- (_m, text, url) => {
1119
- const ph = `\u03A9LINK\u03A9${linkIdx}\u03A9LINK\u03A9`;
1120
- linkPlaceholders.push({ placeholder: ph, html: `<a href="${url}">${text}</a>` });
1121
- linkIdx++;
1122
- return ph;
1123
- }
1563
+ LINK_RE,
1564
+ (_m, text, url) => stash.inline(`<a href="${safeUrl(url)}">${convertEmphasis(text, g)}</a>`)
1124
1565
  );
1125
1566
  html = html.replace(/^#{6}\s+(.+)$/gm, "<h6>$1</h6>").replace(/^#{5}\s+(.+)$/gm, "<h5>$1</h5>").replace(/^#{4}\s+(.+)$/gm, "<h4>$1</h4>").replace(/^#{3}\s+(.+)$/gm, "<h3>$1</h3>").replace(/^#{2}\s+(.+)$/gm, "<h2>$1</h2>").replace(/^#{1}\s+(.+)$/gm, "<h1>$1</h1>");
1126
- html = html.replace(/^> (.+)$/gm, "<blockquote>$1</blockquote>");
1127
- html = html.replace(/^[-*_]{3,}$/gm, "<hr>");
1128
- html = html.replace(/\*\*\*(.+?)\*\*\*/g, "<strong><em>$1</em></strong>").replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>").replace(/\*(.+?)\*/g, "<em>$1</em>").replace(/___(.+?)___/g, "<strong><em>$1</em></strong>").replace(/__(.+?)__/g, "<strong>$1</strong>").replace(/_([^_\s][^_]*)_/g, "<em>$1</em>");
1129
- html = html.replace(/`([^`]+)`/g, '<code class="inline-code">$1</code>');
1130
- const lines = html.split("\n");
1131
- const result = [];
1132
- let inUl = false;
1133
- let inOl = false;
1134
- for (const line of lines) {
1135
- const ulMatch = line.match(/^(\s*)[-*+]\s+(.+)$/);
1136
- const olMatch = line.match(/^(\s*)\d+\.\s+(.+)$/);
1137
- if (ulMatch) {
1138
- if (inOl) {
1139
- result.push("</ol>");
1140
- inOl = false;
1141
- }
1142
- if (!inUl) {
1143
- result.push("<ul>");
1144
- inUl = true;
1145
- }
1146
- result.push(`<li>${ulMatch[2] ?? ""}</li>`);
1147
- } else if (olMatch) {
1148
- if (inUl) {
1149
- result.push("</ul>");
1150
- inUl = false;
1151
- }
1152
- if (!inOl) {
1153
- result.push("<ol>");
1154
- inOl = true;
1155
- }
1156
- result.push(`<li>${olMatch[2] ?? ""}</li>`);
1157
- } else {
1158
- if (inUl) {
1159
- result.push("</ul>");
1160
- inUl = false;
1161
- }
1162
- if (inOl) {
1163
- result.push("</ol>");
1164
- inOl = false;
1165
- }
1166
- result.push(line);
1167
- }
1168
- }
1169
- if (inUl) result.push("</ul>");
1170
- if (inOl) result.push("</ol>");
1171
- html = result.join("\n");
1567
+ html = html.replace(/^> ?(.+)$/gm, "<blockquote>$1</blockquote>");
1568
+ html = convertLists(html, g);
1569
+ html = convertEmphasis(html, g);
1172
1570
  html = html.split("\n").map((line) => {
1173
1571
  const t = line.trim();
1174
1572
  if (!t) return "";
1175
- if (/^<\/?(h[1-6]|ul|ol|li|blockquote|pre|hr|table|thead|tbody|tr|th|td|div|figure)/.test(t) || /^Ω(CODEBLOCK|IMAGE)Ω/.test(t)) {
1573
+ if (/^<\/?(h[1-6]|ul|ol|li|blockquote|pre|hr|table|thead|tbody|tr|th|td|div|figure|section)/.test(t) || /^\uE000B\d+\uE001$/.test(t)) {
1176
1574
  return line;
1177
1575
  }
1178
1576
  return `<p>${t}</p>`;
1179
1577
  }).join("\n");
1180
- for (const { placeholder, html: ph } of codeBlockPlaceholders) {
1181
- html = html.replace(`<p>${placeholder}</p>`, ph);
1182
- html = html.replace(placeholder, ph);
1183
- }
1184
- for (const { placeholder, html: ph } of imagePlaceholders) {
1185
- html = html.replaceAll(`<p>${placeholder}</p>`, ph);
1186
- html = html.replaceAll(placeholder, ph);
1187
- }
1188
- for (const { placeholder, html: ph } of linkPlaceholders) {
1189
- html = html.replaceAll(placeholder, ph);
1190
- }
1191
- return html;
1578
+ return stash.restore(html).replace(/\n{3,}/g, "\n\n").trim();
1192
1579
  }
1193
1580
  var PRINT_ACTIONS_CSS = `
1194
1581
  .print-actions { display: flex; gap: 10px; margin: 0 auto 28px; max-width: 800px; padding: 0 2rem 20px; border-bottom: 2px solid var(--matrx-print-border, #e1e1e1); }
@@ -1202,7 +1589,8 @@ function getMarkdownStylesheet(options = {}) {
1202
1589
  const base = skin === "article" ? `${MARKDOWN_ARTICLE_TOKENS_CSS}
1203
1590
  ${MARKDOWN_ARTICLE_CSS}` : `${MARKDOWN_DOCUMENT_TOKENS_CSS}
1204
1591
  ${MARKDOWN_DOCUMENT_CSS}`;
1205
- return [base, options.tokens ?? "", options.extraCss ?? ""].filter((part) => part.trim().length > 0).join("\n");
1592
+ const page = options.pageNumbers === false ? MARKDOWN_PAGE_PLAIN_CSS : MARKDOWN_PAGE_CSS;
1593
+ return [base, MARKDOWN_SHARED_CSS, page, options.tokens ?? "", options.extraCss ?? ""].filter((part) => part.trim().length > 0).join("\n");
1206
1594
  }
1207
1595
  function markdownToHtmlForSkin(markdown, skin, options = {}) {
1208
1596
  return skin === "article" ? markdownToArticleHtml(markdown, options) : markdownToHtml(markdown, options);
@@ -1243,14 +1631,20 @@ export {
1243
1631
  MARKDOWN_ARTICLE_TOKENS_CSS,
1244
1632
  MARKDOWN_DOCUMENT_CSS,
1245
1633
  MARKDOWN_DOCUMENT_TOKENS_CSS,
1634
+ MARKDOWN_PAGE_CSS,
1635
+ MARKDOWN_SHARED_CSS,
1636
+ PAGE_BREAK_CLASS,
1637
+ PAGE_BREAK_MARKDOWN,
1246
1638
  PRINT_ACTIONS_CSS,
1247
1639
  getMarkdownStylesheet,
1248
1640
  hasThinkingContent,
1641
+ isPageBreakLine,
1249
1642
  markdownToArticleHtml,
1250
1643
  markdownToHtml,
1251
1644
  markdownToHtmlForSkin,
1252
1645
  printMarkdown,
1253
1646
  removeThinkingContent,
1254
- renderMarkdownDocument
1647
+ renderMarkdownDocument,
1648
+ splitAtPageBreaks
1255
1649
  };
1256
1650
  //# sourceMappingURL=markdown.js.map