@drghaliasri/butex 8.1.3 → 8.2.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/book.d.mts +1 -0
- package/dist/book.d.ts +1 -0
- package/dist/book.js +17 -1
- package/dist/book.js.map +1 -1
- package/dist/book.mjs +17 -1
- package/dist/book.mjs.map +1 -1
- package/dist/document-cli.js +16 -1
- package/dist/document-cli.js.map +1 -1
- package/dist/document.d.mts +1 -0
- package/dist/document.d.ts +1 -0
- package/dist/document.js +10 -2
- package/dist/document.js.map +1 -1
- package/dist/document.mjs +10 -2
- package/dist/document.mjs.map +1 -1
- package/dist/react-book.d.mts +12 -1
- package/dist/react-book.d.ts +12 -1
- package/dist/react-book.js +2632 -1917
- package/dist/react-book.js.map +1 -1
- package/dist/react-book.mjs +2475 -1760
- package/dist/react-book.mjs.map +1 -1
- package/dist/react-document-preview.d.mts +2 -1
- package/dist/react-document-preview.d.ts +2 -1
- package/dist/react-document-preview.js +16 -112
- package/dist/react-document-preview.js.map +1 -1
- package/dist/react-document-preview.mjs +16 -112
- package/dist/react-document-preview.mjs.map +1 -1
- package/dist/react-document.d.mts +5 -3
- package/dist/react-document.d.ts +5 -3
- package/dist/react-document.js +1818 -1455
- package/dist/react-document.js.map +1 -1
- package/dist/react-document.mjs +1709 -1346
- package/dist/react-document.mjs.map +1 -1
- package/dist/react.js +1274 -818
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +1232 -776
- package/dist/react.mjs.map +1 -1
- package/package.json +1 -1
package/dist/book.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/book/index.ts","../src/document/ids.ts","../src/editor/digits.ts","../src/document/articleMeta.ts","../src/document/citations.ts","../src/ast/commands/index.ts","../src/ast/arabic_ast.ts","../src/shared/math-document/mathObject.ts","../src/document/labels.ts","../src/document/inlineIdentity.ts","../src/document/inlineScanner.ts","../src/document/importJson.ts","../src/editor/accentCommands.ts","../src/editor/atomicCommands.ts","../src/editor/atomicCommandsOperators.ts","../src/editor/standardCommands.ts","../src/editor/factory.ts","../src/editor/characterFonts.ts","../src/editor/divideOperator.ts","../src/editor/rawOperatorPresentation.ts","../src/editor/indexSequence.ts","../src/editor/render.ts","../src/editor/state.ts","../src/editor/display/delimiter.ts","../src/editor/display/boxed.ts","../src/editor/display/frac.ts","../src/editor/display/sqrt.ts","../src/editor/display/overset.ts","../src/editor/display/underset.ts","../src/editor/display/accent.ts","../src/editor/display/env.ts","../src/diwani-font.ts","../src/editor/display/atomicCommand.ts","../src/editor/display/atomicCommandsOperators.ts","../src/editor/display/standardCommand.ts","../src/editor/styles.ts","../src/shared/math-document/normalizeCharImport.ts","../src/shared/math-document/mathEditorAdapter.ts","../src/document/mathBridge.ts","../src/document/keys.ts","../src/document/diff.ts","../src/document/introspection.ts","../src/document/arabicPreamble.ts","../src/document/exportLatex.ts","../src/book/utils.ts","../src/book/validation.ts","../src/book/jsonCommands.ts","../src/book/introspection.ts","../src/book/exportLatex.ts"],"sourcesContent":["export type * from './contracts.js';\nexport { BookContractError, normalizeBookSnapshot } from './validation.js';\nexport { applyBookCommand, parseBookCommand } from './jsonCommands.js';\nexport type { BookCommand } from './jsonCommands.js';\nexport {\n bookContextForUnit,\n bookOutline,\n getBookReferenceIndex,\n resolveBookSnapshot,\n validateBookSnapshot,\n} from './introspection.js';\nexport type {\n BookIssue, BookOutlineEntry, BookResolution, BookTarget,\n} from './introspection.js';\n\nexport { book2Latex } from './exportLatex.js';\nexport type { BookLatexBundle, BookLatexAsset, BookLatexOptions } from './exportLatex.js';\n","let nextId = 1;\nconst instanceId = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n\nexport function documentId(prefix: string): string {\n const id = `${prefix}_${instanceId}_${String(nextId)}`;\n nextId += 1;\n return id;\n}\n","import type { DigitFormId } from './types.js';\n\nconst WESTERN = '0123456789';\nconst ARABIC_INDIC = '٠١٢٣٤٥٦٧٨٩';\nconst PERSIAN_INDIC = '۰۱۲۳۴۵۶۷۸۹';\n\nconst digitSets: Record<DigitFormId, string> = {\n western: WESTERN,\n arabicIndic: ARABIC_INDIC,\n persianIndic: PERSIAN_INDIC,\n};\n\nfunction digitValue(char: string): number {\n const western = WESTERN.indexOf(char);\n if (western >= 0) {\n return western;\n }\n const arabicIndic = ARABIC_INDIC.indexOf(char);\n if (arabicIndic >= 0) {\n return arabicIndic;\n }\n return PERSIAN_INDIC.indexOf(char);\n}\n\nexport function formatDigits(value: string, digitForm: DigitFormId = 'western'): string {\n const target = digitSets[digitForm];\n return Array.from(value, (char) => {\n const value = digitValue(char);\n return value >= 0 ? target[value] : char;\n }).join('');\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport type { DocumentHijriDate, DocumentMeta, HijriMonthId } from './types.js';\n\nexport const BUTEX_BASMALA_LINE1 = 'بِسْمِ ٱللَّٰهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ';\n\nexport const BUTEX_BASMALA_LINE2 = 'وَٱلصَّلَاةُ وَٱلسَّلَامُ عَلَىٰ رَسُولِ ٱللَّٰهِ';\n\nexport const BUTEX_BASMALA_SALAWAT = 'صَلَّى ٱللَّهُ عَلَيْهِ وَسَلَّمَ';\n\n/** Three-line basmala joined for UI / plain-text matchers. */\nexport const BUTEX_BASMALA = `${BUTEX_BASMALA_LINE1}\\n${BUTEX_BASMALA_LINE2}\\n${BUTEX_BASMALA_SALAWAT}`;\n\nexport const BUTEX_CLOSING_HAMDALA = 'الْحَمْدُ لِلَّهِ نَفَعَنَا بِعِلْمِهِ';\n\nfunction escapeButexTextArg(text: string): string {\n return text.replace(/\\\\/g, '\\\\textbackslash{}').replace(/[{}]/g, '\\\\$&');\n}\n\nfunction butexFontDisplayTex(macro: '\\\\butexdiwani' | '\\\\butexmaghribi', text: string): string {\n return `${macro}{${escapeButexTextArg(text)}}`;\n}\n\n/** Display-math body using BuTeX Diwani (for MathJax preview islands). */\nexport function butexDiwaniDisplayTex(text: string): string {\n return butexFontDisplayTex('\\\\butexdiwani', text);\n}\n\n/** Full display equation for XeLaTeX export. */\nexport function butexDiwaniDisplayLatex(text: string): string {\n return `\\\\[\\n${butexDiwaniDisplayTex(text)}\\n\\\\]`;\n}\n\n/** Display-math body using BuTeX Maghribi (for document chrome). */\nexport function butexMaghribiDisplayTex(text: string): string {\n return butexFontDisplayTex('\\\\butexmaghribi', text);\n}\n\n/** Full display equation using BuTeX Maghribi for XeLaTeX export. */\nexport function butexMaghribiDisplayLatex(text: string): string {\n return `\\\\[\\n${butexMaghribiDisplayTex(text)}\\n\\\\]`;\n}\n\nconst BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT] as const;\n\n/** Three-line Maghribi body for MathJax basmala islands. */\nexport function butexBasmalaDisplayTex(): string {\n return BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(' \\\\\\\\ ');\n}\n\n/** Standalone display equation when there is no \\\\maketitle (title-less docs). */\nexport function butexBasmalaDisplayLatex(): string {\n return `\\\\[\\n\\\\begin{gathered}\\n${BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(' \\\\\\\\\\n')}\\n\\\\end{gathered}\\n\\\\]`;\n}\n\n/**\n * Keep \\\\maketitle inside the current column when twocolumn is on.\n * Standard article otherwise does \\\\twocolumn[\\\\@maketitle] and spans both columns.\n * Call after titling so \\\\@maketitle still includes \\\\pretitle hooks.\n */\nexport function butexInColumnMaketitleHook(): string {\n return String.raw`\\makeatletter\n\\renewcommand{\\maketitle}{%\n \\par\n \\begingroup\n \\renewcommand\\thefootnote{\\@fnsymbol\\c@footnote}%\n \\def\\@makefnmark{\\rlap{\\@textsuperscript{\\normalfont\\@thefnmark}}}%\n \\long\\def\\@makefntext##1{\\parindent 1em\\noindent\n \\hb@xt@1.8em{\\hss\\@textsuperscript{\\normalfont\\@thefnmark}}##1}%\n \\@maketitle\n \\thispagestyle{plain}\\@thanks\n \\endgroup\n \\setcounter{footnote}{0}%\n \\global\\let\\thanks\\relax\n \\global\\let\\maketitle\\relax\n \\global\\let\\@maketitle\\relax\n \\global\\let\\@thanks\\@empty\n \\global\\let\\@author\\@empty\n \\global\\let\\@date\\@empty\n \\global\\let\\@title\\@empty\n \\global\\let\\title\\relax\n \\global\\let\\author\\relax\n \\global\\let\\date\\relax\n \\global\\let\\and\\relax\n}\n\\makeatother`;\n}\n\n/** Titling hooks so the basmala stays attached to the visible title. */\nexport function butexBasmalaTitlingPreamble(options: { twocolumn?: boolean } = {}): string {\n const lines = [\n '\\\\usepackage{titling}',\n '\\\\pretitle{%',\n ' \\\\begin{center}',\n ...BASMALA_LINES.map((line, index) => {\n const suffix = index < BASMALA_LINES.length - 1 ? '\\\\\\\\' : '';\n return ` ${butexMaghribiDisplayTex(line)}${suffix}`;\n }),\n ' \\\\par\\\\vspace{1.5em}',\n ' \\\\LARGE',\n '}',\n '\\\\posttitle{\\\\par\\\\end{center}}',\n ];\n if (options.twocolumn) {\n lines.push(butexInColumnMaketitleHook());\n }\n return lines.join('\\n');\n}\nexport const HIJRI_YEAR_MIN = 1400;\nexport const HIJRI_YEAR_MAX = 1500;\n\nexport const HIJRI_MONTH_IDS: HijriMonthId[] = [\n 'محرم',\n 'صفر',\n 'ربيع الأول',\n 'ربيع الآخر',\n 'جمادى الأولى',\n 'جمادى الآخرة',\n 'رجب',\n 'شعبان',\n 'رمضان',\n 'شوال',\n 'ذو القعدة',\n 'ذو الحجة',\n];\n\nconst HIJRI_MONTH_LABELS_EN: Record<HijriMonthId, string> = {\n محرم: 'Muharram',\n صفر: 'Safar',\n 'ربيع الأول': 'Rabiʻ I',\n 'ربيع الآخر': 'Rabiʻ II',\n 'جمادى الأولى': 'Jumada I',\n 'جمادى الآخرة': 'Jumada II',\n رجب: 'Rajab',\n شعبان: 'Shaʻban',\n رمضان: 'Ramadan',\n شوال: 'Shawwal',\n 'ذو القعدة': 'Dhul Qaʻdah',\n 'ذو الحجة': 'Dhul Hijjah',\n};\n\n/** Legacy Latin month ids from earlier drafts — accepted on import only. */\nconst LEGACY_LATIN_MONTH: Record<string, HijriMonthId> = {\n muharram: 'محرم',\n safar: 'صفر',\n rabiAwwal: 'ربيع الأول',\n rabiThani: 'ربيع الآخر',\n jumadaAwwal: 'جمادى الأولى',\n jumadaThani: 'جمادى الآخرة',\n rajab: 'رجب',\n shaban: 'شعبان',\n ramadan: 'رمضان',\n shawwal: 'شوال',\n dhulQadah: 'ذو القعدة',\n dhulHijjah: 'ذو الحجة',\n};\n\nexport const DEFAULT_HIJRI_DATE: DocumentHijriDate = {\n day: 1,\n month: 'محرم',\n year: 1448,\n};\n\nexport function hijriMonthLabel(month: HijriMonthId, locale: ButexUiLocale = 'ar'): string {\n return locale === 'en' ? HIJRI_MONTH_LABELS_EN[month] : month;\n}\n\nexport function emptyDocumentMeta(): DocumentMeta {\n return {\n title: '',\n authors: '',\n date: { ...DEFAULT_HIJRI_DATE },\n abstract: '',\n };\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) {\n return min;\n }\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\nfunction isHijriMonthId(value: unknown): value is HijriMonthId {\n return typeof value === 'string' && (HIJRI_MONTH_IDS as string[]).includes(value);\n}\n\nfunction resolveHijriMonthId(value: unknown): HijriMonthId {\n if (isHijriMonthId(value)) {\n return value;\n }\n if (typeof value === 'string' && value in LEGACY_LATIN_MONTH) {\n return LEGACY_LATIN_MONTH[value]!;\n }\n return DEFAULT_HIJRI_DATE.month;\n}\n\nexport function normalizeDocumentHijriDate(value: unknown): DocumentHijriDate {\n if (typeof value !== 'object' || value === null) {\n return { ...DEFAULT_HIJRI_DATE };\n }\n const raw = value as Record<string, unknown>;\n const day = clampInt(typeof raw.day === 'number' ? raw.day : Number(raw.day), 1, 30);\n const year = clampInt(typeof raw.year === 'number' ? raw.year : Number(raw.year), HIJRI_YEAR_MIN, HIJRI_YEAR_MAX);\n const month = resolveHijriMonthId(raw.month);\n return { day, month, year };\n}\n\nexport function normalizeDocumentMeta(value: unknown): DocumentMeta {\n if (typeof value !== 'object' || value === null) {\n return emptyDocumentMeta();\n }\n const raw = value as Record<string, unknown>;\n return {\n title: typeof raw.title === 'string' ? raw.title : '',\n authors: typeof raw.authors === 'string' ? raw.authors : '',\n date: normalizeDocumentHijriDate(raw.date),\n abstract: typeof raw.abstract === 'string' ? raw.abstract : '',\n };\n}\n\nexport type DocumentMetaProp = Partial<Omit<DocumentMeta, 'date'>> & {\n date?: Partial<DocumentHijriDate>;\n};\n\n/** Prop fills gaps; JSON wins only when the key is present on the JSON object. */\nexport function mergeDocumentMeta(fromJson: unknown, fromProp?: DocumentMetaProp): DocumentMeta {\n const fromPropMeta: DocumentMeta = {\n title: typeof fromProp?.title === 'string' ? fromProp.title : '',\n authors: typeof fromProp?.authors === 'string' ? fromProp.authors : '',\n abstract: typeof fromProp?.abstract === 'string' ? fromProp.abstract : '',\n date: fromProp?.date\n ? normalizeDocumentHijriDate({ ...DEFAULT_HIJRI_DATE, ...fromProp.date })\n : { ...DEFAULT_HIJRI_DATE },\n };\n if (typeof fromJson !== 'object' || fromJson === null) {\n return fromPropMeta;\n }\n const json = fromJson as Record<string, unknown>;\n return {\n title: 'title' in json && typeof json.title === 'string' ? json.title : fromPropMeta.title,\n authors: 'authors' in json && typeof json.authors === 'string' ? json.authors : fromPropMeta.authors,\n abstract: 'abstract' in json && typeof json.abstract === 'string' ? json.abstract : fromPropMeta.abstract,\n date: 'date' in json ? normalizeDocumentHijriDate(json.date) : fromPropMeta.date,\n };\n}\n\n/** For live DocumentNode meta: prop fills empty title/authors/abstract; date patch merges. */\nexport function fillDocumentMetaGaps(current: DocumentMeta, fromProp?: DocumentMetaProp): DocumentMeta {\n if (!fromProp) {\n return cloneDocumentMeta(current);\n }\n return {\n title: current.title.trim().length > 0 ? current.title : typeof fromProp.title === 'string' ? fromProp.title : current.title,\n authors:\n current.authors.trim().length > 0\n ? current.authors\n : typeof fromProp.authors === 'string'\n ? fromProp.authors\n : current.authors,\n abstract:\n current.abstract.trim().length > 0\n ? current.abstract\n : typeof fromProp.abstract === 'string'\n ? fromProp.abstract\n : current.abstract,\n date: fromProp.date\n ? normalizeDocumentHijriDate({ ...current.date, ...fromProp.date })\n : { ...current.date },\n };\n}\n\nexport function documentHasMaketitle(meta: DocumentMeta): boolean {\n return meta.title.trim().length > 0 || meta.authors.trim().length > 0;\n}\n\nexport function documentHasAbstract(meta: DocumentMeta): boolean {\n return meta.abstract.trim().length > 0;\n}\n\nexport function documentHasTitleStack(meta: DocumentMeta): boolean {\n return documentHasMaketitle(meta) || documentHasAbstract(meta);\n}\n\nexport type FormatHijriDateOptions = {\n locale?: ButexUiLocale;\n digitForm?: DigitFormId;\n};\n\nexport function formatHijriDate(date: DocumentHijriDate, options: FormatHijriDateOptions | ButexUiLocale = 'ar'): string {\n const opts: FormatHijriDateOptions = typeof options === 'string' ? { locale: options } : options;\n const locale = opts.locale ?? 'ar';\n const digitForm: DigitFormId =\n opts.digitForm ?? (locale === 'en' ? 'western' : 'arabicIndic');\n const month = hijriMonthLabel(date.month, locale);\n const day = formatDigits(String(date.day), digitForm);\n const year = formatDigits(String(date.year), digitForm);\n if (locale === 'en') {\n return `${day} ${month} ${year} AH`;\n }\n return `${day} ${month} ${year}هـ`;\n}\n\nexport function cloneDocumentMeta(meta: DocumentMeta): DocumentMeta {\n return {\n title: meta.title,\n authors: meta.authors,\n date: { ...meta.date },\n abstract: meta.abstract,\n };\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { FormatCiteLabelOptions, Reference2, Reference2Json, ReferenceFieldSeparator } from './types.js';\nimport { documentId } from './ids.js';\n\nexport const DEFAULT_REFERENCE_FIELD_SEPARATOR: ReferenceFieldSeparator = '،';\n\nexport function normalizeReferenceFieldSeparator(value: unknown): ReferenceFieldSeparator {\n return value === ',' ? ',' : DEFAULT_REFERENCE_FIELD_SEPARATOR;\n}\n\nexport function referenceNumberMap(references: Array<Pick<Reference2, 'key'>>): Map<string, number> {\n const map = new Map<string, number>();\n references.forEach((reference, index) => {\n if (!map.has(reference.key)) {\n map.set(reference.key, index + 1);\n }\n });\n return map;\n}\n\nexport function resolveCiteNumbers(keys: string[], references: Array<Pick<Reference2, 'key'>>): Array<number | null> {\n const map = referenceNumberMap(references);\n return keys.map((key) => map.get(key) ?? null);\n}\n\nexport function formatCiteLabel(\n keys: string[],\n references: Array<Pick<Reference2, 'key'>>,\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const numbers = resolveCiteNumbers(keys, references).map((value) => (value === null ? '?' : String(value)));\n const display = documentDirection === 'rtl' ? [...numbers].reverse() : numbers;\n const separator = documentDirection === 'rtl' ? '،' : ', ';\n const body = display.map((part) => formatDigits(part, digitForm)).join(separator);\n return `[${body}]`;\n}\n\nexport function formatBibliographyNumber(index: number, options: FormatCiteLabelOptions = {}): string {\n const documentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n return formatDigits(String(index), digitForm);\n}\n\nexport function parseCiteKeys(source: string): string[] {\n const match = /^\\\\cite\\{([^}]*)\\}$/.exec(source.trim());\n if (!match) {\n return [];\n }\n return (match[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0);\n}\n\nexport function citeTokenLatex(keys: string[]): string {\n return `\\\\cite{${keys.join(',')}}`;\n}\n\nexport function referenceFromJson(json: Reference2Json): Reference2 {\n return {\n id: documentId('ref'),\n key: json.key,\n authors: typeof json.authors === 'string' ? json.authors : '',\n title: typeof json.title === 'string' ? json.title : '',\n year: typeof json.year === 'string' ? json.year : '',\n url: typeof json.url === 'string' ? json.url : '',\n venue: typeof json.venue === 'string' ? json.venue : '',\n fieldSeparator: normalizeReferenceFieldSeparator(json.field_separator),\n };\n}\n\nexport function createEmptyReference(partial: Partial<Reference2Json> = {}): Reference2 {\n return referenceFromJson({\n key: partial.key ?? `ref${String(Date.now()).slice(-4)}`,\n authors: partial.authors,\n title: partial.title,\n year: partial.year,\n url: partial.url,\n venue: partial.venue,\n field_separator: partial.field_separator,\n });\n}\n\n/** Joined authors/title/venue/year for preview and export (no \\\\bibitem wrapper). */\nexport function bibliographyEntryBody(\n reference: Pick<Reference2, 'authors' | 'title' | 'venue' | 'year' | 'fieldSeparator'>,\n separator: ReferenceFieldSeparator = reference.fieldSeparator,\n options: { digitForm?: DigitFormId } = {},\n): string {\n const year =\n options.digitForm !== undefined ? formatDigits(reference.year, options.digitForm) : reference.year;\n const parts = [reference.authors, reference.title, reference.venue, year].filter((part) => part.trim().length > 0);\n return parts.join(`${separator} `);\n}\n\nexport function bibliographyEntryLatex(reference: Reference2): string {\n const body = bibliographyEntryBody(reference);\n const url = reference.url.trim().length > 0 ? ` \\\\url{${reference.url}}` : '';\n return `\\\\bibitem{${reference.key}} ${body}${url}`.trim();\n}\n\n/**\n * Build an href for a bibliography URL. Values without a scheme become https://…\n * so the browser does not resolve them against the editor origin (e.g. localhost).\n * Leaves http(s)/mailto/ftp and other schemed URLs unchanged. Empty → ''.\n */\nexport function absoluteHttpHref(url: string): string {\n const trimmed = url.trim();\n if (trimmed.length === 0) {\n return '';\n }\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {\n return trimmed;\n }\n if (trimmed.startsWith('//')) {\n return `https:${trimmed}`;\n }\n return `https://${trimmed}`;\n}\n","import type { ChainNode } from '../arabic_ast.js';\n\ntype CommandRenderContext = {\n name: string;\n optionalArgs: ChainNode[];\n mandatoryArgs: ChainNode[];\n renderChain: (chain: ChainNode) => string;\n};\n\nexport function renderCommandCore(context: CommandRenderContext): string {\n const optional = context.optionalArgs.map((arg) => `[${context.renderChain(arg)}]`).join('');\n const mandatory = context.mandatoryArgs.map((arg) => `{${context.renderChain(arg)}}`).join('');\n return context.name + optional + mandatory;\n}\n","import { renderCommandCore } from './commands/index.js';\n\nexport type ArabicNodeJson = {\n node_type: string;\n expr?: string;\n name?: string;\n superscript?: ChainJson | null;\n subscript?: ChainJson | null;\n left_delim_expr?: string;\n right_delim_expr?: string;\n inner_expr?: ChainJson;\n optional_args?: ChainJson[];\n mandatory_args?: ChainJson[];\n opening?: string;\n closing?: string;\n lines?: ChainJson[];\n source_latex?: string;\n};\n\nexport type ChainJson = {\n node_type: 'ChainClass';\n chain: ArabicNodeJson[];\n};\n\nexport class State {\n // Empty for now, like the Python State placeholder used by BaseNode.\n}\n\nexport class BaseAstNode {\n state: State;\n superscript: ChainNode | null;\n subscript: ChainNode | null;\n nodeType: string;\n sourceLatex: string | null;\n\n constructor(state: State | null = null) {\n if (state === null) {\n state = new State();\n }\n\n this.state = state;\n this.superscript = null;\n this.subscript = null;\n this.nodeType = this.constructor.name;\n this.sourceLatex = null;\n }\n\n latex(): string {\n throw new Error('NotImplementedError');\n }\n\n arabicLatex(): string {\n throw new Error('NotImplementedError');\n }\n\n toArabicLatex(): string {\n return this.arabicLatex();\n }\n\n /** Latin-style scripts: `^{...}` and `_{...}` for english_json rendering. */\n latexScripts(): string {\n let s = '';\n\n if (this.superscript !== null) {\n s += '^{' + this.superscript.latex() + '}';\n }\n\n if (this.subscript !== null) {\n s += '_{' + this.subscript.latex() + '}';\n }\n\n return s;\n }\n\n /**\n * Arabic scripts use \\\\prescript{sup}{sub}{content} (matches reference Python output).\n * Call with rendered strings for sup/sub chains (may be empty strings).\n */\n arabicLatexScripts(sup: string, sub: string, content: string): string {\n if (sup !== '' || sub !== '') {\n return '\\\\prescript{' + sup + '}{' + sub + '}{' + content + '}';\n }\n return content;\n }\n}\n\nexport class ChainNode {\n chain: BaseAstNode[];\n\n constructor(chain: BaseAstNode[] = []) {\n this.chain = chain;\n }\n\n latex(): string {\n return this.chain.map((node) => node.latex()).join(' ');\n }\n toEnglishLatex(): string {\n return this.chain.map((node) => node.latex()).join(' ');\n }\n /** RTL: reverse order relative to Latin chain (see test/ref_tests.txt). */\n arabicLatex(): string {\n const reversed = this.chain.slice().reverse();\n return reversed.map((node) => node.arabicLatex()).join(' ');\n }\n\n toArabicLatex(): string {\n return this.arabicLatex();\n }\n}\n\nexport class NumberNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'NumberObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n return this.arabicLatexScripts(sup, sub, this.expr);\n }\n}\n\nexport class CharNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'CharObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n return this.arabicLatexScripts(sup, sub, this.expr);\n }\n}\n\n/**\n * Operator leaf: value comes from JSON as-is (English or Arabic side already chosen by the service).\n * Scripts are not appended (Python parity).\n */\nexport class OperatorNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'OperatorObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr;\n }\n\n arabicLatex(): string {\n return this.expr;\n }\n}\n\nexport class DelimiterNode extends BaseAstNode {\n leftDelimExpr: string;\n innerExpr: ChainNode;\n rightDelimExpr: string;\n\n constructor(leftDelimExpr: string, innerExpr: ChainNode, rightDelimExpr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'DelimiterObject';\n this.leftDelimExpr = leftDelimExpr;\n this.innerExpr = innerExpr;\n this.rightDelimExpr = rightDelimExpr;\n }\n\n latex(): string {\n return this.leftDelimExpr + ' ' + this.innerExpr.latex() + this.rightDelimExpr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n const content = this.leftDelimExpr + this.innerExpr.arabicLatex() + this.rightDelimExpr;\n return this.arabicLatexScripts(sup, sub, content);\n }\n}\n\nexport class CommandNode extends BaseAstNode {\n name: string;\n optionalArgs: ChainNode[];\n mandatoryArgs: ChainNode[];\n\n constructor(\n name: string,\n optionalArgs: ChainNode[] = [],\n mandatoryArgs: ChainNode[] = [],\n state: State | null = null\n ) {\n super(state);\n this.nodeType = 'CommandObject';\n this.name = name;\n this.optionalArgs = optionalArgs;\n this.mandatoryArgs = mandatoryArgs;\n }\n\n latex(): string {\n const content = renderCommandCore({\n name: this.name,\n optionalArgs: this.optionalArgs,\n mandatoryArgs: this.mandatoryArgs,\n renderChain: (chain) => chain.latex(),\n });\n return content + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n const arabicName =\n this.name === '\\\\sqrt' || this.name === '\\\\arabsqrt' ? '\\\\arsqrt' : this.name;\n const content = renderCommandCore({\n name: arabicName,\n optionalArgs: this.optionalArgs,\n mandatoryArgs: this.mandatoryArgs,\n renderChain: (chain) => chain.arabicLatex(),\n });\n return this.arabicLatexScripts(sup, sub, content);\n }\n}\n\nexport class EnvNode extends BaseAstNode {\n opening: string;\n lines: ChainNode[];\n closing: string;\n\n constructor(opening: string, lines: ChainNode[] = [], closing: string, state: State | null = null) {\n super(state);\n this.nodeType = 'EnvObject';\n this.opening = opening;\n this.lines = lines;\n this.closing = closing;\n }\n\n latex(): string {\n if (this.lines.length === 0) {\n return this.opening + this.closing + this.latexScripts();\n }\n\n const formattedLines = this.lines.map((line) => ` ${line.latex()}`);\n const content = formattedLines.join(' \\\\\\\\' + '\\n');\n return `${this.opening}\\n${content}\\n${this.closing}` + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n\n if (this.lines.length === 0) {\n return this.arabicLatexScripts(sup, sub, this.opening + this.closing);\n }\n\n const formattedLines = this.lines.map((line) => ` ${line.arabicLatex()}`);\n const content = formattedLines.join(' \\\\\\\\' + '\\n');\n // Only the Arabic presentation differs: stored EnvObject stays canonical cases.\n const fullContent = this.opening === '\\\\begin{cases}' && this.closing === '\\\\end{cases}'\n ? `\\\\left.\\\\begin{array}{rl}\\n${content}\\n\\\\end{array}\\\\right\\\\}`\n : `${this.opening}\\n${content}\\n${this.closing}`;\n return this.arabicLatexScripts(sup, sub, fullContent);\n }\n}\n\ntype ParseMode = 'english' | 'arabic';\n\nfunction parseScripts(node: BaseAstNode, json: ArabicNodeJson, mode: ParseMode): void {\n node.sourceLatex = typeof json.source_latex === 'string' && json.source_latex.length > 0\n ? json.source_latex\n : null;\n if (json.superscript) {\n node.superscript = parseChain(json.superscript, mode);\n }\n\n if (json.subscript) {\n node.subscript = parseChain(json.subscript, mode);\n }\n}\n\nfunction parseNode(json: ArabicNodeJson, mode: ParseMode): BaseAstNode {\n if (json.node_type === 'DelimiterObject') {\n const node = parseDelimiter(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'OperatorObject') {\n if (typeof json.expr !== 'string') {\n throw new Error('OperatorObject requires string expr');\n }\n const node = new OperatorNode(json.expr);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'CommandObject') {\n const node = parseCommand(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'EnvObject') {\n const node = parseEnv(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (typeof json.expr !== 'string') {\n throw new Error(`${json.node_type} requires string expr`);\n }\n\n let node: BaseAstNode;\n\n if (json.node_type === 'NumberObject') {\n node = new NumberNode(json.expr);\n } else if (json.node_type === 'CharObject') {\n node = new CharNode(json.expr);\n } else {\n throw new Error(`Unsupported node_type: ${json.node_type}`);\n }\n\n parseScripts(node, json, mode);\n return node;\n}\n\nfunction parseDelimiter(json: ArabicNodeJson, mode: ParseMode): DelimiterNode {\n if (typeof json.left_delim_expr !== 'string') {\n throw new Error('DelimiterObject requires string left_delim_expr');\n }\n\n if (!json.inner_expr || json.inner_expr.node_type !== 'ChainClass') {\n throw new Error('DelimiterObject requires ChainClass inner_expr');\n }\n\n if (typeof json.right_delim_expr !== 'string') {\n throw new Error('DelimiterObject requires string right_delim_expr');\n }\n\n const innerExpr = parseChain(json.inner_expr, mode);\n return new DelimiterNode(json.left_delim_expr, innerExpr, json.right_delim_expr);\n}\n\nfunction parseCommand(json: ArabicNodeJson, mode: ParseMode): CommandNode {\n if (typeof json.name !== 'string') {\n throw new Error('CommandObject requires string name');\n }\n\n const optionalJson = Array.isArray(json.optional_args) ? json.optional_args : [];\n const mandatoryJson = Array.isArray(json.mandatory_args) ? json.mandatory_args : [];\n const optionalArgs = optionalJson.map((arg) => parseChain(arg, mode));\n const mandatoryArgs = mandatoryJson.map((arg) => parseChain(arg, mode));\n\n return new CommandNode(json.name, optionalArgs, mandatoryArgs);\n}\n\nfunction parseEnv(json: ArabicNodeJson, mode: ParseMode): EnvNode {\n if (typeof json.opening !== 'string') {\n throw new Error('EnvObject requires string opening');\n }\n\n if (typeof json.closing !== 'string') {\n throw new Error('EnvObject requires string closing');\n }\n\n if (!Array.isArray(json.lines)) {\n throw new Error('EnvObject requires lines array');\n }\n\n const lines = json.lines.map((line) => parseChain(line, mode));\n return new EnvNode(json.opening, lines, json.closing);\n}\n\nfunction parseChain(json: ChainJson, mode: ParseMode): ChainNode {\n if (json.node_type !== 'ChainClass') {\n throw new Error(`Expected ChainClass, got: ${json.node_type}`);\n }\n\n const nodes = json.chain.map((childJson) => parseNode(childJson, mode));\n return new ChainNode(nodes);\n}\n\n/** Import AST from Python english_dict JSON (Latin expr fields). */\nexport function fromEnglishJson(json: ChainJson | ArabicNodeJson): ChainNode | BaseAstNode {\n if (json.node_type === 'ChainClass') {\n return parseChain(json as ChainJson, 'english');\n }\n return parseNode(json, 'english');\n}\n\n/** Import AST from Python arabic_dict JSON (Arabic expr fields). Same shape as English; values differ. */\nexport function fromArabicJson(json: ChainJson | ArabicNodeJson): ChainNode | BaseAstNode {\n if (json.node_type === 'ChainClass') {\n return parseChain(json as ChainJson, 'arabic');\n }\n return parseNode(json, 'arabic');\n}\n","import {\n BaseAstNode,\n ChainNode,\n CharNode,\n CommandNode,\n DelimiterNode,\n EnvNode,\n NumberNode,\n OperatorNode,\n fromArabicJson,\n fromEnglishJson,\n type ArabicNodeJson,\n type ChainJson,\n} from '../../ast/arabic_ast.js';\nimport type { DocumentParseMode, MathNode, MathObjectJson } from './types.js';\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isMathObjectJson(value: unknown): value is MathObjectJson {\n return isObject(value) && value.node_type === 'MathObject';\n}\n\nfunction assertChainNode(value: unknown): ChainNode {\n if (!(value instanceof ChainNode)) {\n throw new Error('MathObject lines must parse to ChainNode');\n }\n return value;\n}\n\nexport function fromMathObjectJson(json: unknown, mode: DocumentParseMode = 'english'): MathNode {\n if (!isMathObjectJson(json)) {\n throw new Error('MathObject requires node_type \"MathObject\"');\n }\n\n if (typeof json.math_mode !== 'string') {\n throw new Error('MathObject requires string math_mode');\n }\n\n if (typeof json.closing !== 'string') {\n throw new Error('MathObject requires string closing');\n }\n\n if (!Array.isArray(json.lines) || json.lines.length === 0) {\n throw new Error('MathObject requires non-empty lines array');\n }\n\n const parseChain = mode === 'arabic' ? fromArabicJson : fromEnglishJson;\n const lines = json.lines.map((line) => assertChainNode(parseChain(line)));\n\n return {\n nodeType: 'MathObject',\n mathMode: json.math_mode,\n lines,\n closing: json.closing,\n };\n}\n\nfunction scriptsToJson(\n node: BaseAstNode,\n path: string,\n): Pick<ArabicNodeJson, 'superscript' | 'subscript' | 'source_latex'> {\n return {\n ...(node.superscript ? { superscript: chainToJson(node.superscript, `${path}.superscript`) } : {}),\n ...(node.subscript ? { subscript: chainToJson(node.subscript, `${path}.subscript`) } : {}),\n ...(node.sourceLatex ? { source_latex: node.sourceLatex } : {}),\n };\n}\n\nfunction nodeToJson(node: BaseAstNode, path: string): ArabicNodeJson {\n const scripts = scriptsToJson(node, path);\n if (node instanceof CharNode || node instanceof NumberNode || node instanceof OperatorNode) {\n return { node_type: node.nodeType, expr: node.expr, ...scripts };\n }\n if (node instanceof DelimiterNode) {\n return {\n node_type: 'DelimiterObject',\n left_delim_expr: node.leftDelimExpr,\n inner_expr: chainToJson(node.innerExpr, `${path}.inner_expr`),\n right_delim_expr: node.rightDelimExpr,\n ...scripts,\n };\n }\n if (node instanceof CommandNode) {\n return {\n node_type: 'CommandObject',\n name: node.name,\n optional_args: node.optionalArgs.map((arg, index) => chainToJson(arg, `${path}.optional_args[${String(index)}]`)),\n mandatory_args: node.mandatoryArgs.map((arg, index) => chainToJson(arg, `${path}.mandatory_args[${String(index)}]`)),\n ...scripts,\n };\n }\n if (node instanceof EnvNode) {\n return {\n node_type: 'EnvObject',\n opening: node.opening,\n lines: node.lines.map((line, index) => chainToJson(line, `${path}.lines[${String(index)}]`)),\n closing: node.closing,\n ...scripts,\n };\n }\n throw new Error(`Unsupported runtime math node at ${path}: ${node.nodeType}`);\n}\n\nfunction chainToJson(chain: ChainNode, path: string): ChainJson {\n if (!(chain instanceof ChainNode)) {\n throw new Error(`Expected live ChainNode at ${path}`);\n }\n return {\n node_type: 'ChainClass',\n chain: chain.chain.map((node, index) => nodeToJson(node, `${path}.chain[${String(index)}]`)),\n };\n}\n\nexport function toMathObjectJson(math: MathNode): MathObjectJson {\n if (math.nodeType !== 'MathObject' || !Array.isArray(math.lines) || math.lines.length === 0) {\n throw new Error('Cannot serialize invalid runtime MathObject');\n }\n return {\n node_type: 'MathObject',\n math_mode: math.mathMode,\n lines: math.lines.map((line, index) => chainToJson(line, `$.lines[${String(index)}]`)),\n closing: math.closing,\n };\n}\n\nexport function renderMathNodeLatex(math: MathNode): string {\n const lines = math.lines.map((line) => line.arabicLatex());\n\n if (math.mathMode === '$' || math.mathMode === '\\\\(') {\n return math.mathMode + lines.join(' ') + math.closing;\n }\n\n if (math.mathMode === '$$' || math.mathMode === '\\\\[') {\n if (lines.length === 1) {\n return math.mathMode + '\\n' + lines[0] + '\\n' + math.closing;\n }\n return math.mathMode + '\\n' + lines.map((line) => ` ${line}`).join(' \\\\\\\\\\n') + '\\n' + math.closing;\n }\n\n if (lines.length === 1) {\n return `${math.mathMode}\\n ${lines[0]}\\n${math.closing}`;\n }\n\n return `${math.mathMode}\\n${lines.map((line) => ` ${line}`).join(' \\\\\\\\\\n')}\\n${math.closing}`;\n}\n\nexport function isDisplayMathNode(math: MathNode): boolean {\n return math.mathMode === '$$' || math.mathMode === '\\\\[' || math.mathMode.startsWith('\\\\begin{');\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport { formatBibliographyNumber } from './citations.js';\nimport { documentId } from './ids.js';\nimport type {\n DocumentBlock,\n DocumentDirection,\n DocumentNode,\n FormatCiteLabelOptions,\n ImageBlock2,\n InlineField2,\n MathToken2,\n TableBlock2,\n} from './types.js';\n\nexport type DocumentLabelKind = 'fig' | 'tab' | 'eq';\n\nexport type DocumentLabelEntry = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n /** Block id for fig/tab, or math token id for eq. */\n ownerId: string;\n number: number;\n};\n\nexport type FloatMetaPatch = {\n centered?: boolean;\n captionEnabled?: boolean;\n caption?: string;\n labelEnabled?: boolean;\n label?: string;\n};\n\nexport function defaultFloatMeta(): {\n centered: true;\n captionEnabled: false;\n caption: string;\n captionField: InlineField2;\n labelEnabled: false;\n label: string;\n} {\n return {\n centered: true,\n captionEnabled: false,\n caption: '',\n captionField: {\n id: documentId('field'),\n tokens: [{ id: documentId('text'), kind: 'text', text: '' }],\n },\n labelEnabled: false,\n label: '',\n };\n}\n\nexport function parseFloatMetaFromJson(json: {\n caption?: string;\n label?: string;\n caption_enabled?: boolean;\n label_enabled?: boolean;\n centered?: boolean;\n}): {\n centered: boolean;\n captionEnabled: boolean;\n caption: string;\n labelEnabled: boolean;\n label: string;\n} {\n const caption = typeof json.caption === 'string' ? json.caption : '';\n const label = typeof json.label === 'string' ? json.label : '';\n return {\n centered: json.centered !== false,\n captionEnabled: json.caption_enabled === true || (typeof json.caption_enabled !== 'boolean' && caption.length > 0),\n caption,\n labelEnabled: json.label_enabled === true || (typeof json.label_enabled !== 'boolean' && label.trim().length > 0),\n label,\n };\n}\n\nexport function parseRefKeys(source: string): { keys: string[]; refCommand: 'ref' | 'eqref' } {\n const eqref = /^\\\\eqref\\{([^}]*)\\}$/.exec(source.trim());\n if (eqref) {\n return {\n refCommand: 'eqref',\n keys: (eqref[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0),\n };\n }\n const ref = /^\\\\ref\\{([^}]*)\\}$/.exec(source.trim());\n if (ref) {\n return {\n refCommand: 'ref',\n keys: (ref[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0),\n };\n }\n return { keys: [], refCommand: 'ref' };\n}\n\nexport function refTokenLatex(keys: string[], refCommand: 'ref' | 'eqref'): string {\n const command = refCommand === 'eqref' ? '\\\\eqref' : '\\\\ref';\n return `${command}{${keys.join(',')}}`;\n}\n\n/** Deterministic, reversible, TeX-safe reference key from a persisted target ID. */\nfunction implicitObjectKey(kind: string, ownerId: string, unitId?: string): string {\n const hex = (value: string): string =>\n Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, '0')).join('');\n const scope = unitId === undefined ? 'a' : 'u' + hex(unitId);\n return kind + ':butex-auto-' + scope + '-' + hex(ownerId);\n}\n\nexport function implicitReferenceKey(kind: DocumentLabelKind, ownerId: string, unitId?: string): string {\n return implicitObjectKey(kind, ownerId, unitId);\n}\n\nexport function implicitHeadingReferenceKey(kind: 'section' | 'subsection' | 'subsubsection', ownerId: string, unitId: string): string {\n return implicitObjectKey(kind, ownerId, unitId);\n}\n\n/** Single-number display forms supported by the article reference model. */\nexport function supportsSingleEquationNumbering(token: MathToken2): boolean {\n return token.display && (\n token.opening === '\\\\[' || token.opening === String.fromCharCode(36, 36) ||\n token.opening === '\\\\begin{equation}' || token.opening === '\\\\begin{equation*}'\n );\n}\n\n/** Explicit numbering wins; legacy labeled/equation-environment math stays numbered. */\nexport function isNumberedEquation(token: MathToken2): boolean {\n if (!supportsSingleEquationNumbering(token)) return false;\n if (typeof token.numbered === 'boolean') return token.numbered;\n return token.opening === '\\\\begin{equation}' ||\n (Boolean(token.labelEnabled) && Boolean(token.label?.trim()));\n}\n\nexport function isNumberedFloat(block: ImageBlock2 | TableBlock2): boolean {\n return (block.captionEnabled && block.caption.trim().length > 0) ||\n (block.labelEnabled && block.label.trim().length > 0);\n}\n\nexport type DocumentReferenceTarget = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n ownerId: string;\n /** null means a displayed equation that has not been numbered. */\n number: number | null;\n manualKey?: string;\n};\n\n/** Projection of object identities and ordinals; never mutates document state. */\nexport function collectDocumentReferenceTargets(document: DocumentNode): DocumentReferenceTarget[] {\n const targets: DocumentReferenceTarget[] = [];\n const counters: Record<DocumentLabelKind, number> = { fig: 0, tab: 0, eq: 0 };\n function append(kind: DocumentLabelKind, ownerId: string, caption: string, numbered: boolean, manualKey = ''): void {\n if (numbered) counters[kind] += 1;\n targets.push({\n key: implicitReferenceKey(kind, ownerId),\n kind, ownerId, caption,\n number: numbered ? counters[kind] : null,\n ...(manualKey.trim() ? { manualKey: manualKey.trim() } : {}),\n });\n }\n function visitField(field: InlineField2): void {\n for (const token of field.tokens) {\n if (token.kind === 'math' && supportsSingleEquationNumbering(token)) {\n append('eq', token.id, '', isNumberedEquation(token), token.labelEnabled ? token.label ?? '' : '');\n }\n }\n }\n function walk(blocks: DocumentBlock[]): void {\n for (const block of blocks) {\n if (block.kind === 'image' || block.kind === 'table') {\n append(\n block.kind === 'image' ? 'fig' : 'tab',\n block.id, block.captionEnabled ? block.caption : '',\n isNumberedFloat(block), block.labelEnabled ? block.label : '',\n );\n if (block.captionEnabled) visitField(block.captionField);\n if (block.kind === 'table') {\n for (const row of block.rows) for (const cell of row) visitField(cell);\n }\n } else if (block.kind === 'textBlock') {\n visitField(block.field);\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n visitField(item.field);\n walk(item.blocks);\n }\n }\n }\n }\n walk(document.blocks);\n return targets;\n}\n\n/** Author-managed manual labels only; auto keys are not editable author metadata. */\nexport function collectDocumentLabels(document: DocumentNode): DocumentLabelEntry[] {\n return collectDocumentReferenceTargets(document)\n .filter((target): target is DocumentReferenceTarget & { number: number; manualKey: string } =>\n target.number !== null && Boolean(target.manualKey))\n .map(({ manualKey, kind, caption, ownerId, number }) => ({ key: manualKey, kind, caption, ownerId, number }));\n}\n\n/** Key collision checks include generated aliases without adding persistence fields. */\nexport function collectDocumentKeyLabels(document: DocumentNode): Array<Pick<DocumentLabelEntry, 'key' | 'ownerId'>> {\n return collectDocumentReferenceTargets(document).filter((target) => target.number !== null)\n .flatMap((target) => [\n { key: target.key, ownerId: target.ownerId },\n ...(target.manualKey && target.manualKey !== target.key\n ? [{ key: target.manualKey, ownerId: target.ownerId }]\n : []),\n ]);\n}\n\nexport function labelNumberMap(document: DocumentNode): Map<string, { kind: DocumentLabelKind; number: number }> {\n const map = new Map<string, { kind: DocumentLabelKind; number: number }>();\n for (const target of collectDocumentReferenceTargets(document)) {\n if (target.number === null) continue;\n for (const key of [target.key, target.manualKey]) {\n if (key && !map.has(key)) map.set(key, { kind: target.kind, number: target.number });\n }\n }\n return map;\n}\n\nexport type FormatFloatCaptionTitleOptions = {\n uiLocale?: ButexUiLocale;\n documentDirection?: DocumentDirection;\n digitForm?: DigitFormId;\n};\n\nfunction labelKindWord(kind: DocumentLabelKind, uiLocale: ButexUiLocale): string {\n if (kind === 'fig') {\n return uiLocale === 'ar' ? 'الشكل' : 'Figure';\n }\n if (kind === 'tab') {\n return uiLocale === 'ar' ? 'الجدول' : 'Table';\n }\n return uiLocale === 'ar' ? 'المعادلة' : 'Equation';\n}\n\n/** Localized numbered float/equation title: الشكل ١ / Figure 1 / المعادلة ١. */\nexport function formatFloatCaptionTitle(\n kind: DocumentLabelKind,\n number: number,\n options: FormatFloatCaptionTitleOptions = {},\n): string {\n const locale = options.uiLocale ?? 'ar';\n const digits = formatBibliographyNumber(number, {\n documentDirection: options.documentDirection ?? (locale === 'ar' ? 'rtl' : 'ltr'),\n digitForm: options.digitForm ?? (locale === 'ar' ? 'arabicIndic' : 'western'),\n });\n return `${labelKindWord(kind, locale)} ${digits}`;\n}\n\n/** Caption line as shown in document preview: الشكل ١: نص / Figure 1. text. */\nexport function formatFloatCaptionPreview(\n title: string,\n caption: string | undefined,\n uiLocale: ButexUiLocale = 'ar',\n): string {\n const trimmed = caption?.trim() ?? '';\n if (trimmed.length === 0) {\n return title;\n }\n const separator = uiLocale === 'ar' ? ': ' : '. ';\n return `${title}${separator}${trimmed}`;\n}\n\nexport function formatRefLabel(\n keys: string[],\n document: DocumentNode,\n refCommand: 'ref' | 'eqref',\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection: DocumentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const uiLocale: ButexUiLocale = documentDirection === 'rtl' ? 'ar' : 'en';\n const map = labelNumberMap(document);\n const parts = keys.map((key) => {\n const hit = map.get(key);\n if (!hit) {\n return refCommand === 'eqref' ? '(?)' : '?';\n }\n const digits = formatDigits(String(hit.number), digitForm);\n const numberLabel = refCommand === 'eqref' ? `(${digits})` : digits;\n return `${labelKindWord(hit.kind, uiLocale)} ${numberLabel}`;\n });\n return parts.join(documentDirection === 'rtl' ? '،' : ', ');\n}\n\nexport function stripDisplayMathDelimiters(source: string): string {\n const trimmed = source.trim();\n if (trimmed.startsWith('\\\\[') && trimmed.endsWith('\\\\]')) {\n return trimmed.slice(2, -2).trim();\n }\n if (trimmed.startsWith('$$') && trimmed.endsWith('$$')) {\n return trimmed.slice(2, -2).trim();\n }\n for (const environment of ['equation', 'equation*']) {\n const opening = `\\\\begin{${environment}}`;\n const closing = `\\\\end{${environment}}`;\n if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {\n return trimmed.slice(opening.length, -closing.length).trim();\n }\n }\n return trimmed;\n}\n\nexport function applyFloatMetaPatch<T extends ImageBlock2 | TableBlock2>(block: T, patch: FloatMetaPatch): void {\n if (typeof patch.centered === 'boolean') {\n block.centered = patch.centered;\n }\n if (typeof patch.captionEnabled === 'boolean') {\n block.captionEnabled = patch.captionEnabled;\n }\n if (typeof patch.caption === 'string') {\n block.caption = patch.caption;\n const existingText = block.captionField.tokens.find((token) => token.kind === 'text');\n block.captionField.tokens = [\n {\n id: existingText?.id ?? documentId('text'),\n kind: 'text',\n text: patch.caption,\n },\n ];\n }\n if (typeof patch.labelEnabled === 'boolean') {\n block.labelEnabled = patch.labelEnabled;\n }\n if (typeof patch.label === 'string') {\n block.label = patch.label;\n }\n}\n","import { citeTokenLatex } from './citations.js';\nimport { documentId } from './ids.js';\nimport { refTokenLatex } from './labels.js';\nimport type {\n DocumentInlineIdsJson,\n DocumentInlineTokenIdJson,\n InlineField2,\n InlineToken2,\n} from './types.js';\n\nexport type DocumentIdentityState = {\n blockIds: Set<string>;\n itemIds: Set<string>;\n fieldIds: Set<string>;\n tokenIds: Set<string>;\n};\n\nexport function createDocumentIdentityState(): DocumentIdentityState {\n return {\n blockIds: new Set<string>(),\n itemIds: new Set<string>(),\n fieldIds: new Set<string>(),\n tokenIds: new Set<string>(),\n };\n}\n\nexport function importedOrGeneratedId(value: unknown, prefix: string, used: Set<string>): string {\n const imported = typeof value === 'string' ? value.trim() : '';\n if (imported.length > 0 && !used.has(imported)) {\n used.add(imported);\n return imported;\n }\n\n let generated = documentId(prefix);\n while (used.has(generated)) {\n generated = documentId(prefix);\n }\n used.add(generated);\n return generated;\n}\n\nexport function inlineTokenSource(token: InlineToken2): string {\n if (token.kind === 'text') {\n return token.text;\n }\n if (token.kind === 'math') {\n return token.source;\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n return refTokenLatex(token.keys, token.refCommand);\n}\n\nexport function inlineIdsFromField(field: InlineField2): DocumentInlineIdsJson {\n let offset = 0;\n const tokens = field.tokens.map((token): DocumentInlineTokenIdJson => {\n const start = offset;\n offset += inlineTokenSource(token).length;\n return { id: token.id, kind: token.kind, start, end: offset };\n });\n return { field_id: field.id, tokens };\n}\n\nfunction isAlignedSidecar(value: unknown, field: InlineField2): value is DocumentInlineIdsJson {\n if (typeof value !== 'object' || value === null || !Array.isArray((value as DocumentInlineIdsJson).tokens)) {\n return false;\n }\n const tokens = (value as DocumentInlineIdsJson).tokens;\n const expected = inlineIdsFromField(field).tokens;\n if (tokens.length !== expected.length) {\n return false;\n }\n return tokens.every((token, index) => {\n const expectedToken = expected[index];\n return (\n typeof token === 'object' &&\n token !== null &&\n expectedToken !== undefined &&\n token.kind === expectedToken.kind &&\n token.start === expectedToken.start &&\n token.end === expectedToken.end\n );\n });\n}\n\nexport function applyImportedInlineIds(\n field: InlineField2,\n sidecar: unknown,\n state: DocumentIdentityState,\n): InlineField2 {\n field.id = importedOrGeneratedId(\n typeof sidecar === 'object' && sidecar !== null ? (sidecar as { field_id?: unknown }).field_id : undefined,\n 'field',\n state.fieldIds,\n );\n\n const aligned = isAlignedSidecar(sidecar, field);\n field.tokens.forEach((token, index) => {\n token.id = importedOrGeneratedId(aligned ? sidecar.tokens[index]?.id : undefined, token.kind, state.tokenIds);\n });\n return field;\n}\n","import type { DetectedInlineSpan2, DetectedMathSpan2 } from './types.js';\nimport { parseCiteKeys } from './citations.js';\nimport { parseRefKeys } from './labels.js';\n\nconst MATH_ENVIRONMENTS = new Set([\n 'equation',\n 'equation*',\n 'align',\n 'align*',\n 'aligned',\n 'gather',\n 'gather*',\n 'multline',\n 'multline*',\n]);\n\nfunction isEscaped(value: string, index: number): boolean {\n let slashCount = 0;\n let i = index - 1;\n while (i >= 0 && value[i] === '\\\\') {\n slashCount += 1;\n i -= 1;\n }\n return slashCount % 2 === 1;\n}\n\nfunction findClosingDollar(value: string, start: number): number {\n let i = start;\n while (i < value.length) {\n if (value[i] === '$' && !isEscaped(value, i)) {\n return i;\n }\n i += 1;\n }\n return -1;\n}\n\nfunction environmentSpan(value: string, start: number): DetectedMathSpan2 | null {\n const match = /^\\\\begin\\{([A-Za-z*]+)\\}/.exec(value.slice(start));\n if (!match) {\n return null;\n }\n\n const envName = match[1] ?? '';\n if (!MATH_ENVIRONMENTS.has(envName)) {\n return null;\n }\n\n const opening = match[0] ?? '';\n const closing = `\\\\end{${envName}}`;\n const closingStart = value.indexOf(closing, start + opening.length);\n if (closingStart < 0) {\n return null;\n }\n\n const end = closingStart + closing.length;\n return { start, end, source: value.slice(start, end), opening, closing, display: true };\n}\n\nfunction citeSpan(value: string, start: number): DetectedInlineSpan2 | null {\n if (!value.startsWith('\\\\cite{', start) || isEscaped(value, start)) {\n return null;\n }\n const openBrace = start + '\\\\cite'.length;\n if (value[openBrace] !== '{') {\n return null;\n }\n let depth = 0;\n for (let i = openBrace; i < value.length; i += 1) {\n const char = value[i];\n if (char === '{' && !isEscaped(value, i)) {\n depth += 1;\n continue;\n }\n if (char === '}' && !isEscaped(value, i)) {\n depth -= 1;\n if (depth === 0) {\n const end = i + 1;\n const source = value.slice(start, end);\n return { kind: 'cite', start, end, source, keys: parseCiteKeys(source) };\n }\n }\n }\n return null;\n}\n\nfunction refSpan(value: string, start: number): DetectedInlineSpan2 | null {\n const eqrefPrefix = '\\\\eqref{';\n const refPrefix = '\\\\ref{';\n const isEqref = value.startsWith(eqrefPrefix, start) && !isEscaped(value, start);\n const isRef = value.startsWith(refPrefix, start) && !isEscaped(value, start);\n if (!isEqref && !isRef) {\n return null;\n }\n const refCommand: 'ref' | 'eqref' = isEqref ? 'eqref' : 'ref';\n const prefix = isEqref ? eqrefPrefix : refPrefix;\n\n const openBrace = start + prefix.length - 1;\n if (value[openBrace] !== '{') {\n return null;\n }\n let depth = 0;\n for (let i = openBrace; i < value.length; i += 1) {\n const char = value[i];\n if (char === '{' && !isEscaped(value, i)) {\n depth += 1;\n continue;\n }\n if (char === '}' && !isEscaped(value, i)) {\n depth -= 1;\n if (depth === 0) {\n const end = i + 1;\n const source = value.slice(start, end);\n const parsed = parseRefKeys(source);\n return { kind: 'ref', start, end, source, keys: parsed.keys, refCommand };\n }\n }\n }\n return null;\n}\n\nfunction mathSpanAt(value: string, i: number): DetectedMathSpan2 | null {\n if (value.startsWith('\\\\begin{', i)) {\n return environmentSpan(value, i);\n }\n\n if (value.startsWith('\\\\(', i)) {\n const close = value.indexOf('\\\\)', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '\\\\(', closing: '\\\\)', display: false };\n }\n }\n\n if (value.startsWith('\\\\[', i)) {\n const close = value.indexOf('\\\\]', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '\\\\[', closing: '\\\\]', display: true };\n }\n }\n\n if (value.startsWith('$$', i) && !isEscaped(value, i)) {\n const close = value.indexOf('$$', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '$$', closing: '$$', display: true };\n }\n }\n\n if (value[i] === '$' && !isEscaped(value, i)) {\n const close = findClosingDollar(value, i + 1);\n if (close >= 0) {\n const end = close + 1;\n return { start: i, end, source: value.slice(i, end), opening: '$', closing: '$', display: false };\n }\n }\n\n return null;\n}\n\n/** Math-only spans (used for math_objects alignment counts). */\nexport function detectMathSpans(value: string): DetectedMathSpan2[] {\n return detectInlineSpans(value)\n .filter((span): span is DetectedInlineSpan2 & { kind: 'math' } => span.kind === 'math')\n .map((span) => ({\n start: span.start,\n end: span.end,\n source: span.source,\n opening: span.opening,\n closing: span.closing,\n display: span.display,\n }));\n}\n\n/** Left-to-right math + \\\\cite + \\\\ref/\\\\eqref spans without overlap. */\nexport function detectInlineSpans(value: string): DetectedInlineSpan2[] {\n const spans: DetectedInlineSpan2[] = [];\n let i = 0;\n\n while (i < value.length) {\n const cite = citeSpan(value, i);\n if (cite) {\n spans.push(cite);\n i = cite.end;\n continue;\n }\n\n const ref = refSpan(value, i);\n if (ref) {\n spans.push(ref);\n i = ref.end;\n continue;\n }\n\n const math = mathSpanAt(value, i);\n if (math) {\n spans.push({ kind: 'math', ...math });\n i = math.end;\n continue;\n }\n\n i += 1;\n }\n\n return spans;\n}\n","import { fromMathObjectJson } from '../shared/math-document/mathObject.js';\nimport { normalizeDocumentMeta, emptyDocumentMeta } from './articleMeta.js';\nimport { referenceFromJson } from './citations.js';\nimport { documentId } from './ids.js';\nimport {\n applyImportedInlineIds,\n createDocumentIdentityState,\n importedOrGeneratedId,\n type DocumentIdentityState,\n} from './inlineIdentity.js';\nimport { detectInlineSpans, detectMathSpans } from './inlineScanner.js';\nimport { parseFloatMetaFromJson } from './labels.js';\nimport type {\n BibliographyBlock2,\n DocumentBlock,\n DocumentBlockMetadata,\n DocumentBlockJson,\n DocumentDiagnostic,\n DocumentMathObjectJson,\n DocumentListItemJson,\n DocumentNode,\n DocumentParseMode,\n ImageBlock2,\n ImportDocumentOptions,\n InlineField2,\n InlineToken2,\n ListBlock2,\n ListItem2,\n RawBlock2,\n Reference2,\n Reference2Json,\n TableBlock2,\n TextFormatSpan2Json,\n TextStyle2,\n TextBlock2,\n} from './types.js';\n\nconst TEXT_COMMANDS = new Set(['\\\\section', '\\\\subsection', '\\\\subsubsection', '\\\\paragraph']);\nconst LIST_COMMANDS = new Set(['\\\\begin{itemize}', '\\\\begin{enumerate}']);\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction requireString(value: unknown, message: string): string {\n if (typeof value !== 'string') {\n throw new Error(message);\n }\n return value;\n}\n\nfunction isRecordOfStrings(value: unknown): value is Record<string, string> {\n return isObject(value) && Object.values(value).every((entry) => typeof entry === 'string');\n}\n\nfunction asBlockJson(value: unknown): DocumentBlockJson {\n if (!isObject(value)) {\n throw new Error('Document block must be an object');\n }\n if (typeof value.command !== 'string') {\n throw new Error('Document block requires string command');\n }\n return value as DocumentBlockJson;\n}\n\nfunction blockIdFromJson(json: DocumentBlockJson, state: DocumentIdentityState): string {\n return importedOrGeneratedId(json.id, 'block', state.blockIds);\n}\n\nfunction metadataFromJson(value: unknown): { metadata?: DocumentBlockMetadata } {\n if (!isObject(value) || (value.source !== 'agent' && value.source !== 'user')) {\n return {};\n }\n return { metadata: { source: value.source } };\n}\n\nfunction pushDiagnostic(diagnostics: DocumentDiagnostic[], options: ImportDocumentOptions, path: string, message: string): void {\n if (options.strict) {\n throw new Error(message);\n }\n diagnostics.push({ code: 'math_alignment', message, path });\n}\n\nfunction parseReferences(json: unknown): Reference2[] {\n if (!Array.isArray(json)) {\n return [];\n }\n const references: Reference2[] = [];\n for (const entry of json) {\n if (!isObject(entry) || typeof entry.key !== 'string' || entry.key.trim().length === 0) {\n continue;\n }\n references.push(\n referenceFromJson({\n key: entry.key.trim(),\n authors: typeof entry.authors === 'string' ? entry.authors : undefined,\n title: typeof entry.title === 'string' ? entry.title : undefined,\n year: typeof entry.year === 'string' ? entry.year : undefined,\n url: typeof entry.url === 'string' ? entry.url : undefined,\n venue: typeof entry.venue === 'string' ? entry.venue : undefined,\n field_separator:\n entry.field_separator === ',' || entry.field_separator === '،'\n ? entry.field_separator\n : undefined,\n } satisfies Reference2Json),\n );\n }\n return references;\n}\n\nexport function createInlineField(\n value = '',\n mathObjects: Array<DocumentMathObjectJson | null> = [],\n options: ImportDocumentOptions = {},\n path = '$',\n diagnostics: DocumentDiagnostic[] = [],\n formats: TextFormatSpan2Json[] = [],\n): InlineField2 {\n const mode: DocumentParseMode = options.mode ?? 'english';\n const spans = detectInlineSpans(value);\n const mathSpans = spans.filter((span) => span.kind === 'math');\n const tokens: InlineToken2[] = [];\n let index = 0;\n let mathObjectIndex = 0;\n\n if (mathObjects.length > 0 && mathObjects.length !== mathSpans.length) {\n pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathSpans.length)}, got ${String(mathObjects.length)}`);\n }\n\n for (const span of spans) {\n if (span.start > index) {\n pushFormattedTextTokens(tokens, value.slice(index, span.start), index, formats);\n }\n\n if (span.kind === 'cite') {\n tokens.push({\n id: documentId('cite'),\n kind: 'cite',\n keys: span.keys.length > 0 ? span.keys : [],\n });\n index = span.end;\n continue;\n }\n\n if (span.kind === 'ref') {\n tokens.push({\n id: documentId('ref'),\n kind: 'ref',\n keys: span.keys.length > 0 ? span.keys : [],\n refCommand: span.refCommand,\n });\n index = span.end;\n continue;\n }\n\n const mathJson = mathObjects[mathObjectIndex];\n mathObjectIndex += 1;\n const structuredMathJson = mathJson?.node_type === 'MathObject' ? mathJson : null;\n if (structuredMathJson && (structuredMathJson.math_mode !== span.opening || structuredMathJson.closing !== span.closing)) {\n pushDiagnostic(diagnostics, options, path, 'math_objects order mismatch');\n }\n\n if (structuredMathJson && structuredMathJson.math_mode === span.opening && structuredMathJson.closing === span.closing) {\n tokens.push({\n id: documentId('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n sourceSide:\n structuredMathJson.source_side === 'arabic' || structuredMathJson.source_side === 'english'\n ? structuredMathJson.source_side\n : mode,\n math: fromMathObjectJson(structuredMathJson, mode),\n editable: true,\n sourceOwner: structuredMathJson.source_owner === 'editor' ? 'editor' : 'imported-structured',\n ...(typeof structuredMathJson.label_enabled === 'boolean' ? { labelEnabled: structuredMathJson.label_enabled } : {}),\n ...(typeof structuredMathJson.label === 'string' ? { label: structuredMathJson.label } : {}),\n ...(typeof structuredMathJson.numbered === 'boolean' ? { numbered: structuredMathJson.numbered } : {}),\n });\n } else {\n tokens.push({\n id: documentId('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n math: null,\n editable: false,\n reason: 'هذه المعادلة محفوظة كنص خام فقط حاليا',\n sourceOwner: 'raw',\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.label_enabled === 'boolean'\n ? { labelEnabled: mathJson.label_enabled }\n : {}),\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.label === 'string'\n ? { label: mathJson.label }\n : {}),\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.numbered === 'boolean'\n ? { numbered: mathJson.numbered }\n : {}),\n });\n }\n\n index = span.end;\n }\n\n if (index < value.length || tokens.length === 0) {\n pushFormattedTextTokens(tokens, value.slice(index), index, formats);\n }\n\n return { id: documentId('field'), tokens: compactTextTokens(tokens) };\n}\n\nfunction styleFromFormat(format: TextFormatSpan2Json): TextStyle2 | null {\n const style: TextStyle2 = {};\n if (format.bold === true) {\n style.bold = true;\n }\n if (format.italic === true) {\n style.italic = true;\n }\n if (format.underline === true) {\n style.underline = true;\n }\n return style.bold || style.italic || style.underline ? style : null;\n}\n\nfunction mergeTextStyle(base: TextStyle2 | undefined, added: TextStyle2): TextStyle2 {\n return {\n ...(base?.bold ? { bold: true as const } : {}),\n ...(base?.italic ? { italic: true as const } : {}),\n ...(base?.underline ? { underline: true as const } : {}),\n ...(added.bold ? { bold: true as const } : {}),\n ...(added.italic ? { italic: true as const } : {}),\n ...(added.underline ? { underline: true as const } : {}),\n };\n}\n\nfunction textStylesEqual(a: TextStyle2 | undefined, b: TextStyle2 | undefined): boolean {\n return Boolean(a?.bold) === Boolean(b?.bold) && Boolean(a?.italic) === Boolean(b?.italic) && Boolean(a?.underline) === Boolean(b?.underline);\n}\n\nfunction compactTextTokens(tokens: InlineToken2[]): InlineToken2[] {\n const compacted: InlineToken2[] = [];\n for (const token of tokens) {\n const previous = compacted[compacted.length - 1];\n if (previous?.kind === 'text' && token.kind === 'text' && textStylesEqual(previous.style, token.style)) {\n previous.text += token.text;\n } else {\n compacted.push(token);\n }\n }\n return compacted;\n}\n\nfunction styleKey(style: TextStyle2 | undefined): string {\n return `${style?.bold ? 'b' : ''}${style?.italic ? 'i' : ''}${style?.underline ? 'u' : ''}`;\n}\n\nfunction pushFormattedTextTokens(tokens: InlineToken2[], text: string, sourceStart: number, formats: TextFormatSpan2Json[]): void {\n if (text.length === 0) {\n tokens.push({ id: documentId('text'), kind: 'text', text });\n return;\n }\n const styles: Array<TextStyle2 | undefined> = Array.from({ length: text.length });\n for (const format of formats) {\n const style = styleFromFormat(format);\n if (!style || !Number.isFinite(format.start) || !Number.isFinite(format.end)) {\n continue;\n }\n const start = Math.max(0, Math.min(text.length, Math.trunc(format.start) - sourceStart));\n const end = Math.max(0, Math.min(text.length, Math.trunc(format.end) - sourceStart));\n if (end <= start) {\n continue;\n }\n for (let index = start; index < end; index += 1) {\n styles[index] = mergeTextStyle(styles[index], style);\n }\n }\n\n let chunkStart = 0;\n for (let index = 1; index <= text.length; index += 1) {\n if (index < text.length && styleKey(styles[index]) === styleKey(styles[chunkStart])) {\n continue;\n }\n const chunk = text.slice(chunkStart, index);\n const style = styles[chunkStart];\n tokens.push({ id: documentId('text'), kind: 'text', text: chunk, ...(style ? { style } : {}) });\n chunkStart = index;\n }\n}\n\nfunction closingForList(command: '\\\\begin{itemize}' | '\\\\begin{enumerate}'): '\\\\end{itemize}' | '\\\\end{enumerate}' {\n return command === '\\\\begin{itemize}' ? '\\\\end{itemize}' : '\\\\end{enumerate}';\n}\n\nfunction parseTextBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): TextBlock2 {\n const value = requireString(json.value, `${json.command} requires string value`);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'textBlock',\n command: json.command as TextBlock2['command'],\n field: applyImportedInlineIds(\n createInlineField(value, json.math_objects ?? [], options, `${path}.value`, diagnostics, json.command === '\\\\paragraph' ? json.formats ?? [] : []),\n json.inline_ids,\n identities,\n ),\n ...metadataFromJson(json.metadata),\n ...(typeof json.label === 'string' && json.command !== '\\\\paragraph' ? { label: json.label } : {}),\n ...(json.centered === true ? { centered: true } : {}),\n };\n}\n\nfunction parseListItem(\n json: DocumentListItemJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ListItem2 {\n const value = requireString(json.value, 'Document list item requires string value');\n const blocksJson = Array.isArray(json.blocks) ? json.blocks : [];\n return {\n id: importedOrGeneratedId(json.id, 'item', identities.itemIds),\n field: applyImportedInlineIds(\n createInlineField(value, json.math_objects ?? [], options, `${path}.value`, diagnostics, json.formats ?? []),\n json.inline_ids,\n identities,\n ),\n blocks: blocksJson.map((block, index) =>\n parseBlock(asBlockJson(block), options, `${path}.blocks[${String(index)}]`, diagnostics, identities),\n ),\n };\n}\n\nfunction parseListBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ListBlock2 {\n if (!Array.isArray(json.items)) {\n throw new Error(`${json.command} requires items array`);\n }\n const command = json.command as ListBlock2['command'];\n const closing = closingForList(command);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'list',\n command,\n closing,\n items: json.items.map((item, index) =>\n parseListItem(item, options, `${path}.items[${String(index)}]`, diagnostics, identities),\n ),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction captionFieldFromJson(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): InlineField2 {\n const caption = typeof json.caption === 'string' ? json.caption : '';\n return applyImportedInlineIds(\n createInlineField(\n caption,\n json.caption_math_objects ?? [],\n options,\n `${path}.caption`,\n diagnostics,\n json.caption_formats ?? [],\n ),\n json.caption_inline_ids,\n identities,\n );\n}\n\nfunction parseTableBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): TableBlock2 {\n if (!Array.isArray(json.rows)) {\n throw new Error('\\\\begin{tabular} requires rows array');\n }\n\n const mathObjects = json.math_objects ?? [];\n let mathObjectIndex = 0;\n const rows = json.rows.map((row, rowIndex) => {\n if (!Array.isArray(row)) {\n throw new Error('\\\\begin{tabular} rows must be arrays');\n }\n return row.map((cell, columnIndex) => {\n const value = requireString(cell, '\\\\begin{tabular} cells must be strings');\n const spanCount = detectMathSpans(value).length;\n const cellMathObjects = mathObjects.slice(mathObjectIndex, mathObjectIndex + spanCount);\n mathObjectIndex += spanCount;\n const cellFormats = json.cell_formats?.[rowIndex]?.[columnIndex] ?? [];\n return applyImportedInlineIds(\n createInlineField(value, cellMathObjects, options, `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`, diagnostics, cellFormats),\n json.cell_inline_ids?.[rowIndex]?.[columnIndex],\n identities,\n );\n });\n });\n\n if (mathObjects.length > 0 && mathObjects.length !== mathObjectIndex) {\n pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathObjectIndex)}, got ${String(mathObjects.length)}`);\n }\n\n const floatMeta = parseFloatMetaFromJson(json);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: typeof json.columns === 'string' ? json.columns : '',\n rows,\n ...floatMeta,\n captionField: captionFieldFromJson(json, options, path, diagnostics, identities),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseImageBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ImageBlock2 {\n const assetId = typeof json.asset_id === 'string' && json.asset_id.length > 0 ? json.asset_id : undefined;\n const value =\n assetId !== undefined\n ? typeof json.value === 'string'\n ? json.value\n : ''\n : requireString(json.value, '\\\\includegraphics requires string value');\n const floatMeta = parseFloatMetaFromJson(json);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'image',\n command: '\\\\includegraphics',\n value,\n ...(assetId !== undefined ? { assetId } : {}),\n options: isRecordOfStrings(json.options) ? json.options : {},\n ...floatMeta,\n captionField: captionFieldFromJson(json, options, path, diagnostics, identities),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseRawBlock(json: DocumentBlockJson, identities: DocumentIdentityState): RawBlock2 {\n return {\n id: blockIdFromJson(json, identities),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : '',\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseBibliographyBlock(json: DocumentBlockJson, identities: DocumentIdentityState): BibliographyBlock2 {\n return {\n id: blockIdFromJson(json, identities),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): DocumentBlock {\n if (TEXT_COMMANDS.has(json.command)) {\n return parseTextBlock(json, options, path, diagnostics, identities);\n }\n if (LIST_COMMANDS.has(json.command)) {\n return parseListBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\begin{tabular}') {\n return parseTableBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\includegraphics') {\n return parseImageBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\begin{thebibliography}' || json.command === '\\\\bibliography') {\n return parseBibliographyBlock(json, identities);\n }\n if (json.command === '\\\\raw') {\n return parseRawBlock(json, identities);\n }\n return {\n id: blockIdFromJson(json, identities),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : json.command,\n ...metadataFromJson(json.metadata),\n };\n}\n\nexport function fromDocumentJson(json: unknown, options: ImportDocumentOptions = {}): DocumentNode {\n if (!isObject(json) || json.node_type !== 'DocumentObject') {\n throw new Error('DocumentObject requires node_type \"DocumentObject\"');\n }\n if (!Array.isArray(json.blocks)) {\n throw new Error('DocumentObject requires blocks array');\n }\n\n const diagnostics: DocumentDiagnostic[] = [];\n const identities = createDocumentIdentityState();\n return {\n nodeType: 'DocumentObject',\n meta: normalizeDocumentMeta(json.meta),\n references: parseReferences(json.references),\n blocks: json.blocks.map((block, index) =>\n parseBlock(asBlockJson(block), options, `$.blocks[${String(index)}]`, diagnostics, identities),\n ),\n diagnostics,\n };\n}\n\nexport function createEmptyDocument(): DocumentNode {\n return {\n nodeType: 'DocumentObject',\n meta: emptyDocumentMeta(),\n references: [],\n blocks: [],\n diagnostics: [],\n };\n}\n","export type AccentPlacement = 'over' | 'under';\n\nexport const ACCENT_COMMANDS = {\n vec: {\n id: 'vec',\n englishTex: '\\\\vec',\n arabicTex: '\\\\arabvec',\n placement: 'over' as const,\n label: '⃗',\n title: 'سهم فوق',\n },\n hat: {\n id: 'hat',\n englishTex: '\\\\hat',\n arabicTex: '\\\\hat',\n placement: 'over' as const,\n label: 'ˆ',\n title: 'قبعة',\n },\n tilde: {\n id: 'tilde',\n englishTex: '\\\\tilde',\n arabicTex: '\\\\tilde',\n placement: 'over' as const,\n label: '˜',\n title: 'مدة',\n },\n dot: {\n id: 'dot',\n englishTex: '\\\\dot',\n arabicTex: '\\\\dot',\n placement: 'over' as const,\n label: '˙',\n title: 'نقطة فوق',\n },\n ddot: {\n id: 'ddot',\n englishTex: '\\\\ddot',\n arabicTex: '\\\\ddot',\n placement: 'over' as const,\n label: '¨',\n title: 'نقطتان فوق',\n },\n dddot: {\n id: 'dddot',\n englishTex: '\\\\dddot',\n arabicTex: '\\\\dddot',\n placement: 'over' as const,\n label: '⃛',\n title: 'ثلاث نقاط فوق',\n },\n bar: {\n id: 'bar',\n englishTex: '\\\\bar',\n arabicTex: '\\\\bar',\n placement: 'over' as const,\n label: '¯',\n title: 'خط فوق',\n },\n check: {\n id: 'check',\n englishTex: '\\\\check',\n arabicTex: '\\\\check',\n placement: 'over' as const,\n label: 'ˇ',\n title: 'علامة تحقق',\n },\n breve: {\n id: 'breve',\n englishTex: '\\\\breve',\n arabicTex: '\\\\breve',\n placement: 'over' as const,\n label: '˘',\n title: 'قوس قصير',\n },\n acute: {\n id: 'acute',\n englishTex: '\\\\acute',\n arabicTex: '\\\\grave',\n placement: 'over' as const,\n label: '´',\n title: 'نبرة حادة',\n },\n grave: {\n id: 'grave',\n englishTex: '\\\\grave',\n arabicTex: '\\\\acute',\n placement: 'over' as const,\n label: '`',\n title: 'نبرة ثقيلة',\n },\n overline: {\n id: 'overline',\n englishTex: '\\\\overline',\n arabicTex: '\\\\overline',\n placement: 'over' as const,\n label: '‾',\n title: 'خط علوي ممتد',\n },\n underline: {\n id: 'underline',\n englishTex: '\\\\underline',\n arabicTex: '\\\\underline',\n placement: 'under' as const,\n label: '_',\n title: 'خط سفلي',\n },\n overleftarrow: {\n id: 'overleftarrow',\n englishTex: '\\\\overleftarrow',\n arabicTex: '\\\\overrightarrow',\n placement: 'over' as const,\n label: '←',\n title: 'سهم علوي إلى اليسار',\n },\n overrightarrow: {\n id: 'overrightarrow',\n englishTex: '\\\\overrightarrow',\n arabicTex: '\\\\overleftarrow',\n placement: 'over' as const,\n label: '→',\n title: 'سهم علوي إلى اليمين',\n },\n overleftrightarrow: {\n id: 'overleftrightarrow',\n englishTex: '\\\\overleftrightarrow',\n arabicTex: '\\\\overleftrightarrow',\n placement: 'over' as const,\n label: '↔',\n title: 'سهم علوي مزدوج الاتجاه',\n },\n} as const;\n\nexport type AccentCommandId = keyof typeof ACCENT_COMMANDS;\n\nexport type AccentCommandSpec = (typeof ACCENT_COMMANDS)[AccentCommandId] & {\n placement: AccentPlacement;\n};\n\nexport function accentCommandSpec(id: string): AccentCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ACCENT_COMMANDS, id)\n ? ACCENT_COMMANDS[id as AccentCommandId]\n : null;\n}\n\nexport function accentCommandsList(): AccentCommandSpec[] {\n return Object.values(ACCENT_COMMANDS);\n}\n\n/** Resolve accent id from a TeX command name like `\\hat` or `\\arabvec`. */\nexport function accentCommandIdFromTex(tex: string): AccentCommandId | null {\n const normalized = tex.startsWith('\\\\') ? tex : `\\\\${tex}`;\n for (const spec of Object.values(ACCENT_COMMANDS)) {\n if (spec.englishTex === normalized) {\n return spec.id;\n }\n }\n for (const spec of Object.values(ACCENT_COMMANDS)) {\n if (spec.arabicTex === normalized) {\n return spec.id;\n }\n }\n return null;\n}\n","export const ATOMIC_COMMANDS = {\n ///////////////////////// Functions ////////////////////////////////\n\n //////////////// Trigonometric Functions \n cos: {\n id: 'cos',\n category: 'function',\n englishTex: '\\\\cos',\n arabicTex: '\\\\arcos',\n arabicLabel: 'جتا',\n title: 'جيب التمام',\n },\n sin: {\n id: 'sin',\n category: 'function',\n englishTex: '\\\\sin',\n arabicTex: '\\\\arsin',\n arabicLabel: 'جا',\n title: 'جيب',\n },\n tan: {\n id: 'tan',\n category: 'function',\n englishTex: '\\\\tan',\n arabicTex: '\\\\artan',\n arabicLabel: 'ظا',\n title: 'ظل',\n },\n cot: {\n id: 'cot',\n category: 'function',\n englishTex: '\\\\cot',\n arabicTex: '\\\\arcot',\n arabicLabel: 'ظتا',\n title: 'ظل تمام',\n },\n sec: {\n id: 'sec',\n category: 'function',\n englishTex: '\\\\sec',\n arabicTex: '\\\\arsec',\n arabicLabel: 'قا',\n title: 'قاطع',\n },\n csc: {\n id: 'csc',\n category: 'function',\n englishTex: '\\\\csc',\n arabicTex: '\\\\arcsc',\n arabicLabel: 'قتا',\n title: 'قاطع تمام',\n },\n\n\n /////////////////// Arc Trigonometric Functions \n arccos: {\n id: 'arccos',\n category: 'function',\n englishTex: '\\\\arccos',\n arabicTex: '\\\\aracos',\n arabicLabel: 'قجتا',\n title: 'قاطع جيب التمام',\n },\n arcsin: {\n id: 'arcsin',\n category: 'function',\n englishTex: '\\\\arcsin',\n arabicTex: '\\\\arasin',\n arabicLabel: 'قجا',\n title: 'قاطع جيب',\n },\n arctan: {\n id: 'arctan',\n category: 'function',\n englishTex: '\\\\arctan',\n arabicTex: '\\\\aratan',\n arabicLabel: 'قظا',\n title: 'قاطع ظل',\n },\n arccot: {\n id: 'arccot',\n category: 'function',\n englishTex: '\\\\arccot',\n arabicTex: '\\\\aracot',\n arabicLabel: 'قظتا',\n title: 'قاطع ظل التمام',\n },\n arcsec: {\n id: 'arcsec',\n category: 'function',\n englishTex: '\\\\arcsec',\n arabicTex: '\\\\arasec',\n arabicLabel: 'ققا',\n title: 'قاطع القاطع',\n },\n arccsc: {\n id: 'arccsc',\n category: 'function',\n englishTex: '\\\\arccsc',\n arabicTex: '\\\\aracsc',\n arabicLabel: 'ققتا',\n title: 'قاطع القاطع التمام',\n },\n\n ///////////////// Hyperbolic Functions \n cosh: {\n id: 'cosh',\n category: 'function',\n englishTex: '\\\\cosh',\n arabicTex: '\\\\arcosh',\n arabicLabel: 'جتزا',\n title: 'جيب التمام الزائد',\n },\n sinh: {\n id: 'sinh',\n category: 'function',\n englishTex: '\\\\sinh',\n arabicTex: '\\\\arsinh',\n arabicLabel: 'جزا',\n title: 'جيب الزائد',\n },\n tanh: {\n id: 'tanh',\n category: 'function',\n englishTex: '\\\\tanh',\n arabicTex: '\\\\artanh',\n arabicLabel: 'ظزا',\n title: 'ظل الزائد',\n },\n coth: {\n id: 'coth',\n category: 'function',\n englishTex: '\\\\coth',\n arabicTex: '\\\\arcoth',\n arabicLabel: 'ظتزا',\n title: 'ظل تمام الزائد',\n },\n\n ////// These function somehow doesnt exist in LaTeX and therefore MathJax, skip for now. no problem.\n // sech: {\n // id: 'sech',\n // category: 'function',\n // englishTex: '\\\\sech',\n // arabicTex: '\\\\arsech',\n // arabicLabel: 'قزا',\n // title: 'قاطع الزائد',\n // },\n // csch: {\n // id: 'csch',\n // category: 'function',\n // englishTex: '\\\\csch',\n // arabicTex: '\\\\arcsch',\n // arabicLabel: 'قتزا',\n // title: 'قاطع تمام الزائد',\n // },\n\n\n ///////////////// arc Hyperbolic Functions \n ///// Not on MathJax, skip for now, it is okay.\n\n\n\n ////////////////////// Limits & Series ////////////////////////////////\n sum: {\n id: 'sum',\n category: 'limits_series',\n englishTex: '\\\\sum',\n arabicTex: '\\\\arsum',\n arabicLabel: 'مجـــ',\n title: 'مجموع',\n },\n prod: {\n id: 'prod',\n category: 'limits_series',\n englishTex: '\\\\prod',\n arabicTex: '\\\\arprod',\n arabicLabel: 'جـــد',\n title: 'جداء',\n },\n lim: {\n id: 'lim',\n category: 'limits_series',\n englishTex: '\\\\lim',\n arabicTex: '\\\\arlim',\n arabicLabel: 'نـــــها',\n title: 'حد',\n },\n arg: {\n id: 'arg',\n category: 'limits_series',\n englishTex: '\\\\arg',\n arabicTex: '\\\\ararg',\n arabicLabel: 'حج',\n title: 'حجة',\n },\n max: {\n id: 'max',\n category: 'limits_series',\n englishTex: '\\\\max',\n arabicTex: '\\\\armax',\n arabicLabel: 'أكبر',\n title: 'أكبر',\n },\n min: {\n id: 'min',\n category: 'limits_series',\n englishTex: '\\\\min',\n arabicTex: '\\\\armin',\n arabicLabel: 'أصغر',\n title: 'أصغر',\n },\n sup: {\n id: 'sup',\n category: 'limits_series',\n englishTex: '\\\\sup',\n arabicTex: '\\\\arsup',\n arabicLabel: 'أعلى',\n title: 'أعلى',\n },\n inf: {\n id: 'inf',\n category: 'limits_series',\n englishTex: '\\\\inf',\n arabicTex: '\\\\arinf',\n arabicLabel: 'أدنى',\n title: 'أدنى',\n },\n\n ////////////////////// Logarithmic and Exponential and Determinant Functions ////////////////////////////////\n pi: {\n id: 'pi',\n category: 'function2',\n englishTex: '\\\\pi',\n arabicTex: '\\\\arpi',\n arabicLabel: 'ط',\n title: 'نسبة الدائرة',\n },\n exp: {\n id: 'exp',\n category: 'function2',\n englishTex: '\\\\exp',\n arabicTex: '\\\\arexp',\n arabicLabel: 'هـ',\n title: 'أسية',\n },\n ln: {\n id: 'ln',\n category: 'function2',\n englishTex: '\\\\ln',\n arabicTex: '\\\\arln',\n arabicRenderTex: '\\\\prescript{}{\\\\arexp}{\\\\arlog}',\n arabicLabel: 'لو',\n title: 'لوغاريتم طبيعي',\n },\n log: {\n id: 'log',\n category: 'function2',\n englishTex: '\\\\log',\n arabicTex: '\\\\arlog',\n arabicLabel: 'لو',\n title: 'لوغاريتم',\n },\n det: {\n id: 'det',\n category: 'function2',\n englishTex: '\\\\det',\n arabicTex: '\\\\ardet',\n arabicLabel: 'محدد',\n title: 'محدد',\n },\n\n ////////////////////// Derivatives ////////////////////////////////\n ad: {\n id: 'ad',\n category: 'derivative',\n englishTex: '\\\\mathrm{d}',\n englishLabel: 'd',\n arabicTex: '\\\\ad',\n arabicLabel: 'ء',\n title: 'علامة الاشتقاق',\n },\n\n ////////////////////// Groups /////////////////////////////////\n N: {\n id: 'N',\n category: 'groups',\n englishTex: '\\\\mathbb{N}',\n arabicTex: '\\\\arabN',\n arabicLabel: 'ط',\n title: 'أعداد طبيعية',\n },\n Z: {\n id: 'Z',\n category: 'groups',\n englishTex: '\\\\mathbb{Z}',\n arabicTex: '\\\\arabZ',\n arabicLabel: 'ص',\n title: 'أعداد صحيحة',\n },\n Q: {\n id: 'Q',\n category: 'groups',\n englishTex: '\\\\mathbb{Q}',\n arabicTex: '\\\\arabQ',\n arabicLabel: 'ن',\n title: 'أعداد نسبية',\n },\n R: {\n id: 'R',\n category: 'groups',\n englishTex: '\\\\mathbb{R}',\n arabicTex: '\\\\arabR',\n arabicLabel: 'ح',\n title: 'أعداد حقيقية',\n },\n C: {\n id: 'C',\n category: 'groups',\n englishTex: '\\\\mathbb{C}',\n arabicTex: '\\\\arabC',\n arabicLabel: 'ع',\n title: 'أعداد عُقدية',\n },\n H: {\n id: 'H',\n category: 'groups',\n englishTex: '\\\\mathbb{H}',\n arabicTex: '\\\\arabH',\n arabicLabel: 'ر',\n title: 'أعداد رباعية',\n },\n\n ////////////////////// Operations ////////////////////////////\n\n\n ////////////////////// Spacing ////////////////////////////////\n negThinSpace: {\n id: 'negThinSpace',\n category: 'spacing',\n englishTex: '\\\\!',\n arabicTex: '\\\\!',\n arabicLabel: '',\n title: 'فراغ سالب رفيع',\n spacing: { direction: 'negative', level: 1 },\n },\n thinSpace: {\n id: 'thinSpace',\n category: 'spacing',\n englishTex: '\\\\,',\n arabicTex: '\\\\,',\n arabicLabel: '',\n title: 'فراغ رفيع',\n spacing: { direction: 'positive', level: 1 },\n },\n mediumSpace: {\n id: 'mediumSpace',\n category: 'spacing',\n englishTex: '\\\\:',\n arabicTex: '\\\\:',\n arabicLabel: '',\n title: 'فراغ متوسط',\n spacing: { direction: 'positive', level: 1 },\n },\n thickSpace: {\n id: 'thickSpace',\n category: 'spacing',\n englishTex: '\\\\;',\n arabicTex: '\\\\;',\n arabicLabel: '',\n title: 'فراغ عريض',\n spacing: { direction: 'positive', level: 2 },\n },\n quadSpace: {\n id: 'quadSpace',\n category: 'spacing',\n englishTex: '\\\\quad',\n arabicTex: '\\\\quad',\n arabicLabel: '',\n title: 'فراغ كبير',\n spacing: { direction: 'positive', level: 3 },\n },\n qquadSpace: {\n id: 'qquadSpace',\n category: 'spacing',\n englishTex: '\\\\qquad',\n arabicTex: '\\\\qquad',\n arabicLabel: '',\n title: 'فراغ كبير جدا',\n spacing: { direction: 'positive', level: 4 },\n },\n} as const;\n\nexport type AtomicCommandId = keyof typeof ATOMIC_COMMANDS;\nexport type AtomicCommandCategory = 'function' | 'function2' | 'limits_series' | 'groups' | 'spacing' | 'derivative';\nexport type SpacingDirection = 'positive' | 'negative';\n\nexport type AtomicCommandSpec = (typeof ATOMIC_COMMANDS)[AtomicCommandId] & {\n arabicRenderTex?: string;\n englishLabel?: string;\n};\nexport type SpacingCommandSpec = AtomicCommandSpec & {\n category: 'spacing';\n spacing: {\n direction: SpacingDirection;\n level: 1 | 2 | 3 | 4;\n };\n};\n\nexport function atomicCommandsByCategory(category: AtomicCommandCategory): AtomicCommandSpec[] {\n return Object.values(ATOMIC_COMMANDS).filter((command) => command.category === category);\n}\n\nexport function isSpacingCommandSpec(spec: AtomicCommandSpec | null): spec is SpacingCommandSpec {\n return spec?.category === 'spacing';\n}\n\nexport function atomicCommandSpec(id: string): AtomicCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ATOMIC_COMMANDS, id)\n ? ATOMIC_COMMANDS[id as AtomicCommandId]\n : null;\n}\n","export const ATOMIC_OPERATOR_COMMANDS = {\n inf: {\n id: 'inf',\n category: 'operators1',\n Tex: '\\\\infty',\n mirror: true,\n Label: '∞',\n title: 'اللانهاية',\n svg_path: null,\n },\n top: {\n id: 'top',\n category: 'operators1',\n Tex: '\\\\top',\n mirror: false,\n Label: '⊤',\n title: 'المنقول',\n svg_path: null,\n },\n times: {\n id: 'times',\n category: 'operators1',\n Tex: '\\\\times',\n mirror: false,\n Label: '×',\n title: 'ضرب',\n svg_path: null,\n },\n div: {\n id: 'div',\n category: 'operators1',\n Tex: '\\\\div',\n mirror: false,\n Label: '÷',\n title: 'قسمة',\n svg_path: null,\n },\n pm: {\n id: 'pm',\n category: 'operators1',\n Tex: '\\\\pm',\n mirror: false,\n Label: '±',\n title: 'زائد أو ناقص',\n svg_path: null,\n },\n mp: {\n id: 'mp',\n category: 'operators1',\n Tex: '\\\\mp',\n mirror: false,\n Label: '∓',\n title: 'ناقص أو زائد',\n svg_path: null,\n },\n neq: {\n id: 'neq',\n category: 'operators1',\n Tex: '\\\\neq',\n mirror: true,\n compileMirror: true,\n Label: '≠',\n title: 'لا يساوي',\n svg_path: null,\n },\n approx: {\n id: 'approx',\n category: 'operators1',\n Tex: '\\\\approx',\n mirror: false,\n displayMirror: true,\n Label: '≈',\n title: 'تقريبا يساوي',\n svg_path: null,\n },\n sim: {\n id: 'sim',\n category: 'operators1',\n Tex: '\\\\sim',\n mirror: false,\n displayMirror: true,\n Label: '∼',\n title: 'مشابه',\n svg_path: null,\n },\n mid: {\n id: 'mid',\n category: 'operators1',\n Tex: '\\\\mid',\n mirror: false,\n Label: '∣',\n title: 'يقسم',\n svg_path: null,\n },\n leq: {\n id: 'leq',\n category: 'operators1',\n Tex: '\\\\leq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≤',\n title: 'أصغر من أو يساوي',\n svg_path: null,\n },\n geq: {\n id: 'geq',\n category: 'operators1',\n Tex: '\\\\geq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≥',\n title: 'أكبر من أو يساوي',\n svg_path: null,\n },\n coloneqq: {\n id: 'coloneqq',\n category: 'operators1',\n Tex: '\\\\coloneqq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≔',\n title: 'يعرف بأنه يساوي',\n svg_path: null,\n },\n eqqcolon: {\n id: 'eqqcolon',\n category: 'operators1',\n Tex: '\\\\eqqcolon',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≕',\n title: 'يساوي بالتعريف',\n svg_path: null,\n },\n\n ///// Operators 2\n propto: {\n id: 'propto',\n category: 'operators2',\n Tex: '\\\\propto',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∝',\n title: 'يتناسب مع',\n svg_path: null,\n },\n in: {\n id: 'in',\n category: 'operators2',\n Tex: '\\\\in',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∈',\n title: 'ينتمي إلى',\n svg_path: null,\n },\n notin: {\n id: 'notin',\n category: 'operators2',\n Tex: '\\\\notin',\n mirror: false,\n displayMirror: true,\n Label: '∉',\n title: 'لا ينتمي إلى',\n svg_path: null,\n },\n subset: {\n id: 'subset',\n category: 'operators2',\n Tex: '\\\\subset',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊂',\n title: 'مجموعة جزئية من',\n svg_path: null,\n },\n supset: {\n id: 'supset',\n category: 'operators2',\n Tex: '\\\\supset',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊃',\n title: 'مجموعة شاملة لـ',\n svg_path: null,\n },\n subseteq: {\n id: 'subseteq',\n category: 'operators2',\n Tex: '\\\\subseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊆',\n title: 'مجموعة جزئية أو تساوي',\n svg_path: null,\n },\n supseteq: {\n id: 'supseteq',\n category: 'operators2',\n Tex: '\\\\supseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊇',\n title: 'مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n cap: {\n id: 'cap',\n category: 'operators2',\n Tex: '\\\\cap',\n mirror: false,\n displayMirror: true,\n Label: '∩',\n title: 'تقاطع',\n svg_path: null,\n },\n cup: {\n id: 'cup',\n category: 'operators2',\n Tex: '\\\\cup',\n mirror: false,\n displayMirror: true,\n Label: '∪',\n title: 'اتحاد',\n svg_path: null,\n },\n emptyset: {\n id: 'emptyset',\n category: 'operators2',\n Tex: '\\\\emptyset',\n mirror: false,\n displayMirror: true,\n Label: '∅',\n title: 'المجموعة الخالية',\n svg_path: null,\n },\n nsubseteq: {\n id: 'nsubseteq',\n category: 'operators2',\n Tex: '\\\\nsubseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊈',\n title: 'ليست مجموعة جزئية أو تساوي',\n svg_path: null,\n },\n nsupseteq: {\n id: 'nsupseteq',\n category: 'operators2',\n Tex: '\\\\nsupseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊉',\n title: 'ليست مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n\n ///// Dots\n ldots: {\n id: 'ldots',\n category: 'dots',\n Tex: '\\\\ldots',\n mirror: false,\n Label: '…',\n title: 'نقاط أفقية',\n svg_path: null,\n },\n cdot: {\n id: 'cdot',\n category: 'dots',\n Tex: '\\\\cdot',\n mirror: false,\n Label: '·',\n title: 'نقطة ضرب',\n svg_path: null,\n },\n cdots: {\n id: 'cdots',\n category: 'dots',\n Tex: '\\\\cdots',\n mirror: false,\n Label: '⋯',\n title: 'نقاط وسطية أفقية',\n svg_path: null,\n },\n vdots: {\n id: 'vdots',\n category: 'dots',\n Tex: '\\\\vdots',\n mirror: false,\n Label: '⋮',\n title: 'نقاط عمودية',\n svg_path: null,\n },\n ddots: {\n id: 'ddots',\n category: 'dots',\n Tex: '\\\\ddots',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⋱',\n title: 'نقاط قطرية',\n svg_path: null,\n },\n\n /// Operators 3\n leftrightarrowDouble: {\n id: 'leftrightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Leftrightarrow',\n mirror: false,\n Label: '⇔',\n title: 'يكافئ',\n svg_path: null,\n },\n implies: {\n id: 'implies',\n category: 'operators3',\n Tex: '\\\\implies',\n mirror: true,\n compileMirror: true,\n Label: '⇒',\n title: 'يستلزم',\n svg_path: null,\n },\n impliedby: {\n id: 'impliedby',\n category: 'operators3',\n Tex: '\\\\impliedby',\n mirror: true,\n compileMirror: true,\n Label: '⇐',\n title: 'مستلزم من',\n svg_path: null,\n },\n iff: {\n id: 'iff',\n category: 'operators3',\n Tex: '\\\\iff',\n mirror: false,\n Label: '⇔',\n title: 'إذا وفقط إذا',\n svg_path: null,\n },\n Longrightarrow: {\n id: 'Longrightarrow',\n category: 'operators3',\n Tex: '\\\\Longrightarrow',\n mirror: true,\n compileMirror: true,\n Label: '⟹',\n title: 'سهم مزدوج طويل إلى اليمين',\n svg_path: null,\n },\n Longleftarrow: {\n id: 'Longleftarrow',\n category: 'operators3',\n Tex: '\\\\Longleftarrow',\n mirror: true,\n compileMirror: true,\n Label: '⟸',\n title: 'سهم مزدوج طويل إلى اليسار',\n svg_path: null,\n },\n to: {\n id: 'to',\n category: 'operators3',\n Tex: '\\\\to',\n mirror: true,\n compileMirror: true,\n Label: '→',\n title: 'يؤول إلى',\n svg_path: null,\n },\n rightleftharpoons: {\n id: 'rightleftharpoons',\n category: 'operators3',\n Tex: '\\\\rightleftharpoons',\n mirror: true,\n compileMirror: true,\n Label: '⇌',\n title: 'اتزان',\n svg_path: null,\n },\n leftarrow: {\n id: 'leftarrow',\n category: 'operators3',\n Tex: '\\\\leftarrow',\n mirror: true,\n compileMirror: true,\n Label: '←',\n title: 'سهم إلى اليسار',\n svg_path: null,\n },\n rightarrow: {\n id: 'rightarrow',\n category: 'operators3',\n Tex: '\\\\rightarrow',\n mirror: true,\n compileMirror: true,\n Label: '→',\n title: 'سهم إلى اليمين',\n svg_path: null,\n },\n leftarrowDouble: {\n id: 'leftarrowDouble',\n category: 'operators3',\n Tex: '\\\\Leftarrow',\n mirror: true,\n compileMirror: true,\n Label: '⇐',\n title: 'سهم مزدوج إلى اليسار',\n svg_path: null,\n },\n rightarrowDouble: {\n id: 'rightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Rightarrow',\n mirror: true,\n compileMirror: true,\n Label: '⇒',\n title: 'سهم مزدوج إلى اليمين',\n svg_path: null,\n },\n leftharpoonup: {\n id: 'leftharpoonup',\n category: 'operators3',\n Tex: '\\\\leftharpoonup',\n mirror: true,\n compileMirror: true,\n Label: '↼',\n title: 'سهم خطافي علوي إلى اليسار',\n svg_path: null,\n },\n rightharpoonup: {\n id: 'rightharpoonup',\n category: 'operators3',\n Tex: '\\\\rightharpoonup',\n mirror: true,\n compileMirror: true,\n Label: '⇀',\n title: 'سهم خطافي علوي إلى اليمين',\n svg_path: null,\n },\n leftharpoondown: {\n id: 'leftharpoondown',\n category: 'operators3',\n Tex: '\\\\leftharpoondown',\n mirror: true,\n compileMirror: true,\n Label: '↽',\n title: 'سهم خطافي سفلي إلى اليسار',\n svg_path: null,\n },\n rightharpoondown: {\n id: 'rightharpoondown',\n category: 'operators3',\n Tex: '\\\\rightharpoondown',\n mirror: true,\n compileMirror: true,\n Label: '⇁',\n title: 'سهم خطافي سفلي إلى اليمين',\n svg_path: null,\n },\n\n // Integrals\n int: {\n id: 'int',\n category: 'integrals',\n Tex: '\\\\int',\n mirror: true,\n compileMirror: true,\n Label: '∫',\n title: 'تكامل',\n svg_path: null,\n },\n iint: {\n id: 'iint',\n category: 'integrals',\n Tex: '\\\\iint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∬',\n title: 'تكامل مزدوج',\n svg_path: null,\n },\n iiint: {\n id: 'iiint',\n category: 'integrals',\n Tex: '\\\\iiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∭',\n title: 'تكامل ثلاثي',\n svg_path: null,\n },\n iiiint: {\n id: 'iiiint',\n category: 'integrals',\n Tex: '\\\\iiiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⨌',\n title: 'تكامل رباعي',\n svg_path: null,\n },\n oint: {\n id: 'oint',\n category: 'integrals',\n Tex: '\\\\oint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∮',\n title: 'تكامل مغلق',\n svg_path: null,\n },\n oiint: {\n id: 'oiint',\n category: 'integrals',\n Tex: '\\\\oiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∯',\n title: 'تكامل سطحي مغلق',\n svg_path: null,\n },\n oiiint: {\n id: 'oiiint',\n category: 'integrals',\n Tex: '\\\\oiiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∰',\n title: 'تكامل حجمي مغلق',\n svg_path: null,\n },\n} as const;\n\nexport type AtomicOperatorCommandId = keyof typeof ATOMIC_OPERATOR_COMMANDS;\n\nexport type AtomicOperatorCommandCategory =\n | 'operators1'\n | 'operators2'\n | 'operators3'\n | 'dots'\n | 'integrals';\n\nexport type AtomicOperatorCommandSpec =\n (typeof ATOMIC_OPERATOR_COMMANDS)[AtomicOperatorCommandId] & {\n displayMirror?: boolean;\n compileMirror?: boolean;\n };\n\nexport function shouldMirrorOperatorDisplay(\n command: AtomicOperatorCommandSpec | null | undefined,\n): boolean {\n return command?.displayMirror ?? command?.mirror ?? false;\n}\n\nconst MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS)\n .filter((command) => command.mirror)\n .map((command) => command.Tex)\n .sort((a, b) => b.length - a.length) as string[];\n\nconst COMPILE_MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS)\n .filter((command) => 'compileMirror' in command && command.compileMirror)\n .map((command) => command.Tex)\n .sort((a, b) => b.length - a.length) as string[];\n\nfunction matchingMirroredOperatorFrom(tex: string, index: number, operatorTexList: string[]): string | null {\n for (const operatorTex of operatorTexList) {\n if (!tex.startsWith(operatorTex, index)) {\n continue;\n }\n const next = tex[index + operatorTex.length];\n if (next != null && /[A-Za-z]/.test(next)) {\n continue;\n }\n return operatorTex;\n }\n return null;\n}\n\nfunction findMatchingBrace(tex: string, openIndex: number): number {\n let depth = 0;\n for (let index = openIndex; index < tex.length; index += 1) {\n const char = tex[index];\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n return -1;\n}\n\nexport function mirrorBuTeXOperatorsInTex(tex: string, options: { target?: 'preview' | 'compile' } = {}): string {\n const mirroredOperatorTex = options.target === 'compile'\n ? COMPILE_MIRRORED_OPERATOR_TEX\n : MIRRORED_OPERATOR_TEX;\n let result = '';\n let index = 0;\n\n while (index < tex.length) {\n if (tex.startsWith('\\\\butexmirror{', index)) {\n const end = findMatchingBrace(tex, index + '\\\\butexmirror'.length);\n if (end !== -1) {\n const bodyStart = index + '\\\\butexmirror{'.length;\n const body = tex.slice(bodyStart, end);\n if (\n options.target === 'compile' &&\n MIRRORED_OPERATOR_TEX.includes(body) &&\n !mirroredOperatorTex.includes(body)\n ) {\n result += body;\n } else {\n result += tex.slice(index, end + 1);\n }\n index = end + 1;\n continue;\n }\n }\n\n const operatorTex = matchingMirroredOperatorFrom(tex, index, mirroredOperatorTex);\n if (operatorTex) {\n result += `\\\\butexmirror{${operatorTex}}`;\n index += operatorTex.length;\n continue;\n }\n\n result += tex[index];\n index += 1;\n }\n\n return result;\n}\n\nexport function atomicOperatorCommandsByCategory(\n category: AtomicOperatorCommandCategory,\n): AtomicOperatorCommandSpec[] {\n return Object.values(ATOMIC_OPERATOR_COMMANDS).filter(\n (command) => command.category === category,\n );\n}\n\nexport function atomicOperatorCommandSpec(\n id: string,\n): AtomicOperatorCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ATOMIC_OPERATOR_COMMANDS, id)\n ? ATOMIC_OPERATOR_COMMANDS[id as AtomicOperatorCommandId]\n : null;\n}\n","import type { EditorChain, EditorSession } from './types.js';\n\nexport const STANDARD_COMMANDS = {\n '\\\\alpha': { tex: '\\\\alpha', label: 'α', title: 'alpha' },\n '\\\\beta': { tex: '\\\\beta', label: 'β', title: 'beta' },\n '\\\\gamma': { tex: '\\\\gamma', label: 'γ', title: 'gamma' },\n '\\\\delta': { tex: '\\\\delta', label: 'δ', title: 'delta' },\n '\\\\epsilon': { tex: '\\\\epsilon', label: 'ε', title: 'epsilon' },\n '\\\\eta': { tex: '\\\\eta', label: 'η', title: 'eta' },\n '\\\\theta': { tex: '\\\\theta', label: 'θ', title: 'theta' },\n '\\\\lambda': { tex: '\\\\lambda', label: 'λ', title: 'lambda' },\n '\\\\mu': { tex: '\\\\mu', label: 'μ', title: 'mu' },\n '\\\\rho': { tex: '\\\\rho', label: 'ρ', title: 'rho' },\n '\\\\sigma': { tex: '\\\\sigma', label: 'σ', title: 'sigma' },\n '\\\\tau': { tex: '\\\\tau', label: 'τ', title: 'tau' },\n '\\\\phi': { tex: '\\\\phi', label: 'φ', title: 'phi' },\n '\\\\chi': { tex: '\\\\chi', label: 'χ', title: 'chi' },\n '\\\\psi': { tex: '\\\\psi', label: 'ψ', title: 'psi' },\n '\\\\omega': { tex: '\\\\omega', label: 'ω', title: 'omega' },\n '\\\\zeta': { tex: '\\\\zeta', label: 'ζ', title: 'zeta' },\n '\\\\nabla': { tex: '\\\\nabla', label: '∇', title: 'nabla' },\n '\\\\Delta': { tex: '\\\\Delta', label: 'Δ', title: 'Delta' },\n '\\\\partial': { tex: '\\\\partial', label: '∂', title: 'partial derivative' },\n '\\\\Longleftrightarrow': { tex: '\\\\Longleftrightarrow', label: '⟺', title: 'long equivalence arrow' },\n '\\\\backslash': { tex: '\\\\backslash', label: '∖', title: 'reverse solidus' },\n} as const;\n\nexport type StandardCommandTex = keyof typeof STANDARD_COMMANDS;\nexport type StandardCommandSpec = (typeof STANDARD_COMMANDS)[StandardCommandTex];\n\nexport function standardCommandSpec(tex: string): StandardCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(STANDARD_COMMANDS, tex)\n ? STANDARD_COMMANDS[tex as StandardCommandTex]\n : null;\n}\n\nexport function isStandardCommandTex(tex: string): tex is StandardCommandTex {\n return standardCommandSpec(tex) !== null;\n}\n\nfunction chainHasStandardCommands(chain: EditorChain): boolean {\n for (const node of chain.nodes) {\n if (node.kind === 'standardCommand') {\n return true;\n }\n const childChains = [\n node.superscript,\n node.subscript,\n node.innerExpr,\n node.numerator,\n node.denominator,\n node.radicand,\n node.rootIndex,\n node.overExpr,\n node.underExpr,\n node.baseExpr,\n ];\n if (childChains.some((child) => child && chainHasStandardCommands(child))) {\n return true;\n }\n if (node.matrixRows?.some((row) => row.some(chainHasStandardCommands))) {\n return true;\n }\n }\n return false;\n}\n\nexport function sessionHasStandardCommands(session: EditorSession): boolean {\n return chainHasStandardCommands(session.englishTree) || chainHasStandardCommands(session.arabicTree);\n}\n","import type { EditorChain, EditorNode, EditorSession, EditorSide, EnvColumnAlignment, GridEnvName, MatrixEnvStyle } from './types.js';\nimport type { AccentCommandId } from './accentCommands.js';\nimport type { AtomicCommandId } from './atomicCommands.js';\nimport type { AtomicOperatorCommandId } from './atomicCommandsOperators.js';\n\nlet nextId = 1;\n\nfunction makeId(prefix: string): string {\n const id = `${prefix}_${String(nextId)}`;\n nextId += 1;\n return id;\n}\n\nexport function createEditorChain(nodes: EditorNode[] = []): EditorChain {\n return {\n id: makeId('chain'),\n nodes,\n };\n}\n\nexport function createEditorNode(kind: EditorNode['kind'], expr: string): EditorNode {\n return {\n id: makeId('node'),\n kind,\n expr,\n characterFont: undefined,\n superscript: null,\n subscript: null,\n leftDelimExpr: '',\n rightDelimExpr: '',\n innerExpr: null,\n numerator: null,\n denominator: null,\n radicand: null,\n rootIndex: null,\n overExpr: null,\n underExpr: null,\n baseExpr: null,\n envName: null,\n matrixStyle: null,\n matrixRows: null,\n columnAlignments: null,\n };\n}\n\nexport function createDelimiterNode(leftDelimExpr: string, rightDelimExpr: string): EditorNode {\n return {\n ...createEditorNode('delimiter', ''),\n leftDelimExpr,\n rightDelimExpr,\n innerExpr: createEditorChain(),\n };\n}\n\nexport function createBoxedNode(): EditorNode {\n return {\n ...createEditorNode('boxed', ''),\n innerExpr: createEditorChain(),\n };\n}\n\nexport function createFracNode(): EditorNode {\n return {\n ...createEditorNode('frac', ''),\n numerator: createEditorChain(),\n denominator: createEditorChain(),\n };\n}\n\nexport function createSqrtNode(): EditorNode {\n return {\n ...createEditorNode('sqrt', ''),\n radicand: createEditorChain(),\n rootIndex: createEditorChain(),\n };\n}\n\nexport function createOversetNode(): EditorNode {\n return {\n ...createEditorNode('overset', ''),\n overExpr: createEditorChain(),\n baseExpr: createEditorChain(),\n };\n}\n\nexport function createUndersetNode(): EditorNode {\n return {\n ...createEditorNode('underset', ''),\n underExpr: createEditorChain(),\n baseExpr: createEditorChain(),\n };\n}\n\nexport function createAccentNode(accentId: AccentCommandId): EditorNode {\n return {\n ...createEditorNode('accent', accentId),\n baseExpr: createEditorChain(),\n };\n}\n\nexport function createMatrixEnvNode(style: MatrixEnvStyle, rows: number, columns: number): EditorNode {\n return createGridEnvNode(style, rows, columns);\n}\n\nexport function createGridEnvNode(\n envName: GridEnvName,\n rows: number,\n columns: number,\n columnAlignments?: EnvColumnAlignment[],\n): EditorNode {\n const safeRows = Math.max(1, Math.min(12, Math.trunc(rows)));\n const safeColumns = envName === 'cases' ? 2 : Math.max(1, Math.min(12, Math.trunc(columns)));\n const matrixStyles = new Set<GridEnvName>(['matrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix', 'Vmatrix']);\n const isMatrix = matrixStyles.has(envName) && envName !== 'array' && envName !== 'aligned';\n return {\n ...createEditorNode('env', ''),\n envName,\n matrixStyle: isMatrix ? (envName as MatrixEnvStyle) : null,\n matrixRows: Array.from({ length: safeRows }, () =>\n Array.from({ length: safeColumns }, () => createEditorChain()),\n ),\n columnAlignments: envName === 'array'\n ? Array.from({ length: safeColumns }, (_, index) => columnAlignments?.[index] ?? 'c')\n : null,\n };\n}\n\nexport function createAtomicCommandNode(commandId: AtomicCommandId): EditorNode {\n return createEditorNode('atomicCommand', commandId);\n}\n\nexport function createAtomicOperatorCommandNode(commandId: AtomicOperatorCommandId): EditorNode {\n return createEditorNode('atomicOperatorCommand', commandId);\n}\n\nexport function cloneEditorSession(session: EditorSession): EditorSession {\n return {\n englishTree: structuredClone(session.englishTree),\n arabicTree: structuredClone(session.arabicTree),\n activeSide: session.activeSide,\n splitLeafTyping: session.splitLeafTyping,\n forceSplitNextLeaf: session.forceSplitNextLeaf,\n arabicReverseNumberTyping: session.arabicReverseNumberTyping,\n currentCharacterFont: session.currentCharacterFont ?? 'default',\n currentCharacterWrapper: session.currentCharacterWrapper ?? null,\n currentDigitForm: session.currentDigitForm ?? 'western',\n caret: { ...session.caret },\n selection: session.selection ? { ...session.selection } : null,\n selectedNodeId: session.selectedNodeId,\n selectedStructureNodeId: session.selectedStructureNodeId,\n sync: structuredClone(session.sync),\n debugLog: session.debugLog.slice(),\n };\n}\n\nfunction collectNodeIds(chain: EditorChain, ids: string[]): void {\n for (const node of chain.nodes) {\n ids.push(node.id);\n if (node.superscript) {\n collectNodeIds(node.superscript, ids);\n }\n if (node.subscript) {\n collectNodeIds(node.subscript, ids);\n }\n if (node.innerExpr) {\n collectNodeIds(node.innerExpr, ids);\n }\n if (node.numerator) {\n collectNodeIds(node.numerator, ids);\n }\n if (node.denominator) {\n collectNodeIds(node.denominator, ids);\n }\n if (node.rootIndex) {\n collectNodeIds(node.rootIndex, ids);\n }\n if (node.radicand) {\n collectNodeIds(node.radicand, ids);\n }\n if (node.overExpr) {\n collectNodeIds(node.overExpr, ids);\n }\n if (node.underExpr) {\n collectNodeIds(node.underExpr, ids);\n }\n if (node.baseExpr) {\n collectNodeIds(node.baseExpr, ids);\n }\n if (node.matrixRows) {\n for (const row of node.matrixRows) {\n for (const cell of row) {\n collectNodeIds(cell, ids);\n }\n }\n }\n }\n}\n\nexport function buildInitialSyncMap(englishTree: EditorChain, arabicTree: EditorChain): EditorSession['sync'] {\n const englishIds: string[] = [];\n const arabicIds: string[] = [];\n collectNodeIds(englishTree, englishIds);\n collectNodeIds(arabicTree, arabicIds);\n\n const all = new Set<string>([...englishIds, ...arabicIds]);\n const sync: EditorSession['sync'] = {};\n for (const nodeId of all) {\n sync[nodeId] = { expr: 'synced' };\n }\n return sync;\n}\n\nexport function createEditorSession(englishTree: EditorChain, arabicTree: EditorChain, activeSide: EditorSide = 'arabic'): EditorSession {\n return {\n englishTree,\n arabicTree,\n activeSide,\n splitLeafTyping: false,\n forceSplitNextLeaf: false,\n arabicReverseNumberTyping: true,\n currentCharacterFont: 'default',\n currentCharacterWrapper: null,\n currentDigitForm: 'western',\n caret: {\n chainId: englishTree.id,\n index: 0,\n },\n selection: null,\n selectedNodeId: null,\n selectedStructureNodeId: null,\n sync: buildInitialSyncMap(englishTree, arabicTree),\n debugLog: [],\n };\n}\n","import type { CharacterFontId } from './types.js';\n\nexport type CharacterFontSpec = {\n id: CharacterFontId;\n label: string;\n titleKey:\n | 'defaultFont'\n | 'takweenFont'\n | 'diwaniFont'\n | 'diwaniOutlineFont'\n | 'maghribiFont';\n cssClass?: string;\n mathJaxClass?: string;\n macro?: string;\n latexFontCommand?: string;\n latexFontFamily?: string;\n browserFontStack?: string;\n importAliases?: string[];\n svgLayoutKey?: string;\n};\n\nexport const CHARACTER_FONT_SPECS: CharacterFontSpec[] = [\n {\n id: 'default',\n label: 'س',\n titleKey: 'defaultFont',\n },\n {\n id: 'takween',\n label: 'تك',\n titleKey: 'takweenFont',\n cssClass: 'node-value--takween',\n mathJaxClass: 'butex-takween-text',\n macro: '\\\\butextakween',\n latexFontCommand: '\\\\takween',\n latexFontFamily: 'Takween',\n browserFontStack: '\"BuTeX Takween\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\takween'],\n svgLayoutKey: 'takween',\n },\n {\n id: 'diwani',\n label: 'ديو',\n titleKey: 'diwaniFont',\n cssClass: 'node-value--diwani',\n mathJaxClass: 'butex-diwani-text',\n macro: '\\\\butexdiwani',\n latexFontCommand: '\\\\diwani',\n latexFontFamily: 'Diwani Letter',\n browserFontStack: '\"Diwani Letter\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\diwani'],\n svgLayoutKey: 'diwani',\n },\n {\n id: 'diwaniOutline',\n label: 'ظل',\n titleKey: 'diwaniOutlineFont',\n cssClass: 'node-value--diwani-outline',\n mathJaxClass: 'butex-diwani-outline-text',\n macro: '\\\\butexdiwanioutline',\n latexFontCommand: '\\\\diwanioutlineshaded',\n latexFontFamily: 'Diwani Outline Shaded',\n browserFontStack: '\"BuTeX Diwani Outline\", \"Diwani Letter\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\diwanioutlineshaded'],\n svgLayoutKey: 'diwani-outline',\n },\n {\n id: 'maghribi',\n label: 'مغ',\n titleKey: 'maghribiFont',\n cssClass: 'node-value--maghribi',\n mathJaxClass: 'butex-maghribi-text',\n macro: '\\\\butexmaghribi',\n latexFontCommand: '\\\\maghribi',\n latexFontFamily: 'Almaghribi Warsh Quran',\n browserFontStack: '\"Almaghribi Warsh Quran\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\maghribi'],\n svgLayoutKey: 'maghribi',\n },\n];\n\nexport const CHARACTER_FONT_OPTIONS = CHARACTER_FONT_SPECS.map(({ id, label }) => ({ id, label }));\n\nexport const NON_DEFAULT_CHARACTER_FONT_SPECS = CHARACTER_FONT_SPECS.filter(\n (font): font is CharacterFontSpec & { macro: string } => font.id !== 'default' && typeof font.macro === 'string',\n);\n\nexport function characterFontSpec(fontId: CharacterFontId): CharacterFontSpec {\n return CHARACTER_FONT_SPECS.find((font) => font.id === fontId) ?? CHARACTER_FONT_SPECS[0];\n}\n\nexport function characterFontSpecByMacro(macro: string): CharacterFontSpec | null {\n return NON_DEFAULT_CHARACTER_FONT_SPECS.find(\n (font) => font.macro === macro || font.importAliases?.includes(macro),\n ) ?? null;\n}\n","import type { EditorSide } from './types.js';\n\n/** LTR divide stroke stored on the English tree (reference OperatorObject `/`). */\nexport const DIVIDE_OPERATOR_EN = '/';\n\n/** RTL divide stroke shown on the Arabic editing surface. */\nexport const DIVIDE_OPERATOR_AR = '\\\\';\n\n/** Structured Burhan Arabic AST spelling of the same RTL divide stroke. */\nexport const DIVIDE_OPERATOR_AR_LATEX = '\\\\backslash';\n\nexport function isDivideOperatorExpr(expr: string): boolean {\n return (\n expr === DIVIDE_OPERATOR_EN ||\n expr === DIVIDE_OPERATOR_AR ||\n expr === DIVIDE_OPERATOR_AR_LATEX\n );\n}\n\nexport function divideOperatorSurfaceExpr(expr: string, side: EditorSide): string {\n if (!isDivideOperatorExpr(expr)) {\n return expr;\n }\n return side === 'arabic' ? DIVIDE_OPERATOR_AR : DIVIDE_OPERATOR_EN;\n}\n\nexport function renderDivideOperatorLatex(side: EditorSide): string {\n return side === 'arabic' ? '\\\\backslash' : DIVIDE_OPERATOR_EN;\n}\n","import type { EditorSide } from './types.js';\nimport {\n divideOperatorSurfaceExpr,\n isDivideOperatorExpr,\n renderDivideOperatorLatex,\n} from './divideOperator.js';\n\nconst RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE: Readonly<Record<string, string>> = {\n '<': '>',\n '>': '<',\n};\n\n/**\n * Return the visible glyph for a raw OperatorObject without changing its\n * canonical stored identity. Arabic chains reverse operand order, so\n * directional comparison glyphs must be mirrored at presentation time.\n */\nexport function rawOperatorSurfaceExpr(expr: string, side: EditorSide): string {\n if (isDivideOperatorExpr(expr)) {\n return divideOperatorSurfaceExpr(expr, side);\n }\n if (side === 'arabic') {\n return RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE[expr] ?? expr;\n }\n return expr;\n}\n\n/**\n * Render a raw OperatorObject as LaTeX for one editor side while preserving\n * the operator stored in the structured AST. BuTeX's mirror macro handles\n * directional glyph presentation for Arabic MathJax/XeLaTeX output.\n */\nexport function renderRawOperatorLatex(expr: string, side: EditorSide): string {\n if (isDivideOperatorExpr(expr)) {\n return renderDivideOperatorLatex(side);\n }\n if (\n side === 'arabic' &&\n Object.prototype.hasOwnProperty.call(RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE, expr)\n ) {\n return `\\\\butexmirror{${expr}}`;\n }\n return expr;\n}\n","import type { EditorChain, EditorNode } from './types.js';\n\nexport function isIndexComma(node: EditorNode): boolean {\n return node.kind === 'operator' && (node.expr === ',' || node.expr === '،');\n}\n\n/** Only simple single-character indices and separating commas stay annotated. */\nexport function isValidIndexSequence(chain: EditorChain): boolean {\n let count = 0;\n let afterComma = false;\n for (const node of chain.nodes) {\n if (node.superscript || node.subscript) return false;\n if (isIndexComma(node)) {\n if (count === 0 || afterComma) return false;\n afterComma = true;\n continue;\n }\n const isDigit = node.kind === 'number' && /^[0-9]$/.test(node.expr);\n const identity = node.sourceLatex ?? node.expr;\n const isLetter = node.kind === 'char' &&\n (/^[A-Za-z]$/.test(identity) || (Array.from(identity).length === 1 && /^\\p{L}$/u.test(identity)));\n if (!isDigit && !isLetter) return false;\n count += 1;\n afterComma = false;\n if (count > 64) return false;\n }\n return count >= 2 && !afterComma;\n}\n","import type { DigitFormId, EditorChain, EditorNode, EditorSession, EnvColumnAlignment } from './types.js';\nimport { accentCommandSpec } from './accentCommands.js';\nimport { atomicCommandSpec } from './atomicCommands.js';\nimport { atomicOperatorCommandSpec } from './atomicCommandsOperators.js';\nimport { characterFontSpec } from './characterFonts.js';\nimport { renderRawOperatorLatex } from './rawOperatorPresentation.js';\nimport { formatDigits } from './digits.js';\nimport { isValidIndexSequence, isIndexComma } from './indexSequence.js';\n\ntype RenderOptions = {\n digitForm?: DigitFormId;\n casesPresentation?: boolean;\n};\n\nfunction selectedDigitForm(options?: RenderOptions): DigitFormId {\n return options?.digitForm ?? 'western';\n}\n\nfunction latinScripts(node: EditorNode, options?: RenderOptions): string {\n let scripts = '';\n if (node.superscript) {\n scripts += `^{${renderChainEnglish(node.superscript, options)}}`;\n }\n if (node.subscript) {\n scripts += `_{${renderChainEnglish(node.subscript, options)}}`;\n }\n return scripts;\n}\n\nfunction optionalRootIndexEnglish(node: EditorNode, options?: RenderOptions): string {\n if (!node.rootIndex) {\n return '';\n }\n const rendered = renderChainEnglish(node.rootIndex, options);\n return rendered === '' ? '' : `[${rendered}]`;\n}\n\nfunction optionalRootIndexArabic(node: EditorNode, options?: RenderOptions): string {\n if (!node.rootIndex) {\n return '';\n }\n const rendered = renderChainArabic(node.rootIndex, options);\n return rendered === '' ? '' : `[${rendered}]`;\n}\n\nfunction arabicScripts(node: EditorNode, content: string, options?: RenderOptions): string {\n const sup = node.superscript ? renderChainArabic(node.superscript, options) : '';\n const sub = node.subscript ? renderChainArabic(node.subscript, options) : '';\n if (sup !== '' || sub !== '') {\n return `\\\\prescript{${sup}}{${sub}}{${content}}`;\n }\n return content;\n}\n\nfunction renderMatrixRowsEnglish(node: EditorNode, options?: RenderOptions): string {\n if (!node.matrixRows) {\n return '';\n }\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return '';\n }\n const rows = node.matrixRows.map((row) => row.map((cell) => renderChainEnglish(cell, options)).join(' & '));\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows[0]?.length ?? 0).join('');\n return `\\\\begin{array}{${spec || 'c'}}${rows.join(' \\\\\\\\\\n')}\\\\end{array}`;\n }\n return `\\\\begin{${envName}}${rows.join(' \\\\\\\\\\n')}\\\\end{${envName}}`;\n}\n\nfunction reverseAlignmentForArabic(alignment: EnvColumnAlignment): EnvColumnAlignment {\n if (alignment === 'l') {\n return 'r';\n }\n if (alignment === 'r') {\n return 'l';\n }\n return 'c';\n}\n\nfunction renderMatrixRowsArabic(node: EditorNode, options?: RenderOptions): string {\n if (!node.matrixRows) {\n return '';\n }\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return '';\n }\n const rows = node.matrixRows.map((row) =>\n row\n .slice()\n .reverse()\n .map((cell) => renderChainArabic(cell, options))\n .join(' & '),\n );\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? [])\n .slice(0, node.matrixRows[0]?.length ?? 0)\n .reverse()\n .map(reverseAlignmentForArabic)\n .join('');\n return `\\\\begin{array}{${spec || 'c'}}${rows.join(' \\\\\\\\\\n')}\\\\end{array}`;\n }\n if (envName === 'cases' && options?.casesPresentation) {\n return `\\\\left.\\\\begin{array}{rl}${rows.join(' \\\\\\\\\\n')}\\\\end{array}\\\\right\\\\}`;\n }\n return `\\\\begin{${envName}}${rows.join(' \\\\\\\\\\n')}\\\\end{${envName}}`;\n}\n\nfunction renderAccentEnglish(\n command: 'overset' | 'underset',\n accent: EditorChain | null,\n base: EditorChain | null,\n options?: RenderOptions,\n): string {\n const baseTex = base ? renderChainEnglish(base, options) : '';\n const accentTex = accent ? renderChainEnglish(accent, options) : '';\n if (accentTex === '') {\n return baseTex;\n }\n return `\\\\${command}{${accentTex}}{${baseTex}}`;\n}\n\nfunction renderAccentArabic(\n command: 'overset' | 'underset',\n accent: EditorChain | null,\n base: EditorChain | null,\n options?: RenderOptions,\n): string {\n const baseTex = base ? renderChainArabic(base, options) : '';\n const accentTex = accent ? renderChainArabic(accent, options) : '';\n if (accentTex === '') {\n return baseTex;\n }\n return `\\\\${command}{${accentTex}}{${baseTex}}`;\n}\n\nfunction escapeText(s: string): string {\n return s.replace(/\\\\/g, '\\\\textbackslash{}').replace(/[{}]/g, '\\\\$&');\n}\n\n// Imported literal spans can contain already-escaped LaTeX punctuation.\n// Normalize these before escaping newly authored text, without double-escaping.\nfunction escapeAtomicLiteral(text: string): string {\n const unescaped = text.replace(/\\\\([%_&#{}$])/g, '$1');\n return escapeText(unescaped).replace(/[%_&#$]/g, '\\\\$&');\n}\n\nfunction renderCharContent(node: EditorNode, options?: RenderOptions): string {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const font = node.characterFont ?? 'default';\n const macro = characterFontSpec(font).macro;\n if (macro) {\n return `${macro}{${escapeText(expr)}}`;\n }\n return expr;\n}\n\nfunction renderNodeEnglish(node: EditorNode, options?: RenderOptions): string {\n if (node.kind === 'delimiter' && node.innerExpr) {\n return `${node.leftDelimExpr} ${renderChainEnglish(node.innerExpr, options)}${node.rightDelimExpr}${latinScripts(node, options)}`;\n }\n if (node.kind === 'boxed' && node.innerExpr) {\n const body = `\\\\boxed{${renderChainEnglish(node.innerExpr, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'frac' && node.numerator && node.denominator) {\n const body = `\\\\frac{${renderChainEnglish(node.numerator, options)}}{${renderChainEnglish(node.denominator, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'sqrt' && node.radicand) {\n const body = `\\\\sqrt${optionalRootIndexEnglish(node, options)}{${renderChainEnglish(node.radicand, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'overset' && node.baseExpr) {\n const body = renderAccentEnglish('overset', node.overExpr, node.baseExpr, options);\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'underset' && node.baseExpr) {\n const body = renderAccentEnglish('underset', node.underExpr, node.baseExpr, options);\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'accent' && node.baseExpr) {\n const cmd = accentCommandSpec(node.expr)?.englishTex ?? `\\\\${node.expr}`;\n const body = `${cmd}{${renderChainEnglish(node.baseExpr, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'env') {\n return `${renderMatrixRowsEnglish(node, options)}${latinScripts(node, options)}`;\n }\n if (node.kind === 'atomicCommand') {\n const body = atomicCommandSpec(node.expr)?.englishTex ?? node.expr;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'atomicOperatorCommand') {\n const body = node.sourceLatex === '\\\\le' || node.sourceLatex === '\\\\ge'\n ? node.sourceLatex : atomicOperatorCommandSpec(node.expr)?.Tex ?? node.expr;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'standardCommand') {\n return `${node.expr}${latinScripts(node, options)}`;\n }\n if (node.kind === 'char') {\n if (node.sourceLatex) {\n // Burhan's mapped bold Arabic character records the underlying English\n // variable on the inner text node. Keep the original variable identity\n // *and* its enclosing bold style when emitting interoperable English TeX.\n if (node.wrapperCommand === '\\\\boldarabic' || node.wrapperCommand === '\\\\mathbf') {\n const boldSource = node.sourceLatex.startsWith('\\\\mathbf{')\n ? node.sourceLatex\n : `\\\\mathbf{${node.sourceLatex}}`;\n return `${boldSource}${latinScripts(node, options)}`;\n }\n return `${node.sourceLatex}${latinScripts(node, options)}`;\n }\n if (node.wrapperCommand) {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const wrapper = node.wrapperCommand === '\\\\boldarabic' ? '\\\\mathbf' : node.wrapperCommand;\n const escaped = wrapper === '\\\\operatorname' || wrapper === '\\\\text'\n ? escapeAtomicLiteral(expr) : escapeText(expr);\n return `${wrapper}{${escaped}}${latinScripts(node, options)}`;\n }\n return `${renderCharContent(node, options)}${latinScripts(node, options)}`;\n }\n if (node.kind === 'operator') {\n return `${renderRawOperatorLatex(node.expr, 'english')}${latinScripts(node, options)}`;\n }\n return `${formatDigits(node.expr, selectedDigitForm(options))}${latinScripts(node, options)}`;\n}\n\nfunction renderNodeArabic(node: EditorNode, options?: RenderOptions): string {\n if (node.kind === 'delimiter' && node.innerExpr) {\n const content = `${node.leftDelimExpr}${renderChainArabic(node.innerExpr, options)}${node.rightDelimExpr}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'boxed' && node.innerExpr) {\n const content = `\\\\boxed{${renderChainArabic(node.innerExpr, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'frac' && node.numerator && node.denominator) {\n const content = `\\\\frac{${renderChainArabic(node.numerator, options)}}{${renderChainArabic(node.denominator, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'sqrt' && node.radicand) {\n const content = `\\\\arsqrt${optionalRootIndexArabic(node, options)}{${renderChainArabic(node.radicand, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'overset' && node.baseExpr) {\n const content = renderAccentArabic('overset', node.overExpr, node.baseExpr, options);\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'underset' && node.baseExpr) {\n const content = renderAccentArabic('underset', node.underExpr, node.baseExpr, options);\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'accent' && node.baseExpr) {\n const cmd = accentCommandSpec(node.expr)?.arabicTex ?? `\\\\${node.expr}`;\n const content = `${cmd}{${renderChainArabic(node.baseExpr, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'env') {\n return arabicScripts(node, renderMatrixRowsArabic(node, options), options);\n }\n if (node.kind === 'atomicCommand') {\n const spec = atomicCommandSpec(node.expr);\n const content = spec?.arabicRenderTex ?? spec?.arabicTex ?? node.expr;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'atomicOperatorCommand') {\n const spec = atomicOperatorCommandSpec(node.expr);\n const tex = spec?.Tex ?? node.expr;\n const content = spec?.mirror ? `\\\\butexmirror{${tex}}` : tex;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'standardCommand') {\n return arabicScripts(node, node.expr, options);\n }\n if (node.kind === 'char') {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const content = renderCharContent(node, options);\n if (node.wrapperCommand) {\n const wrapper = node.wrapperCommand === '\\\\mathbf' ? '\\\\boldarabic' : node.wrapperCommand;\n const literal = wrapper === '\\\\operatorname' || wrapper === '\\\\text'\n ? escapeAtomicLiteral(expr) : content;\n return arabicScripts(node, `${wrapper}{${literal}}`, options);\n }\n return arabicScripts(node, (node.characterFont ?? 'default') === 'default'\n ? `\\\\text{${escapeText(expr)}}`\n : content, options);\n }\n if (node.kind === 'operator') {\n return arabicScripts(node, renderRawOperatorLatex(node.expr, 'arabic'), options);\n }\n return arabicScripts(node, formatDigits(node.expr, selectedDigitForm(options)), options);\n}\n\nexport function renderChainEnglish(chain: EditorChain, options?: RenderOptions): string {\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n const atoms = chain.nodes.map((node) => isIndexComma(node) ? ',' : renderNodeEnglish(node, options));\n return '\\\\mathnormal{' + atoms.join('') + '}';\n }\n return chain.nodes.map((node) => renderNodeEnglish(node, options)).join(' ');\n}\n\nexport function renderChainArabic(chain: EditorChain, options?: RenderOptions): string {\n const rendered = chain.nodes.slice().reverse().map((node) => renderNodeArabic(node, options));\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n return '\\\\mathnormal{' + rendered.join('\\\\,') + '}';\n }\n return rendered.join(' ');\n}\n\nexport function renderEnglishLatexFromSession(session: EditorSession): string {\n return renderChainEnglish(session.englishTree, { digitForm: session.currentDigitForm ?? 'western' });\n}\n\nexport function renderArabicLatexFromSession(session: EditorSession): string {\n return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? 'western' });\n}\n\n/** Render-only RTL cases; never use this for source or stored MathObjects. */\nexport function renderArabicPreviewLatexFromSession(session: EditorSession): string {\n return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? 'western', casesPresentation: true });\n}\n","import { caretStep } from './caretOrder.js';\nimport {\n type EditorFragment,\n regenerateFragmentIds,\n serializeSelection,\n} from './clipboard.js';\nimport {\n cloneEditorSession,\n createDelimiterNode,\n createEditorChain,\n createEditorNode,\n createFracNode,\n createSqrtNode,\n createAccentNode,\n createOversetNode,\n createUndersetNode,\n createGridEnvNode,\n createAtomicCommandNode,\n createAtomicOperatorCommandNode,\n} from './factory.js';\nimport { renderArabicLatexFromSession, renderEnglishLatexFromSession } from './render.js';\nimport { formatDigits } from './digits.js';\nimport { buildFirstDerivativeFrac, buildSecondDerivativeFrac, derivativeTemplateInitialCaret } from './derivativeTemplates.js';\nimport {\n buildLimitsSeriesTemplate,\n limitsSeriesTemplateInitialCaret,\n buildAccentPairTemplate,\n accentPairTemplateInitialCaret,\n} from './limitsTemplates.js';\nimport { DIVIDE_OPERATOR_AR, DIVIDE_OPERATOR_EN } from './divideOperator.js';\nimport { coveredNodeIds, isSelectionActive, nodeChildChains, normalizeSelection } from './selection.js';\nimport { activeTreeKey, findChainById, findNodeById, passiveTreeKey } from './traversal.js';\nimport type {\n CharacterFontId,\n DigitFormId,\n EditorChain,\n EditorDebugEntry,\n EditorNode,\n EditorSession,\n EditorSide,\n EnvColumnAlignment,\n GridEnvName,\n MatrixEnvStyle,\n} from './types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport { equationEditorMessages } from './uiLocale.js';\nimport type { AccentCommandId } from './accentCommands.js';\nimport type { AtomicCommandId } from './atomicCommands.js';\nimport type { AtomicOperatorCommandId } from './atomicCommandsOperators.js';\n\nfunction ensureSyncEntry(session: EditorSession, nodeId: string): void {\n if (!session.sync[nodeId]) {\n session.sync[nodeId] = { expr: 'synced' };\n }\n}\n\nfunction markExprSync(session: EditorSession, nodeId: string): void {\n const english = findNodeById(session.englishTree, nodeId);\n const arabic = findNodeById(session.arabicTree, nodeId);\n ensureSyncEntry(session, nodeId);\n if (!english || !arabic) {\n session.sync[nodeId].expr = 'diverged';\n return;\n }\n session.sync[nodeId].expr = english.node.expr === arabic.node.expr ? 'synced' : 'diverged';\n}\n\nfunction clearSourceIdentity(session: EditorSession, nodeId: string): void {\n const english = findNodeById(session.englishTree, nodeId);\n const arabic = findNodeById(session.arabicTree, nodeId);\n // An Arabic label edit changes presentation, not the canonical source.\n // English-side edits still replace the source, as before.\n if (session.activeSide === 'arabic' && english?.node.kind === 'char' &&\n ['\\\\mathtt', '\\\\operatorname', '\\\\text'].includes(english.node.wrapperCommand ?? '') &&\n english.node.sourceLatex) {\n return;\n }\n if (english) {\n delete english.node.sourceLatex;\n }\n if (arabic) {\n delete arabic.node.sourceLatex;\n }\n}\n\n\n/** Keep highlighted node aligned with caret (keyboard + programmatic caret moves). */\nexport function syncSelectionToCaret(session: EditorSession): void {\n const activeKey = activeTreeKey(session.activeSide);\n const tree = session[activeKey];\n const { chainId, index } = session.caret;\n const located = findChainById(tree, chainId);\n if (!located) {\n session.selectedNodeId = null;\n return;\n }\n if (index > 0) {\n session.selectedNodeId = located.chain.nodes[index - 1].id;\n return;\n }\n if (located.relation.kind === 'superscript' || located.relation.kind === 'subscript') {\n session.selectedNodeId = located.relation.ownerNodeId;\n return;\n }\n if (\n located.relation.kind === 'inner' ||\n located.relation.kind === 'numerator' ||\n located.relation.kind === 'denominator' ||\n located.relation.kind === 'radicand' ||\n located.relation.kind === 'rootIndex' ||\n located.relation.kind === 'overExpr' ||\n located.relation.kind === 'underExpr' ||\n located.relation.kind === 'baseExpr' ||\n located.relation.kind === 'matrixCell'\n ) {\n session.selectedNodeId = located.relation.ownerNodeId;\n return;\n }\n session.selectedNodeId = null;\n}\n\nfunction appendDebug(session: EditorSession, command: string, note: string): void {\n const entry: EditorDebugEntry = {\n timestamp: new Date().toISOString(),\n command,\n activeSide: session.activeSide,\n englishLatex: renderEnglishLatexFromSession(session),\n arabicLatex: renderArabicLatexFromSession(session),\n renderOk: true,\n renderError: null,\n note,\n };\n const nextLog = session.debugLog.concat(entry);\n session.debugLog = nextLog.slice(-120);\n}\n\nfunction insertMirroredNode(session: EditorSession, chainId: string, index: number, englishNode: EditorNode, arabicNode: EditorNode): void {\n const englishLocated = findChainById(session.englishTree, chainId);\n const arabicLocated = findChainById(session.arabicTree, chainId);\n if (!englishLocated || !arabicLocated) {\n return;\n }\n const safeIndex = Math.max(0, Math.min(index, englishLocated.chain.nodes.length));\n englishLocated.chain.nodes.splice(safeIndex, 0, englishNode);\n arabicLocated.chain.nodes.splice(safeIndex, 0, arabicNode);\n ensureSyncEntry(session, englishNode.id);\n markExprSync(session, englishNode.id);\n}\n\nfunction syncMatrixCellChainIds(englishNode: EditorNode, arabicNode: EditorNode): void {\n const englishRows = englishNode.matrixRows ?? [];\n const arabicRows = arabicNode.matrixRows ?? [];\n const rowLimit = Math.min(englishRows.length, arabicRows.length);\n for (let rowIndex = 0; rowIndex < rowLimit; rowIndex += 1) {\n const englishRow = englishRows[rowIndex];\n const arabicRow = arabicRows[rowIndex];\n const columnLimit = Math.min(englishRow.length, arabicRow.length);\n for (let columnIndex = 0; columnIndex < columnLimit; columnIndex += 1) {\n arabicRow[columnIndex].id = englishRow[columnIndex].id;\n }\n }\n}\n\nfunction createMatrixRow(columnCount: number): EditorChain[] {\n return Array.from({ length: columnCount }, () => createEditorChain());\n}\n\nfunction findSelectedMatrixPair(session: EditorSession): { english: EditorNode; arabic: EditorNode } | null {\n const targetNodeId = session.selectedStructureNodeId ?? session.selectedNodeId;\n if (!targetNodeId) {\n return null;\n }\n const englishLocated = findNodeById(session.englishTree, targetNodeId);\n const arabicLocated = findNodeById(session.arabicTree, targetNodeId);\n if (!englishLocated || !arabicLocated) {\n return null;\n }\n if (englishLocated.node.kind !== 'env' || arabicLocated.node.kind !== 'env') {\n return null;\n }\n return { english: englishLocated.node, arabic: arabicLocated.node };\n}\n\nfunction normalizeArrayAlignments(node: EditorNode): void {\n if ((node.envName ?? node.matrixStyle) !== 'array' || !node.matrixRows) {\n return;\n }\n const columnCount = Math.max(1, node.matrixRows[0]?.length ?? 1);\n const current = node.columnAlignments ?? [];\n node.columnAlignments = Array.from({ length: columnCount }, (_, index) => current[index] ?? 'c');\n}\n\nfunction removeMirroredNodeById(session: EditorSession, nodeId: string): boolean {\n const englishLocated = findNodeById(session.englishTree, nodeId);\n const arabicLocated = findNodeById(session.arabicTree, nodeId);\n if (!englishLocated || !arabicLocated) {\n return false;\n }\n englishLocated.chain.nodes.splice(englishLocated.index, 1);\n arabicLocated.chain.nodes.splice(arabicLocated.index, 1);\n delete session.sync[nodeId];\n return true;\n}\n\n/**\n * Mutates `next` to remove every node covered by its current selection (mirrored\n * across EN/AR), parks the caret at selection.start, and clears the selection.\n * Returns true when something was removed.\n */\nfunction applyDeleteSelectionRange(next: EditorSession): boolean {\n if (!isSelectionActive(next.selection)) {\n next.selection = null;\n return false;\n }\n const ids = coveredNodeIds(next);\n if (ids.length === 0) {\n next.selection = null;\n return false;\n }\n const sel = next.selection;\n if (!sel) {\n return false;\n }\n const start = Math.min(sel.anchorIndex, sel.focusIndex);\n const chainId = sel.chainId;\n for (const id of ids) {\n removeMirroredNodeById(next, id);\n }\n next.caret = { chainId, index: start };\n next.selection = null;\n next.selectedStructureNodeId = null;\n return true;\n}\n\n/** Recursively ensure sync entries for an inserted mirrored subtree (top + nested). */\nfunction syncSubtreeRecursive(session: EditorSession, eng: EditorNode, ar: EditorNode): void {\n ensureSyncEntry(session, eng.id);\n markExprSync(session, eng.id);\n const engChains = nodeChildChains(eng);\n const arChains = nodeChildChains(ar);\n const limit = Math.min(engChains.length, arChains.length);\n for (let c = 0; c < limit; c += 1) {\n const ec = engChains[c];\n const ac = arChains[c];\n const innerLimit = Math.min(ec.nodes.length, ac.nodes.length);\n for (let j = 0; j < innerLimit; j += 1) {\n syncSubtreeRecursive(session, ec.nodes[j], ac.nodes[j]);\n }\n }\n}\n\nexport function switchSide(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n next.activeSide = next.activeSide === 'english' ? 'arabic' : 'english';\n next.selection = null;\n appendDebug(next, 'switchSide', `active=${next.activeSide}`);\n return next;\n}\n\nexport function setSplitLeafTyping(session: EditorSession, enabled: boolean): EditorSession {\n const next = cloneEditorSession(session);\n next.splitLeafTyping = enabled;\n appendDebug(next, 'setSplitLeafTyping', enabled ? 'on' : 'off');\n return next;\n}\n\nexport function setArabicReverseNumberTyping(session: EditorSession, enabled: boolean): EditorSession {\n const next = cloneEditorSession(session);\n next.arabicReverseNumberTyping = enabled;\n appendDebug(next, 'setArabicReverseNumberTyping', enabled ? 'on' : 'off');\n return next;\n}\n\nexport function setCaret(session: EditorSession, chainId: string, index: number): EditorSession {\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findChainById(next[activeKey], chainId);\n if (!located) {\n return session;\n }\n next.caret = {\n chainId,\n index: Math.max(0, Math.min(index, located.chain.nodes.length)),\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n return next;\n}\n\nexport function moveCaret(session: EditorSession, delta: -1 | 1): EditorSession {\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const tree = next[activeKey];\n const located = findChainById(tree, next.caret.chainId);\n if (!located) {\n return session;\n }\n next.caret = caretStep(tree, next.caret, delta);\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaret', `delta=${String(delta)} dfs`);\n return next;\n}\n\nexport function horizontalCaretDelta(session: EditorSession, direction: 'left' | 'right'): -1 | 1 {\n const activeKey = activeTreeKey(session.activeSide);\n const tree = session[activeKey];\n const located = findChainById(tree, session.caret.chainId);\n const inMatrixCell = located?.relation.kind === 'matrixCell';\n const canMoveInsideCell =\n inMatrixCell &&\n session.activeSide === 'arabic' &&\n ((direction === 'left' && session.caret.index < located.chain.nodes.length) ||\n (direction === 'right' && session.caret.index > 0));\n if (session.activeSide === 'arabic' && (!inMatrixCell || canMoveInsideCell)) {\n return direction === 'left' ? 1 : -1;\n }\n return direction === 'left' ? -1 : 1;\n}\n\nexport function moveCaretHorizontal(session: EditorSession, direction: 'left' | 'right'): EditorSession {\n const activeKey = activeTreeKey(session.activeSide);\n const tree = session[activeKey];\n const located = findChainById(tree, session.caret.chainId);\n if (!located || located.relation.kind !== 'matrixCell') {\n return moveCaret(session, horizontalCaretDelta(session, direction));\n }\n\n const textDelta = session.activeSide === 'arabic'\n ? direction === 'left' ? 1 : -1\n : direction === 'left' ? -1 : 1;\n const nextIndex = session.caret.index + textDelta;\n if (nextIndex >= 0 && nextIndex <= located.chain.nodes.length) {\n return moveCaret(session, textDelta);\n }\n\n const ownerLocated =\n located.relation.ownerNodeId !== null ? findNodeById(tree, located.relation.ownerNodeId) : null;\n const ownerNode = ownerLocated?.node ?? null;\n if (!ownerLocated || !ownerNode?.matrixRows) {\n return session;\n }\n\n const rowIndex = located.relation.rowIndex ?? 0;\n const columnIndex = located.relation.columnIndex ?? 0;\n const row = ownerNode.matrixRows[rowIndex];\n if (!row) {\n return session;\n }\n\n const toVisualIndex = (column: number, columnCount: number): number =>\n session.activeSide === 'arabic' ? columnCount - 1 - column : column;\n const fromVisualIndex = (visualColumn: number, columnCount: number): number =>\n session.activeSide === 'arabic' ? columnCount - 1 - visualColumn : visualColumn;\n const entryIndex = (cell: EditorChain): number => {\n if (session.activeSide === 'arabic') {\n return direction === 'left' ? 0 : cell.nodes.length;\n }\n return direction === 'left' ? cell.nodes.length : 0;\n };\n\n const visualDelta = direction === 'left' ? -1 : 1;\n const currentVisualIndex = toVisualIndex(columnIndex, row.length);\n let targetRowIndex = rowIndex;\n let targetVisualIndex = currentVisualIndex + visualDelta;\n\n if (targetVisualIndex < 0 || targetVisualIndex >= row.length) {\n if (direction === 'left') {\n if (session.activeSide === 'arabic') {\n targetRowIndex = rowIndex + 1;\n const targetRow = ownerNode.matrixRows[targetRowIndex];\n if (targetRow) {\n targetVisualIndex = targetRow.length - 1;\n }\n } else {\n targetRowIndex = rowIndex - 1;\n const targetRow = ownerNode.matrixRows[targetRowIndex];\n if (targetRow) {\n targetVisualIndex = targetRow.length - 1;\n }\n }\n } else if (session.activeSide === 'arabic') {\n targetRowIndex = rowIndex - 1;\n targetVisualIndex = 0;\n } else {\n targetRowIndex = rowIndex + 1;\n targetVisualIndex = 0;\n }\n }\n\n const targetRow = ownerNode.matrixRows[targetRowIndex];\n if (targetRow && targetVisualIndex >= 0 && targetVisualIndex < targetRow.length) {\n const targetColumnIndex = fromVisualIndex(targetVisualIndex, targetRow.length);\n const targetCell = targetRow[targetColumnIndex];\n if (targetCell) {\n const next = cloneEditorSession(session);\n next.caret = { chainId: targetCell.id, index: entryIndex(targetCell) };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretHorizontal', `matrix-${direction}`);\n return next;\n }\n }\n\n const next = cloneEditorSession(session);\n const exitsAfter =\n (session.activeSide === 'english' && direction === 'right') ||\n (session.activeSide === 'arabic' && direction === 'left');\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: exitsAfter ? ownerLocated.index + 1 : ownerLocated.index,\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretHorizontal', `matrix-${direction}-exit`);\n return next;\n}\n\nexport function moveCaretVertical(session: EditorSession, direction: 'up' | 'down'): EditorSession {\n const next = cloneEditorSession(session);\n next.selection = null;\n const activeKey = activeTreeKey(next.activeSide);\n const tree = next[activeKey];\n const located = findChainById(tree, next.caret.chainId);\n if (!located) {\n return session;\n }\n\n const ownerLocated =\n located.relation.ownerNodeId !== null ? findNodeById(tree, located.relation.ownerNodeId) : null;\n const ownerNode = ownerLocated?.node ?? null;\n\n if (located.relation.kind === 'numerator' && ownerLocated && ownerNode && ownerNode.denominator) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.denominator.id,\n index: ownerNode.denominator.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-num->den');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-num-up-exit');\n return next;\n }\n\n if (located.relation.kind === 'denominator' && ownerLocated && ownerNode && ownerNode.numerator) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.numerator.id,\n index: ownerNode.numerator.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-den->num');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-den-down-exit');\n return next;\n }\n\n if (located.relation.kind === 'rootIndex' && ownerLocated && ownerNode && ownerNode.radicand) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.radicand.id,\n index: ownerNode.radicand.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-root->radicand');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-root-up-exit');\n return next;\n }\n\n if (located.relation.kind === 'radicand' && ownerLocated && ownerNode && ownerNode.rootIndex) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.rootIndex.id,\n index: ownerNode.rootIndex.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-radicand->root');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-radicand-down-exit');\n return next;\n }\n\n if (located.relation.kind === 'overExpr' && ownerLocated && ownerNode && ownerNode.baseExpr) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.baseExpr.id,\n index: ownerNode.baseExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-over->base');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-over-up-exit');\n return next;\n }\n\n if (\n located.relation.kind === 'baseExpr' &&\n ownerLocated &&\n ownerNode &&\n ownerNode.kind === 'overset' &&\n ownerNode.overExpr\n ) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.overExpr.id,\n index: ownerNode.overExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-base->over');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-base-down-exit');\n return next;\n }\n\n if (\n located.relation.kind === 'baseExpr' &&\n ownerLocated &&\n ownerNode &&\n ownerNode.kind === 'underset' &&\n ownerNode.underExpr\n ) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.underExpr.id,\n index: ownerNode.underExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-base->under');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-base-up-exit');\n return next;\n }\n\n if (located.relation.kind === 'underExpr' && ownerLocated && ownerNode && ownerNode.baseExpr) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.baseExpr.id,\n index: ownerNode.baseExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-under->base');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-under-down-exit');\n return next;\n }\n\n if (\n located.relation.kind === 'baseExpr' &&\n ownerLocated &&\n ownerNode &&\n ownerNode.kind === 'accent'\n ) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'accent-base-up-exit');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'accent-base-down-exit');\n return next;\n }\n\n if (located.relation.kind === 'matrixCell' && ownerLocated && ownerNode?.matrixRows) {\n const rowIndex = located.relation.rowIndex ?? 0;\n const columnIndex = located.relation.columnIndex ?? 0;\n const nextRowIndex = direction === 'up' ? rowIndex - 1 : rowIndex + 1;\n if (nextRowIndex >= 0 && nextRowIndex < ownerNode.matrixRows.length) {\n const nextRow = ownerNode.matrixRows[nextRowIndex];\n const nextCell = nextRow[Math.min(columnIndex, nextRow.length - 1)];\n if (nextCell) {\n next.caret = {\n chainId: nextCell.id,\n index: nextCell.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'matrix-cell');\n return next;\n }\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: direction === 'up' ? ownerLocated.index : ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', `matrix-${direction}-exit`);\n return next;\n }\n\n if (located.relation.kind === 'superscript' && ownerLocated && ownerNode) {\n if (direction === 'down') {\n if (ownerNode.subscript) {\n next.caret = {\n chainId: ownerNode.subscript.id,\n index: ownerNode.subscript.nodes.length,\n };\n } else {\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sup->down');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sup->up-exit');\n return next;\n }\n\n if (located.relation.kind === 'subscript' && ownerLocated && ownerNode) {\n if (direction === 'up') {\n if (ownerNode.superscript) {\n next.caret = {\n chainId: ownerNode.superscript.id,\n index: ownerNode.superscript.nodes.length,\n };\n } else {\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sub->up');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sub->down-exit');\n return next;\n }\n\n if (located.relation.kind !== 'root' && located.relation.kind !== 'inner') {\n return session;\n }\n\n const caretIdx = next.caret.index;\n if (caretIdx <= 0) {\n return session;\n }\n const nodeBeforeCaret = located.chain.nodes[caretIdx - 1];\n if (!nodeBeforeCaret) {\n return session;\n }\n\n const targetChain =\n direction === 'up'\n ? nodeBeforeCaret.superscript ?? nodeBeforeCaret.subscript\n : nodeBeforeCaret.subscript ?? nodeBeforeCaret.superscript;\n\n if (!targetChain) {\n return session;\n }\n next.caret = {\n chainId: targetChain.id,\n index: targetChain.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', `base->script:${direction}`);\n return next;\n}\n\nfunction insertLeaf(session: EditorSession, kind: 'char' | 'number' | 'operator', expr: string): EditorSession {\n const next = cloneEditorSession(session);\n const englishNode = createEditorNode(kind, expr);\n const arabicNode = createEditorNode(kind, expr);\n if (kind === 'char' && next.currentCharacterWrapper === '\\\\boldarabic') {\n englishNode.wrapperCommand = '\\\\boldarabic';\n arabicNode.wrapperCommand = '\\\\boldarabic';\n } else if (kind === 'char' && (next.currentCharacterFont ?? 'default') !== 'default') {\n englishNode.characterFont = next.currentCharacterFont;\n arabicNode.characterFont = next.currentCharacterFont;\n }\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertLeaf', `${kind}:${expr}`);\n return next;\n}\n\n/** When Arabic active and flag on, number fragments prepend on both mirrored exprs (same printed string on EN/AR). */\nfunction shouldReverseArabicNumber(session: EditorSession): boolean {\n return session.activeSide === 'arabic' && session.arabicReverseNumberTyping;\n}\n\nfunction characterTypingStyleOf(node: EditorNode): string {\n if (node.kind !== 'char') return 'none';\n return node.wrapperCommand\n ? `wrapper:${node.wrapperCommand}`\n : `font:${node.characterFont ?? 'default'}`;\n}\n\nfunction currentCharacterTypingStyle(session: EditorSession): string {\n return session.currentCharacterWrapper\n ? `wrapper:${session.currentCharacterWrapper}`\n : `font:${session.currentCharacterFont ?? 'default'}`;\n}\n\n/** When split mode is off: merge into adjacent same-kind leaf (append after node at index-1, else prepend node at index). */\nfunction tryMergeLeafTyping(session: EditorSession, kind: 'char' | 'number', fragment: string): boolean {\n const engLocated = findChainById(session.englishTree, session.caret.chainId);\n if (!engLocated) {\n return false;\n }\n // Index digits are individual atoms, never merge them into an integer.\n if (engLocated.chain.indexSequence) return false;\n const nodes = engLocated.chain.nodes;\n const i = session.caret.index;\n let targetId: string | null = null;\n let prepend = false;\n if (i > 0) {\n const prev = nodes[i - 1];\n if (prev.kind === kind && (kind !== 'char' || characterTypingStyleOf(prev) === currentCharacterTypingStyle(session))) {\n targetId = prev.id;\n prepend = false;\n }\n }\n if (!targetId && i < nodes.length) {\n const fwd = nodes[i];\n if (fwd.kind === kind && (kind !== 'char' || characterTypingStyleOf(fwd) === currentCharacterTypingStyle(session))) {\n targetId = fwd.id;\n prepend = true;\n }\n }\n if (!targetId) {\n return false;\n }\n const englishHit = findNodeById(session.englishTree, targetId);\n const arabicHit = findNodeById(session.arabicTree, targetId);\n if (!englishHit || !arabicHit) {\n return false;\n }\n const prependBoth = kind === 'number' && shouldReverseArabicNumber(session) ? true : prepend;\n if (prependBoth) {\n englishHit.node.expr = `${fragment}${englishHit.node.expr}`;\n arabicHit.node.expr = `${fragment}${arabicHit.node.expr}`;\n } else {\n englishHit.node.expr = `${englishHit.node.expr}${fragment}`;\n arabicHit.node.expr = `${arabicHit.node.expr}${fragment}`;\n }\n clearSourceIdentity(session, targetId);\n markExprSync(session, targetId);\n return true;\n}\n\n/**\n * Replace any active selection with a freshly-cleared range, then return a base\n * session ready for the actual insert. Mutating helper so reducers stay short.\n */\nfunction replaceSelectionFirst(session: EditorSession): EditorSession {\n if (!isSelectionActive(session.selection)) {\n return session;\n }\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n return next;\n}\n\n/** Returns true when the node before the caret is a pure-digit number leaf (no existing dot). */\nfunction precedingIsExtendableNumber(session: EditorSession): boolean {\n const located = findChainById(session.englishTree, session.caret.chainId);\n if (!located || session.caret.index <= 0) {\n return false;\n }\n const prev = located.chain.nodes[session.caret.index - 1];\n if (!prev || prev.kind !== 'number') {\n return false;\n }\n if (prev.expr.includes('.')) {\n return false;\n }\n return /^\\d+$/.test(prev.expr);\n}\n\n/** One-shot: forces the next insertChar/insertNumber to start a new leaf instead of merging. No-op in split mode. */\nexport function breakLeafTyping(session: EditorSession): EditorSession {\n if (session.splitLeafTyping) {\n return session;\n }\n const next = cloneEditorSession(session);\n next.forceSplitNextLeaf = true;\n appendDebug(next, 'breakLeafTyping', 'split-next');\n return next;\n}\n\nexport function setCurrentCharacterFont(session: EditorSession, fontId: CharacterFontId): EditorSession {\n const next = cloneEditorSession(session);\n next.currentCharacterFont = fontId;\n next.currentCharacterWrapper = null;\n appendDebug(next, 'setCurrentCharacterFont', fontId);\n return next;\n}\n\nexport function setCurrentBoldCharacterStyle(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n next.currentCharacterFont = 'default';\n next.currentCharacterWrapper = '\\\\boldarabic';\n appendDebug(next, 'setCurrentBoldCharacterStyle', '\\\\boldarabic');\n return next;\n}\n\nexport function toggleTakweenCharacterFont(session: EditorSession): EditorSession {\n return setCurrentCharacterFont(session, (session.currentCharacterFont ?? 'default') === 'takween' ? 'default' : 'takween');\n}\n\nexport function setCurrentDigitForm(session: EditorSession, digitForm: DigitFormId): EditorSession {\n const next = cloneEditorSession(session);\n next.currentDigitForm = digitForm;\n appendDebug(next, 'setCurrentDigitForm', digitForm);\n return next;\n}\n\nexport function insertChar(session: EditorSession, expr: string): EditorSession {\n // Treat Western, Arabic-Indic, and Persian-Indic keyboard digits as numbers.\n const digit = formatDigits(expr, 'western');\n if (/^[0-9]$/.test(digit)) return insertNumber(session, digit);\n const base = replaceSelectionFirst(session);\n if (!base.splitLeafTyping && !base.forceSplitNextLeaf) {\n const next = cloneEditorSession(base);\n if (tryMergeLeafTyping(next, 'char', expr)) {\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'mergeLeaf', `char:${expr}`);\n return next;\n }\n }\n const inserted = insertLeaf(base, 'char', expr);\n inserted.forceSplitNextLeaf = false;\n return inserted;\n}\n\nexport function insertNumber(session: EditorSession, expr: string): EditorSession {\n const digit = formatDigits(expr, 'western');\n const base = replaceSelectionFirst(session);\n if (!base.splitLeafTyping && !base.forceSplitNextLeaf) {\n const next = cloneEditorSession(base);\n if (tryMergeLeafTyping(next, 'number', digit)) {\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'mergeLeaf', `number:${expr}`);\n return next;\n }\n }\n const inserted = insertLeaf(base, 'number', digit);\n inserted.forceSplitNextLeaf = false;\n return inserted;\n}\n\nexport function insertDivideOperator(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createEditorNode('operator', DIVIDE_OPERATOR_EN);\n const arabicNode = createEditorNode('operator', DIVIDE_OPERATOR_AR);\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n markExprSync(next, englishNode.id);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertDivideOperator', '');\n return next;\n}\n\nexport function insertOperator(session: EditorSession, expr: string): EditorSession {\n if (expr === '.' && !session.splitLeafTyping && precedingIsExtendableNumber(session)) {\n return insertNumber(session, '.');\n }\n if (expr === DIVIDE_OPERATOR_EN || expr === DIVIDE_OPERATOR_AR) {\n return insertDivideOperator(session);\n }\n const base = replaceSelectionFirst(session);\n return insertLeaf(base, 'operator', expr);\n}\n\nexport function insertAtomicCommand(session: EditorSession, commandId: AtomicCommandId): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createAtomicCommandNode(commandId);\n const arabicNode = createAtomicCommandNode(commandId);\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAtomicCommand', commandId);\n return next;\n}\n\nexport function insertAtomicOperatorCommand(session: EditorSession, commandId: AtomicOperatorCommandId): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createAtomicOperatorCommandNode(commandId);\n const arabicNode = createAtomicOperatorCommandNode(commandId);\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAtomicOperatorCommand', commandId);\n return next;\n}\n\nexport function insertDelimiterPair(session: EditorSession, leftDelimExpr: string, rightDelimExpr: string): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createDelimiterNode(leftDelimExpr, rightDelimExpr);\n const arabicNode = createDelimiterNode(leftDelimExpr, rightDelimExpr);\n arabicNode.id = englishNode.id;\n if (arabicNode.innerExpr && englishNode.innerExpr) {\n arabicNode.innerExpr.id = englishNode.innerExpr.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.innerExpr ? englishNode.innerExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertDelimiterPair', `${leftDelimExpr}${rightDelimExpr}`);\n return next;\n}\n\nexport function insertFraction(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createFracNode();\n const arabicNode = createFracNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.numerator && englishNode.numerator) {\n arabicNode.numerator.id = englishNode.numerator.id;\n }\n if (arabicNode.denominator && englishNode.denominator) {\n arabicNode.denominator.id = englishNode.denominator.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.numerator ? englishNode.numerator.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertFraction', '');\n return next;\n}\n\nfunction insertDerivativeFrac(\n session: EditorSession,\n build: () => { english: EditorNode; arabic: EditorNode },\n debugLabel: string,\n): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const { english, arabic } = build();\n insertMirroredNode(next, next.caret.chainId, next.caret.index, english, arabic);\n syncSubtreeRecursive(next, english, arabic);\n next.caret = derivativeTemplateInitialCaret(english);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, debugLabel, '');\n return next;\n}\n\nexport function insertFirstDerivative(session: EditorSession): EditorSession {\n return insertDerivativeFrac(session, buildFirstDerivativeFrac, 'insertFirstDerivative');\n}\n\nexport function insertSecondDerivative(session: EditorSession): EditorSession {\n return insertDerivativeFrac(session, buildSecondDerivativeFrac, 'insertSecondDerivative');\n}\n\nexport function insertSqrt(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createSqrtNode();\n const arabicNode = createSqrtNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.radicand && englishNode.radicand) {\n arabicNode.radicand.id = englishNode.radicand.id;\n }\n if (arabicNode.rootIndex && englishNode.rootIndex) {\n arabicNode.rootIndex.id = englishNode.rootIndex.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.radicand ? englishNode.radicand.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertSqrt', '');\n return next;\n}\n\nexport function insertOverset(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createOversetNode();\n const arabicNode = createOversetNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.overExpr && englishNode.overExpr) {\n arabicNode.overExpr.id = englishNode.overExpr.id;\n }\n if (arabicNode.baseExpr && englishNode.baseExpr) {\n arabicNode.baseExpr.id = englishNode.baseExpr.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.overExpr ? englishNode.overExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertOverset', '');\n return next;\n}\n\nexport function insertUnderset(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createUndersetNode();\n const arabicNode = createUndersetNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.underExpr && englishNode.underExpr) {\n arabicNode.underExpr.id = englishNode.underExpr.id;\n }\n if (arabicNode.baseExpr && englishNode.baseExpr) {\n arabicNode.baseExpr.id = englishNode.baseExpr.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.underExpr ? englishNode.underExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertUnderset', '');\n return next;\n}\n\nexport function insertLimitsSeriesTemplate(\n session: EditorSession,\n commandId: AtomicCommandId,\n): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const { english, arabic } = buildLimitsSeriesTemplate(commandId);\n insertMirroredNode(next, next.caret.chainId, next.caret.index, english, arabic);\n syncSubtreeRecursive(next, english, arabic);\n next.caret = limitsSeriesTemplateInitialCaret(english);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertLimitsSeriesTemplate', commandId);\n return next;\n}\n\nexport function insertAccentPair(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const { english, arabic } = buildAccentPairTemplate();\n insertMirroredNode(next, next.caret.chainId, next.caret.index, english, arabic);\n syncSubtreeRecursive(next, english, arabic);\n next.caret = accentPairTemplateInitialCaret(english);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAccentPair', '');\n return next;\n}\n\n/**\n * Insert a one-argument math accent. When a selection is active in one chain,\n * wrap the selected nodes into the accent base; otherwise insert an empty base\n * and place the caret inside it.\n */\nexport function insertAccent(session: EditorSession, accentId: AccentCommandId): EditorSession {\n const next = cloneEditorSession(session);\n const englishNode = createAccentNode(accentId);\n const arabicNode = createAccentNode(accentId);\n arabicNode.id = englishNode.id;\n if (arabicNode.baseExpr && englishNode.baseExpr) {\n arabicNode.baseExpr.id = englishNode.baseExpr.id;\n }\n\n if (isSelectionActive(next.selection) && next.selection) {\n const sel = next.selection;\n const { start, end } = normalizeSelection(sel);\n const englishLocated = findChainById(next.englishTree, sel.chainId);\n const arabicLocated = findChainById(next.arabicTree, sel.chainId);\n if (englishLocated && arabicLocated && end > start) {\n const count = end - start;\n const englishWrapped = englishLocated.chain.nodes.splice(start, count);\n const arabicWrapped = arabicLocated.chain.nodes.splice(start, count);\n englishNode.baseExpr!.nodes = englishWrapped;\n arabicNode.baseExpr!.nodes = arabicWrapped;\n englishLocated.chain.nodes.splice(start, 0, englishNode);\n arabicLocated.chain.nodes.splice(start, 0, arabicNode);\n syncSubtreeRecursive(next, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.baseExpr!.id,\n index: englishWrapped.length,\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAccent', `${accentId}:wrap`);\n return next;\n }\n }\n\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n syncSubtreeRecursive(next, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.baseExpr ? englishNode.baseExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAccent', `${accentId}:empty`);\n return next;\n}\n\nexport function insertMatrixEnv(\n session: EditorSession,\n style: MatrixEnvStyle,\n rows: number,\n columns: number,\n): EditorSession {\n return insertGridEnv(session, style, rows, columns);\n}\n\nexport function insertArrayEnv(\n session: EditorSession,\n rows: number,\n columns: number,\n columnAlignments?: EnvColumnAlignment[],\n): EditorSession {\n return insertGridEnv(session, 'array', rows, columns, columnAlignments);\n}\n\nexport function insertAlignedEnv(\n session: EditorSession,\n rows: number,\n columns: number,\n): EditorSession {\n return insertGridEnv(session, 'aligned', rows, columns);\n}\n\nexport function insertCasesEnv(session: EditorSession, rows: number): EditorSession {\n return insertGridEnv(session, 'cases', rows, 2);\n}\n\nfunction insertGridEnv(\n session: EditorSession,\n envName: GridEnvName,\n rows: number,\n columns: number,\n columnAlignments?: EnvColumnAlignment[],\n): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createGridEnvNode(envName, rows, columns, columnAlignments);\n const arabicNode = createGridEnvNode(envName, rows, columns, columnAlignments);\n arabicNode.id = englishNode.id;\n syncMatrixCellChainIds(englishNode, arabicNode);\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.matrixRows?.[0]?.[0]?.id ?? next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertGridEnv', `${envName}:${String(rows)}x${String(columns)}`);\n return next;\n}\n\nexport function setMatrixEnvStyle(session: EditorSession, style: MatrixEnvStyle): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || pair.english.envName === 'cases') {\n return session;\n }\n pair.english.envName = style;\n pair.arabic.envName = style;\n pair.english.matrixStyle = style;\n pair.arabic.matrixStyle = style;\n pair.english.columnAlignments = null;\n pair.arabic.columnAlignments = null;\n appendDebug(next, 'setMatrixEnvStyle', style);\n return next;\n}\n\nexport function setArrayColumnAlignment(\n session: EditorSession,\n columnIndex: number,\n alignment: EnvColumnAlignment,\n): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || (pair.english.envName ?? pair.english.matrixStyle) !== 'array') {\n return session;\n }\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n const columnCount = pair.english.columnAlignments?.length ?? 0;\n const safeIndex = Math.max(0, Math.min(columnIndex, Math.max(0, columnCount - 1)));\n if (pair.english.columnAlignments && pair.arabic.columnAlignments && columnCount > 0) {\n pair.english.columnAlignments[safeIndex] = alignment;\n pair.arabic.columnAlignments[safeIndex] = alignment;\n }\n appendDebug(next, 'setArrayColumnAlignment', `${String(safeIndex)}:${alignment}`);\n return next;\n}\n\nexport function addMatrixRow(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.matrixRows.length >= 12) {\n return session;\n }\n const columnCount = Math.max(1, pair.english.matrixRows[0]?.length ?? 1);\n const englishRow = createMatrixRow(columnCount);\n const arabicRow = createMatrixRow(columnCount);\n for (let i = 0; i < columnCount; i += 1) {\n arabicRow[i].id = englishRow[i].id;\n }\n pair.english.matrixRows.push(englishRow);\n pair.arabic.matrixRows.push(arabicRow);\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'addMatrixRow', pair.english.id);\n return next;\n}\n\nexport function removeMatrixRow(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.matrixRows.length <= 1) {\n return session;\n }\n pair.english.matrixRows.pop();\n pair.arabic.matrixRows.pop();\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'removeMatrixRow', pair.english.id);\n return next;\n}\n\nexport function addMatrixColumn(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.envName === 'cases') {\n return session;\n }\n const columnCount = pair.english.matrixRows[0]?.length ?? 0;\n if (columnCount >= 12) {\n return session;\n }\n for (let rowIndex = 0; rowIndex < pair.english.matrixRows.length; rowIndex += 1) {\n const englishCell = createEditorChain();\n const arabicCell = createEditorChain();\n arabicCell.id = englishCell.id;\n pair.english.matrixRows[rowIndex].push(englishCell);\n pair.arabic.matrixRows[rowIndex].push(arabicCell);\n }\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'addMatrixColumn', pair.english.id);\n return next;\n}\n\nexport function removeMatrixColumn(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.envName === 'cases') {\n return session;\n }\n const columnCount = pair.english.matrixRows[0]?.length ?? 0;\n if (columnCount <= 1) {\n return session;\n }\n for (let rowIndex = 0; rowIndex < pair.english.matrixRows.length; rowIndex += 1) {\n pair.english.matrixRows[rowIndex].pop();\n pair.arabic.matrixRows[rowIndex].pop();\n }\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'removeMatrixColumn', pair.english.id);\n return next;\n}\n\nfunction addScript(session: EditorSession, type: 'superscript' | 'subscript'): EditorSession {\n const targetNodeId = session.selectedNodeId;\n if (!targetNodeId) {\n return session;\n }\n const next = cloneEditorSession(session);\n const englishLocated = findNodeById(next.englishTree, targetNodeId);\n const arabicLocated = findNodeById(next.arabicTree, targetNodeId);\n if (!englishLocated || !arabicLocated) {\n return session;\n }\n const englishNode = englishLocated.node;\n const arabicNode = arabicLocated.node;\n if (!englishNode[type]) {\n englishNode[type] = createEditorChain();\n }\n if (!arabicNode[type]) {\n arabicNode[type] = createEditorChain();\n }\n if (englishNode[type] && arabicNode[type]) {\n arabicNode[type].id = englishNode[type].id;\n next.caret = {\n chainId: englishNode[type].id,\n index: englishNode[type].nodes.length,\n };\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, `add${type === 'superscript' ? 'Sup' : 'Sub'}`, targetNodeId);\n return next;\n}\n\nfunction removeScript(session: EditorSession, type: 'superscript' | 'subscript'): EditorSession {\n const targetNodeId = session.selectedNodeId;\n if (!targetNodeId) {\n return session;\n }\n const next = cloneEditorSession(session);\n const englishLocated = findNodeById(next.englishTree, targetNodeId);\n const arabicLocated = findNodeById(next.arabicTree, targetNodeId);\n if (!englishLocated || !arabicLocated) {\n return session;\n }\n englishLocated.node[type] = null;\n arabicLocated.node[type] = null;\n next.caret = {\n chainId: englishLocated.chain.id,\n index: englishLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, `remove${type === 'superscript' ? 'Sup' : 'Sub'}`, targetNodeId);\n return next;\n}\n\nexport function addSup(session: EditorSession): EditorSession {\n return addScript(session, 'superscript');\n}\n\nexport function addSub(session: EditorSession): EditorSession {\n return addScript(session, 'subscript');\n}\n\nexport function removeSup(session: EditorSession): EditorSession {\n return removeScript(session, 'superscript');\n}\n\nexport function removeSub(session: EditorSession): EditorSession {\n return removeScript(session, 'subscript');\n}\n\nexport function selectNode(session: EditorSession, nodeId: string | null): EditorSession {\n const next = cloneEditorSession(session);\n next.selectedNodeId = nodeId;\n next.selectedStructureNodeId = null;\n return next;\n}\n\nexport function deleteStructure(session: EditorSession): EditorSession {\n const targetNodeId = session.selectedStructureNodeId ?? session.selectedNodeId;\n if (!targetNodeId) {\n return session;\n }\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findNodeById(next[activeKey], targetNodeId);\n if (!located) {\n return session;\n }\n const removed = removeMirroredNodeById(next, targetNodeId);\n if (!removed) {\n return session;\n }\n next.caret = {\n chainId: located.chain.id,\n index: located.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteStructure', targetNodeId);\n return next;\n}\n\nexport function deleteBackward(session: EditorSession): EditorSession {\n if (isSelectionActive(session.selection)) {\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteBackward', 'deleted range');\n return next;\n }\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findChainById(next[activeKey], next.caret.chainId);\n if (!located) {\n return session;\n }\n if (next.caret.index <= 0) {\n return session;\n }\n const previousNode = located.chain.nodes[next.caret.index - 1];\n if (!previousNode) {\n return session;\n }\n if (\n (previousNode.kind === 'delimiter' || previousNode.kind === 'frac' || previousNode.kind === 'sqrt' || previousNode.kind === 'overset' || previousNode.kind === 'underset' || previousNode.kind === 'accent' || previousNode.kind === 'env') &&\n next.selectedStructureNodeId !== previousNode.id\n ) {\n next.selectedStructureNodeId = previousNode.id;\n next.selectedNodeId = previousNode.id;\n appendDebug(next, 'deleteBackward', 'selected structure');\n return next;\n }\n if (\n !next.splitLeafTyping &&\n (previousNode.kind === 'char' || previousNode.kind === 'number') &&\n previousNode.expr.length > 1\n ) {\n const id = previousNode.id;\n const englishHit = findNodeById(next.englishTree, id);\n const arabicHit = findNodeById(next.arabicTree, id);\n if (englishHit && arabicHit) {\n if (previousNode.kind === 'number' && shouldReverseArabicNumber(next)) {\n englishHit.node.expr = englishHit.node.expr.slice(1);\n arabicHit.node.expr = arabicHit.node.expr.slice(1);\n } else {\n englishHit.node.expr = englishHit.node.expr.slice(0, -1);\n arabicHit.node.expr = arabicHit.node.expr.slice(0, -1);\n }\n clearSourceIdentity(next, id);\n markExprSync(next, id);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteBackward', 'trimmed leaf');\n return next;\n }\n }\n const removed = removeMirroredNodeById(next, previousNode.id);\n if (!removed) {\n return session;\n }\n next.caret.index = Math.max(0, next.caret.index - 1);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteBackward', 'removed node');\n return next;\n}\n\nexport function deleteForward(session: EditorSession): EditorSession {\n if (isSelectionActive(session.selection)) {\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteForward', 'deleted range');\n return next;\n }\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findChainById(next[activeKey], next.caret.chainId);\n if (!located) {\n return session;\n }\n if (next.caret.index >= located.chain.nodes.length) {\n return session;\n }\n const node = located.chain.nodes[next.caret.index];\n if (!node) {\n return session;\n }\n if (!next.splitLeafTyping && (node.kind === 'char' || node.kind === 'number') && node.expr.length > 1) {\n const englishHit = findNodeById(next.englishTree, node.id);\n const arabicHit = findNodeById(next.arabicTree, node.id);\n if (englishHit && arabicHit) {\n if (node.kind === 'number' && shouldReverseArabicNumber(next)) {\n englishHit.node.expr = englishHit.node.expr.slice(0, -1);\n arabicHit.node.expr = arabicHit.node.expr.slice(0, -1);\n } else {\n englishHit.node.expr = englishHit.node.expr.slice(1);\n arabicHit.node.expr = arabicHit.node.expr.slice(1);\n }\n clearSourceIdentity(next, node.id);\n markExprSync(next, node.id);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteForward', 'trimmed leaf');\n return next;\n }\n }\n const removed = removeMirroredNodeById(next, node.id);\n if (!removed) {\n return session;\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteForward', 'removed node');\n return next;\n}\n\nexport function setExpr(session: EditorSession, nodeId: string, expr: string): EditorSession {\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const passiveKey = passiveTreeKey(next.activeSide);\n const activeNode = findNodeById(next[activeKey], nodeId);\n const passiveNode = findNodeById(next[passiveKey], nodeId);\n if (!activeNode || !passiveNode) {\n return session;\n }\n activeNode.node.expr = expr;\n // An atomic label is one authored expression: persist the same edited\n // value in both mirrors, including when the Arabic side was active.\n if (['\\\\mathtt', '\\\\operatorname', '\\\\text'].includes(activeNode.node.wrapperCommand ?? '')) {\n passiveNode.node.expr = expr;\n }\n clearSourceIdentity(next, nodeId);\n markExprSync(next, nodeId);\n appendDebug(next, 'setExpr', nodeId);\n return next;\n}\n\nexport function createStarterSession(): EditorSession {\n const englishRoot = createEditorChain([createEditorNode('char', 'x')]);\n const arabicRoot = createEditorChain([createEditorNode('char', 'س')]);\n arabicRoot.id = englishRoot.id;\n arabicRoot.nodes[0].id = englishRoot.nodes[0].id;\n const session: EditorSession = {\n englishTree: englishRoot,\n arabicTree: arabicRoot,\n activeSide: 'arabic',\n splitLeafTyping: false,\n forceSplitNextLeaf: false,\n arabicReverseNumberTyping: true,\n currentCharacterFont: 'default',\n currentCharacterWrapper: null,\n currentDigitForm: 'western',\n caret: {\n chainId: englishRoot.id,\n index: 1,\n },\n selection: null,\n selectedNodeId: englishRoot.nodes[0].id,\n selectedStructureNodeId: null,\n sync: {\n [englishRoot.nodes[0].id]: { expr: 'diverged' },\n },\n debugLog: [],\n };\n appendDebug(session, 'createStarterSession', 'initialized');\n return session;\n}\n\nexport function syncStateSummary(session: EditorSession, uiLocale: ButexUiLocale = 'ar'): string {\n const messages = equationEditorMessages(uiLocale);\n const diverged = Object.values(session.sync).filter((entry) => entry.expr === 'diverged').length;\n if (diverged === 0) {\n return messages.synced;\n }\n return uiLocale === 'ar' ? `يوجد ${String(diverged)} ${messages.differentItems}` : `${String(diverged)} ${messages.differentItems}`;\n}\n\nexport function setRenderError(session: EditorSession, message: string | null): EditorSession {\n const next = cloneEditorSession(session);\n if (next.debugLog.length === 0) {\n appendDebug(next, 'render', 'init');\n }\n const last = next.debugLog[next.debugLog.length - 1];\n next.debugLog[next.debugLog.length - 1] = {\n ...last,\n renderOk: message === null,\n renderError: message,\n };\n return next;\n}\n\nexport function activeSideLabel(side: EditorSide, uiLocale: ButexUiLocale = 'ar'): string {\n const messages = equationEditorMessages(uiLocale);\n return side === 'arabic' ? messages.arabicSide : messages.englishSide;\n}\n\nconst PASTE_OPERATORS = new Set(['+', '-', '*', '/', '=', '<', '>', '.']);\n\n/** Read-only: build a fragment from the active selection (or null when collapsed). */\nexport function copySelection(session: EditorSession): EditorFragment | null {\n return serializeSelection(session);\n}\n\n/** Cut: removes the selection and returns both the cleaned session and the fragment. */\nexport function cutSelection(\n session: EditorSession,\n): { session: EditorSession; fragment: EditorFragment | null } {\n const fragment = serializeSelection(session);\n if (!fragment) {\n return { session, fragment: null };\n }\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n appendDebug(next, 'cutSelection', `count=${String(fragment.english.length)}`);\n return { session: next, fragment };\n}\n\n/**\n * Insert a structured fragment at the caret in the active chain. The fragment\n * is re-id'd so it can't collide with the live tree, mirrored EN/AR ids are\n * preserved, and sync entries are populated for every nested node.\n */\nexport function pasteFragment(session: EditorSession, fragment: EditorFragment): EditorSession {\n if (!fragment || !fragment.english.length || !fragment.arabic.length) {\n return session;\n }\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n\n const fresh = regenerateFragmentIds(fragment);\n const limit = Math.min(fresh.english.length, fresh.arabic.length);\n for (let i = 0; i < limit; i += 1) {\n const eng = fresh.english[i];\n const ar = fresh.arabic[i];\n insertMirroredNode(next, next.caret.chainId, next.caret.index, eng, ar);\n syncSubtreeRecursive(next, eng, ar);\n next.caret = { chainId: next.caret.chainId, index: next.caret.index + 1 };\n }\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'pasteFragment', `count=${String(limit)}`);\n return next;\n}\n\n/**\n * Plain-text fallback paste. Each character is dispatched through the existing\n * typing path so split/merge mode and selection-replace behave the same as\n * keyboard input. Whitespace is silently skipped in this MVP.\n */\nexport function pasteText(session: EditorSession, text: string): EditorSession {\n if (!text) {\n return session;\n }\n // A selected atomic label is edited as ONE span, not pasted as math\n // characters (which would otherwise discard the spaces in a sentence).\n const selection = session.selection;\n if (selection && Math.abs(selection.anchorIndex - selection.focusIndex) === 1) {\n const selectedChain = findChainById(session[activeTreeKey(session.activeSide)], selection.chainId);\n const selected = selectedChain?.chain.nodes[Math.min(selection.anchorIndex, selection.focusIndex)];\n if (selected?.kind === 'char' &&\n ['\\\\mathtt', '\\\\operatorname', '\\\\text'].includes(selected.wrapperCommand ?? '')) {\n return setExpr(session, selected.id, text);\n }\n }\n let s = session;\n let i = 0;\n while (i < text.length) {\n const ch = text[i]!;\n if (ch === '\\n' || ch === '\\r' || ch === '\\t' || ch === ' ') {\n if (!s.splitLeafTyping) {\n s = breakLeafTyping(s);\n }\n i += 1;\n continue;\n }\n if (/^[0-9]$/.test(ch)) {\n let j = i + 1;\n let sawDot = false;\n while (j < text.length) {\n const c = text[j]!;\n if (/^[0-9]$/.test(c)) {\n j += 1;\n continue;\n }\n if (c === '.' && !sawDot && j + 1 < text.length && /^[0-9]$/.test(text[j + 1]!)) {\n sawDot = true;\n j += 1;\n continue;\n }\n break;\n }\n s = insertNumber(s, text.slice(i, j));\n i = j;\n continue;\n }\n if (PASTE_OPERATORS.has(ch)) {\n s = insertOperator(s, ch);\n i += 1;\n continue;\n }\n if (ch === DIVIDE_OPERATOR_AR) {\n s = insertDivideOperator(s);\n i += 1;\n continue;\n }\n s = insertChar(s, ch);\n i += 1;\n }\n return s;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const DELIMITER_CSS = `\n.delim-pair {\n display: inline-flex;\n align-items: stretch;\n min-height: 1.85em;\n}\n\n.delim-inner {\n display: inline-flex;\n align-items: center;\n}\n\n.delim {\n display: inline-flex;\n align-self: stretch;\n align-items: center;\n justify-content: center;\n color: var(--butex-delim-color, #475569);\n padding: 0 1px;\n min-height: 100%;\n}\n\n.delim-glyph {\n display: inline-flex;\n align-items: center;\n line-height: 1;\n font-size: clamp(20px, 1.08em + 0.8vh, 36px);\n transform: translateY(-20%) scaleY(var(--butex-delim-scale, 1));\n transform-origin: center;\n}\n`.trim();\n\nfunction escapeDelimiterExpr(value: string): string {\n return value.replace(/[.*+?^$()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildDelimiterExpr(prefixes: string[], delimiters: string[]): RegExp {\n const prefixExpr = prefixes.map(escapeDelimiterExpr).join('|');\n const delimiterExpr = delimiters.map(escapeDelimiterExpr).join('|');\n return new RegExp(`^(?:(?:${prefixExpr}))?(?:${delimiterExpr})$`);\n}\n\nexport const leftDelimExpr = buildDelimiterExpr(\n ['\\\\left', '\\\\bigl', '\\\\Bigl', '\\\\biggl', '\\\\Biggl'],\n ['(', '[', '\\\\{', '\\\\lfloor', '\\\\lceil', '\\\\langle', '`', '|', '\\\\|', '\\\\lvert', '\\\\vert', '\\\\lVert', '\\\\Vert'],\n);\nexport const rightDelimExpr = buildDelimiterExpr(\n ['\\\\right', '\\\\bigr', '\\\\Bigr', '\\\\biggr', '\\\\Biggr'],\n [')', ']', '\\\\}', '\\\\rfloor', '\\\\rceil', '\\\\rangle', '`', '|', '\\\\|', '\\\\rvert', '\\\\vert', '\\\\rVert', '\\\\Vert'],\n);\n\nconst DELIMITER_BASE_HEIGHT_PX = 18;\nconst DELIMITER_MAX_SCALE = 4.8;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applyDelimiterScale(pair: HTMLElement, inner: HTMLElement): void {\n const innerHeight = Math.max(inner.getBoundingClientRect().height, DELIMITER_BASE_HEIGHT_PX);\n const scale = clamp((innerHeight / DELIMITER_BASE_HEIGHT_PX) * 1.18, 1.18, DELIMITER_MAX_SCALE);\n pair.style.setProperty('--butex-delim-scale', scale.toFixed(3));\n}\n\nfunction visibleDelimiter(expr: string): string {\n return expr\n .replace(/\\\\(?:left|right|bigl|Bigl|biggl|Biggl|bigr|Bigr|biggr|Biggr)/, '')\n .replace('\\\\{', '{')\n .replace('\\\\}', '}')\n .replace(/\\\\(?:lvert|rvert|vert)/, '|')\n .replace(/\\\\(?:lVert|rVert|Vert)/, '‖')\n .replace('\\\\|', '‖');\n}\n\nexport function buildDelimiterNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const pair = document.createElement('span');\n pair.className = 'delim-pair';\n\n const left = document.createElement('span');\n left.className = 'delim delim--left';\n const leftGlyph = document.createElement('span');\n leftGlyph.className = 'delim-glyph';\n leftGlyph.textContent = visibleDelimiter(node.leftDelimExpr);\n left.appendChild(leftGlyph);\n pair.appendChild(left);\n\n const inner = document.createElement('span');\n inner.className = 'delim-inner';\n if (node.innerExpr) {\n inner.appendChild(buildChain(node.innerExpr));\n }\n pair.appendChild(inner);\n\n const right = document.createElement('span');\n right.className = 'delim delim--right';\n const rightGlyph = document.createElement('span');\n rightGlyph.className = 'delim-glyph';\n rightGlyph.textContent = visibleDelimiter(node.rightDelimExpr);\n right.appendChild(rightGlyph);\n pair.appendChild(right);\n\n applyDelimiterScale(pair, inner);\n requestAnimationFrame(() => applyDelimiterScale(pair, inner));\n\n return pair;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const BOXED_CSS = `\n.boxed-command {\n display: inline-flex;\n align-items: center;\n border: 1.5px solid currentColor;\n padding: 0.12em 0.22em;\n min-height: 1.25em;\n}\n\n.boxed-command > .chain {\n min-height: auto;\n}\n`.trim();\n\nexport function buildBoxedNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const box = document.createElement('span');\n box.className = 'boxed-command';\n if (node.innerExpr) {\n box.appendChild(buildChain(node.innerExpr));\n }\n return box;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const FRAC_CSS = `\n.frac {\n display: inline-flex;\n flex-direction: column;\n align-items: stretch;\n justify-content: center;\n vertical-align: middle;\n margin: 0 3px;\n min-width: 1.5em;\n}\n\n.frac-num,\n.frac-den {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.1em;\n padding: 0 4px;\n}\n\n.frac-bar {\n align-self: stretch;\n height: 1px;\n background: var(--butex-frac-bar, currentColor);\n opacity: 0.88;\n}\n`.trim();\n\nexport function buildFracNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'frac';\n\n const num = document.createElement('span');\n num.className = 'frac-num';\n if (node.numerator) {\n num.appendChild(buildChain(node.numerator));\n }\n\n const bar = document.createElement('span');\n bar.className = 'frac-bar';\n bar.setAttribute('aria-hidden', 'true');\n\n const den = document.createElement('span');\n den.className = 'frac-den';\n if (node.denominator) {\n den.appendChild(buildChain(node.denominator));\n }\n\n wrap.appendChild(num);\n wrap.appendChild(bar);\n wrap.appendChild(den);\n\n return wrap;\n}\n","import type { EditorChain, EditorNode, EditorSide } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const SQRT_CSS = `\n.sqrt {\n display: inline-flex;\n align-items: stretch;\n position: relative;\n vertical-align: middle;\n margin: 0 2px;\n min-height: 2.1em;\n direction: ltr;\n --butex-sqrt-scale: 1;\n}\n\n.sqrt.sqrt--english .sqrt-root {\n order: 1;\n}\n\n.sqrt.sqrt--english .sqrt-sign {\n order: 2;\n}\n\n.sqrt.sqrt--english .sqrt-radicand {\n order: 3;\n}\n\n.sqrt.sqrt--arabic .sqrt-radicand {\n order: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-sign {\n order: 2;\n}\n\n.sqrt.sqrt--arabic .sqrt-root {\n order: 3;\n}\n\n.sqrt.sqrt--arabic .sqrt-root,\n.sqrt.sqrt--arabic .sqrt-radicand {\n direction: rtl;\n}\n\n.sqrt-root {\n align-self: flex-start;\n min-width: 0.9em;\n min-height: 1em;\n margin-inline-end: -0.18em;\n transform: translate(0.16em, 0.02em);\n font-size: 0.64em;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n position: relative;\n z-index: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-root {\n margin-inline-start: -0.22em;\n margin-inline-end: 0;\n transform: translate(-0.16em, 0.02em);\n}\n\n.sqrt-root .chain {\n min-height: auto;\n}\n\n.sqrt-sign {\n display: inline-flex;\n align-items: flex-end;\n justify-content: center;\n align-self: stretch;\n line-height: 0.78;\n font-size: 2em;\n color: var(--butex-sqrt-color, currentColor);\n transform: scaleY(var(--butex-sqrt-scale));\n transform-origin: center bottom;\n margin-inline-end: -0.24em;\n min-height: 100%;\n position: relative;\n z-index: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-sign {\n transform: scaleX(-1) scaleY(var(--butex-sqrt-scale));\n margin-inline-start: -0.24em;\n margin-inline-end: 0;\n}\n\n.sqrt-radicand {\n display: inline-flex;\n align-items: center;\n min-width: 1.35em;\n min-height: 1.35em;\n padding: 0.06em 0.24em 0;\n border-top: 2px solid var(--butex-sqrt-bar, currentColor);\n transform: translateY(-0.08em);\n position: relative;\n}\n\n.sqrt-radicand .chain {\n min-height: auto;\n}\n`.trim();\n\nconst SQRT_BASE_HEIGHT_PX = 32;\nconst SQRT_MAX_SCALE = 3.8;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applySqrtScale(wrap: HTMLElement, radicand: HTMLElement): void {\n const radicandHeight = Math.max(radicand.getBoundingClientRect().height, SQRT_BASE_HEIGHT_PX);\n const scale = clamp(radicandHeight / SQRT_BASE_HEIGHT_PX, 1, SQRT_MAX_SCALE);\n wrap.style.setProperty('--butex-sqrt-scale', scale.toFixed(3));\n}\n\nexport function buildSqrtNodeBody(node: EditorNode, buildChain: BuildChain, side: EditorSide): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = `sqrt sqrt--${side}`;\n\n const root = document.createElement('span');\n root.className = 'sqrt-root';\n if (node.rootIndex) {\n root.appendChild(buildChain(node.rootIndex));\n }\n\n const sign = document.createElement('span');\n sign.className = 'sqrt-sign';\n sign.setAttribute('aria-hidden', 'true');\n sign.textContent = '\\u221a';\n\n const radicand = document.createElement('span');\n radicand.className = 'sqrt-radicand';\n if (node.radicand) {\n radicand.appendChild(buildChain(node.radicand));\n }\n\n wrap.appendChild(root);\n wrap.appendChild(sign);\n wrap.appendChild(radicand);\n\n applySqrtScale(wrap, radicand);\n requestAnimationFrame(() => applySqrtScale(wrap, radicand));\n\n return wrap;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const OVERSET_CSS = `\n.overset {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.2em;\n}\n\n.overset-over {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.85em;\n padding: 0 2px;\n font-size: 0.72em;\n line-height: 1.1;\n}\n\n.overset-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n`.trim();\n\nexport function buildOversetNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'overset';\n\n const over = document.createElement('span');\n over.className = 'overset-over';\n if (node.overExpr) {\n over.appendChild(buildChain(node.overExpr));\n }\n\n const base = document.createElement('span');\n base.className = 'overset-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n wrap.appendChild(over);\n wrap.appendChild(base);\n return wrap;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const UNDERSET_CSS = `\n.underset {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.2em;\n}\n\n.underset-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n\n.underset-under {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.85em;\n padding: 0 2px;\n font-size: 0.72em;\n line-height: 1.1;\n}\n`.trim();\n\nexport function buildUndersetNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'underset';\n\n const base = document.createElement('span');\n base.className = 'underset-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n const under = document.createElement('span');\n under.className = 'underset-under';\n if (node.underExpr) {\n under.appendChild(buildChain(node.underExpr));\n }\n\n wrap.appendChild(base);\n wrap.appendChild(under);\n return wrap;\n}\n","import { accentCommandSpec } from '../accentCommands.js';\nimport type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const ACCENT_CSS = `\n.math-accent {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.1em;\n}\n\n.math-accent-chrome {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.7em;\n padding: 0 2px;\n font-size: 0.85em;\n line-height: 1;\n color: var(--butex-script-color, #475569);\n user-select: none;\n}\n\n.math-accent-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n\n.math-accent--under .math-accent-chrome {\n min-height: 0.45em;\n border-top: 1.5px solid currentColor;\n width: 100%;\n font-size: 0;\n color: var(--butex-surface-fg, #0f172a);\n}\n`.trim();\n\nexport function buildAccentNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n const spec = accentCommandSpec(node.expr);\n const placement = spec?.placement ?? 'over';\n wrap.className = placement === 'under' ? 'math-accent math-accent--under' : 'math-accent math-accent--over';\n\n const chrome = document.createElement('span');\n chrome.className = 'math-accent-chrome';\n chrome.setAttribute('aria-hidden', 'true');\n if (placement === 'over') {\n chrome.textContent = spec?.label ?? 'ˆ';\n }\n\n const base = document.createElement('span');\n base.className = 'math-accent-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n if (placement === 'under') {\n wrap.appendChild(base);\n wrap.appendChild(chrome);\n } else {\n wrap.appendChild(chrome);\n wrap.appendChild(base);\n }\n return wrap;\n}\n","import type { EditorChain, EditorNode, EditorSide, MatrixEnvStyle } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nconst WRAPPERS: Record<MatrixEnvStyle, { left: string; right: string }> = {\n matrix: { left: '', right: '' },\n pmatrix: { left: '(', right: ')' },\n bmatrix: { left: '[', right: ']' },\n Bmatrix: { left: '{', right: '}' },\n vmatrix: { left: '|', right: '|' },\n Vmatrix: { left: '||', right: '||' },\n};\n\nexport const MATRIX_ENV_CSS = `\n.matrix-env {\n display: inline-flex;\n align-items: stretch;\n vertical-align: middle;\n margin: 0 3px;\n --butex-matrix-delim-scale: 1.25;\n}\n\n.matrix-env__wrapper {\n display: inline-flex;\n align-self: stretch;\n align-items: center;\n justify-content: center;\n min-width: 0.42em;\n padding: 0 2px;\n color: var(--butex-delim-color, currentColor);\n font-family: ui-serif, \"Cambria Math\", \"Times New Roman\", serif;\n font-size: clamp(22px, 1.35em + 0.8vh, 42px);\n line-height: 1;\n transform: scaleY(var(--butex-matrix-delim-scale));\n transform-origin: center;\n}\n\n.matrix-env--cases .matrix-env__wrapper:empty {\n min-width: 0;\n padding: 0;\n}\n\n.matrix-env__grid {\n display: inline-grid;\n direction: ltr;\n gap: 2px 5px;\n align-items: center;\n justify-items: center;\n padding: 2px 3px;\n}\n\n.matrix-env__cell {\n min-width: 1.35em;\n min-height: 1.45em;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: 5px;\n border: 1px dashed rgba(148, 163, 184, 0.48);\n padding: 1px 3px;\n}\n\n.matrix-env__cell .chain {\n min-height: auto;\n}\n\n.matrix-env--arabic .matrix-env__cell {\n direction: rtl;\n}\n\n.matrix-env--english .matrix-env__cell {\n direction: ltr;\n}\n`.trim();\n\nconst MATRIX_DELIMITER_BASE_HEIGHT_PX = 20;\nconst MATRIX_DELIMITER_MAX_SCALE = 5.2;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applyMatrixDelimiterScale(wrap: HTMLElement, grid: HTMLElement): void {\n const gridHeight = Math.max(grid.getBoundingClientRect().height, MATRIX_DELIMITER_BASE_HEIGHT_PX);\n const scale = clamp((gridHeight / MATRIX_DELIMITER_BASE_HEIGHT_PX) * 1.22, 1.25, MATRIX_DELIMITER_MAX_SCALE);\n wrap.style.setProperty('--butex-matrix-delim-scale', scale.toFixed(3));\n}\n\nexport function buildMatrixEnvNodeBody(node: EditorNode, buildChain: BuildChain, side: EditorSide): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = `matrix-env matrix-env--${side}${node.envName === 'cases' ? ' matrix-env--cases' : ''}`;\n if (node.envName === 'cases') wrap.dir = 'ltr';\n\n const style = node.envName ?? node.matrixStyle ?? 'matrix';\n const glyphs = style === 'cases'\n ? (side === 'arabic' ? { left: '', right: '}' } : { left: '{', right: '' })\n : style === 'array' || style === 'aligned' ? undefined : WRAPPERS[style];\n\n const left = document.createElement('span');\n left.className = 'matrix-env__wrapper matrix-env__wrapper--left';\n left.textContent = glyphs?.left ?? '';\n\n const grid = document.createElement('span');\n grid.className = 'matrix-env__grid';\n\n const rows = node.matrixRows ?? [];\n const columnCount = Math.max(1, ...rows.map((row) => row.length));\n grid.style.gridTemplateColumns = `repeat(${String(columnCount)}, minmax(1.35em, auto))`;\n\n const displayRows = side === 'arabic' ? rows.map((row) => row.slice().reverse()) : rows;\n for (const row of displayRows) {\n for (const cellChain of row) {\n const cell = document.createElement('span');\n cell.className = 'matrix-env__cell';\n cell.dir = side === 'arabic' ? 'rtl' : 'ltr';\n cell.appendChild(buildChain(cellChain));\n grid.appendChild(cell);\n }\n }\n\n const right = document.createElement('span');\n right.className = 'matrix-env__wrapper matrix-env__wrapper--right';\n right.textContent = glyphs?.right ?? '';\n\n wrap.appendChild(left);\n wrap.appendChild(grid);\n wrap.appendChild(right);\n\n applyMatrixDelimiterScale(wrap, grid);\n requestAnimationFrame(() => applyMatrixDelimiterScale(wrap, grid));\n\n return wrap;\n}\n","import diwaniLetterUrl from './fonts/Diwani Letter Regular.ttf';\nimport diwaniOutlineUrl from './fonts/DWNOUTSH.TTF';\nimport maghribiUrl from './fonts/Almaghribi-Warsh-Quran.otf';\nimport takweenUrl from './fonts/Takween.otf';\n\n\nexport const BUTEX_DIWANI_FONT_FAMILY = 'Diwani Letter';\nexport const BUTEX_DIWANI_OUTLINE_FONT_FAMILY = 'BuTeX Diwani Outline';\nexport const BUTEX_MAGHRIBI_FONT_FAMILY = 'Almaghribi Warsh Quran';\nexport const BUTEX_TAKWEEN_FONT_FAMILY = 'BuTeX Takween';\n\nexport const BUTEX_DIWANI_FONT_STACK = `\"${BUTEX_DIWANI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_DIWANI_OUTLINE_FONT_STACK = `\"${BUTEX_DIWANI_OUTLINE_FONT_FAMILY}\", \"${BUTEX_DIWANI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_MAGHRIBI_FONT_STACK = `\"${BUTEX_MAGHRIBI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_TAKWEEN_FONT_STACK = `\"${BUTEX_TAKWEEN_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\n\nexport const BUTEX_DIWANI_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_DIWANI_FONT_FAMILY}\";\n src: url(\"${diwaniLetterUrl}\") format(\"truetype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_TAKWEEN_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_TAKWEEN_FONT_FAMILY}\";\n src: url(\"${takweenUrl}\") format(\"opentype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_DIWANI_OUTLINE_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_DIWANI_OUTLINE_FONT_FAMILY}\";\n src: url(\"${diwaniOutlineUrl}\") format(\"truetype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_MAGHRIBI_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_MAGHRIBI_FONT_FAMILY}\";\n src: url(\"${maghribiUrl}\") format(\"opentype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_FONT_FACE_CSS = `\n${BUTEX_DIWANI_FONT_FACE_CSS}\n\n${BUTEX_DIWANI_OUTLINE_FONT_FACE_CSS}\n\n${BUTEX_TAKWEEN_FONT_FACE_CSS}\n\n${BUTEX_MAGHRIBI_FONT_FACE_CSS}\n`.trim();\n","import { atomicCommandSpec, isSpacingCommandSpec, type AtomicCommandSpec, type SpacingCommandSpec } from '../atomicCommands.js';\nimport { BUTEX_DIWANI_FONT_STACK, BUTEX_DIWANI_OUTLINE_FONT_STACK } from '../../diwani-font.js';\nimport type { EditorNode, EditorSide } from '../types.js';\nimport type { ButexUiLocale } from '../../uiLocale.js';\nimport { atomicCommandTitle } from '../uiLocale.js';\n\nexport const ATOMIC_COMMAND_CSS = `\n/* Shared atomic-command display */\n.atomic-command {\n display: inline-flex;\n align-items: center;\n font-weight: 600;\n line-height: 1;\n}\n\n/* Function-style commands: sin/cos/tan families. */\n.atomic-command--arabic {\n font-family: ${BUTEX_DIWANI_FONT_STACK};\n font-size: 1.15em;\n direction: rtl;\n}\n\n.atomic-command--diwani-outline {\n font-family: ${BUTEX_DIWANI_OUTLINE_FONT_STACK};\n}\n\n.atomic-command--english {\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 0.96em;\n}\n\n.atomic-command-label-with-sub {\n position: relative;\n display: inline-block;\n padding-inline-end: 0.45em;\n padding-block-end: 0.22em;\n line-height: 1;\n}\n\n.atomic-command-label-with-sub__sub {\n position: absolute;\n inset-inline-end: 0;\n inset-block-end: 0;\n font-size: 0.62em;\n line-height: 1;\n}\n\n/* Spacing commands: tiny selectable marker, real spacing remains in LaTeX preview. */\n.atomic-spacing {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 3px;\n min-width: 3px;\n height: 1em;\n color: var(--butex-accent, currentColor);\n opacity: 0.62;\n}\n\n.atomic-spacing__marker {\n display: inline-block;\n width: 3px;\n height: 0.85em;\n border-radius: 999px;\n background: currentColor;\n}\n\n.atomic-spacing--negative {\n color: var(--butex-danger, #dc2626);\n}\n`.trim();\n\nfunction spacingArrowForSide(spec: SpacingCommandSpec, side: EditorSide): string {\n const pointsWithFlow = spec.spacing.direction === 'positive';\n if (pointsWithFlow) {\n return side === 'arabic' ? '\\u2190' : '\\u2192';\n }\n return side === 'arabic' ? '\\u2192' : '\\u2190';\n}\n\nexport function spacingTooltipForSide(spec: SpacingCommandSpec, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): string {\n return `${atomicCommandTitle(spec, uiLocale)} ${spacingArrowForSide(spec, side).repeat(spec.spacing.level)}`;\n}\n\nfunction buildFunctionAtomicCommandBody(node: EditorNode, side: EditorSide, spec: AtomicCommandSpec | null): HTMLElement {\n const value = document.createElement('span');\n value.className = `atomic-command atomic-command--${side}`;\n if (side === 'arabic' && spec?.category === 'groups') {\n value.classList.add('atomic-command--diwani-outline');\n }\n if (side === 'arabic' && node.expr === 'ln') {\n const label = document.createElement('span');\n label.className = 'atomic-command-label-with-sub';\n const base = document.createElement('span');\n base.className = 'atomic-command-label-with-sub__base';\n base.textContent = spec?.arabicLabel ?? node.expr;\n const sub = document.createElement('span');\n sub.className = 'atomic-command-label-with-sub__sub';\n sub.textContent = 'هـ';\n label.append(base, sub);\n value.appendChild(label);\n return value;\n }\n value.textContent = side === 'arabic'\n ? spec?.arabicLabel ?? node.expr\n : spec?.englishLabel ?? spec?.englishTex.replace(/^\\\\/, '') ?? node.expr;\n return value;\n}\n\nfunction buildSpacingAtomicCommandBody(spec: SpacingCommandSpec, side: EditorSide, uiLocale: ButexUiLocale): HTMLElement {\n const value = document.createElement('span');\n value.className = `atomic-spacing atomic-spacing--${spec.spacing.direction} atomic-spacing--level-${String(spec.spacing.level)}`;\n value.title = spacingTooltipForSide(spec, side, uiLocale);\n const marker = document.createElement('span');\n marker.className = 'atomic-spacing__marker';\n value.appendChild(marker);\n return value;\n}\n\nexport function buildAtomicCommandNodeBody(node: EditorNode, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): HTMLElement {\n const spec = atomicCommandSpec(node.expr);\n if (isSpacingCommandSpec(spec)) {\n return buildSpacingAtomicCommandBody(spec, side, uiLocale);\n }\n return buildFunctionAtomicCommandBody(node, side, spec);\n}\n","import { atomicOperatorCommandSpec, shouldMirrorOperatorDisplay, type AtomicOperatorCommandSpec } from '../atomicCommandsOperators.js';\nimport type { EditorNode, EditorSide } from '../types.js';\nimport type { ButexUiLocale } from '../../uiLocale.js';\nimport { atomicOperatorCommandTitle } from '../uiLocale.js';\n\nexport const ATOMIC_OPERATOR_COMMAND_CSS = `\n.atomic-operator-command {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 0.9em;\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 1.05em;\n font-weight: 600;\n line-height: 1;\n}\n\n.atomic-operator-command--mirrored {\n transform: scaleX(-1);\n}\n\n.atomic-operator-command__svg {\n width: 1em;\n height: 1em;\n background: currentColor;\n}\n`.trim();\n\nfunction buildOperatorLabel(spec: AtomicOperatorCommandSpec): HTMLElement {\n const value = document.createElement('span');\n value.className = 'atomic-operator-command__label';\n value.textContent = spec.Label;\n return value;\n}\n\nexport function buildAtomicOperatorCommandNodeBody(node: EditorNode, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): HTMLElement {\n const spec = atomicOperatorCommandSpec(node.expr);\n const value = document.createElement('span');\n value.className = 'atomic-operator-command';\n value.title = spec ? atomicOperatorCommandTitle(spec, uiLocale) : node.expr;\n if (side === 'arabic' && shouldMirrorOperatorDisplay(spec)) {\n value.classList.add('atomic-operator-command--mirrored');\n }\n\n if (spec?.svg_path) {\n const icon = document.createElement('span');\n icon.className = 'atomic-operator-command__svg';\n icon.style.mask = `url(\"${spec.svg_path}\") center / contain no-repeat`;\n icon.style.webkitMask = `url(\"${spec.svg_path}\") center / contain no-repeat`;\n value.appendChild(icon);\n return value;\n }\n\n if (spec) {\n value.appendChild(buildOperatorLabel(spec));\n } else {\n const label = document.createElement('span');\n label.className = 'atomic-operator-command__label';\n label.textContent = node.expr;\n value.appendChild(label);\n }\n return value;\n}\n","import { standardCommandSpec } from '../standardCommands.js';\nimport type { EditorNode } from '../types.js';\n\nexport const STANDARD_COMMAND_CSS = `\n.standard-command {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 0.9em;\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 1.05em;\n line-height: 1;\n}\n`.trim();\n\nexport function buildStandardCommandNodeBody(node: EditorNode): HTMLElement {\n const spec = standardCommandSpec(node.expr);\n const value = document.createElement('span');\n value.className = 'standard-command';\n value.title = spec?.title ?? node.expr;\n value.textContent = spec?.label ?? node.expr;\n return value;\n}\n","import { DELIMITER_CSS } from './display/delimiter.js';\nimport { BOXED_CSS } from './display/boxed.js';\nimport { FRAC_CSS } from './display/frac.js';\nimport { SQRT_CSS } from './display/sqrt.js';\nimport { OVERSET_CSS } from './display/overset.js';\nimport { UNDERSET_CSS } from './display/underset.js';\nimport { ACCENT_CSS } from './display/accent.js';\nimport { MATRIX_ENV_CSS } from './display/env.js';\nimport { ATOMIC_COMMAND_CSS } from './display/atomicCommand.js';\nimport { ATOMIC_OPERATOR_COMMAND_CSS } from './display/atomicCommandsOperators.js';\nimport { STANDARD_COMMAND_CSS } from './display/standardCommand.js';\nimport { BUTEX_FONT_FACE_CSS } from '../diwani-font.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from './characterFonts.js';\n\nconst CHARACTER_FONT_CSS = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.cssClass && font.browserFontStack)\n .map((font) => `.${font.cssClass} {\\n font-family: ${font.browserFontStack};\\n}`)\n .join('\\n\\n');\n\nexport const BUTEX_EDITOR_CSS = `\n${BUTEX_FONT_FACE_CSS}\n\n.surface {\n background: var(--butex-surface-bg, linear-gradient(180deg, #ffffff 0%, #fafbfc 100%));\n border: 1px solid var(--butex-border, #e2e8f0);\n border-radius: 12px;\n color: var(--butex-surface-fg, #0f172a);\n cursor: text;\n max-width: 100%;\n min-height: 100px;\n min-width: 0;\n outline: none;\n overflow-x: auto;\n overflow-y: hidden;\n overscroll-behavior-inline: contain;\n padding: 8px 10px;\n touch-action: pan-x pan-y;\n transition: box-shadow 0.15s ease, border-color 0.15s ease;\n}\n\n.surface:focus,\n.surface.surface--typing-focus {\n border-color: var(--butex-focus-border, rgba(13, 148, 136, 0.45));\n box-shadow: 0 0 0 3px var(--butex-focus-shadow, rgba(13, 148, 136, 0.12));\n}\n\n.surface.surface--arabic {\n direction: rtl;\n}\n\n.surface.surface--english {\n direction: ltr;\n}\n\n${CHARACTER_FONT_CSS}\n\n.node-value--bold {\n font-family: var(--font-display-ar, Amiri), \"Noto Serif Arabic\", serif;\n font-weight: 700;\n}\n\n.node-value--unit {\n font-style: normal;\n text-decoration-line: underline;\n text-decoration-style: dotted;\n text-underline-offset: 0.2em;\n}\n\n.chain {\n display: inline-flex;\n align-items: center;\n gap: 0;\n min-height: 28px;\n flex-wrap: wrap;\n row-gap: 2px;\n}\n\n.slot {\n width: 5px;\n min-height: 28px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n border-radius: 3px;\n}\n\n.slot:hover {\n background: var(--butex-slot-hover, rgba(13, 148, 136, 0.08));\n}\n\n.slot.range-highlight {\n background: var(--butex-selection-bg, rgba(13, 148, 136, 0.34));\n width: 11px;\n min-height: 42px;\n border: 2px solid var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n position: relative;\n z-index: 1;\n}\n\n.caret {\n display: inline-block;\n width: 2px;\n height: 20px;\n background: var(--butex-caret, #0f172a);\n border-radius: 1px;\n animation: butex-editor-blink 1s step-end infinite;\n}\n\n@keyframes butex-editor-blink {\n 50% { opacity: 0; }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .surface {\n scroll-behavior: auto;\n transition: none;\n }\n\n .caret {\n animation: none;\n }\n}\n\n.node {\n display: inline-flex;\n align-items: stretch;\n gap: 3px;\n border-radius: 8px;\n padding: 2px 4px;\n cursor: pointer;\n border: 1px solid transparent;\n user-select: none;\n}\n\n.node.node--atomic-spacing {\n padding-inline: 0;\n margin-inline: -2px;\n border-color: transparent;\n}\n\n.node:hover {\n border-color: var(--butex-border, #e2e8f0);\n background: var(--butex-node-hover, rgba(148, 163, 184, 0.08));\n}\n\n.node.selected {\n background: var(--butex-node-selected-bg, rgba(13, 148, 136, 0.14));\n border-color: var(--butex-node-selected-border, rgba(13, 148, 136, 0.45));\n}\n\n.node.range-highlight {\n background: var(--butex-selection-bg, rgba(13, 148, 136, 0.34));\n border-color: var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n box-shadow: inset 0 0 0 3px var(--butex-selection-border, rgba(15, 118, 110, 0.9)),\n 0 0 0 1px var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n position: relative;\n z-index: 2;\n}\n\n.chain .slot.range-highlight + .node.range-highlight,\n.chain .node.range-highlight + .slot.range-highlight {\n margin-inline: -1px;\n}\n\n.node-body {\n display: inline-flex;\n align-items: stretch;\n gap: 0;\n min-height: 1.6em;\n}\n\n.node-value {\n font-size: 16px;\n font-weight: 500;\n line-height: 1.25;\n display: inline-flex;\n align-items: center;\n}\n\n.scripts {\n display: flex;\n flex-direction: column;\n flex-shrink: 0;\n justify-content: space-between;\n align-items: center;\n padding: 1px 0;\n min-width: 0.75em;\n}\n\n.scripts.scripts--sup-only {\n justify-content: flex-start;\n padding-bottom: 2px;\n}\n\n.scripts.scripts--sub-only {\n justify-content: flex-end;\n padding-top: 2px;\n}\n\n.script-box {\n min-height: 12px;\n min-width: 10px;\n border-radius: 4px;\n border: 1px dashed var(--butex-script-border, #cbd5e1);\n padding: 0 2px;\n font-size: 0.68em;\n line-height: 1.15;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n background: var(--butex-script-bg, rgba(248, 250, 252, 0.95));\n color: var(--butex-script-color, #475569);\n}\n\n.script-box .chain {\n min-height: auto;\n}\n\n${DELIMITER_CSS}\n\n${BOXED_CSS}\n\n${FRAC_CSS}\n\n${SQRT_CSS}\n\n${OVERSET_CSS}\n\n${UNDERSET_CSS}\n\n${ACCENT_CSS}\n\n${MATRIX_ENV_CSS}\n\n${ATOMIC_COMMAND_CSS}\n\n${ATOMIC_OPERATOR_COMMAND_CSS}\n\n${STANDARD_COMMAND_CSS}\n`.trim();\n\n/**\n * Injects BuTeX editor surface styles into `document.head` if not already present.\n * Browser-only; no-op if `document` is undefined (Node).\n */\nexport function injectBuTeXEditorStyles(doc?: Document): void {\n const d = doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!d) {\n return;\n }\n const id = 'butex-editor-styles';\n const existing = d.getElementById(id);\n if (existing) {\n existing.textContent = BUTEX_EDITOR_CSS;\n return;\n }\n const style = d.createElement('style');\n style.id = id;\n style.textContent = BUTEX_EDITOR_CSS;\n d.head.appendChild(style);\n}\n","import type { CharacterFontId } from '../../editor/types.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../../editor/characterFonts.js';\n\nexport type NormalizedCharImport = {\n expr: string;\n characterFont: CharacterFontId;\n};\n\ntype WrapperSpec = {\n prefix: string;\n font?: CharacterFontId;\n};\n\nconst WRAPPER_SPECS: WrapperSpec[] = [\n ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [\n { prefix: font.macro, font: font.id },\n ...(font.importAliases ?? []).map((alias) => ({ prefix: alias, font: font.id })),\n ]),\n { prefix: '\\\\text' },\n];\n\nfunction readBracedArg(source: string, openBraceIndex: number): { inner: string; end: number } | null {\n if (source[openBraceIndex] !== '{') {\n return null;\n }\n\n let depth = 0;\n for (let index = openBraceIndex; index < source.length; index += 1) {\n const char = source[index];\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n return { inner: source.slice(openBraceIndex + 1, index), end: index + 1 };\n }\n }\n }\n\n return null;\n}\n\nfunction peelWrapper(source: string): { inner: string; font?: CharacterFontId } | null {\n for (const wrapper of WRAPPER_SPECS) {\n if (!source.startsWith(wrapper.prefix)) {\n continue;\n }\n\n const braced = readBracedArg(source, wrapper.prefix.length);\n if (!braced || braced.end !== source.length) {\n continue;\n }\n\n return { inner: braced.inner, font: wrapper.font };\n }\n\n return null;\n}\n\nexport function normalizeCharImportExpr(expr: string): NormalizedCharImport {\n const original = expr;\n let current = expr;\n let characterFont: CharacterFontId = 'default';\n let changed = false;\n\n while (true) {\n const peeled = peelWrapper(current);\n if (!peeled) {\n break;\n }\n\n current = peeled.inner;\n if (peeled.font) {\n characterFont = peeled.font;\n }\n changed = true;\n }\n\n if (!changed) {\n return { expr: original, characterFont: 'default' };\n }\n\n if (current.includes('\\\\')) {\n return { expr: original, characterFont: 'default' };\n }\n\n return { expr: current, characterFont };\n}\n","import {\n BaseAstNode,\n ChainNode,\n CharNode,\n CommandNode,\n DelimiterNode,\n EnvNode,\n NumberNode,\n OperatorNode,\n} from '../../ast/arabic_ast.js';\nimport {\n accentCommandIdFromTex,\n accentCommandSpec,\n} from '../../editor/accentCommands.js';\nimport {\n ATOMIC_COMMANDS,\n atomicCommandSpec,\n type AtomicCommandId,\n} from '../../editor/atomicCommands.js';\nimport {\n ATOMIC_OPERATOR_COMMANDS,\n atomicOperatorCommandSpec,\n type AtomicOperatorCommandId,\n} from '../../editor/atomicCommandsOperators.js';\nimport { isStandardCommandTex } from '../../editor/standardCommands.js';\nimport {\n buildInitialSyncMap,\n cloneEditorSession,\n createAccentNode,\n createDelimiterNode,\n createBoxedNode,\n createEditorChain,\n createEditorNode,\n createEditorSession,\n createFracNode,\n createGridEnvNode,\n createSqrtNode,\n createOversetNode,\n createUndersetNode,\n renderArabicLatexFromSession,\n} from '../../editor/index.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../../editor/characterFonts.js';\nimport type {\n CharacterFontId,\n EditorChain,\n EditorNode,\n EditorSession,\n EnvColumnAlignment,\n GridEnvName,\n MatrixEnvStyle,\n} from '../../editor/index.js';\nimport { normalizeCharImportExpr } from './normalizeCharImport.js';\nimport { isValidIndexSequence } from '../../editor/indexSequence.js';\nimport type { MathNode } from './types.js';\n\ntype CommandFontPolicy = CharacterFontId | 'infer';\n\nconst COMMAND_FONT_MAP: Record<string, CommandFontPolicy> = Object.fromEntries([\n ['\\\\text', 'infer'],\n ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [\n [font.macro, font.id],\n ...(font.importAliases ?? []).map((alias) => [alias, font.id]),\n ]),\n]) as Record<string, CommandFontPolicy>;\n\nconst CHAR_FONT_EXPORT_TEX: Record<Exclude<CharacterFontId, 'default'>, string> = Object.fromEntries(\n NON_DEFAULT_CHARACTER_FONT_SPECS.map((font) => [font.id, font.macro]),\n) as Record<Exclude<CharacterFontId, 'default'>, string>;\n\nfunction hasBareBoldCharSource(node: EditorNode): boolean {\n return node.kind === 'char'\n && (node.wrapperCommand === '\\\\boldarabic' || node.wrapperCommand === '\\\\mathbf')\n && typeof node.sourceLatex === 'string'\n && node.sourceLatex.length > 0\n && !node.sourceLatex.startsWith('\\\\mathbf{');\n}\n\nfunction charEditorNodeToAstNode(node: EditorNode): BaseAstNode {\n const font = node.characterFont ?? 'default';\n const charNode = new CharNode(node.expr);\n if (node.wrapperCommand) {\n const wrapper = node.wrapperCommand === '\\\\boldarabic' ? '\\\\mathbf' : node.wrapperCommand;\n // Burhan's nested boldarabic{text{س}} supplies 'x' as source identity\n // for the inner character. Keep it on that character, not the enclosing\n // \\\\mathbf command: reverse conversion would otherwise replace the entire\n // styled command with an unstyled x.\n if (hasBareBoldCharSource(node)) {\n charNode.sourceLatex = node.sourceLatex!;\n }\n return new CommandNode(wrapper, [], [new ChainNode([charNode])]);\n }\n if (font === 'default') {\n return charNode;\n }\n return new CommandNode(CHAR_FONT_EXPORT_TEX[font], [], [new ChainNode([charNode])]);\n}\n\nexport type MathEditorAdapterResult =\n | { editable: true; session: EditorSession }\n | { editable: false; reason: string };\n\ntype NodeAdapterResult =\n | { editable: true; node: EditorNode }\n | { editable: false; reason: string };\n\ntype UnsupportedAdapterResult = { editable: false; reason: string };\n\nexport type MathNodeFromEditorResult =\n | { ok: true; math: MathNode }\n | { ok: false; reason: string };\n\nfunction commandIdForTex(tex: string): AtomicCommandId | null {\n for (const spec of Object.values(ATOMIC_COMMANDS)) {\n const renderTex = (spec as { arabicRenderTex?: string }).arabicRenderTex;\n if (spec.englishTex === tex || spec.arabicTex === tex || renderTex === tex) {\n return spec.id as AtomicCommandId;\n }\n }\n return null;\n}\n\nfunction operatorCommandIdForTex(tex: string): AtomicOperatorCommandId | null {\n const normalized = tex === '\\\\le' ? '\\\\leq' : tex === '\\\\ge' ? '\\\\geq' : tex;\n for (const spec of Object.values(ATOMIC_OPERATOR_COMMANDS)) {\n if (spec.Tex === normalized) {\n return spec.id as AtomicOperatorCommandId;\n }\n }\n return null;\n}\n\nfunction cloneChainWithFreshIds(chain: EditorChain): EditorChain {\n return structuredClone(chain);\n}\n\nfunction attachScripts(astNode: BaseAstNode, editorNode: EditorNode): UnsupportedAdapterResult | null {\n if (astNode.sourceLatex) {\n editorNode.sourceLatex = astNode.sourceLatex;\n }\n if (astNode.superscript) {\n const sup = chainToEditorChain(astNode.superscript, true);\n if (!sup.editable) {\n return sup;\n }\n editorNode.superscript = sup.chain;\n }\n if (astNode.subscript) {\n const sub = chainToEditorChain(astNode.subscript, true);\n if (!sub.editable) {\n return sub;\n }\n editorNode.subscript = sub.chain;\n }\n return null;\n}\n\ntype ChainAdapterResult =\n | { editable: true; chain: EditorChain }\n | { editable: false; reason: string };\n\nconst MATRIX_ENV_NAMES = new Set<GridEnvName>(['matrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix', 'Vmatrix']);\n\nfunction isGridEnvName(value: string): value is GridEnvName {\n return MATRIX_ENV_NAMES.has(value as GridEnvName) || value === 'array' || value === 'aligned' || value === 'cases';\n}\n\nfunction isMatrixEnvName(value: GridEnvName): value is MatrixEnvStyle {\n return MATRIX_ENV_NAMES.has(value);\n}\n\nfunction parseEnvOpening(opening: string): { envName: GridEnvName; alignments?: EnvColumnAlignment[] } | null {\n const match = /^\\\\begin\\{([^}]+)\\}(?:\\{([lcr]+)\\})?$/.exec(opening);\n if (!match) {\n return null;\n }\n\n const envName = match[1] ?? '';\n if (!isGridEnvName(envName)) {\n return null;\n }\n\n if (envName === 'array') {\n const spec = match[2] ?? 'c';\n return {\n envName,\n alignments: spec.split('').map((alignment) => alignment as EnvColumnAlignment),\n };\n }\n\n return { envName };\n}\n\nfunction splitEnvLine(line: ChainNode): ChainNode[] {\n const cells: ChainNode[] = [];\n let current: BaseAstNode[] = [];\n for (const node of line.chain) {\n if (node instanceof OperatorNode && node.expr === '&') {\n cells.push(new ChainNode(current));\n current = [];\n } else {\n current.push(node);\n }\n }\n cells.push(new ChainNode(current));\n return cells;\n}\n\nfunction envToEditorNode(node: EnvNode): NodeAdapterResult {\n const parsed = parseEnvOpening(node.opening);\n if (!parsed) {\n return { editable: false, reason: `بيئة رياضية غير مدعومة حاليا: ${node.opening}` };\n }\n\n const expectedClosing = `\\\\end{${parsed.envName}}`;\n if (node.closing !== expectedClosing) {\n return { editable: false, reason: `إغلاق بيئة رياضية غير مدعوم حاليا: ${node.closing}` };\n }\n\n const rowCells = node.lines.map(splitEnvLine);\n if (parsed.envName === 'cases' && (rowCells.length === 0 || rowCells.length > 12 || rowCells.some((row) => row.length !== 2))) {\n return { editable: false, reason: 'بيئة cases تتطلب تعبيرا وشرطا في كل صف (عمودان)' };\n }\n const rows = Math.max(1, rowCells.length);\n const columns = Math.max(1, ...rowCells.map((row) => row.length));\n const env = createGridEnvNode(parsed.envName, rows, columns, parsed.alignments);\n\n for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) {\n const row = rowCells[rowIndex] ?? [];\n for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) {\n const cell = chainToEditorChain(row[columnIndex] ?? new ChainNode());\n if (!cell.editable) {\n return cell;\n }\n env.matrixRows![rowIndex]![columnIndex] = cell.chain;\n }\n }\n\n if (parsed.envName === 'array') {\n env.columnAlignments = Array.from(\n { length: columns },\n (_, index) => parsed.alignments?.[index] ?? 'c',\n );\n }\n if (isMatrixEnvName(parsed.envName)) {\n env.matrixStyle = parsed.envName;\n }\n\n const scripts = attachScripts(node, env);\n return scripts ?? { editable: true, node: env };\n}\n\nfunction charFromTextLikeCommand(node: CommandNode): NodeAdapterResult | null {\n const commandFont = COMMAND_FONT_MAP[node.name];\n if (commandFont === undefined) {\n return null;\n }\n if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {\n return null;\n }\n\n const arg = node.mandatoryArgs[0]!;\n if (arg.chain.length !== 1) {\n return null;\n }\n\n const child = arg.chain[0]!;\n if (child instanceof CommandNode) {\n const nested = charFromTextLikeCommand(child);\n if (!nested?.editable) {\n return null;\n }\n if (commandFont !== 'infer') {\n nested.node.characterFont = commandFont;\n }\n const scripts = attachScripts(node, nested.node);\n return scripts ?? nested;\n }\n\n if (!(child instanceof CharNode)) {\n return null;\n }\n\n const normalized = normalizeCharImportExpr(child.expr);\n const characterFont = commandFont === 'infer' ? normalized.characterFont : commandFont;\n const editorNode = createEditorNode('char', normalized.expr);\n if (characterFont !== 'default') {\n editorNode.characterFont = characterFont;\n }\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n}\n\nfunction singleCommandChar(node: CommandNode): CharNode | null {\n if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {\n return null;\n }\n const arg = node.mandatoryArgs[0]!;\n if (arg.chain.length !== 1 || !(arg.chain[0] instanceof CharNode)) {\n return null;\n }\n return arg.chain[0];\n}\n\nfunction wrappedAtomicCommandId(node: CommandNode): AtomicCommandId | null {\n if (node.name !== '\\\\mathbb' && node.name !== '\\\\mathrm') {\n return null;\n }\n const child = singleCommandChar(node);\n if (!child) {\n return null;\n }\n return commandIdForTex(`${node.name}{${child.expr}}`);\n}\n\nfunction editableWrapperCommand(node: CommandNode): NodeAdapterResult | null {\n if (\n node.name !== '\\\\mathtt' &&\n node.name !== '\\\\operatorname' &&\n node.name !== '\\\\text' &&\n node.name !== '\\\\mathsf' &&\n node.name !== '\\\\unit' &&\n node.name !== '\\\\mathbf' &&\n node.name !== '\\\\boldarabic'\n ) {\n return null;\n }\n // A mapped legacy variable may be represented as \\text{س}, sourced from x.\n // Only a canonical \\text invocation (or edited literal) is a text wrapper.\n if (node.name === '\\\\text' && node.sourceLatex && !node.sourceLatex.startsWith('\\\\text{')) {\n return null;\n }\n const child = singleCommandChar(node);\n if (node.name === '\\\\text' && child?.sourceLatex && !node.sourceLatex) return null;\n let editorNode: EditorNode;\n if (child) {\n const normalized = normalizeCharImportExpr(child.expr);\n editorNode = createEditorNode('char', normalized.expr);\n // Keep source identity when reopening an editor-exported wrapped CharObject.\n // Without it, reopening \\mathbf{س} loses the original English x.\n if (child.sourceLatex) editorNode.sourceLatex = child.sourceLatex;\n if (normalized.characterFont !== 'default') {\n editorNode.characterFont = normalized.characterFont;\n }\n } else {\n // Burhan represents mapped mathbf characters as boldarabic{text{Arabic}}\n // with source_latex on the inner text node, not as a single CharObject.\n // Import that existing supported character without discarding its identity.\n if (node.optionalArgs.length || node.mandatoryArgs.length !== 1) return null;\n const nodes = node.mandatoryArgs[0]?.chain;\n if (!nodes || nodes.length !== 1 || !(nodes[0] instanceof CommandNode)) return null;\n const nested = charFromTextLikeCommand(nodes[0]);\n if (!nested?.editable) return null;\n editorNode = nested.node;\n }\n\n editorNode.wrapperCommand = node.name === '\\\\mathsf' ? '\\\\unit'\n : node.name as NonNullable<EditorNode['wrapperCommand']>;\n\n const scripts = attachScripts(node, editorNode);\n if (scripts) {\n return scripts;\n }\n if (!editorNode.sourceLatex && node.name === '\\\\mathsf' && child) {\n editorNode.sourceLatex = `\\\\mathsf{${child.expr}}`;\n }\n return { editable: true, node: editorNode };\n}\n\nfunction commandToEditorNode(node: CommandNode): NodeAdapterResult {\n if (node.name === '\\\\frac' && node.mandatoryArgs.length >= 2) {\n const frac = createFracNode();\n const numerator = chainToEditorChain(node.mandatoryArgs[0]!);\n const denominator = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!numerator.editable) {\n return numerator;\n }\n if (!denominator.editable) {\n return denominator;\n }\n frac.numerator = numerator.chain;\n frac.denominator = denominator.chain;\n const scripts = attachScripts(node, frac);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: frac };\n }\n\n if (\n (node.name === '\\\\sqrt' || node.name === '\\\\arabsqrt' || node.name === '\\\\arsqrt') &&\n node.mandatoryArgs.length >= 1\n ) {\n const sqrt = createSqrtNode();\n const radicand = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!radicand.editable) {\n return radicand;\n }\n sqrt.radicand = radicand.chain;\n if (node.optionalArgs[0]) {\n const rootIndex = chainToEditorChain(node.optionalArgs[0]);\n if (!rootIndex.editable) {\n return rootIndex;\n }\n sqrt.rootIndex = rootIndex.chain;\n }\n const scripts = attachScripts(node, sqrt);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: sqrt };\n }\n\n if (node.name === '\\\\boxed' && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 1) {\n const boxed = createBoxedNode();\n const inner = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!inner.editable) {\n return inner;\n }\n boxed.innerExpr = inner.chain;\n const scripts = attachScripts(node, boxed);\n return scripts ?? { editable: true, node: boxed };\n }\n\n if (node.name === '\\\\overset' && node.mandatoryArgs.length >= 2) {\n const overset = createOversetNode();\n const overExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!overExpr.editable) {\n return overExpr;\n }\n if (!baseExpr.editable) {\n return baseExpr;\n }\n overset.overExpr = overExpr.chain;\n overset.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, overset);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: overset };\n }\n\n if (node.name === '\\\\underset' && node.mandatoryArgs.length >= 2) {\n const underset = createUndersetNode();\n const underExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!underExpr.editable) {\n return underExpr;\n }\n if (!baseExpr.editable) {\n return baseExpr;\n }\n underset.underExpr = underExpr.chain;\n underset.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, underset);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: underset };\n }\n\n const accentId = accentCommandIdFromTex(node.name);\n if (accentId && node.mandatoryArgs.length >= 1) {\n const accent = createAccentNode(accentId);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!baseExpr.editable) {\n return baseExpr;\n }\n accent.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, accent);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: accent };\n }\n\n const wrappedAtomicId = wrappedAtomicCommandId(node);\n if (wrappedAtomicId) {\n const atomic = createEditorNode('atomicCommand', wrappedAtomicId);\n const scripts = attachScripts(node, atomic);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomic };\n }\n\n const wrapper = editableWrapperCommand(node);\n if (wrapper) {\n return wrapper;\n }\n\n const atomicId = commandIdForTex(node.name);\n if (atomicId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const atomic = createEditorNode('atomicCommand', atomicId);\n const scripts = attachScripts(node, atomic);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomic };\n }\n\n const operatorId = operatorCommandIdForTex(node.name);\n if (operatorId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const atomicOperator = createEditorNode('atomicOperatorCommand', operatorId);\n if (node.name === '\\\\le' || node.name === '\\\\ge') atomicOperator.sourceLatex = node.name;\n const scripts = attachScripts(node, atomicOperator);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomicOperator };\n }\n\n if (isStandardCommandTex(node.name) && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const standard = createEditorNode('standardCommand', node.name);\n const scripts = attachScripts(node, standard);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: standard };\n }\n\n const textLike = charFromTextLikeCommand(node);\n if (textLike) {\n return textLike;\n }\n\n return { editable: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.name}` };\n}\n\nfunction astNodeToEditorNode(node: ChainNode['chain'][number]): NodeAdapterResult {\n if (node instanceof CharNode) {\n const normalized = normalizeCharImportExpr(node.expr);\n const editorNode = createEditorNode('char', normalized.expr);\n if (normalized.characterFont !== 'default') {\n editorNode.characterFont = normalized.characterFont;\n }\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof NumberNode) {\n const editorNode = createEditorNode('number', node.expr);\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof OperatorNode) {\n return { editable: true, node: createEditorNode('operator', node.expr) };\n }\n if (node instanceof DelimiterNode) {\n const editorNode = createDelimiterNode(node.leftDelimExpr, node.rightDelimExpr);\n const inner = chainToEditorChain(node.innerExpr);\n if (!inner.editable) {\n return inner;\n }\n editorNode.innerExpr = inner.chain;\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof CommandNode) {\n return commandToEditorNode(node);\n }\n if (node instanceof EnvNode) {\n return envToEditorNode(node);\n }\n return { editable: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.nodeType}` };\n}\n\nconst VERTICAL_DELIMITER_COMMAND_PAIRS: Readonly<Record<string, string>> = {\n '\\\\vert': '\\\\vert',\n '\\\\lvert': '\\\\rvert',\n '\\\\Vert': '\\\\Vert',\n '\\\\lVert': '\\\\rVert',\n '\\\\|': '\\\\|',\n};\n\nfunction isBareCommand(node: BaseAstNode, name: string): node is CommandNode {\n return node instanceof CommandNode &&\n node.name === name &&\n node.optionalArgs.length === 0 &&\n node.mandatoryArgs.length === 0;\n}\n\nfunction normalizeVerticalDelimiterCommands(chain: ChainNode): ChainNode {\n const normalized: BaseAstNode[] = [];\n\n for (let index = 0; index < chain.chain.length; index += 1) {\n const left = chain.chain[index]!;\n if (!(left instanceof CommandNode) || left.superscript || left.subscript) {\n normalized.push(left);\n continue;\n }\n\n const rightName = VERTICAL_DELIMITER_COMMAND_PAIRS[left.name];\n if (!rightName || left.optionalArgs.length > 0 || left.mandatoryArgs.length > 0) {\n normalized.push(left);\n continue;\n }\n\n let rightIndex = -1;\n for (let candidate = index + 1; candidate < chain.chain.length; candidate += 1) {\n if (isBareCommand(chain.chain[candidate]!, rightName)) {\n rightIndex = candidate;\n break;\n }\n }\n\n if (rightIndex < 0) {\n normalized.push(left);\n continue;\n }\n\n const right = chain.chain[rightIndex]! as CommandNode;\n const delimiter = new DelimiterNode(\n left.name,\n new ChainNode(chain.chain.slice(index + 1, rightIndex)),\n right.name,\n );\n delimiter.superscript = right.superscript;\n delimiter.subscript = right.subscript;\n normalized.push(delimiter);\n index = rightIndex;\n }\n\n return new ChainNode(normalized);\n}\n\nfunction chainToEditorChain(chain: ChainNode, script = false): ChainAdapterResult {\n // Only a complete script wrapper is semantic; ordinary \\mathnormal font use\n // elsewhere is not silently reinterpreted as ordered indices.\n if (script && chain.chain.length === 1) {\n const wrapper = chain.chain[0]!;\n if (wrapper instanceof CommandNode && wrapper.name === '\\\\mathnormal') {\n if (wrapper.optionalArgs.length || wrapper.mandatoryArgs.length !== 1) {\n return { editable: false, reason: 'صيغة مجموعة الفهارس غير مدعومة' };\n }\n const imported = chainToEditorChain(wrapper.mandatoryArgs[0]!);\n if (!imported.editable) return imported;\n // Be compatible with older Burhan versions that stored \"23\" as one NumberObject.\n const atoms: EditorNode[] = [];\n for (const node of imported.chain.nodes) {\n if (node.kind === 'number' && /^[0-9]{2,}$/.test(node.expr)) {\n atoms.push(...node.expr.split('').map((digit) => createEditorNode('number', digit)));\n } else if (node.kind === 'char' && !node.sourceLatex && /^[A-Za-z]{2,}$/.test(node.expr)) {\n atoms.push(...node.expr.split('').map((letter) => createEditorNode('char', letter)));\n } else {\n atoms.push(node);\n }\n }\n imported.chain.nodes = atoms;\n if (!isValidIndexSequence(imported.chain)) {\n return { editable: false, reason: 'محتوى مجموعة الفهارس غير مدعوم' };\n }\n imported.chain.indexSequence = true;\n return imported;\n }\n }\n const nodes: EditorNode[] = [];\n for (const astNode of normalizeVerticalDelimiterCommands(chain).chain) {\n const converted = astNodeToEditorNode(astNode);\n if (!converted.editable) {\n return converted;\n }\n nodes.push(converted.node);\n }\n return { editable: true, chain: createEditorChain(nodes) };\n}\n\nexport function mathObjectToEditorSession(math: MathNode): MathEditorAdapterResult {\n if (math.lines.length !== 1) {\n return { editable: false, reason: 'تحرير المعادلات متعددة الأسطر داخل المستند غير مدعوم بعد' };\n }\n\n const english = chainToEditorChain(math.lines[0]!);\n if (!english.editable) {\n return english;\n }\n\n const arabic = cloneChainWithFreshIds(english.chain);\n const session = createEditorSession(english.chain, arabic, 'english');\n session.sync = buildInitialSyncMap(session.englishTree, session.arabicTree);\n return { editable: true, session: cloneEditorSession(session) };\n}\n\ntype AstNodeResult =\n | { ok: true; node: BaseAstNode }\n | { ok: false; reason: string };\n\ntype AstChainResult =\n | { ok: true; chain: ChainNode }\n | { ok: false; reason: string };\n\nfunction attachAstScripts(editorNode: EditorNode, astNode: BaseAstNode): AstNodeResult | null {\n if (editorNode.superscript) {\n const sup = editorChainToAstChain(editorNode.superscript);\n if (!sup.ok) {\n return sup;\n }\n astNode.superscript = sup.chain;\n }\n if (editorNode.subscript) {\n const sub = editorChainToAstChain(editorNode.subscript);\n if (!sub.ok) {\n return sub;\n }\n astNode.subscript = sub.chain;\n }\n return null;\n}\n\nfunction editorEnvOpening(node: EditorNode): { opening: string; closing: string } | null {\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return null;\n }\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows?.[0]?.length ?? 0).join('') || 'c';\n return { opening: `\\\\begin{array}{${spec}}`, closing: '\\\\end{array}' };\n }\n return { opening: `\\\\begin{${envName}}`, closing: `\\\\end{${envName}}` };\n}\n\nfunction editorEnvToAstNode(node: EditorNode): AstNodeResult {\n const wrapper = editorEnvOpening(node);\n if (!wrapper || !node.matrixRows) {\n return { ok: false, reason: 'بيئة رياضية غير مدعومة حاليا' };\n }\n const lines: ChainNode[] = [];\n for (const row of node.matrixRows) {\n const lineNodes: BaseAstNode[] = [];\n for (let columnIndex = 0; columnIndex < row.length; columnIndex += 1) {\n if (columnIndex > 0) {\n lineNodes.push(new OperatorNode('&'));\n }\n const cell = editorChainToAstChain(row[columnIndex]!);\n if (!cell.ok) {\n return cell;\n }\n lineNodes.push(...cell.chain.chain);\n }\n lines.push(new ChainNode(lineNodes));\n }\n const env = new EnvNode(wrapper.opening, lines, wrapper.closing);\n const scripts = attachAstScripts(node, env);\n return scripts ?? { ok: true, node: env };\n}\n\nfunction accentChainForExport(accent: EditorChain | null): AstChainResult {\n if (!accent) {\n return { ok: true, chain: new ChainNode([]) };\n }\n return editorChainToAstChain(accent);\n}\n\nfunction nodeFromAccentBase(\n command: '\\\\overset' | '\\\\underset',\n accent: ChainNode,\n base: ChainNode,\n): BaseAstNode {\n if (accent.chain.length > 0) {\n return new CommandNode(command, [], [accent, base]);\n }\n if (base.chain.length === 1) {\n return base.chain[0]!;\n }\n return new DelimiterNode('', base, '');\n}\n\nfunction editorNodeToAstNode(node: EditorNode): AstNodeResult {\n let astNode: BaseAstNode;\n\n if (node.kind === 'char') {\n astNode = charEditorNodeToAstNode(node);\n } else if (node.kind === 'number') {\n astNode = new NumberNode(node.expr);\n } else if (node.kind === 'operator') {\n astNode = new OperatorNode(node.expr);\n } else if (node.kind === 'delimiter' && node.innerExpr) {\n const inner = editorChainToAstChain(node.innerExpr);\n if (!inner.ok) {\n return inner;\n }\n astNode = new DelimiterNode(node.leftDelimExpr, inner.chain, node.rightDelimExpr);\n } else if (node.kind === 'boxed' && node.innerExpr) {\n const inner = editorChainToAstChain(node.innerExpr);\n if (!inner.ok) {\n return inner;\n }\n astNode = new CommandNode('\\\\boxed', [], [inner.chain]);\n } else if (node.kind === 'frac' && node.numerator && node.denominator) {\n const numerator = editorChainToAstChain(node.numerator);\n const denominator = editorChainToAstChain(node.denominator);\n if (!numerator.ok) {\n return numerator;\n }\n if (!denominator.ok) {\n return denominator;\n }\n astNode = new CommandNode('\\\\frac', [], [numerator.chain, denominator.chain]);\n } else if (node.kind === 'sqrt' && node.radicand) {\n const radicand = editorChainToAstChain(node.radicand);\n if (!radicand.ok) {\n return radicand;\n }\n const optionalArgs: ChainNode[] = [];\n if (node.rootIndex && node.rootIndex.nodes.length > 0) {\n const rootIndex = editorChainToAstChain(node.rootIndex);\n if (!rootIndex.ok) {\n return rootIndex;\n }\n optionalArgs.push(rootIndex.chain);\n }\n astNode = new CommandNode('\\\\sqrt', optionalArgs, [radicand.chain]);\n } else if (node.kind === 'overset' && node.baseExpr) {\n const accent = accentChainForExport(node.overExpr);\n if (!accent.ok) {\n return accent;\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = nodeFromAccentBase('\\\\overset', accent.chain, baseExpr.chain);\n } else if (node.kind === 'underset' && node.baseExpr) {\n const accent = accentChainForExport(node.underExpr);\n if (!accent.ok) {\n return accent;\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = nodeFromAccentBase('\\\\underset', accent.chain, baseExpr.chain);\n } else if (node.kind === 'accent' && node.baseExpr) {\n const tex = accentCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `لكنة رياضية غير مدعومة حاليا: ${node.expr}` };\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = new CommandNode(tex, [], [baseExpr.chain]);\n } else if (node.kind === 'atomicCommand') {\n const tex = atomicCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n if (node.expr === 'ad') {\n astNode = new CommandNode('\\\\mathrm', [], [new ChainNode([new CharNode('d')])]);\n } else if (['N', 'Z', 'Q', 'R', 'C', 'H'].includes(node.expr)) {\n astNode = new CommandNode('\\\\mathbb', [], [new ChainNode([new CharNode(node.expr)])]);\n } else {\n astNode = new CommandNode(tex);\n }\n } else if (node.kind === 'atomicOperatorCommand') {\n const tex = atomicOperatorCommandSpec(node.expr)?.Tex;\n if (!tex) {\n return { ok: false, reason: `رمز رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(node.sourceLatex === '\\\\le' || node.sourceLatex === '\\\\ge' ? node.sourceLatex : tex);\n } else if (node.kind === 'standardCommand') {\n if (!isStandardCommandTex(node.expr)) {\n return { ok: false, reason: `أمر رياضي قياسي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(node.expr);\n } else if (node.kind === 'env') {\n return editorEnvToAstNode(node);\n } else {\n return { ok: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.kind}` };\n }\n\n if (node.sourceLatex && !hasBareBoldCharSource(node)) {\n astNode.sourceLatex = node.sourceLatex;\n }\n const scripts = attachAstScripts(node, astNode);\n return scripts ?? { ok: true, node: astNode };\n}\n\nfunction editorChainToAstChain(chain: EditorChain): AstChainResult {\n const nodes: BaseAstNode[] = [];\n for (const editorNode of chain.nodes) {\n const converted = editorNodeToAstNode(editorNode);\n if (!converted.ok) {\n return converted;\n }\n nodes.push(converted.node);\n }\n const content = new ChainNode(nodes);\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n return { ok: true, chain: new ChainNode([new CommandNode('\\\\mathnormal', [], [content])]) };\n }\n return { ok: true, chain: content };\n}\n\nexport function mathNodeFromEditorSession(\n session: EditorSession,\n mathMode = '$',\n closing = '$',\n): MathNodeFromEditorResult {\n const converted = editorChainToAstChain(session.englishTree);\n if (!converted.ok) {\n return converted;\n }\n return {\n ok: true,\n math: {\n nodeType: 'MathObject',\n mathMode,\n lines: [converted.chain],\n closing,\n },\n };\n}\n\nexport function mathSourceFromEditorSession(\n session: EditorSession,\n mathMode = '$',\n closing = '$',\n): string {\n const inner = renderArabicLatexFromSession(session);\n if (mathMode === '$' || mathMode === '\\\\(') {\n return mathMode + inner + closing;\n }\n if (mathMode === '$$' || mathMode === '\\\\[') {\n if (!inner.includes('\\n')) {\n return `${mathMode}\\n${inner}\\n${closing}`;\n }\n return `${mathMode}\\n${inner.split('\\n').map((line) => ` ${line}`).join(' \\\\\\\\\\n')}\\n${closing}`;\n }\n return `${mathMode}\\n ${inner}\\n${closing}`;\n}\n\nexport function mathSourceWithReplacement(source: string, replacementInnerLatex: string): string {\n if (source.startsWith('$$') && source.endsWith('$$')) {\n return `$$${replacementInnerLatex}$$`;\n }\n if (source.startsWith('$') && source.endsWith('$')) {\n return `$${replacementInnerLatex}$`;\n }\n if (source.startsWith('\\\\(') && source.endsWith('\\\\)')) {\n return `\\\\(${replacementInnerLatex}\\\\)`;\n }\n if (source.startsWith('\\\\[') && source.endsWith('\\\\]')) {\n return `\\\\[${replacementInnerLatex}\\\\]`;\n }\n const begin = /^\\\\begin\\{([A-Za-z*]+)\\}/.exec(source);\n if (begin) {\n const opening = begin[0] ?? '';\n const closing = `\\\\end{${begin[1] ?? ''}}`;\n if (source.endsWith(closing)) {\n return `${opening}${replacementInnerLatex}${closing}`;\n }\n }\n return replacementInnerLatex;\n}\n","import { mathNodeFromEditorSession, mathObjectToEditorSession } from '../shared/math-document/mathEditorAdapter.js';\nimport type { MathNode } from '../shared/math-document/types.js';\nimport {\n buildInitialSyncMap,\n createEditorChain,\n createEditorSession,\n renderArabicLatexFromSession,\n renderArabicPreviewLatexFromSession,\n renderEnglishLatexFromSession,\n setCurrentDigitForm,\n type DigitFormId,\n type EditorSide,\n type EditorSession,\n} from '../editor/index.js';\nimport type { MathToken2 } from './types.js';\n\nexport type DocumentMathBridgeResult =\n | { editable: true; session: EditorSession }\n | { editable: false; reason: string };\n\nexport function createEmptyEquationSession(side: EditorSide = 'arabic'): EditorSession {\n const english = createEditorChain();\n const arabic = createEditorChain();\n arabic.id = english.id;\n const session = createEditorSession(english, arabic, side);\n session.sync = buildInitialSyncMap(session.englishTree, session.arabicTree);\n return session;\n}\n\nexport function createEmptyArabicEquationSession(): EditorSession {\n return createEmptyEquationSession('arabic');\n}\n\nexport function mathTokenToEditorSession(math: MathNode | null, side: EditorSide = 'arabic'): DocumentMathBridgeResult {\n if (!math) {\n return { editable: false, reason: 'هذه المعادلة محفوظة كنص خام فقط حاليا' };\n }\n const result = mathObjectToEditorSession(math);\n if (!result.editable) {\n return result;\n }\n result.session.activeSide = side;\n result.session.sync = buildInitialSyncMap(result.session.englishTree, result.session.arabicTree);\n return result;\n}\n\nexport function mathTokenToArabicEditorSession(math: MathNode | null): DocumentMathBridgeResult {\n return mathTokenToEditorSession(math, 'arabic');\n}\n\nexport function mathSourceFromSession(\n session: EditorSession,\n side: EditorSide,\n opening = '$',\n closing = '$',\n presentation = false,\n): string {\n const inner = side === 'english'\n ? renderEnglishLatexFromSession(session)\n : presentation ? renderArabicPreviewLatexFromSession(session) : renderArabicLatexFromSession(session);\n if (opening === '$' || opening === '\\\\(') {\n return opening + inner + closing;\n }\n if (opening === '$$' || opening === '\\\\[') {\n return `${opening}\\n${inner}\\n${closing}`;\n }\n return `${opening}\\n ${inner}\\n${closing}`;\n}\n\nexport function mathSourceFromArabicSession(session: EditorSession, opening = '$', closing = '$'): string {\n return mathSourceFromSession(session, 'arabic', opening, closing);\n}\n\nexport function mathNodeFromSession(session: EditorSession, opening = '$', closing = '$'): MathNode {\n const converted = mathNodeFromEditorSession(session, opening, closing);\n if (converted.ok) {\n return converted.math;\n }\n return { nodeType: 'MathObject', mathMode: opening, lines: [], closing };\n}\n\nexport function mathNodeFromArabicSession(session: EditorSession, opening = '$', closing = '$'): MathNode {\n return mathNodeFromSession(session, opening, closing);\n}\n\nexport function mathTokenSourceForSide(token: MathToken2, side: EditorSide, digitForm?: DigitFormId, presentation = false): string {\n if (!token.math || token.sourceOwner === 'raw') {\n return token.source;\n }\n if (!presentation && token.sourceSide === side && digitForm === undefined) {\n return token.source;\n }\n const result = mathTokenToEditorSession(token.math, side);\n if (!result.editable) {\n return token.source;\n }\n const session = digitForm === undefined\n ? result.session\n : setCurrentDigitForm(result.session, digitForm);\n return mathSourceFromSession(session, side, token.opening, token.closing, presentation);\n}\n","import type { DocumentLabelEntry } from './labels.js';\nimport type { Reference2 } from './types.js';\n\nexport type DocumentKeyError = 'empty' | 'invalid' | 'duplicate';\n\nconst DOCUMENT_KEY_PATTERN = /^[\\p{L}\\p{M}\\p{Nd}:._-]+$/u;\n\n/** NFC-normalize and trim a document key (label or bibliography). */\nexport function normalizeDocumentKey(key: string): string {\n return key.normalize('NFC').trim();\n}\n\n/** True when key matches Unicode letters/marks, decimal digits, and :._- with no spaces. */\nexport function isValidDocumentKey(key: string): boolean {\n const normalized = normalizeDocumentKey(key);\n return normalized.length > 0 && DOCUMENT_KEY_PATTERN.test(normalized);\n}\n\nexport type DocumentKeyNamespace = {\n references?: Array<Pick<Reference2, 'id' | 'key'>>;\n labels?: Array<Pick<DocumentLabelEntry, 'ownerId' | 'key'>>;\n /** Skip this reference id when checking (editing that entry). */\n excludeReferenceId?: string;\n /** Skip this label owner id when checking (editing that float/eq). */\n excludeOwnerId?: string;\n};\n\n/** Returns true if another reference or label already uses this key (NFC match). */\nexport function isDuplicateDocumentKey(key: string, namespace: DocumentKeyNamespace): boolean {\n const normalized = normalizeDocumentKey(key);\n if (normalized.length === 0) {\n return false;\n }\n for (const reference of namespace.references ?? []) {\n if (namespace.excludeReferenceId && reference.id === namespace.excludeReferenceId) {\n continue;\n }\n if (normalizeDocumentKey(reference.key) === normalized) {\n return true;\n }\n }\n for (const label of namespace.labels ?? []) {\n if (namespace.excludeOwnerId && label.ownerId === namespace.excludeOwnerId) {\n continue;\n }\n if (normalizeDocumentKey(label.key) === normalized) {\n return true;\n }\n }\n return false;\n}\n\n/** Classify a key for UI messaging: empty, invalid charset, or duplicate. */\nexport function documentKeyError(key: string, namespace: DocumentKeyNamespace = {}): DocumentKeyError | null {\n const normalized = normalizeDocumentKey(key);\n if (normalized.length === 0) {\n return 'empty';\n }\n if (!DOCUMENT_KEY_PATTERN.test(normalized)) {\n return 'invalid';\n }\n if (isDuplicateDocumentKey(normalized, namespace)) {\n return 'duplicate';\n }\n return null;\n}\n","import { diffJson } from 'diff';\nimport { fromDocumentJson } from './importJson.js';\nimport { toDocumentJson } from './exportJson.js';\nimport type { DocumentJson } from './types.js';\n\nexport type DocumentDiffChunkKind = 'added' | 'removed' | 'context';\n\nexport type DocumentDiffChunk = {\n kind: DocumentDiffChunkKind;\n text: string;\n};\n\nexport type DocumentDiff = {\n version: 1;\n changed: boolean;\n truncated: boolean;\n chunks: DocumentDiffChunk[];\n};\n\ntype JsonDiffPart = {\n value: string;\n added?: boolean;\n removed?: boolean;\n};\n\nconst MAX_TOTAL_TEXT_CHARS = 16_000;\nconst MAX_CHANGED_CHUNK_CHARS = 4_000;\nconst MAX_CONTEXT_CHUNK_CHARS = 600;\nconst TRUNCATION_MARKER = '\\n…\\n';\nconst IDENTITY_KEYS = new Set(['id', 'inline_ids', 'caption_inline_ids', 'cell_inline_ids']);\n\ntype SliceMode = 'head' | 'tail' | 'both';\n\nfunction comparisonValue(value: unknown, key?: string): unknown {\n if (key && IDENTITY_KEYS.has(key)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map((entry) => comparisonValue(entry));\n }\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const childKey of Object.keys(value as Record<string, unknown>).sort()) {\n const child = comparisonValue((value as Record<string, unknown>)[childKey], childKey);\n if (child !== undefined) {\n result[childKey] = child;\n }\n }\n return result;\n }\n return value;\n}\n\nfunction normalizedComparisonDocument(document: DocumentJson): Record<string, unknown> {\n return comparisonValue(toDocumentJson(fromDocumentJson(document))) as Record<string, unknown>;\n}\n\nfunction withoutFinalNewline(value: string): string {\n return value.endsWith('\\n') ? value.slice(0, -1) : value;\n}\n\nfunction shorten(text: string, limit: number, mode: SliceMode): { text: string; truncated: boolean } {\n if (text.length <= limit) {\n return { text, truncated: false };\n }\n if (limit <= TRUNCATION_MARKER.length) {\n return { text: text.slice(0, Math.max(0, limit)), truncated: true };\n }\n const available = limit - TRUNCATION_MARKER.length;\n if (mode === 'head') {\n return { text: `${text.slice(0, available)}${TRUNCATION_MARKER}`, truncated: true };\n }\n if (mode === 'tail') {\n return { text: `${TRUNCATION_MARKER}${text.slice(text.length - available)}`, truncated: true };\n }\n const head = Math.ceil(available / 2);\n const tail = available - head;\n return {\n text: `${text.slice(0, head)}${TRUNCATION_MARKER}${text.slice(text.length - tail)}`,\n truncated: true,\n };\n}\n\n/**\n * Compare two persisted Document documents using canonical Document import/export\n * semantics and jsdiff's maintained JSON diff implementation.\n *\n * Generated editor identity sidecars are intentionally excluded so equivalent\n * legacy documents do not differ merely because normalization assigned new IDs.\n */\nexport function diffDocument(before: DocumentJson, after: DocumentJson): DocumentDiff {\n const beforeComparable = normalizedComparisonDocument(before);\n const afterComparable = normalizedComparisonDocument(after);\n const parts = diffJson(beforeComparable, afterComparable) as JsonDiffPart[];\n const changed = parts.some((part) => part.added === true || part.removed === true);\n\n if (!changed) {\n return { version: 1, changed: false, truncated: false, chunks: [] };\n }\n\n const chunks: DocumentDiffChunk[] = [];\n let truncated = false;\n let totalTextChars = 0;\n\n const append = (kind: DocumentDiffChunkKind, rawText: string, limit: number, mode: SliceMode): void => {\n const cleaned = withoutFinalNewline(rawText);\n if (cleaned.length === 0) return;\n\n const perChunk = shorten(cleaned, limit, mode);\n truncated ||= perChunk.truncated;\n const remaining = MAX_TOTAL_TEXT_CHARS - totalTextChars;\n if (remaining <= 0) {\n truncated = true;\n return;\n }\n\n const withinBudget = shorten(perChunk.text, remaining, mode);\n truncated ||= withinBudget.truncated;\n if (withinBudget.text.length === 0) return;\n chunks.push({ kind, text: withinBudget.text });\n totalTextChars += withinBudget.text.length;\n };\n\n parts.forEach((part, index) => {\n if (part.added) {\n append('added', part.value, MAX_CHANGED_CHUNK_CHARS, 'both');\n return;\n }\n if (part.removed) {\n append('removed', part.value, MAX_CHANGED_CHUNK_CHARS, 'both');\n return;\n }\n\n const previousChanged = index > 0 && (parts[index - 1]?.added === true || parts[index - 1]?.removed === true);\n const nextChanged = index + 1 < parts.length && (parts[index + 1]?.added === true || parts[index + 1]?.removed === true);\n if (!previousChanged && !nextChanged) return;\n\n const mode: SliceMode = previousChanged && nextChanged ? 'both' : previousChanged ? 'head' : 'tail';\n append('context', part.value, MAX_CONTEXT_CHUNK_CHARS, mode);\n });\n\n return { version: 1, changed: true, truncated, chunks };\n}\n","import { collectDocumentLabels, collectDocumentReferenceTargets, labelNumberMap, type DocumentLabelKind } from './labels.js';\nimport type {\n DocumentBlock,\n DocumentNode,\n InlineField2,\n Reference2Json,\n} from './types.js';\n\nexport type DocumentCitationIndexEntry = {\n kind: 'cite';\n block_id: string;\n field_id: string;\n token_id: string;\n keys: string[];\n unresolved_keys: string[];\n};\n\nexport type DocumentCrossReferenceIndexEntry = {\n kind: 'ref';\n ref_command: 'ref' | 'eqref';\n block_id: string;\n field_id: string;\n token_id: string;\n keys: string[];\n unresolved_keys: string[];\n};\n\nexport type DocumentIndexedLabel = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n number: number;\n block_id?: string;\n field_id?: string;\n token_id?: string;\n};\n\nexport type DocumentReferenceIndex = {\n citations: DocumentCitationIndexEntry[];\n cross_references: DocumentCrossReferenceIndexEntry[];\n labels: DocumentIndexedLabel[];\n reference_targets: Array<Omit<DocumentIndexedLabel, 'number'> & { number: number | null; manual_key?: string }>;\n unresolved: {\n citation_keys: string[];\n cross_reference_keys: string[];\n };\n};\n\ntype TokenLocation = {\n block_id: string;\n field_id: string;\n};\n\nfunction appendUnique(target: string[], seen: Set<string>, values: string[]): void {\n for (const value of values) {\n if (!seen.has(value)) {\n seen.add(value);\n target.push(value);\n }\n }\n}\n\n/** Return a detached, read-only view of the registered bibliography catalog. */\nexport function getDocumentReferences(document: DocumentNode): Reference2Json[] {\n return document.references.map((reference) => ({\n key: reference.key,\n authors: reference.authors,\n title: reference.title,\n year: reference.year,\n venue: reference.venue,\n url: reference.url,\n field_separator: reference.fieldSeparator,\n }));\n}\n\n/**\n * Return semantic citation, cross-reference, and label relationships without\n * changing the document. Entries follow document/token order and preserve the\n * stable IDs already present in the live Document node.\n */\nexport function getDocumentReferenceIndex(document: DocumentNode): DocumentReferenceIndex {\n const referenceKeys = new Set(document.references.map((reference) => reference.key));\n const labelEntries = collectDocumentLabels(document);\n const labelKeys = new Set(labelNumberMap(document).keys());\n const citations: DocumentCitationIndexEntry[] = [];\n const crossReferences: DocumentCrossReferenceIndexEntry[] = [];\n const tokenLocations = new Map<string, TokenLocation>();\n const unresolvedCitationKeys: string[] = [];\n const unresolvedCrossReferenceKeys: string[] = [];\n const seenCitationKeys = new Set<string>();\n const seenCrossReferenceKeys = new Set<string>();\n\n function visitField(blockId: string, field: InlineField2): void {\n for (const token of field.tokens) {\n tokenLocations.set(token.id, { block_id: blockId, field_id: field.id });\n if (token.kind === 'cite') {\n const unresolvedKeys = token.keys.filter((key) => !referenceKeys.has(key));\n citations.push({\n kind: 'cite',\n block_id: blockId,\n field_id: field.id,\n token_id: token.id,\n keys: [...token.keys],\n unresolved_keys: unresolvedKeys,\n });\n appendUnique(unresolvedCitationKeys, seenCitationKeys, unresolvedKeys);\n } else if (token.kind === 'ref') {\n const unresolvedKeys = token.keys.filter((key) => !labelKeys.has(key));\n crossReferences.push({\n kind: 'ref',\n ref_command: token.refCommand,\n block_id: blockId,\n field_id: field.id,\n token_id: token.id,\n keys: [...token.keys],\n unresolved_keys: unresolvedKeys,\n });\n appendUnique(unresolvedCrossReferenceKeys, seenCrossReferenceKeys, unresolvedKeys);\n }\n }\n }\n\n function visitBlocks(blocks: DocumentBlock[]): void {\n for (const block of blocks) {\n if (block.kind === 'textBlock') {\n visitField(block.id, block.field);\n } else if (block.kind === 'table') {\n visitField(block.id, block.captionField);\n for (const row of block.rows) {\n for (const cell of row) {\n visitField(block.id, cell);\n }\n }\n } else if (block.kind === 'image') {\n visitField(block.id, block.captionField);\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n visitField(block.id, item.field);\n visitBlocks(item.blocks);\n }\n }\n }\n }\n\n visitBlocks(document.blocks);\n\n const labels: DocumentIndexedLabel[] = labelEntries.map((entry) => {\n if (entry.kind !== 'eq') {\n return {\n key: entry.key,\n kind: entry.kind,\n caption: entry.caption,\n number: entry.number,\n block_id: entry.ownerId,\n };\n }\n const location = tokenLocations.get(entry.ownerId);\n return {\n key: entry.key,\n kind: entry.kind,\n caption: entry.caption,\n number: entry.number,\n ...(location ? { block_id: location.block_id, field_id: location.field_id } : {}),\n token_id: entry.ownerId,\n };\n });\n\n return {\n citations,\n cross_references: crossReferences,\n labels,\n reference_targets: collectDocumentReferenceTargets(document).map((target) => ({\n key: target.key,\n kind: target.kind,\n caption: target.caption,\n number: target.number,\n ...(target.kind === 'eq' ? { token_id: target.ownerId } : { block_id: target.ownerId }),\n ...(target.manualKey ? { manual_key: target.manualKey } : {}),\n })),\n unresolved: {\n citation_keys: unresolvedCitationKeys,\n cross_reference_keys: unresolvedCrossReferenceKeys,\n },\n };\n}\n","/** Arabic XeLaTeX preamble fragments for full-document export. */\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../editor/characterFonts.js';\n\nexport type ArabicDigitsMapping = 'arabicdigits' | 'farsidigits' | 'digits';\n\nexport type ArabicXeLatexPreambleOptions = {\n digitsMapping?: ArabicDigitsMapping;\n /** When true, add the article class twocolumn option. Default false. */\n twocolumn?: boolean;\n};\n\nfunction fontOptions(digitsMapping: ArabicDigitsMapping, includeScript = true): string {\n const parts: string[] = [];\n if (includeScript) {\n parts.push('Script=Arabic');\n }\n if (digitsMapping !== 'digits') {\n parts.push(`Mapping=${digitsMapping}`);\n }\n if (parts.length === 0) {\n return '';\n }\n return `[${parts.join(',')}]`;\n}\n\nexport function arabicXeLatexPreamblePkg(twocolumn = false): string {\n const classOptions = twocolumn\n ? '12pt,a4paper,notitlepage,twocolumn'\n : '12pt,a4paper,notitlepage';\n return (\n `\n\\\\documentclass[${classOptions}]{article}\n` +\n String.raw`\\usepackage{amsmath,amsfonts,amssymb,mathrsfs,tikz,fancyhdr, mathtools}\n\\usepackage{fontspec} % For loading OpenType fonts\n\\usepackage{unicode-math} % For setting the math font\n\\usepackage{polyglossia} % For Arabic support\n\\usepackage{array}\n\\usepackage{cancel}\n\\usepackage{bidi}\n\\usepackage{multirow}\n\\usepackage{booktabs}\n\\usepackage{graphicx} % For \\reflectbox\n\\usepackage{xcolor}\n\\usepackage{tikz}\n\\usepackage{tcolorbox} % For tcolorbox environment\n\\usepackage{textcomp} % For \\textrightarrow command\n\\usepackage{url}\n\n\n% visit : https://www.symbolcopy.com/punctuation-symbol.html\n% for inversed punctuation\n\n% save inverted comma for use - copy paste -> ،\n% save back tick for use - copy paste -> ` + '`'\n );\n}\n\nexport function arabicXeLatexPreambleFont(digitsMapping: ArabicDigitsMapping = 'arabicdigits'): string {\n const customFonts = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.latexFontCommand && font.latexFontFamily)\n .map((font) => `\\\\newfontfamily${font.latexFontCommand}${fontOptions(digitsMapping)}{${font.latexFontFamily}}`)\n .join('\\n');\n const mathFontOptions = fontOptions(digitsMapping, false);\n return `\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Persian digits: Mapping=farsidigits\n% Arabic-Indic digits: Mapping=arabicdigits\n% Western digits: omit Mapping entirely\n\\\\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia\n\\\\setmainfont${fontOptions(digitsMapping)}{Amiri}\n${customFonts}\n\\\\newfontfamily\\\\boldarabic${fontOptions(digitsMapping)}{Amiri Bold}\n\\\\newfontfamily\\\\italicarabic${fontOptions(digitsMapping)}{Amiri Italic}\n\n% for polyglossia url I dont know, sugggested by cursor\n\\\\newfontfamily\\\\arabicfonttt${fontOptions(digitsMapping)}{Amiri}\n\\\\newfontfamily\\\\arabicfontsf${fontOptions(digitsMapping)}{Amiri}\n\n\n% Explicitly set math font to XITS Math\n\\\\setmathfont${mathFontOptions}{XITS Math} % Ensure XITS Math is correctly installed and available\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n`;\n}\n\nexport function arabicXeLatexPreambleCmd(): string {\n const fontCommands = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.macro && font.latexFontCommand)\n .map((font) => `\\\\newcommand{${font.macro}}[1]{\\\\text{${font.latexFontCommand}{#1}}}`)\n .join('\\n');\n return String.raw`\n% Run with XeLaTeX compiler\n${fontCommands}\n\\newcommand{\\butexmirror}[1]{\\reflectbox{\\(#1\\)}}\n\n\\newcommand{\\arabN}{\\text{\\diwanioutlineshaded{ط}}}\n\\newcommand{\\arabZ}{\\text{\\diwanioutlineshaded{ص}}}\n\\newcommand{\\arabQ}{\\text{\\diwanioutlineshaded{ن}}}\n\\newcommand{\\arabR}{\\text{\\diwanioutlineshaded{ح}}}\n\\newcommand{\\arabC}{\\text{\\diwanioutlineshaded{ع}}}\n\\newcommand{\\arabH}{\\text{\\diwanioutlineshaded{ر}}}\n\n\n\\newcommand{\\lowerscript}[1]{\\raisebox{-4pt}{\\scriptsize #1}}\n\\newcommand{\\llowerscript}[1]{\\raisebox{-8pt}{\\scriptsize #1}}\n\\newcommand{\\lllowerscript}[2]{\\raisebox{#2pt}{\\scriptsize #1}}\n\n\\newcommand{\\arabdsub}[3]{\\prescript{}{#1}{\\prescript{}{#2}{#3}}} % arabic double subscript\n\\newcommand{\\arabsub}[2]{\\prescript{}{#1}{#2}} % arabic single subscript\n\n\n\n\\newcommand{\\upperscript}[1]{\\raisebox{8pt}{\\scriptsize #1}}\n\\newcommand{\\uupperscript}[2]{\\raisebox{#2pt}{\\scriptsize #1}}\n\\newcommand{\\vertbar}{\\rule[-1ex]{0.5pt}{2.5ex}}\n\\newcommand{\\horzbar}{\\rule[.5ex]{2.5ex}{0.5pt}}\n\n\n\\newcommand{\\arsqrt}[2][]{\\reflectbox{\\(\\sqrt[\\reflectbox{\\(#1\\)}]{\\reflectbox{\\(#2\\)}}\\)}}\n\\newcommand{\\arabsqrt}[2][]{\\arsqrt[#1]{#2}}\n\\newcommand{\\arabvec}[1]{\\reflectbox{$\\vec{\\reflectbox{$#1$}}$}}\n\n\\newcommand{\\arabexp}[1]{{}^{#1}\\!\\raisebox{-4.5pt}{\\text{\\diwani{ه}}}}\n\\newcommand{\\arablog}[2]{\\left(\\text{#2}\\right)\\!\\prescript{}{\\text{#1}}{\\text{\\diwani{لو}}}}\n\\newcommand{\\arabnlog}[1]{\\left(\\text{#1}\\right)\\!\\prescript{}{\\text{\\diwani{ه}}}{\\text{\\diwani{لو}}}}\n\n\\newcommand{\\arabcos}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جتا}}}}\n\\newcommand{\\arabsin}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جا}}}}\n\\newcommand{\\arabtan}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظا}}}}\n\\newcommand{\\arabcot}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظتا}}}}\n\\newcommand{\\arabsec}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قا}}}}\n\\newcommand{\\arabcsc}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قتا}}}}\n\n\\newcommand{\\arabacos}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجتا}}}}\n\\newcommand{\\arabasin}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجا}}}}\n\\newcommand{\\arabatan}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظا}}}}\n\\newcommand{\\arabacot}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظتا}}}}\n\\newcommand{\\arabasec}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققا}}}}\n\\newcommand{\\arabacsc}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققتا}}}}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% summation\n\\newcommand{\\arablim}[2]{\\underset{#2 \\leftarrow #1}{\\text{نـــــها}}}\n\\newcommand{\\arabsum}[2]{\\underset{#1}{\\overset{#2}{\\text{مجـــ}}}}\n\\newcommand{\\arabprod}[2]{\\underset{#1}{\\overset{#2}{\\text{جـــذ}}}}\n\\newcommand{\\arabint}[2]{\\prescript{#2}{#1\\!\\!\\!}\\int}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% we define this command to make it ease for change of notation later\n\\newcommand{\\ad}[0]{\\text{ء}} % \"ad\" for arabic differentiation or derivative (ء\" لإشتقاق\")\n\\newcommand{\\arpi}[0]{\\!\\text{\\diwani{ط}}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% differentials\n\n\\newcommand{\\arabdiff}[2]{\\frac{#1\\ad}{#2\\ad}} % arabic differential\n\\newcommand{\\arabddiff}[2]{\\frac{#1{}^{2}\\ad}{{}^{2}#2\\ad}} % arabic second differential\n\n\\newcommand{\\arabode}[2][-5pt]{\\stackrel{\\raisebox{#1}{$\\cdot$}}{\\text{#2}}}\n\\newcommand{\\arabodde}[2][-5pt]{\\stackrel{\\raisebox{#1}{$\\vcenter{\\hbox{$\\cdot\\!\\cdot$}}$}}{\\text{#2}}}\n\\newcommand{\\araboddde}[2][-5pt]{\\stackrel{\\raisebox{#1}{$\\vcenter{\\hbox{$\\cdot\\!\\cdot\\!\\cdot$}}$}}{\\text{#2}}}\n\\newcommand{\\arabpde}[1]{\\prescript{}{#1\\!\\!}{\\nabla}} % arabic partial differential equation (PDE)\n\n\\newcommand{\\arabprime}[0]{\\reflectbox{$\\prime$}\\!} % arabic prime notation\n\\newcommand{\\arabpprime}[0]{\\reflectbox{$\\prime$}\\reflectbox{$\\prime$}\\!} % arabic prime notation\n\\newcommand{\\arabppprime}[0]{\\reflectbox{$\\prime$}\\reflectbox{$\\prime$}\\reflectbox{$\\prime$}\\!} % arabic prime notation\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% probability\n\\newcommand{\\ap}[0]{\\!\\text{\\diwani{حـ}}} % arabic Probability - used a lot so short form\n\\newcommand{\\arabExpct}[0]{\\text{\\diwani{توقـ}}} % arabic Expectation\n\\newcommand{\\arabVar}[0]{\\!\\text{\\diwani{با}}} % arabic Variance\n\\newcommand{\\arabCov}[0]{\\!\\text{\\diwani{ت}}} % arabic Covariance\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% custom commands specific to lesson\n\\newcommand{\\lagrange}[2]{\\left(#2\\right)\\!\\prescript{}{#1}{\\text{\\diwani{لا}}}}\n\\newcommand{\\xii}[0]{\\left(\\prescript{}{\\text{يـ}}{\\text{س}}\\right)\\!}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\newcommand{\\arexp}[0]{\\!\\raisebox{-4.5pt}{\\text{\\diwani{ه}}}}\n\\newcommand{\\arlog}[0]{\\!\\!\\text{\\diwani{لو}}}\n\\newcommand{\\arln}[0]{\\!\\!\\prescript{}{\\text{\\diwani{ه}}}{\\text{\\diwani{لو}}}}\n\\newcommand{\\ardet}[0]{\\!\\!\\text{\\diwani{محدد}}}\n\n\\newcommand{\\arsum}[0]{\\text{مجـــ}}\n\\newcommand{\\arprod}[0]{\\text{جـــذ}}\n\n\\newcommand{\\arlim}[0]{\\text{نـــــها}}\n\\newcommand{\\ararg}[0]{\\text{حج}}\n\\newcommand{\\armax}[0]{\\text{أكبر}}\n\\newcommand{\\armin}[0]{\\text{أصغر}}\n\\newcommand{\\arsup}[0]{\\text{أعلى}}\n\\newcommand{\\arinf}[0]{\\text{أدنى}}\n\n\\newcommand{\\arsin}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جا}}}}\n\\newcommand{\\arcos}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جتا}}}}\n\\newcommand{\\artan}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظا}}}}\n\\newcommand{\\arcot}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظتا}}}}\n\\newcommand{\\arsec}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قا}}}}\n\\newcommand{\\arcsc}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قتا}}}} \n\n\\newcommand{\\arasin}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجا}}}}\n\\newcommand{\\aracos}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجتا}}}}\n\\newcommand{\\aratan}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظا}}}}\n\\newcommand{\\aracot}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظتا}}}}\n\\newcommand{\\arasec}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققا}}}}\n\\newcommand{\\aracsc}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققتا}}}}\n\n\\newcommand{\\arsinh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جزا}}}}\n\\newcommand{\\arcosh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جتزا}}}}\n\\newcommand{\\artanh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظزا}}}}\n\\newcommand{\\arcoth}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظتزا}}}}\n\\newcommand{\\arsech}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قزا}}}}\n\\newcommand{\\arcsch}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قتزا}}}}\n\n\\newcommand{\\arasinh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجزا}}}}\n\\newcommand{\\aracosh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجتزا}}}} \n\\newcommand{\\aratanh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظزا}}}}\n\\newcommand{\\aracoth}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظتزا}}}}\n\\newcommand{\\arasech}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققزا}}}}\n\\newcommand{\\aracsch}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققتزا}}}}\n\n\\newcommand{\\unit}[1]{\\text{#1}}\n\\newcommand{\\idx}[1]{#1}\n\\newcommand{\\arbinom}[2]{\\left(\\begin{array}{c} #1 \\\\ #2 \\end{array} \\right)}\n`;\n}\n\nexport function getArabicXeLatexPreamble(\n digitsMappingOrOptions: ArabicDigitsMapping | ArabicXeLatexPreambleOptions = 'arabicdigits',\n): string {\n const options: ArabicXeLatexPreambleOptions =\n typeof digitsMappingOrOptions === 'string'\n ? { digitsMapping: digitsMappingOrOptions }\n : digitsMappingOrOptions;\n const digitsMapping = options.digitsMapping ?? 'arabicdigits';\n const twocolumn = options.twocolumn === true;\n return (\n arabicXeLatexPreamblePkg(twocolumn) +\n arabicXeLatexPreambleFont(digitsMapping) +\n arabicXeLatexPreambleCmd()\n );\n}\n","import { renderMathNodeLatex } from '../shared/math-document/mathObject.js';\nimport { mathTokenSourceForSide } from './mathBridge.js';\nimport { mirrorBuTeXOperatorsInTex } from '../editor/atomicCommandsOperators.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport {\n getArabicXeLatexPreamble,\n type ArabicDigitsMapping,\n} from './arabicPreamble.js';\nimport {\n BUTEX_CLOSING_HAMDALA,\n butexBasmalaDisplayLatex,\n butexBasmalaTitlingPreamble,\n documentHasAbstract,\n documentHasMaketitle,\n emptyDocumentMeta,\n formatHijriDate,\n} from './articleMeta.js';\nimport { bibliographyEntryLatex, citeTokenLatex } from './citations.js';\nimport {\n implicitReferenceKey,\n implicitHeadingReferenceKey,\n isNumberedEquation,\n labelNumberMap,\n refTokenLatex,\n stripDisplayMathDelimiters,\n type DocumentLabelKind,\n} from './labels.js';\nimport type { DocumentBookContext } from './bookContent.js';\nimport type {\n DocumentBlock,\n DocumentMeta,\n DocumentNode,\n ImageBlock2,\n InlineField2,\n InlineToken2,\n ListBlock2,\n MathToken2,\n TableBlock2,\n TextStyle2,\n TextBlock2,\n} from './types.js';\n\nexport type DocumentLatexOptions = {\n /**\n * When true (default), emit a complete Arabic XeLaTeX file:\n * preamble + \\\\begin{document} + body + \\\\end{document}.\n * Pass false for body-only blocks.\n */\n wrapDocument?: boolean;\n /** Font digit Mapping when wrapping. Default 'arabicdigits'. */\n digitsMapping?: ArabicDigitsMapping;\n /** Document-level digit form for XeLaTeX font Mapping. Ignored when digitsMapping is set. */\n digitForm?: DigitFormId;\n /** When true, use article class option twocolumn. Default false. */\n twocolumn?: boolean;\n};\n\ntype LabelKindMap = ReadonlyMap<string, DocumentLabelKind>;\n\nfunction digitsMappingFromDigitForm(digitForm: DigitFormId | undefined): ArabicDigitsMapping {\n if (digitForm === 'western') {\n return 'digits';\n }\n if (digitForm === 'persianIndic') {\n return 'farsidigits';\n }\n return 'arabicdigits';\n}\n\nfunction editorMathLatexForCompile(token: MathToken2): string {\n // Presentation only: retain the saved canonical cases source for editing/readback.\n const source = token.math && token.sourceSide === 'arabic' && token.source.includes('\\\\begin{cases}')\n ? mathTokenSourceForSide(token, 'arabic', undefined, true)\n : token.source;\n return mirrorBuTeXOperatorsInTex(source, { target: 'compile' });\n}\n\nfunction mathBodyLatex(token: MathToken2): string {\n if (token.sourceOwner === 'editor') {\n return stripDisplayMathDelimiters(editorMathLatexForCompile(token));\n }\n if (!token.math || token.sourceOwner === 'raw') {\n return stripDisplayMathDelimiters(token.source);\n }\n const rendered = renderMathNodeLatex(token.math);\n return stripDisplayMathDelimiters(rendered);\n}\n\nfunction styledTextLatex(text: string, style: TextStyle2 | undefined): string {\n let output = text;\n if (style?.bold) {\n output = `\\\\textbf{${output}}`;\n }\n if (style?.italic) {\n output = `\\\\textit{${output}}`;\n }\n if (style?.underline) {\n output = `\\\\underline{${output}}`;\n }\n return output;\n}\n\nfunction semanticRefPrefix(kind: DocumentLabelKind): string {\n if (kind === 'fig') {\n return 'الشكل';\n }\n if (kind === 'tab') {\n return 'الجدول';\n }\n return 'المعادلة';\n}\n\nfunction semanticRefNames(kind: DocumentLabelKind): string[] {\n if (kind === 'fig') {\n return ['الشكل', 'شكل', 'Figure', 'figure'];\n }\n if (kind === 'tab') {\n return ['الجدول', 'جدول', 'Table', 'table'];\n }\n return ['المعادلة', 'معادلة', 'Equation', 'equation'];\n}\n\nfunction previousTextAlreadyNamesKind(previousToken: InlineToken2 | undefined, kind: DocumentLabelKind): boolean {\n if (previousToken?.kind !== 'text') {\n return false;\n }\n const text = previousToken.text.trimEnd();\n return semanticRefNames(kind).some((name) => text.endsWith(name));\n}\n\nfunction refTokenLatexForDocument(\n token: Extract<InlineToken2, { kind: 'ref' }>,\n labelKinds: LabelKindMap | undefined,\n previousToken: InlineToken2 | undefined,\n): string {\n const reference = refTokenLatex(token.keys, token.refCommand);\n if (!labelKinds || token.keys.length !== 1) {\n return reference;\n }\n const kind = labelKinds.get(token.keys[0]!);\n if (!kind || previousTextAlreadyNamesKind(previousToken, kind)) {\n return reference;\n }\n return `${semanticRefPrefix(kind)}~${reference}`;\n}\n\nfunction tokenLatex(\n token: InlineToken2,\n labelKinds?: LabelKindMap,\n previousToken?: InlineToken2,\n unitId?: string,\n): string {\n if (token.kind === 'text') {\n return styledTextLatex(token.text, token.style);\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n if (token.kind === 'ref') {\n return refTokenLatexForDocument(token, labelKinds, previousToken);\n }\n if (isNumberedEquation(token)) {\n const body = mathBodyLatex(token);\n const autoKey = implicitReferenceKey('eq', token.id, unitId);\n const aliases = [autoKey];\n if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());\n return '\\\\begin{equation}\\n' + body + '\\n' +\n aliases.map((key) => '\\\\label{' + key + '}').join('\\n') + '\\n\\\\end{equation}';\n }\n if (token.display && token.numbered === false && token.opening === '\\\\begin{equation}') {\n return '\\\\[' + mathBodyLatex(token) + '\\\\]';\n }\n if (token.sourceOwner === 'editor') {\n return editorMathLatexForCompile(token);\n }\n if (!token.math || token.sourceOwner === 'raw') {\n return token.source;\n }\n return renderMathNodeLatex(token.math);\n}\n\nfunction inlineFieldLatexWithLabelKinds(field: InlineField2, labelKinds?: LabelKindMap, unitId?: string): string {\n return field.tokens\n .map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId))\n .join('');\n}\n\nexport function inlineFieldLatex(field: InlineField2): string {\n return inlineFieldLatexWithLabelKinds(field);\n}\n\nfunction textBlockLatex(block: TextBlock2, labelKinds: LabelKindMap, unitId?: string): string {\n const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);\n const body = block.command === '\\\\paragraph' ? `\\\\par\\n${content}` : `${block.command}{${content}}`;\n if (block.command !== '\\\\paragraph') {\n const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1) as 'section' | 'subsection' | 'subsubsection', block.id, unitId)] : [];\n if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());\n return [body, ...keys.map((key) => `\\\\label{${key}}`)].join('\\n');\n }\n if (block.command === '\\\\paragraph' && block.centered) {\n return `\\\\begin{center}\\n${body}\\n\\\\end{center}`;\n }\n return body;\n}\n\nfunction indent(value: string): string {\n return value\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n');\n}\n\nfunction listBlockLatex(\n block: ListBlock2,\n references: DocumentNode['references'],\n labelKinds: LabelKindMap,\n fixedFloats: boolean,\n unitId?: string,\n): string {\n const items = block.items\n .map((item) => {\n const nested = item.blocks\n .map((child) => '\\n' + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId)))\n .join('');\n return ` \\\\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;\n })\n .join('\\n');\n return `${block.command}\\n${items}\\n${block.closing}`;\n}\n\nfunction defaultGridColumnSpec(block: TableBlock2): string | null {\n const compact = block.columns.replace(/\\s+/g, '');\n const columnCount = block.rows[0]?.length ?? 0;\n if (columnCount === 0 || compact.length !== columnCount || !/^[lcr]+$/.test(compact)) {\n return null;\n }\n return `|${compact.split('').join('|')}|`;\n}\n\nfunction tabularInnerLatex(block: TableBlock2, labelKinds: LabelKindMap, unitId?: string): string {\n const rows = block.rows.map((row) =>\n ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(' & ')}`,\n );\n const gridColumns = defaultGridColumnSpec(block);\n if (gridColumns) {\n const griddedRows = rows.map((row) => `${row} \\\\\\\\ \\\\hline`).join('\\n');\n return `${block.command}{${gridColumns}}\\n \\\\hline\\n${griddedRows}\\n${block.closing}`;\n }\n return `${block.command}{${block.columns}}\\n${rows.join(' \\\\\\\\' + '\\n')}\\n${block.closing}`;\n}\n\nfunction floatCaptionLabelLines(\n block: ImageBlock2 | TableBlock2,\n counter: 'figure' | 'table',\n labelKinds: LabelKindMap,\n unitId?: string,\n): string[] {\n const lines: string[] = [];\n const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();\n const hasCaption = block.captionEnabled && caption.length > 0;\n if (hasCaption) {\n lines.push(` \\\\caption{${caption}}`);\n }\n const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;\n if (hasCaption || hasManualLabel) {\n if (!hasCaption) lines.push(' \\\\refstepcounter{' + counter + '}');\n const autoKey = implicitReferenceKey(counter === 'figure' ? 'fig' : 'tab', block.id, unitId);\n lines.push(' \\\\label{' + autoKey + '}');\n if (hasManualLabel && block.label.trim() !== autoKey) lines.push(' \\\\label{' + block.label.trim() + '}');\n }\n return lines;\n}\n\nfunction tableBlockLatex(block: TableBlock2, labelKinds: LabelKindMap, fixedFloats: boolean, unitId?: string): string {\n const placement = fixedFloats ? 'H' : 'htbp';\n const lines = [`\\\\begin{table}[${placement}]`];\n if (block.centered) {\n lines.push(' \\\\centering');\n }\n lines.push(...floatCaptionLabelLines(block, 'table', labelKinds, unitId));\n lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));\n lines.push('\\\\end{table}');\n return lines.join('\\n');\n}\n\n/** Prefer \\\\columnwidth so figures fit a column (equals \\\\textwidth in one-column). */\nfunction remapImageWidthForColumns(value: string): string {\n return value.replace(/\\\\textwidth\\b/g, '\\\\columnwidth');\n}\n\nfunction imageOptionsLatex(block: ImageBlock2, constrainToColumn: boolean): string {\n const entries = Object.entries(block.options).map(([key, value]) => {\n if (constrainToColumn && key === 'width') {\n return [key, remapImageWidthForColumns(value)] as const;\n }\n return [key, value] as const;\n });\n if (entries.length === 0) {\n return '';\n }\n return `[${entries.map(([key, value]) => `${key}=${value}`).join(',')}]`;\n}\n\nfunction imageBlockLatex(block: ImageBlock2, labelKinds: LabelKindMap, fixedFloats: boolean, unitId?: string): string {\n const placement = fixedFloats ? 'H' : 'htbp';\n const lines = [`\\\\begin{figure}[${placement}]`];\n if (block.centered) {\n lines.push(' \\\\centering');\n }\n // Remap textwidth→columnwidth: safe in one-column, required in twocolumn.\n lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);\n lines.push(...floatCaptionLabelLines(block, 'figure', labelKinds, unitId));\n lines.push('\\\\end{figure}');\n return lines.join('\\n');\n}\n\nfunction blockLatex(\n block: DocumentBlock,\n references: DocumentNode['references'],\n labelKinds: LabelKindMap,\n fixedFloats: boolean,\n unitId?: string,\n): string {\n if (block.kind === 'textBlock') {\n return textBlockLatex(block, labelKinds, unitId);\n }\n if (block.kind === 'list') {\n return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);\n }\n if (block.kind === 'table') {\n return tableBlockLatex(block, labelKinds, fixedFloats, unitId);\n }\n if (block.kind === 'image') {\n return imageBlockLatex(block, labelKinds, fixedFloats, unitId);\n }\n if (block.kind === 'bibliography') {\n const width = String(Math.max(references.length, 9));\n const items = references.map((reference) => ` ${bibliographyEntryLatex(reference)}`).join('\\n');\n return `${block.command}{${width}}\\n${items}\\n${block.closing}`;\n }\n return block.value;\n}\n\nfunction authorLatex(authors: string): string {\n return authors\n .split(/\\n+/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(' \\\\\\\\ ');\n}\n\n/** Title metadata + titling hooks for the XeLaTeX preamble (before \\\\begin{document}). */\nfunction articleMaketitlePreamble(meta: DocumentMeta, twocolumn = false): string {\n if (!documentHasMaketitle(meta)) {\n return '';\n }\n const parts: string[] = [butexBasmalaTitlingPreamble({ twocolumn })];\n if (meta.title.trim().length > 0) {\n parts.push(`\\\\title{${meta.title.trim()}}`);\n }\n if (meta.authors.trim().length > 0) {\n parts.push(`\\\\author{${authorLatex(meta.authors)}}`);\n }\n parts.push(`\\\\date{${formatHijriDate(meta.date, { locale: 'ar', digitForm: 'western' })}}`);\n return parts.join('\\n');\n}\n\nfunction articleFrontMatterLatex(meta: DocumentMeta): string[] {\n const parts: string[] = [];\n if (documentHasMaketitle(meta)) {\n parts.push('\\\\maketitle');\n } else {\n parts.push(butexBasmalaDisplayLatex());\n }\n if (documentHasAbstract(meta)) {\n parts.push(`\\\\begin{abstract}\\n${meta.abstract.trim()}\\n\\\\end{abstract}`);\n }\n return parts;\n}\n\nfunction documentLabelKindMap(document: DocumentNode): Map<string, DocumentLabelKind> {\n const map = new Map<string, DocumentLabelKind>();\n for (const [key, entry] of labelNumberMap(document)) {\n map.set(key, entry.kind);\n }\n return map;\n}\n\nfunction closingHamdalaLatex(): string {\n // Use the font family directly: the math-oriented \\\\butexmaghribi wrapper uses\n // \\\\text/\\\\mbox and would keep the whole sentence in one unbreakable box.\n return `\\\\begin{center}\\n\\\\maghribi{${BUTEX_CLOSING_HAMDALA}}\\n\\\\end{center}`;\n}\n\n/** A book unit is content, not an article. Never emit article chrome or a bibliography. */\nexport function documentContentLatex(document: DocumentNode, context?: DocumentBookContext): string {\n if (!context?.unitId?.trim()) throw new Error('book-content export requires a stable unitId');\n const labelKinds = documentLabelKindMap(document);\n for (const target of context?.targets ?? []) {\n if (target.kind === 'fig' || target.kind === 'tab' || target.kind === 'eq') {\n labelKinds.set(target.key, target.kind);\n if (target.manualKey) labelKinds.set(target.manualKey, target.kind);\n }\n }\n return document.blocks.filter((block) => block.kind !== 'bibliography')\n .map((block) => blockLatex(block, document.references, labelKinds, false, context?.unitId))\n .filter((part) => part.length > 0).join('\\n\\n');\n}\n\nexport function documentLatex(\n document: DocumentNode,\n options: DocumentLatexOptions = {},\n): string {\n const meta = document.meta ?? emptyDocumentMeta();\n const twocolumn = options.twocolumn === true;\n const front = articleFrontMatterLatex(meta);\n const labelKinds = documentLabelKindMap(document);\n const bodyBlocks = document.blocks.map((block) =>\n blockLatex(block, document.references, labelKinds, twocolumn),\n );\n const closing = closingHamdalaLatex();\n const body = [...front, ...bodyBlocks, closing].filter((part) => part.length > 0).join('\\n\\n');\n const wrapDocument = options.wrapDocument !== false;\n if (!wrapDocument) {\n // Body-only: include title metadata so callers still see \\\\title / titling when present.\n const metaPreamble = articleMaketitlePreamble(meta, twocolumn);\n return metaPreamble.length > 0 ? `${metaPreamble}\\n\\n${body}` : body;\n }\n const floatPackage = twocolumn ? '\\n\\\\usepackage{float}\\n' : '\\n';\n const preamble =\n getArabicXeLatexPreamble({\n digitsMapping: options.digitsMapping ?? digitsMappingFromDigitForm(options.digitForm),\n twocolumn,\n }) +\n floatPackage +\n articleMaketitlePreamble(meta, twocolumn);\n return `${preamble}\\n\\\\begin{document}\\n\\n${body}\\n\\n\\\\end{document}\\n`;\n}\n","/** Pure JSON and stable-identity helpers shared by book adapters. */\nconst ID = /^[A-Za-z0-9_-]{1,128}$/;\nexport function safeId(id: string): boolean {\n return ID.test(id) && !['__proto__', 'prototype', 'constructor'].includes(id);\n}\n\nexport function object(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\nexport function copy<T>(value: T): T { return JSON.parse(JSON.stringify(value)) as T; }\n","import { isValidDocumentKey } from '../document/index.js';\nimport type { BookSnapshotJson } from './contracts.js';\nimport { copy, object, safeId } from './utils.js';\n\nexport class BookContractError extends Error {\n readonly code = 'invalid_book';\n constructor(message: string) { super(message); this.name = 'BookContractError'; }\n}\n\nconst KEYS = new Set(['title-page', 'table-of-contents', 'list-of-figures', 'list-of-tables', 'bibliography']);\nconst UNIT_TYPES = new Set(['abstract', 'dedication', 'acknowledgements', 'preface', 'abbreviations', 'chapter', 'appendix', 'backmatter']);\n\n/** Structural validation is deterministic and preserves every authored title and key. */\nexport function normalizeBookSnapshot(value: unknown): BookSnapshotJson {\n if (!object(value) || !object(value.manifest) || !object(value.references) || !object(value.documents)) {\n throw new BookContractError('Book snapshot requires manifest, references and documents');\n }\n const manifest = value.manifest;\n const meta = manifest.meta;\n if (manifest.node_type !== 'BookManifest' || manifest.schema_version !== 1 ||\n typeof manifest.id !== 'string' || !safeId(manifest.id) ||\n manifest.references_path !== 'references.json' || !Array.isArray(manifest.entries) ||\n !object(meta) || typeof meta.title !== 'string' || !Array.isArray(meta.authors) ||\n !meta.authors.every(x => typeof x === 'string') || meta.language !== 'ar' || meta.direction !== 'rtl' ||\n (meta.numbering !== undefined && (!object(meta.numbering) ||\n (meta.numbering.digit_form !== undefined && !['arabicIndic', 'western'].includes(String(meta.numbering.digit_form))) ||\n (meta.numbering.chapter_heading !== undefined && !['ordinal-words', 'digits'].includes(String(meta.numbering.chapter_heading))) ||\n (meta.numbering.appendix_heading !== undefined && !['letters', 'digits'].includes(String(meta.numbering.appendix_heading)))))) {\n throw new BookContractError('Invalid BookManifest v1');\n }\n if (value.references.node_type !== 'BookReferences' || value.references.schema_version !== 1 ||\n !Array.isArray(value.references.references)) {\n throw new BookContractError('Invalid BookReferences v1');\n }\n const ids = new Set<string>();\n const generated = new Set<string>();\n const unitIds = new Set<string>();\n for (const entry of manifest.entries as unknown[]) {\n if (!object(entry) || typeof entry.id !== 'string' || !safeId(entry.id) || ids.has(entry.id)) {\n throw new BookContractError('Duplicate or unsafe book entry ID');\n }\n ids.add(entry.id);\n if (entry.kind === 'generated') {\n if (typeof entry.generated !== 'string' || !KEYS.has(entry.generated) || generated.has(entry.generated)) {\n throw new BookContractError('Invalid or repeated generated entry');\n }\n generated.add(entry.generated);\n } else if (entry.kind === 'document') {\n if (typeof entry.type !== 'string' || !UNIT_TYPES.has(entry.type) ||\n typeof entry.title !== 'string' || typeof entry.numbered !== 'boolean' ||\n typeof entry.include_in_toc !== 'boolean' ||\n entry.document_path !== 'content/units/' + entry.id + '/document.json') {\n throw new BookContractError('Invalid or unsafe unit entry');\n }\n unitIds.add(entry.id);\n } else {\n throw new BookContractError('Unknown book entry kind');\n }\n }\n const documents = value.documents;\n if (Object.keys(documents).length !== unitIds.size || Object.keys(documents).some(id => !unitIds.has(id))) {\n throw new BookContractError('Unit documents must exactly match manifest');\n }\n for (const id of unitIds) {\n const doc = documents[id];\n if (!object(doc) || doc.node_type !== 'DocumentObject' || !Array.isArray(doc.blocks)) {\n throw new BookContractError('Invalid unit DocumentJson for ' + id);\n }\n }\n for (const ref of value.references.references) {\n if (!object(ref) || typeof ref.key !== 'string' || !isValidDocumentKey(ref.key)) {\n throw new BookContractError('Invalid shared bibliography entry');\n }\n }\n return copy(value as BookSnapshotJson);\n}\n","import type { DocumentJson, Reference2Json } from '../document/index.js';\nimport type { BookEntry, BookMetaJson, BookSnapshotJson } from './contracts.js';\nimport { copy, object, safeId } from './utils.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookCommand =\n | { op: 'reorder_entries'; entry_ids: string[] }\n | { op: 'update_entry'; entry_id: string; title?: string; numbered?: boolean; include_in_toc?: boolean; label?: string | null }\n | { op: 'set_meta'; meta: BookMetaJson }\n | { op: 'set_references'; references: Reference2Json[] }\n | { op: 'insert_entry'; entry: BookEntry; document?: DocumentJson; index: number }\n | { op: 'remove_entry'; entry_id: string };\n\n/** Validate untrusted book-command JSON before it reaches the typed reducer. */\nexport function parseBookCommand(value: unknown): BookCommand {\n if (!object(value) || typeof value.op !== 'string') {\n throw new BookContractError('Book command requires an operation');\n }\n const rules: Record<string, string[]> = {\n reorder_entries: ['entry_ids'],\n update_entry: ['entry_id', 'title', 'numbered', 'include_in_toc', 'label'],\n set_meta: ['meta'],\n set_references: ['references'],\n insert_entry: ['entry', 'document', 'index'],\n remove_entry: ['entry_id'],\n };\n const allowed = rules[value.op];\n if (!allowed || Object.keys(value).some(key => key !== 'op' && !allowed.includes(key))) {\n throw new BookContractError('Unsupported book command fields');\n }\n if (value.op === 'reorder_entries' &&\n (!Array.isArray(value.entry_ids) || !value.entry_ids.every(id => typeof id === 'string'))) {\n throw new BookContractError('Reorder requires entry ID list');\n }\n if (value.op === 'update_entry' &&\n (typeof value.entry_id !== 'string' || !safeId(value.entry_id) ||\n !['title', 'numbered', 'include_in_toc', 'label'].some(key => key in value) ||\n (value.title !== undefined && typeof value.title !== 'string') ||\n (value.numbered !== undefined && typeof value.numbered !== 'boolean') ||\n (value.include_in_toc !== undefined && typeof value.include_in_toc !== 'boolean') ||\n (value.label !== undefined && value.label !== null && typeof value.label !== 'string'))) {\n throw new BookContractError('Invalid book entry patch');\n }\n if (value.op === 'set_meta' && !object(value.meta)) {\n throw new BookContractError('Book metadata must be an object');\n }\n if (value.op === 'set_references' &&\n (!Array.isArray(value.references) || !value.references.every(entry => object(entry)))) {\n throw new BookContractError('Shared bibliography must be an array of entries');\n }\n if (value.op === 'insert_entry' &&\n (!object(value.entry) || !Number.isInteger(value.index) ||\n ((value.entry.kind !== 'document') && (value.entry.kind !== 'generated')) ||\n (value.entry.kind === 'document' && !object(value.document)) ||\n (value.entry.kind === 'generated' && value.document !== undefined))) {\n throw new BookContractError('Invalid book insertion command');\n }\n if (value.op === 'remove_entry' && (typeof value.entry_id !== 'string' || !safeId(value.entry_id))) {\n throw new BookContractError('Removal requires stable entry ID');\n }\n return value as BookCommand;\n}\n\n/** Commands only edit a manifest/catalog; individual Document commands remain on /v1/document. */\nexport function applyBookCommand(raw: unknown, command: BookCommand): BookSnapshotJson {\n const snapshot = normalizeBookSnapshot(raw);\n command = parseBookCommand(command);\n if (command.op === 'reorder_entries') {\n const actual = snapshot.manifest.entries.map(e => e.id);\n if (command.entry_ids.length !== actual.length ||\n new Set(command.entry_ids).size !== actual.length ||\n actual.some(id => !command.entry_ids.includes(id))) {\n throw new BookContractError('Reorder must contain every existing entry exactly once');\n }\n const byId = new Map(snapshot.manifest.entries.map(e => [e.id, e]));\n snapshot.manifest.entries = command.entry_ids.map(id => byId.get(id)!);\n } else if (command.op === 'update_entry') {\n const entry = snapshot.manifest.entries.find(e => e.id === command.entry_id);\n if (!entry || entry.kind !== 'document') throw new BookContractError('Unknown document unit');\n if (command.title !== undefined) entry.title = command.title;\n if (command.numbered !== undefined) entry.numbered = command.numbered;\n if (command.include_in_toc !== undefined) entry.include_in_toc = command.include_in_toc;\n if (command.label !== undefined) {\n if (command.label === null) delete entry.label;\n else entry.label = command.label;\n }\n } else if (command.op === 'set_meta') {\n snapshot.manifest.meta = copy(command.meta);\n } else if (command.op === 'set_references') {\n snapshot.references.references = copy(command.references);\n } else if (command.op === 'insert_entry') {\n if (!Number.isInteger(command.index) || command.index < 0 || command.index > snapshot.manifest.entries.length) {\n throw new BookContractError('Invalid insertion index');\n }\n snapshot.manifest.entries.splice(command.index, 0, copy(command.entry));\n if (command.entry.kind === 'document') {\n if (!command.document) throw new BookContractError('New document unit needs a separate DocumentJson');\n snapshot.documents[command.entry.id] = copy(command.document);\n }\n } else if (command.op === 'remove_entry') {\n const at = snapshot.manifest.entries.findIndex(e => e.id === command.entry_id);\n if (at < 0) throw new BookContractError('Unknown book entry');\n const [removed] = snapshot.manifest.entries.splice(at, 1);\n if (removed?.kind === 'document') delete snapshot.documents[removed.id];\n } else {\n throw new BookContractError('Unknown book structure operation');\n }\n return normalizeBookSnapshot(snapshot);\n}\n","import {\n collectDocumentReferenceTargets,\n fromDocumentJson,\n getDocumentReferenceIndex,\n implicitHeadingReferenceKey,\n implicitReferenceKey,\n isValidDocumentKey,\n} from '../document/index.js';\nimport type { DocumentBlockJson, DocumentBookContext, DocumentBookTarget } from '../document/index.js';\nimport type { BookSnapshotJson } from './contracts.js';\nimport { copy } from './utils.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookIssue = {\n code: 'invalid_snapshot' | 'invalid_entry' | 'missing_document' | 'duplicate_entry' |\n 'duplicate_generated' | 'local_bibliography' | 'unstable_block_id' |\n 'duplicate_key' | 'invalid_key' | 'missing_citation' | 'missing_reference' |\n 'invalid_reference_kind';\n path: string;\n severity: 'error' | 'warning';\n unit_id?: string;\n block_id?: string;\n token_id?: string;\n key?: string;\n};\n\nexport type BookOutlineEntry = {\n id: string;\n kind: 'chapter' | 'appendix' | 'unit' | 'generated' | 'section' | 'subsection' | 'subsubsection';\n title: string;\n display_label: string;\n level: number;\n unit_id?: string;\n parent_unit_id?: string;\n numbered: boolean;\n include_in_toc: boolean;\n};\n\nexport type BookTarget = DocumentBookTarget & {\n numbered: boolean;\n ordinal?: string;\n};\n\nexport type BookResolution = {\n manifest_id: string;\n outline: BookOutlineEntry[];\n targets: BookTarget[];\n citations: Array<{ key: string; number: number; display_label: string }>;\n issues: BookIssue[];\n};\n\nconst LETTERS = ['أ', 'ب', 'ج', 'د', 'هـ', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ'];\nconst ORDINALS = ['الأول', 'الثاني', 'الثالث', 'الرابع', 'الخامس', 'السادس', 'السابع', 'الثامن', 'التاسع', 'العاشر',\n 'الحادي عشر', 'الثاني عشر', 'الثالث عشر', 'الرابع عشر', 'الخامس عشر', 'السادس عشر', 'السابع عشر', 'الثامن عشر', 'التاسع عشر', 'العشرون'];\n\nfunction digits(value: number | string, form: 'arabicIndic' | 'western'): string {\n return form === 'western' ? String(value) : String(value).replace(/[0-9]/g, ch => '٠١٢٣٤٥٦٧٨٩'[Number(ch)]!);\n}\nfunction ordinal(number: number, form: 'arabicIndic' | 'western', style: 'ordinal-words' | 'digits'): string {\n return style === 'digits' ? digits(number, form) : ORDINALS[number - 1] ?? digits(number, form);\n}\nfunction appendix(number: number, form: 'arabicIndic' | 'western', style: 'letters' | 'digits'): string {\n return style === 'digits' ? digits(number, form) : LETTERS[number - 1] ?? digits(number, form);\n}\nfunction unitAlias(kind: 'chapter' | 'appendix', unitId: string): string {\n const hex = Array.from(new TextEncoder().encode(unitId), byte => byte.toString(16).padStart(2, '0')).join('');\n return kind + ':butex-auto-u' + hex + '-' + hex;\n}\nfunction issue(code: BookIssue['code'], path: string, extra: Partial<BookIssue> = {}): BookIssue {\n return { code, path, severity: code === 'missing_citation' || code === 'missing_reference' ? 'warning' : 'error', ...extra };\n}\n\nfunction headingKind(block: DocumentBlockJson): 'section' | 'subsection' | 'subsubsection' | null {\n if (block.command === '\\\\section') return 'section';\n if (block.command === '\\\\subsection') return 'subsection';\n if (block.command === '\\\\subsubsection') return 'subsubsection';\n return null;\n}\nfunction headingLevel(kind: 'section' | 'subsection' | 'subsubsection'): number {\n return kind === 'section' ? 1 : kind === 'subsection' ? 2 : 3;\n}\n\n/** One global, read-only catalog; no ordinals or shared bibliography are written into chapter JSON. */\nexport function resolveBookSnapshot(raw: unknown): BookResolution {\n const snapshot = normalizeBookSnapshot(raw);\n const { manifest, references, documents } = snapshot;\n const digitForm = manifest.meta.numbering?.digit_form ?? 'arabicIndic';\n const chapterStyle = manifest.meta.numbering?.chapter_heading ?? 'ordinal-words';\n const appendixStyle = manifest.meta.numbering?.appendix_heading ?? 'letters';\n const outline: BookOutlineEntry[] = [];\n const targets: BookTarget[] = [];\n const issues: BookIssue[] = [];\n const aliasOwners = new Map<string, { unitId?: string; ownerId?: string }>();\n const citationKeys = new Set<string>();\n const unnumbered = { fig: 0, tab: 0, eq: 0 };\n let chapterCount = 0;\n let appendixCount = 0;\n\n function register(key: string | undefined, unitId?: string, ownerId?: string): void {\n if (!key) return;\n if (!isValidDocumentKey(key)) {\n issues.push(issue('invalid_key', '$.references', { unit_id: unitId, block_id: ownerId, key }));\n }\n if (aliasOwners.has(key)) {\n issues.push(issue('duplicate_key', '$.references', { unit_id: unitId, block_id: ownerId, key }));\n } else {\n aliasOwners.set(key, { unitId, ownerId });\n }\n }\n for (let n = 0; n < references.references.length; n++) {\n const ref = references.references[n]!;\n citationKeys.add(ref.key);\n register(ref.key);\n }\n const citations = references.references.map((ref, i) => ({\n key: ref.key, number: i + 1, display_label: '[' + digits(i + 1, digitForm) + ']',\n }));\n\n for (const entry of manifest.entries) {\n if (entry.kind === 'generated') {\n outline.push({ id: entry.id, kind: 'generated', title: entry.generated,\n display_label: entry.generated, level: 0, numbered: false, include_in_toc: false });\n continue;\n }\n const unitId = entry.id;\n const isChapter = entry.type === 'chapter';\n const isAppendix = entry.type === 'appendix';\n if (isChapter && entry.numbered) chapterCount++;\n if (isAppendix && entry.numbered) appendixCount++;\n const chapterNumber = isChapter && entry.numbered ? chapterCount : null;\n const appendixNumber = isAppendix && entry.numbered ? appendixCount : null;\n const prefix = chapterNumber !== null ? digits(chapterNumber, digitForm)\n : appendixNumber !== null ? appendix(appendixNumber, digitForm, appendixStyle) : '';\n const generatedTitle = chapterNumber !== null ? 'الفصل ' + ordinal(chapterNumber, digitForm, chapterStyle)\n : appendixNumber !== null ? 'الملحق ' + prefix : '';\n const displayTitle = generatedTitle ? generatedTitle + ': ' + entry.title : entry.title;\n outline.push({\n id: unitId, unit_id: unitId, kind: isChapter ? 'chapter' : isAppendix ? 'appendix' : 'unit',\n title: entry.title, display_label: displayTitle, level: 0, numbered: entry.numbered,\n include_in_toc: entry.include_in_toc,\n });\n if (isChapter || isAppendix) {\n const kind = isChapter ? 'chapter' : 'appendix';\n const key = unitAlias(kind, unitId);\n targets.push({ unitId, ownerId: unitId, key, kind, caption: entry.title,\n displayLabel: generatedTitle || entry.title, numbered: entry.numbered,\n ...(prefix ? { ordinal: prefix } : {}), ...(entry.label ? { manualKey: entry.label } : {}) });\n register(key, unitId, unitId);\n register(entry.label, unitId, unitId);\n } else {\n register(entry.label, unitId, unitId);\n }\n\n const doc = documents[unitId]!;\n const seenBlocks = new Set<string>();\n const headingNumbers = { section: 0, subsection: 0, subsubsection: 0 };\n for (let b = 0; b < doc.blocks.length; b++) {\n const block = doc.blocks[b]!;\n if (!block.id || seenBlocks.has(block.id)) {\n issues.push(issue('unstable_block_id', '$.documents.' + unitId + '.blocks[' + b + ']',\n { unit_id: unitId, block_id: block.id }));\n } else seenBlocks.add(block.id);\n if (block.command === '\\\\begin{thebibliography}' || block.command === '\\\\bibliography') {\n issues.push(issue('local_bibliography', '$.documents.' + unitId + '.blocks[' + b + ']',\n { unit_id: unitId, block_id: block.id }));\n }\n const kind = headingKind(block);\n if (kind && block.id) {\n // Chapter-aware heading numbers are a projection; never persist them\n // in a unit's canonical DocumentJson or overwrite authored titles.\n if (kind === 'section') {\n headingNumbers.section++;\n headingNumbers.subsection = 0;\n headingNumbers.subsubsection = 0;\n } else if (kind === 'subsection') {\n headingNumbers.subsection++;\n headingNumbers.subsubsection = 0;\n } else {\n headingNumbers.subsubsection++;\n }\n const levels = kind === 'section' ? [headingNumbers.section]\n : kind === 'subsection' ? [headingNumbers.section, headingNumbers.subsection]\n : [headingNumbers.section, headingNumbers.subsection, headingNumbers.subsubsection];\n const ordinalLabel = [...(prefix ? [prefix] : []),\n ...levels.map(number => digits(number, digitForm))].join('.');\n const visible = 'القسم ' + ordinalLabel;\n const key = implicitHeadingReferenceKey(kind, block.id, unitId);\n const label = block.value ?? '';\n outline.push({ id: block.id, parent_unit_id: unitId, unit_id: unitId, kind,\n title: label, display_label: visible + ': ' + label, level: headingLevel(kind), numbered: true,\n include_in_toc: entry.include_in_toc });\n targets.push({ unitId, ownerId: block.id, key, kind, caption: label,\n displayLabel: visible, ordinal: ordinalLabel, numbered: true,\n ...(block.label ? { manualKey: block.label } : {}) });\n register(key, unitId, block.id);\n register(block.label, unitId, block.id);\n }\n }\n const resolved = fromDocumentJson(doc);\n const localCounts = { fig: 0, tab: 0, eq: 0 };\n for (const target of collectDocumentReferenceTargets(resolved)) {\n const key = implicitReferenceKey(target.kind, target.ownerId, unitId);\n const numbered = target.number !== null;\n if (numbered) {\n if (prefix) localCounts[target.kind]++;\n else unnumbered[target.kind]++;\n }\n const index = prefix ? localCounts[target.kind] : unnumbered[target.kind];\n const displayOrdinal = numbered ? (prefix ? prefix + '.' : '') + digits(index, digitForm) : '';\n const name = target.kind === 'fig' ? 'الشكل' : target.kind === 'tab' ? 'الجدول' : 'المعادلة';\n const displayLabel = numbered ? (target.kind === 'eq' ? name + ' (' + displayOrdinal + ')' : name + ' ' + displayOrdinal) : '';\n targets.push({ unitId, ownerId: target.ownerId, key, kind: target.kind,\n caption: target.caption, numbered, ...(displayOrdinal ? { ordinal: displayOrdinal, displayLabel } : {}),\n ...(target.manualKey ? { manualKey: target.manualKey } : {}) });\n if (numbered) {\n register(key, unitId, target.ownerId);\n register(target.manualKey, unitId, target.ownerId);\n }\n }\n }\n // Validate relationships only after seeing all units: references may point forward.\n for (const entry of manifest.entries) {\n if (entry.kind !== 'document') continue;\n const doc = fromDocumentJson(documents[entry.id]!);\n const refs = getDocumentReferenceIndex(doc);\n for (const citation of refs.citations) {\n for (const key of citation.keys) {\n if (!citationKeys.has(key)) {\n issues.push(issue('missing_citation', '$.documents.' + entry.id + '.citations', {\n unit_id: entry.id, block_id: citation.block_id, token_id: citation.token_id, key,\n }));\n }\n }\n }\n for (const reference of refs.cross_references) {\n for (const key of reference.keys) {\n const hit = targets.find(t => t.key === key || t.manualKey === key);\n if (!hit || (!hit.numbered && (hit.kind === 'fig' || hit.kind === 'tab' || hit.kind === 'eq'))) {\n issues.push(issue('missing_reference', '$.documents.' + entry.id + '.references', {\n unit_id: entry.id, block_id: reference.block_id, token_id: reference.token_id, key,\n }));\n } else if (reference.ref_command === 'eqref' && hit.kind !== 'eq') {\n issues.push(issue('invalid_reference_kind', '$.documents.' + entry.id + '.references', {\n unit_id: entry.id, block_id: reference.block_id, token_id: reference.token_id, key,\n }));\n }\n }\n }\n }\n return { manifest_id: manifest.id, outline, targets, citations, issues };\n}\n\nexport function bookContextForUnit(snapshot: BookSnapshotJson, unitId: string): DocumentBookContext {\n if (!Object.prototype.hasOwnProperty.call(snapshot.documents, unitId)) {\n throw new BookContractError('Unknown book unit: ' + unitId);\n }\n const projection = resolveBookSnapshot(snapshot);\n return { unitId, references: copy(snapshot.references.references), targets: projection.targets.map(t => ({\n unitId: t.unitId, ownerId: t.ownerId, key: t.key, kind: t.kind,\n ...(t.caption !== undefined ? { caption: t.caption } : {}),\n ...(t.displayLabel !== undefined ? { displayLabel: t.displayLabel } : {}),\n ...(t.manualKey !== undefined ? { manualKey: t.manualKey } : {}),\n })) };\n}\n\nexport function bookOutline(snapshot: unknown): BookOutlineEntry[] {\n return resolveBookSnapshot(snapshot).outline;\n}\nexport function getBookReferenceIndex(snapshot: unknown): BookResolution {\n return resolveBookSnapshot(snapshot);\n}\nexport function validateBookSnapshot(snapshot: unknown): { valid: boolean; issues: BookIssue[] } {\n const resolution = resolveBookSnapshot(snapshot);\n return { valid: resolution.issues.every(x => x.severity !== 'error'), issues: resolution.issues };\n}\n","/** Deterministic, pure multi-file XeLaTeX Book export. No ZIP, filesystem or S3. */\nimport {\n bibliographyEntryLatex, documentContentLatex, fromDocumentJson,\n getArabicXeLatexPreamble, referenceFromJson,\n} from '../document/index.js';\nimport type { DocumentBlockJson, DocumentBookContext } from '../document/index.js';\nimport type { BookSnapshotJson, BookUnitEntry } from './contracts.js';\nimport type { BookIssue, BookResolution } from './introspection.js';\nimport { resolveBookSnapshot } from './introspection.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookLatexAsset = { asset_id: string; output_path: string };\nexport type BookLatexBundle = {\n main_file: 'main.tex';\n files: Record<string, string>;\n assets: BookLatexAsset[];\n diagnostics: BookIssue[];\n /** Stable source fingerprint; Al-Bayan computes SHA-256 for stored artifacts. */\n fingerprint: string;\n};\nexport type BookLatexOptions = { include_toc_if_missing?: boolean };\n\nconst SAFE_PATH = /^[A-Za-z0-9][A-Za-z0-9._-]*(\\/[A-Za-z0-9][A-Za-z0-9._-]*){0,3}$/;\nconst IMAGE_EXT = /\\.(?:png|jpe?g|pdf)$/i;\n\nfunction escapeLatex(value: string): string {\n return value.replace(/[\\\\{}%#$&_~^]/g, (char) => ({\n '\\\\': '\\\\textbackslash{}', '{': '\\\\{', '}': '\\\\}', '%': '\\\\%',\n '#': '\\\\#', '$': '\\\\$', '&': '\\\\&', '_': '\\\\_',\n '~': '\\\\textasciitilde{}', '^': '\\\\textasciicircum{}',\n })[char] ?? char);\n}\n\nfunction visitAssets(blocks: DocumentBlockJson[], collect: (assetId: string, path: string) => void): void {\n for (const block of blocks) {\n if (block.command === '\\\\includegraphics') {\n if (!block.asset_id || typeof block.value !== 'string') {\n throw new BookContractError('Book images require an asset_id and relative image path');\n }\n collect(block.asset_id, block.value);\n }\n for (const item of block.items ?? []) {\n visitAssets(item.blocks ?? [], collect);\n }\n }\n}\n\nfunction fingerprint(files: Record<string, string>, assets: BookLatexAsset[]): string {\n // Browser-safe deterministic FNV-1a (source fingerprint only; not a security hash).\n let value = 2166136261;\n const payload = JSON.stringify({ files, assets });\n for (const byte of new TextEncoder().encode(payload)) {\n value = Math.imul(value ^ byte, 16777619) >>> 0;\n }\n return 'fnv1a32:' + value.toString(16).padStart(8, '0');\n}\n\nfunction heading(entry: BookUnitEntry, resolution: BookResolution): string {\n return resolution.outline.find(item => item.id === entry.id)?.display_label ?? entry.title;\n}\n\nfunction unitBoundary(entry: BookUnitEntry, projection: BookResolution, unnumbered: { fig: number; tab: number; eq: number }): string {\n const numbered = (entry.type === 'chapter' || entry.type === 'appendix') && entry.numbered;\n const lines: string[] = [];\n if (numbered) {\n const target = projection.targets.find(t => t.unitId === entry.id && t.ownerId === entry.id);\n if (!target?.ordinal) throw new BookContractError('Missing Book numbering projection for ' + entry.id);\n lines.push(\n '\\\\renewcommand{\\\\thechapter}{' + target.ordinal + '}',\n '\\\\refstepcounter{chapter}',\n '\\\\renewcommand{\\\\thesection}{\\\\thechapter.\\\\arabic{section}}',\n );\n } else {\n lines.push(\n '\\\\setcounter{section}{0}',\n '\\\\renewcommand{\\\\thesection}{\\\\arabic{section}}',\n );\n }\n for (const [kind, counter] of [['fig', 'figure'], ['tab', 'table'], ['eq', 'equation']] as const) {\n lines.push('\\\\setcounter{' + counter + '}{' + (numbered ? '0' : String(unnumbered[kind])) + '}');\n lines.push('\\\\renewcommand{\\\\the' + counter + '}{' + (numbered ? '\\\\thechapter.' : '') + '\\\\arabic{' + counter + '}}');\n }\n\n const title = escapeLatex(heading(entry, projection));\n lines.push('\\\\chapter*{' + title + '}');\n if (entry.include_in_toc) {\n lines.push('\\\\addcontentsline{toc}{chapter}{' + title + '}');\n }\n if (numbered) {\n const target = projection.targets.find(t => t.unitId === entry.id && t.ownerId === entry.id);\n if (target) lines.push('\\\\label{' + target.key + '}');\n if (entry.label && entry.label !== target?.key) lines.push('\\\\label{' + entry.label + '}');\n } else if (entry.label) {\n lines.push('\\\\label{' + entry.label + '}');\n }\n return lines.join('\\n');\n}\n\nfunction bookPreamble(snapshot: BookSnapshotJson): string {\n const arabicDigits = snapshot.manifest.meta.numbering?.digit_form !== 'western';\n const articlePreamble = getArabicXeLatexPreamble({\n digitsMapping: arabicDigits ? 'arabicdigits' : 'digits',\n });\n const withoutClass = articlePreamble.replace(/\\\\documentclass\\[[^\\]]*\\]\\{article\\}/, '');\n if (withoutClass === articlePreamble) throw new BookContractError('Arabic preamble class seam has changed');\n return [\n '\\\\NeedsTeXFormat{LaTeX2e}',\n '\\\\ProvidesPackage{book}[2026/11/14 BuTeX Arabic Book]',\n withoutClass.replace(/\\\\usepackage/g, '\\\\RequirePackage'),\n '\\\\renewcommand{\\\\figurename}{الشكل}',\n '\\\\renewcommand{\\\\tablename}{الجدول}',\n '\\\\renewcommand{\\\\contentsname}{المحتويات}',\n ].join('\\n');\n}\n\nexport function book2Latex(raw: unknown, _options: BookLatexOptions = {}): BookLatexBundle {\n const snapshot = normalizeBookSnapshot(raw);\n const projection = resolveBookSnapshot(snapshot);\n const fatal = projection.issues.filter(issue => issue.severity === 'error');\n if (fatal.length) {\n throw new BookContractError('Book export blocked: ' + fatal[0]!.code + ' at ' + fatal[0]!.path);\n }\n const files: Record<string, string> = {};\n const assets: BookLatexAsset[] = [];\n const paths = new Map<string, string>();\n const addAsset = (assetId: string, path: string): void => {\n const tail = path.split('/').at(-1) ?? '';\n const extensionless = !tail.includes('.');\n if (!SAFE_PATH.test(path) || path.split('/').some(part => part.startsWith('.')) ||\n !(IMAGE_EXT.test(path) || extensionless)) {\n throw new BookContractError('Unsafe or unsupported Book image path: ' + path);\n }\n const alias = path.toLowerCase();\n const prior = paths.get(alias);\n if (prior && prior !== assetId) {\n throw new BookContractError('Multiple Book assets claim the same image path: ' + path);\n }\n paths.set(alias, assetId);\n if (!assets.some(a => a.asset_id === assetId && a.output_path === path)) {\n assets.push({ asset_id: assetId, output_path: path });\n }\n };\n const meta = snapshot.manifest.meta;\n const main = [\n '\\\\documentclass[12pt,a4paper]{book}',\n '\\\\usepackage{book}',\n '\\\\begin{document}',\n ];\n const unnumbered = { fig: 0, tab: 0, eq: 0 };\n let hasBibliography = false;\n let hasToc = false;\n\n for (const entry of snapshot.manifest.entries) {\n if (entry.kind === 'generated') {\n if (entry.generated === 'title-page') {\n main.push('\\\\begin{titlepage}\\\\centering',\n '{\\\\Huge ' + escapeLatex(meta.title) + '\\\\par}',\n '\\\\vspace{2cm}', ...meta.authors.map(author => escapeLatex(author) + '\\\\par'),\n ...(meta.date ? [escapeLatex(meta.date) + '\\\\par'] : []), '\\\\end{titlepage}');\n } else if (entry.generated === 'table-of-contents') {\n hasToc = true;\n main.push('\\\\tableofcontents');\n } else if (entry.generated === 'list-of-figures') {\n main.push('\\\\listoffigures');\n } else if (entry.generated === 'list-of-tables') {\n main.push('\\\\listoftables');\n } else if (entry.generated === 'bibliography') {\n hasBibliography = true;\n main.push('\\\\input{references.tex}');\n }\n continue;\n }\n\n const unitPath = 'units/' + entry.id + '.tex';\n const doc = snapshot.documents[entry.id]!;\n visitAssets(doc.blocks, addAsset);\n const context: DocumentBookContext = {\n unitId: entry.id, references: snapshot.references.references,\n targets: projection.targets,\n };\n const content = documentContentLatex(fromDocumentJson(doc), context);\n files[unitPath] = [unitBoundary(entry, projection, unnumbered), content, ''].join('\\n\\n');\n main.push('\\\\input{' + unitPath + '}');\n if (!((entry.type === 'chapter' || entry.type === 'appendix') && entry.numbered)) {\n for (const kind of ['fig', 'tab', 'eq'] as const) {\n unnumbered[kind] += projection.targets.filter(t =>\n t.unitId === entry.id && t.kind === kind && t.numbered).length;\n }\n }\n }\n if (!hasToc && _options.include_toc_if_missing) {\n main.splice(3, 0, '\\\\tableofcontents');\n }\n if (snapshot.references.references.length) {\n const entries = snapshot.references.references.map(ref => ' ' + bibliographyEntryLatex(referenceFromJson(ref)));\n files['references.tex'] = ['\\\\begin{thebibliography}{' + String(Math.max(9, entries.length)) + '}',\n ...entries, '\\\\end{thebibliography}', ''].join('\\n');\n if (!hasBibliography) main.push('\\\\input{references.tex}');\n } else if (hasBibliography) {\n files['references.tex'] = '% No shared references\\n';\n }\n main.push('\\\\end{document}', '');\n files['main.tex'] = main.join('\\n\\n');\n files['book.sty'] = bookPreamble(snapshot);\n const ordered = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))) as Record<string, string>;\n return { main_file: 'main.tex', files: ordered, assets,\n diagnostics: projection.issues, fingerprint: fingerprint(ordered, assets) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AAU,SAAS,wBAAwB;AAC9C,SAAK,OAAO,GAAG,GAAG,mBAAmB;AAAA,EACvC;AACA,MAAI,SAAS,WAAW,WAAW,QAAQ;AACzC,UAAM,UAAU,SAAS,WAAW,WAAW,IAAI,SAAO,OAAO,uBAAuB,kBAAkB,GAAG,CAAC,CAAC;AAC/G,UAAM,gBAAgB,IAAI;AAAA,MAAC,8BAA8B,OAAO,KAAK,IAAI,GAAG,QAAQ,MAAM,CAAC,IAAI;AAAA,MAC7F,GAAG;AAAA,MAAS;AAAA,MAA0B;AAAA,IAAE,EAAE,KAAK,IAAI;AACrD,QAAI,CAAC,gBAAiB,MAAK,KAAK,yBAAyB;AAAA,EAC3D,WAAW,iBAAiB;AAC1B,UAAM,gBAAgB,IAAI;AAAA,EAC5B;AACA,OAAK,KAAK,mBAAmB,EAAE;AAC/B,QAAM,UAAU,IAAI,KAAK,KAAK,MAAM;AACpC,QAAM,UAAU,IAAI,aAAa,QAAQ;AACzC,QAAM,UAAU,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AAC/F,SAAO;AAAA,IAAE,WAAW;AAAA,IAAY,OAAO;AAAA,IAAS;AAAA,IAC9C,aAAa,WAAW;AAAA,IAAQ,aAAa,YAAY,SAAS,MAAM;AAAA,EAAE;AAC9E;","names":["value","leftDelimExpr","rightDelimExpr","node","parseChain","document","document","isObject","nextId","leftDelimExpr","rightDelimExpr","scripts","document","document","document","issue"]}
|
|
1
|
+
{"version":3,"sources":["../src/book/index.ts","../src/document/ids.ts","../src/editor/digits.ts","../src/document/articleMeta.ts","../src/document/citations.ts","../src/ast/commands/index.ts","../src/ast/arabic_ast.ts","../src/shared/math-document/mathObject.ts","../src/document/labels.ts","../src/document/inlineIdentity.ts","../src/document/inlineScanner.ts","../src/document/importJson.ts","../src/editor/accentCommands.ts","../src/editor/atomicCommands.ts","../src/editor/atomicCommandsOperators.ts","../src/editor/standardCommands.ts","../src/editor/factory.ts","../src/editor/characterFonts.ts","../src/editor/divideOperator.ts","../src/editor/rawOperatorPresentation.ts","../src/editor/indexSequence.ts","../src/editor/render.ts","../src/editor/state.ts","../src/editor/display/delimiter.ts","../src/editor/display/boxed.ts","../src/editor/display/frac.ts","../src/editor/display/sqrt.ts","../src/editor/display/overset.ts","../src/editor/display/underset.ts","../src/editor/display/accent.ts","../src/editor/display/env.ts","../src/diwani-font.ts","../src/editor/display/atomicCommand.ts","../src/editor/display/atomicCommandsOperators.ts","../src/editor/display/standardCommand.ts","../src/editor/styles.ts","../src/shared/math-document/normalizeCharImport.ts","../src/shared/math-document/mathEditorAdapter.ts","../src/document/mathBridge.ts","../src/document/keys.ts","../src/document/diff.ts","../src/document/introspection.ts","../src/document/arabicPreamble.ts","../src/document/exportLatex.ts","../src/book/utils.ts","../src/book/validation.ts","../src/book/jsonCommands.ts","../src/book/introspection.ts","../src/book/exportLatex.ts"],"sourcesContent":["export type * from './contracts.js';\nexport { BookContractError, normalizeBookSnapshot } from './validation.js';\nexport { applyBookCommand, parseBookCommand } from './jsonCommands.js';\nexport type { BookCommand } from './jsonCommands.js';\nexport {\n bookContextForUnit,\n bookOutline,\n getBookReferenceIndex,\n resolveBookSnapshot,\n validateBookSnapshot,\n} from './introspection.js';\nexport type {\n BookIssue, BookOutlineEntry, BookResolution, BookTarget,\n} from './introspection.js';\n\nexport { book2Latex } from './exportLatex.js';\nexport type { BookLatexBundle, BookLatexAsset, BookLatexOptions } from './exportLatex.js';\n","let nextId = 1;\nconst instanceId = `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n\nexport function documentId(prefix: string): string {\n const id = `${prefix}_${instanceId}_${String(nextId)}`;\n nextId += 1;\n return id;\n}\n","import type { DigitFormId } from './types.js';\n\nconst WESTERN = '0123456789';\nconst ARABIC_INDIC = '٠١٢٣٤٥٦٧٨٩';\nconst PERSIAN_INDIC = '۰۱۲۳۴۵۶۷۸۹';\n\nconst digitSets: Record<DigitFormId, string> = {\n western: WESTERN,\n arabicIndic: ARABIC_INDIC,\n persianIndic: PERSIAN_INDIC,\n};\n\nfunction digitValue(char: string): number {\n const western = WESTERN.indexOf(char);\n if (western >= 0) {\n return western;\n }\n const arabicIndic = ARABIC_INDIC.indexOf(char);\n if (arabicIndic >= 0) {\n return arabicIndic;\n }\n return PERSIAN_INDIC.indexOf(char);\n}\n\nexport function formatDigits(value: string, digitForm: DigitFormId = 'western'): string {\n const target = digitSets[digitForm];\n return Array.from(value, (char) => {\n const value = digitValue(char);\n return value >= 0 ? target[value] : char;\n }).join('');\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport type { DocumentHijriDate, DocumentMeta, HijriMonthId } from './types.js';\n\nexport const BUTEX_BASMALA_LINE1 = 'بِسْمِ ٱللَّٰهِ ٱلرَّحْمَٰنِ ٱلرَّحِيمِ';\n\nexport const BUTEX_BASMALA_LINE2 = 'وَٱلصَّلَاةُ وَٱلسَّلَامُ عَلَىٰ رَسُولِ ٱللَّٰهِ';\n\nexport const BUTEX_BASMALA_SALAWAT = 'صَلَّى ٱللَّهُ عَلَيْهِ وَسَلَّمَ';\n\n/** Three-line basmala joined for UI / plain-text matchers. */\nexport const BUTEX_BASMALA = `${BUTEX_BASMALA_LINE1}\\n${BUTEX_BASMALA_LINE2}\\n${BUTEX_BASMALA_SALAWAT}`;\n\nexport const BUTEX_CLOSING_HAMDALA = 'الْحَمْدُ لِلَّهِ نَفَعَنَا بِعِلْمِهِ';\n\nfunction escapeButexTextArg(text: string): string {\n return text.replace(/\\\\/g, '\\\\textbackslash{}').replace(/[{}]/g, '\\\\$&');\n}\n\nfunction butexFontDisplayTex(macro: '\\\\butexdiwani' | '\\\\butexmaghribi', text: string): string {\n return `${macro}{${escapeButexTextArg(text)}}`;\n}\n\n/** Display-math body using BuTeX Diwani (for MathJax preview islands). */\nexport function butexDiwaniDisplayTex(text: string): string {\n return butexFontDisplayTex('\\\\butexdiwani', text);\n}\n\n/** Full display equation for XeLaTeX export. */\nexport function butexDiwaniDisplayLatex(text: string): string {\n return `\\\\[\\n${butexDiwaniDisplayTex(text)}\\n\\\\]`;\n}\n\n/** Display-math body using BuTeX Maghribi (for document chrome). */\nexport function butexMaghribiDisplayTex(text: string): string {\n return butexFontDisplayTex('\\\\butexmaghribi', text);\n}\n\n/** Full display equation using BuTeX Maghribi for XeLaTeX export. */\nexport function butexMaghribiDisplayLatex(text: string): string {\n return `\\\\[\\n${butexMaghribiDisplayTex(text)}\\n\\\\]`;\n}\n\nconst BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT] as const;\n\n/** Three-line Maghribi body for MathJax basmala islands. */\nexport function butexBasmalaDisplayTex(): string {\n return BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(' \\\\\\\\ ');\n}\n\n/** Standalone display equation when there is no \\\\maketitle (title-less docs). */\nexport function butexBasmalaDisplayLatex(): string {\n return `\\\\[\\n\\\\begin{gathered}\\n${BASMALA_LINES.map((line) => butexMaghribiDisplayTex(line)).join(' \\\\\\\\\\n')}\\n\\\\end{gathered}\\n\\\\]`;\n}\n\n/**\n * Keep \\\\maketitle inside the current column when twocolumn is on.\n * Standard article otherwise does \\\\twocolumn[\\\\@maketitle] and spans both columns.\n * Call after titling so \\\\@maketitle still includes \\\\pretitle hooks.\n */\nexport function butexInColumnMaketitleHook(): string {\n return String.raw`\\makeatletter\n\\renewcommand{\\maketitle}{%\n \\par\n \\begingroup\n \\renewcommand\\thefootnote{\\@fnsymbol\\c@footnote}%\n \\def\\@makefnmark{\\rlap{\\@textsuperscript{\\normalfont\\@thefnmark}}}%\n \\long\\def\\@makefntext##1{\\parindent 1em\\noindent\n \\hb@xt@1.8em{\\hss\\@textsuperscript{\\normalfont\\@thefnmark}}##1}%\n \\@maketitle\n \\thispagestyle{plain}\\@thanks\n \\endgroup\n \\setcounter{footnote}{0}%\n \\global\\let\\thanks\\relax\n \\global\\let\\maketitle\\relax\n \\global\\let\\@maketitle\\relax\n \\global\\let\\@thanks\\@empty\n \\global\\let\\@author\\@empty\n \\global\\let\\@date\\@empty\n \\global\\let\\@title\\@empty\n \\global\\let\\title\\relax\n \\global\\let\\author\\relax\n \\global\\let\\date\\relax\n \\global\\let\\and\\relax\n}\n\\makeatother`;\n}\n\n/** Titling hooks so the basmala stays attached to the visible title. */\nexport function butexBasmalaTitlingPreamble(options: { twocolumn?: boolean } = {}): string {\n const lines = [\n '\\\\usepackage{titling}',\n '\\\\pretitle{%',\n ' \\\\begin{center}',\n ...BASMALA_LINES.map((line, index) => {\n const suffix = index < BASMALA_LINES.length - 1 ? '\\\\\\\\' : '';\n return ` ${butexMaghribiDisplayTex(line)}${suffix}`;\n }),\n ' \\\\par\\\\vspace{1.5em}',\n ' \\\\LARGE',\n '}',\n '\\\\posttitle{\\\\par\\\\end{center}}',\n ];\n if (options.twocolumn) {\n lines.push(butexInColumnMaketitleHook());\n }\n return lines.join('\\n');\n}\nexport const HIJRI_YEAR_MIN = 1400;\nexport const HIJRI_YEAR_MAX = 1500;\n\nexport const HIJRI_MONTH_IDS: HijriMonthId[] = [\n 'محرم',\n 'صفر',\n 'ربيع الأول',\n 'ربيع الآخر',\n 'جمادى الأولى',\n 'جمادى الآخرة',\n 'رجب',\n 'شعبان',\n 'رمضان',\n 'شوال',\n 'ذو القعدة',\n 'ذو الحجة',\n];\n\nconst HIJRI_MONTH_LABELS_EN: Record<HijriMonthId, string> = {\n محرم: 'Muharram',\n صفر: 'Safar',\n 'ربيع الأول': 'Rabiʻ I',\n 'ربيع الآخر': 'Rabiʻ II',\n 'جمادى الأولى': 'Jumada I',\n 'جمادى الآخرة': 'Jumada II',\n رجب: 'Rajab',\n شعبان: 'Shaʻban',\n رمضان: 'Ramadan',\n شوال: 'Shawwal',\n 'ذو القعدة': 'Dhul Qaʻdah',\n 'ذو الحجة': 'Dhul Hijjah',\n};\n\n/** Legacy Latin month ids from earlier drafts — accepted on import only. */\nconst LEGACY_LATIN_MONTH: Record<string, HijriMonthId> = {\n muharram: 'محرم',\n safar: 'صفر',\n rabiAwwal: 'ربيع الأول',\n rabiThani: 'ربيع الآخر',\n jumadaAwwal: 'جمادى الأولى',\n jumadaThani: 'جمادى الآخرة',\n rajab: 'رجب',\n shaban: 'شعبان',\n ramadan: 'رمضان',\n shawwal: 'شوال',\n dhulQadah: 'ذو القعدة',\n dhulHijjah: 'ذو الحجة',\n};\n\nexport const DEFAULT_HIJRI_DATE: DocumentHijriDate = {\n day: 1,\n month: 'محرم',\n year: 1448,\n};\n\nexport function hijriMonthLabel(month: HijriMonthId, locale: ButexUiLocale = 'ar'): string {\n return locale === 'en' ? HIJRI_MONTH_LABELS_EN[month] : month;\n}\n\nexport function emptyDocumentMeta(): DocumentMeta {\n return {\n title: '',\n authors: '',\n date: { ...DEFAULT_HIJRI_DATE },\n abstract: '',\n };\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) {\n return min;\n }\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\nfunction isHijriMonthId(value: unknown): value is HijriMonthId {\n return typeof value === 'string' && (HIJRI_MONTH_IDS as string[]).includes(value);\n}\n\nfunction resolveHijriMonthId(value: unknown): HijriMonthId {\n if (isHijriMonthId(value)) {\n return value;\n }\n if (typeof value === 'string' && value in LEGACY_LATIN_MONTH) {\n return LEGACY_LATIN_MONTH[value]!;\n }\n return DEFAULT_HIJRI_DATE.month;\n}\n\nexport function normalizeDocumentHijriDate(value: unknown): DocumentHijriDate {\n if (typeof value !== 'object' || value === null) {\n return { ...DEFAULT_HIJRI_DATE };\n }\n const raw = value as Record<string, unknown>;\n const day = clampInt(typeof raw.day === 'number' ? raw.day : Number(raw.day), 1, 30);\n const year = clampInt(typeof raw.year === 'number' ? raw.year : Number(raw.year), HIJRI_YEAR_MIN, HIJRI_YEAR_MAX);\n const month = resolveHijriMonthId(raw.month);\n return { day, month, year };\n}\n\nexport function normalizeDocumentMeta(value: unknown): DocumentMeta {\n if (typeof value !== 'object' || value === null) {\n return emptyDocumentMeta();\n }\n const raw = value as Record<string, unknown>;\n return {\n title: typeof raw.title === 'string' ? raw.title : '',\n authors: typeof raw.authors === 'string' ? raw.authors : '',\n date: normalizeDocumentHijriDate(raw.date),\n abstract: typeof raw.abstract === 'string' ? raw.abstract : '',\n };\n}\n\nexport type DocumentMetaProp = Partial<Omit<DocumentMeta, 'date'>> & {\n date?: Partial<DocumentHijriDate>;\n};\n\n/** Prop fills gaps; JSON wins only when the key is present on the JSON object. */\nexport function mergeDocumentMeta(fromJson: unknown, fromProp?: DocumentMetaProp): DocumentMeta {\n const fromPropMeta: DocumentMeta = {\n title: typeof fromProp?.title === 'string' ? fromProp.title : '',\n authors: typeof fromProp?.authors === 'string' ? fromProp.authors : '',\n abstract: typeof fromProp?.abstract === 'string' ? fromProp.abstract : '',\n date: fromProp?.date\n ? normalizeDocumentHijriDate({ ...DEFAULT_HIJRI_DATE, ...fromProp.date })\n : { ...DEFAULT_HIJRI_DATE },\n };\n if (typeof fromJson !== 'object' || fromJson === null) {\n return fromPropMeta;\n }\n const json = fromJson as Record<string, unknown>;\n return {\n title: 'title' in json && typeof json.title === 'string' ? json.title : fromPropMeta.title,\n authors: 'authors' in json && typeof json.authors === 'string' ? json.authors : fromPropMeta.authors,\n abstract: 'abstract' in json && typeof json.abstract === 'string' ? json.abstract : fromPropMeta.abstract,\n date: 'date' in json ? normalizeDocumentHijriDate(json.date) : fromPropMeta.date,\n };\n}\n\n/** For live DocumentNode meta: prop fills empty title/authors/abstract; date patch merges. */\nexport function fillDocumentMetaGaps(current: DocumentMeta, fromProp?: DocumentMetaProp): DocumentMeta {\n if (!fromProp) {\n return cloneDocumentMeta(current);\n }\n return {\n title: current.title.trim().length > 0 ? current.title : typeof fromProp.title === 'string' ? fromProp.title : current.title,\n authors:\n current.authors.trim().length > 0\n ? current.authors\n : typeof fromProp.authors === 'string'\n ? fromProp.authors\n : current.authors,\n abstract:\n current.abstract.trim().length > 0\n ? current.abstract\n : typeof fromProp.abstract === 'string'\n ? fromProp.abstract\n : current.abstract,\n date: fromProp.date\n ? normalizeDocumentHijriDate({ ...current.date, ...fromProp.date })\n : { ...current.date },\n };\n}\n\nexport function documentHasMaketitle(meta: DocumentMeta): boolean {\n return meta.title.trim().length > 0 || meta.authors.trim().length > 0;\n}\n\nexport function documentHasAbstract(meta: DocumentMeta): boolean {\n return meta.abstract.trim().length > 0;\n}\n\nexport function documentHasTitleStack(meta: DocumentMeta): boolean {\n return documentHasMaketitle(meta) || documentHasAbstract(meta);\n}\n\nexport type FormatHijriDateOptions = {\n locale?: ButexUiLocale;\n digitForm?: DigitFormId;\n};\n\nexport function formatHijriDate(date: DocumentHijriDate, options: FormatHijriDateOptions | ButexUiLocale = 'ar'): string {\n const opts: FormatHijriDateOptions = typeof options === 'string' ? { locale: options } : options;\n const locale = opts.locale ?? 'ar';\n const digitForm: DigitFormId =\n opts.digitForm ?? (locale === 'en' ? 'western' : 'arabicIndic');\n const month = hijriMonthLabel(date.month, locale);\n const day = formatDigits(String(date.day), digitForm);\n const year = formatDigits(String(date.year), digitForm);\n if (locale === 'en') {\n return `${day} ${month} ${year} AH`;\n }\n return `${day} ${month} ${year}هـ`;\n}\n\nexport function cloneDocumentMeta(meta: DocumentMeta): DocumentMeta {\n return {\n title: meta.title,\n authors: meta.authors,\n date: { ...meta.date },\n abstract: meta.abstract,\n };\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { FormatCiteLabelOptions, Reference2, Reference2Json, ReferenceFieldSeparator } from './types.js';\nimport { documentId } from './ids.js';\n\nexport const DEFAULT_REFERENCE_FIELD_SEPARATOR: ReferenceFieldSeparator = '،';\n\nexport function normalizeReferenceFieldSeparator(value: unknown): ReferenceFieldSeparator {\n return value === ',' ? ',' : DEFAULT_REFERENCE_FIELD_SEPARATOR;\n}\n\nexport function referenceNumberMap(references: Array<Pick<Reference2, 'key'>>): Map<string, number> {\n const map = new Map<string, number>();\n references.forEach((reference, index) => {\n if (!map.has(reference.key)) {\n map.set(reference.key, index + 1);\n }\n });\n return map;\n}\n\nexport function resolveCiteNumbers(keys: string[], references: Array<Pick<Reference2, 'key'>>): Array<number | null> {\n const map = referenceNumberMap(references);\n return keys.map((key) => map.get(key) ?? null);\n}\n\nexport function formatCiteLabel(\n keys: string[],\n references: Array<Pick<Reference2, 'key'>>,\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const numbers = resolveCiteNumbers(keys, references).map((value) => (value === null ? '?' : String(value)));\n const display = documentDirection === 'rtl' ? [...numbers].reverse() : numbers;\n const separator = documentDirection === 'rtl' ? '،' : ', ';\n const body = display.map((part) => formatDigits(part, digitForm)).join(separator);\n return `[${body}]`;\n}\n\nexport function formatBibliographyNumber(index: number, options: FormatCiteLabelOptions = {}): string {\n const documentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n return formatDigits(String(index), digitForm);\n}\n\nexport function parseCiteKeys(source: string): string[] {\n const match = /^\\\\cite\\{([^}]*)\\}$/.exec(source.trim());\n if (!match) {\n return [];\n }\n return (match[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0);\n}\n\nexport function citeTokenLatex(keys: string[]): string {\n return `\\\\cite{${keys.join(',')}}`;\n}\n\nexport function referenceFromJson(json: Reference2Json): Reference2 {\n return {\n id: documentId('ref'),\n key: json.key,\n authors: typeof json.authors === 'string' ? json.authors : '',\n title: typeof json.title === 'string' ? json.title : '',\n year: typeof json.year === 'string' ? json.year : '',\n url: typeof json.url === 'string' ? json.url : '',\n venue: typeof json.venue === 'string' ? json.venue : '',\n fieldSeparator: normalizeReferenceFieldSeparator(json.field_separator),\n };\n}\n\nexport function createEmptyReference(partial: Partial<Reference2Json> = {}): Reference2 {\n return referenceFromJson({\n key: partial.key ?? `ref${String(Date.now()).slice(-4)}`,\n authors: partial.authors,\n title: partial.title,\n year: partial.year,\n url: partial.url,\n venue: partial.venue,\n field_separator: partial.field_separator,\n });\n}\n\n/** Joined authors/title/venue/year for preview and export (no \\\\bibitem wrapper). */\nexport function bibliographyEntryBody(\n reference: Pick<Reference2, 'authors' | 'title' | 'venue' | 'year' | 'fieldSeparator'>,\n separator: ReferenceFieldSeparator = reference.fieldSeparator,\n options: { digitForm?: DigitFormId } = {},\n): string {\n const year =\n options.digitForm !== undefined ? formatDigits(reference.year, options.digitForm) : reference.year;\n const parts = [reference.authors, reference.title, reference.venue, year].filter((part) => part.trim().length > 0);\n return parts.join(`${separator} `);\n}\n\nexport function bibliographyEntryLatex(reference: Reference2): string {\n const body = bibliographyEntryBody(reference);\n const url = reference.url.trim().length > 0 ? ` \\\\url{${reference.url}}` : '';\n return `\\\\bibitem{${reference.key}} ${body}${url}`.trim();\n}\n\n/**\n * Build an href for a bibliography URL. Values without a scheme become https://…\n * so the browser does not resolve them against the editor origin (e.g. localhost).\n * Leaves http(s)/mailto/ftp and other schemed URLs unchanged. Empty → ''.\n */\nexport function absoluteHttpHref(url: string): string {\n const trimmed = url.trim();\n if (trimmed.length === 0) {\n return '';\n }\n if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {\n return trimmed;\n }\n if (trimmed.startsWith('//')) {\n return `https:${trimmed}`;\n }\n return `https://${trimmed}`;\n}\n","import type { ChainNode } from '../arabic_ast.js';\n\ntype CommandRenderContext = {\n name: string;\n optionalArgs: ChainNode[];\n mandatoryArgs: ChainNode[];\n renderChain: (chain: ChainNode) => string;\n};\n\nexport function renderCommandCore(context: CommandRenderContext): string {\n const optional = context.optionalArgs.map((arg) => `[${context.renderChain(arg)}]`).join('');\n const mandatory = context.mandatoryArgs.map((arg) => `{${context.renderChain(arg)}}`).join('');\n return context.name + optional + mandatory;\n}\n","import { renderCommandCore } from './commands/index.js';\n\nexport type ArabicNodeJson = {\n node_type: string;\n expr?: string;\n name?: string;\n superscript?: ChainJson | null;\n subscript?: ChainJson | null;\n left_delim_expr?: string;\n right_delim_expr?: string;\n inner_expr?: ChainJson;\n optional_args?: ChainJson[];\n mandatory_args?: ChainJson[];\n opening?: string;\n closing?: string;\n lines?: ChainJson[];\n source_latex?: string;\n};\n\nexport type ChainJson = {\n node_type: 'ChainClass';\n chain: ArabicNodeJson[];\n};\n\nexport class State {\n // Empty for now, like the Python State placeholder used by BaseNode.\n}\n\nexport class BaseAstNode {\n state: State;\n superscript: ChainNode | null;\n subscript: ChainNode | null;\n nodeType: string;\n sourceLatex: string | null;\n\n constructor(state: State | null = null) {\n if (state === null) {\n state = new State();\n }\n\n this.state = state;\n this.superscript = null;\n this.subscript = null;\n this.nodeType = this.constructor.name;\n this.sourceLatex = null;\n }\n\n latex(): string {\n throw new Error('NotImplementedError');\n }\n\n arabicLatex(): string {\n throw new Error('NotImplementedError');\n }\n\n toArabicLatex(): string {\n return this.arabicLatex();\n }\n\n /** Latin-style scripts: `^{...}` and `_{...}` for english_json rendering. */\n latexScripts(): string {\n let s = '';\n\n if (this.superscript !== null) {\n s += '^{' + this.superscript.latex() + '}';\n }\n\n if (this.subscript !== null) {\n s += '_{' + this.subscript.latex() + '}';\n }\n\n return s;\n }\n\n /**\n * Arabic scripts use \\\\prescript{sup}{sub}{content} (matches reference Python output).\n * Call with rendered strings for sup/sub chains (may be empty strings).\n */\n arabicLatexScripts(sup: string, sub: string, content: string): string {\n if (sup !== '' || sub !== '') {\n return '\\\\prescript{' + sup + '}{' + sub + '}{' + content + '}';\n }\n return content;\n }\n}\n\nexport class ChainNode {\n chain: BaseAstNode[];\n\n constructor(chain: BaseAstNode[] = []) {\n this.chain = chain;\n }\n\n latex(): string {\n return this.chain.map((node) => node.latex()).join(' ');\n }\n toEnglishLatex(): string {\n return this.chain.map((node) => node.latex()).join(' ');\n }\n /** RTL: reverse order relative to Latin chain (see test/ref_tests.txt). */\n arabicLatex(): string {\n const reversed = this.chain.slice().reverse();\n return reversed.map((node) => node.arabicLatex()).join(' ');\n }\n\n toArabicLatex(): string {\n return this.arabicLatex();\n }\n}\n\nexport class NumberNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'NumberObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n return this.arabicLatexScripts(sup, sub, this.expr);\n }\n}\n\nexport class CharNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'CharObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n return this.arabicLatexScripts(sup, sub, this.expr);\n }\n}\n\n/**\n * Operator leaf: value comes from JSON as-is (English or Arabic side already chosen by the service).\n * Scripts are not appended (Python parity).\n */\nexport class OperatorNode extends BaseAstNode {\n expr: string;\n\n constructor(expr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'OperatorObject';\n this.expr = expr;\n }\n\n latex(): string {\n return this.expr;\n }\n\n arabicLatex(): string {\n return this.expr;\n }\n}\n\nexport class DelimiterNode extends BaseAstNode {\n leftDelimExpr: string;\n innerExpr: ChainNode;\n rightDelimExpr: string;\n\n constructor(leftDelimExpr: string, innerExpr: ChainNode, rightDelimExpr: string, state: State | null = null) {\n super(state);\n this.nodeType = 'DelimiterObject';\n this.leftDelimExpr = leftDelimExpr;\n this.innerExpr = innerExpr;\n this.rightDelimExpr = rightDelimExpr;\n }\n\n latex(): string {\n return this.leftDelimExpr + ' ' + this.innerExpr.latex() + this.rightDelimExpr + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n const content = this.leftDelimExpr + this.innerExpr.arabicLatex() + this.rightDelimExpr;\n return this.arabicLatexScripts(sup, sub, content);\n }\n}\n\nexport class CommandNode extends BaseAstNode {\n name: string;\n optionalArgs: ChainNode[];\n mandatoryArgs: ChainNode[];\n\n constructor(\n name: string,\n optionalArgs: ChainNode[] = [],\n mandatoryArgs: ChainNode[] = [],\n state: State | null = null\n ) {\n super(state);\n this.nodeType = 'CommandObject';\n this.name = name;\n this.optionalArgs = optionalArgs;\n this.mandatoryArgs = mandatoryArgs;\n }\n\n latex(): string {\n const content = renderCommandCore({\n name: this.name,\n optionalArgs: this.optionalArgs,\n mandatoryArgs: this.mandatoryArgs,\n renderChain: (chain) => chain.latex(),\n });\n return content + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n const arabicName =\n this.name === '\\\\sqrt' || this.name === '\\\\arabsqrt' ? '\\\\arsqrt' : this.name;\n const content = renderCommandCore({\n name: arabicName,\n optionalArgs: this.optionalArgs,\n mandatoryArgs: this.mandatoryArgs,\n renderChain: (chain) => chain.arabicLatex(),\n });\n return this.arabicLatexScripts(sup, sub, content);\n }\n}\n\nexport class EnvNode extends BaseAstNode {\n opening: string;\n lines: ChainNode[];\n closing: string;\n\n constructor(opening: string, lines: ChainNode[] = [], closing: string, state: State | null = null) {\n super(state);\n this.nodeType = 'EnvObject';\n this.opening = opening;\n this.lines = lines;\n this.closing = closing;\n }\n\n latex(): string {\n if (this.lines.length === 0) {\n return this.opening + this.closing + this.latexScripts();\n }\n\n const formattedLines = this.lines.map((line) => ` ${line.latex()}`);\n const content = formattedLines.join(' \\\\\\\\' + '\\n');\n return `${this.opening}\\n${content}\\n${this.closing}` + this.latexScripts();\n }\n\n arabicLatex(): string {\n const sup = this.superscript !== null ? this.superscript.arabicLatex() : '';\n const sub = this.subscript !== null ? this.subscript.arabicLatex() : '';\n\n if (this.lines.length === 0) {\n return this.arabicLatexScripts(sup, sub, this.opening + this.closing);\n }\n\n const formattedLines = this.lines.map((line) => ` ${line.arabicLatex()}`);\n const content = formattedLines.join(' \\\\\\\\' + '\\n');\n // Only the Arabic presentation differs: stored EnvObject stays canonical cases.\n const fullContent = this.opening === '\\\\begin{cases}' && this.closing === '\\\\end{cases}'\n ? `\\\\left.\\\\begin{array}{rl}\\n${content}\\n\\\\end{array}\\\\right\\\\}`\n : `${this.opening}\\n${content}\\n${this.closing}`;\n return this.arabicLatexScripts(sup, sub, fullContent);\n }\n}\n\ntype ParseMode = 'english' | 'arabic';\n\nfunction parseScripts(node: BaseAstNode, json: ArabicNodeJson, mode: ParseMode): void {\n node.sourceLatex = typeof json.source_latex === 'string' && json.source_latex.length > 0\n ? json.source_latex\n : null;\n if (json.superscript) {\n node.superscript = parseChain(json.superscript, mode);\n }\n\n if (json.subscript) {\n node.subscript = parseChain(json.subscript, mode);\n }\n}\n\nfunction parseNode(json: ArabicNodeJson, mode: ParseMode): BaseAstNode {\n if (json.node_type === 'DelimiterObject') {\n const node = parseDelimiter(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'OperatorObject') {\n if (typeof json.expr !== 'string') {\n throw new Error('OperatorObject requires string expr');\n }\n const node = new OperatorNode(json.expr);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'CommandObject') {\n const node = parseCommand(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (json.node_type === 'EnvObject') {\n const node = parseEnv(json, mode);\n parseScripts(node, json, mode);\n return node;\n }\n\n if (typeof json.expr !== 'string') {\n throw new Error(`${json.node_type} requires string expr`);\n }\n\n let node: BaseAstNode;\n\n if (json.node_type === 'NumberObject') {\n node = new NumberNode(json.expr);\n } else if (json.node_type === 'CharObject') {\n node = new CharNode(json.expr);\n } else {\n throw new Error(`Unsupported node_type: ${json.node_type}`);\n }\n\n parseScripts(node, json, mode);\n return node;\n}\n\nfunction parseDelimiter(json: ArabicNodeJson, mode: ParseMode): DelimiterNode {\n if (typeof json.left_delim_expr !== 'string') {\n throw new Error('DelimiterObject requires string left_delim_expr');\n }\n\n if (!json.inner_expr || json.inner_expr.node_type !== 'ChainClass') {\n throw new Error('DelimiterObject requires ChainClass inner_expr');\n }\n\n if (typeof json.right_delim_expr !== 'string') {\n throw new Error('DelimiterObject requires string right_delim_expr');\n }\n\n const innerExpr = parseChain(json.inner_expr, mode);\n return new DelimiterNode(json.left_delim_expr, innerExpr, json.right_delim_expr);\n}\n\nfunction parseCommand(json: ArabicNodeJson, mode: ParseMode): CommandNode {\n if (typeof json.name !== 'string') {\n throw new Error('CommandObject requires string name');\n }\n\n const optionalJson = Array.isArray(json.optional_args) ? json.optional_args : [];\n const mandatoryJson = Array.isArray(json.mandatory_args) ? json.mandatory_args : [];\n const optionalArgs = optionalJson.map((arg) => parseChain(arg, mode));\n const mandatoryArgs = mandatoryJson.map((arg) => parseChain(arg, mode));\n\n return new CommandNode(json.name, optionalArgs, mandatoryArgs);\n}\n\nfunction parseEnv(json: ArabicNodeJson, mode: ParseMode): EnvNode {\n if (typeof json.opening !== 'string') {\n throw new Error('EnvObject requires string opening');\n }\n\n if (typeof json.closing !== 'string') {\n throw new Error('EnvObject requires string closing');\n }\n\n if (!Array.isArray(json.lines)) {\n throw new Error('EnvObject requires lines array');\n }\n\n const lines = json.lines.map((line) => parseChain(line, mode));\n return new EnvNode(json.opening, lines, json.closing);\n}\n\nfunction parseChain(json: ChainJson, mode: ParseMode): ChainNode {\n if (json.node_type !== 'ChainClass') {\n throw new Error(`Expected ChainClass, got: ${json.node_type}`);\n }\n\n const nodes = json.chain.map((childJson) => parseNode(childJson, mode));\n return new ChainNode(nodes);\n}\n\n/** Import AST from Python english_dict JSON (Latin expr fields). */\nexport function fromEnglishJson(json: ChainJson | ArabicNodeJson): ChainNode | BaseAstNode {\n if (json.node_type === 'ChainClass') {\n return parseChain(json as ChainJson, 'english');\n }\n return parseNode(json, 'english');\n}\n\n/** Import AST from Python arabic_dict JSON (Arabic expr fields). Same shape as English; values differ. */\nexport function fromArabicJson(json: ChainJson | ArabicNodeJson): ChainNode | BaseAstNode {\n if (json.node_type === 'ChainClass') {\n return parseChain(json as ChainJson, 'arabic');\n }\n return parseNode(json, 'arabic');\n}\n","import {\n BaseAstNode,\n ChainNode,\n CharNode,\n CommandNode,\n DelimiterNode,\n EnvNode,\n NumberNode,\n OperatorNode,\n fromArabicJson,\n fromEnglishJson,\n type ArabicNodeJson,\n type ChainJson,\n} from '../../ast/arabic_ast.js';\nimport type { DocumentParseMode, MathNode, MathObjectJson } from './types.js';\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isMathObjectJson(value: unknown): value is MathObjectJson {\n return isObject(value) && value.node_type === 'MathObject';\n}\n\nfunction assertChainNode(value: unknown): ChainNode {\n if (!(value instanceof ChainNode)) {\n throw new Error('MathObject lines must parse to ChainNode');\n }\n return value;\n}\n\nexport function fromMathObjectJson(json: unknown, mode: DocumentParseMode = 'english'): MathNode {\n if (!isMathObjectJson(json)) {\n throw new Error('MathObject requires node_type \"MathObject\"');\n }\n\n if (typeof json.math_mode !== 'string') {\n throw new Error('MathObject requires string math_mode');\n }\n\n if (typeof json.closing !== 'string') {\n throw new Error('MathObject requires string closing');\n }\n\n if (!Array.isArray(json.lines) || json.lines.length === 0) {\n throw new Error('MathObject requires non-empty lines array');\n }\n\n const parseChain = mode === 'arabic' ? fromArabicJson : fromEnglishJson;\n const lines = json.lines.map((line) => assertChainNode(parseChain(line)));\n\n return {\n nodeType: 'MathObject',\n mathMode: json.math_mode,\n lines,\n closing: json.closing,\n };\n}\n\nfunction scriptsToJson(\n node: BaseAstNode,\n path: string,\n): Pick<ArabicNodeJson, 'superscript' | 'subscript' | 'source_latex'> {\n return {\n ...(node.superscript ? { superscript: chainToJson(node.superscript, `${path}.superscript`) } : {}),\n ...(node.subscript ? { subscript: chainToJson(node.subscript, `${path}.subscript`) } : {}),\n ...(node.sourceLatex ? { source_latex: node.sourceLatex } : {}),\n };\n}\n\nfunction nodeToJson(node: BaseAstNode, path: string): ArabicNodeJson {\n const scripts = scriptsToJson(node, path);\n if (node instanceof CharNode || node instanceof NumberNode || node instanceof OperatorNode) {\n return { node_type: node.nodeType, expr: node.expr, ...scripts };\n }\n if (node instanceof DelimiterNode) {\n return {\n node_type: 'DelimiterObject',\n left_delim_expr: node.leftDelimExpr,\n inner_expr: chainToJson(node.innerExpr, `${path}.inner_expr`),\n right_delim_expr: node.rightDelimExpr,\n ...scripts,\n };\n }\n if (node instanceof CommandNode) {\n return {\n node_type: 'CommandObject',\n name: node.name,\n optional_args: node.optionalArgs.map((arg, index) => chainToJson(arg, `${path}.optional_args[${String(index)}]`)),\n mandatory_args: node.mandatoryArgs.map((arg, index) => chainToJson(arg, `${path}.mandatory_args[${String(index)}]`)),\n ...scripts,\n };\n }\n if (node instanceof EnvNode) {\n return {\n node_type: 'EnvObject',\n opening: node.opening,\n lines: node.lines.map((line, index) => chainToJson(line, `${path}.lines[${String(index)}]`)),\n closing: node.closing,\n ...scripts,\n };\n }\n throw new Error(`Unsupported runtime math node at ${path}: ${node.nodeType}`);\n}\n\nfunction chainToJson(chain: ChainNode, path: string): ChainJson {\n if (!(chain instanceof ChainNode)) {\n throw new Error(`Expected live ChainNode at ${path}`);\n }\n return {\n node_type: 'ChainClass',\n chain: chain.chain.map((node, index) => nodeToJson(node, `${path}.chain[${String(index)}]`)),\n };\n}\n\nexport function toMathObjectJson(math: MathNode): MathObjectJson {\n if (math.nodeType !== 'MathObject' || !Array.isArray(math.lines) || math.lines.length === 0) {\n throw new Error('Cannot serialize invalid runtime MathObject');\n }\n return {\n node_type: 'MathObject',\n math_mode: math.mathMode,\n lines: math.lines.map((line, index) => chainToJson(line, `$.lines[${String(index)}]`)),\n closing: math.closing,\n };\n}\n\nexport function renderMathNodeLatex(math: MathNode): string {\n const lines = math.lines.map((line) => line.arabicLatex());\n\n if (math.mathMode === '$' || math.mathMode === '\\\\(') {\n return math.mathMode + lines.join(' ') + math.closing;\n }\n\n if (math.mathMode === '$$' || math.mathMode === '\\\\[') {\n if (lines.length === 1) {\n return math.mathMode + '\\n' + lines[0] + '\\n' + math.closing;\n }\n return math.mathMode + '\\n' + lines.map((line) => ` ${line}`).join(' \\\\\\\\\\n') + '\\n' + math.closing;\n }\n\n if (lines.length === 1) {\n return `${math.mathMode}\\n ${lines[0]}\\n${math.closing}`;\n }\n\n return `${math.mathMode}\\n${lines.map((line) => ` ${line}`).join(' \\\\\\\\\\n')}\\n${math.closing}`;\n}\n\nexport function isDisplayMathNode(math: MathNode): boolean {\n return math.mathMode === '$$' || math.mathMode === '\\\\[' || math.mathMode.startsWith('\\\\begin{');\n}\n","import { formatDigits } from '../editor/digits.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport { formatBibliographyNumber } from './citations.js';\nimport { documentId } from './ids.js';\nimport type {\n DocumentBlock,\n DocumentDirection,\n DocumentNode,\n FormatCiteLabelOptions,\n ImageBlock2,\n InlineField2,\n MathToken2,\n TableBlock2,\n} from './types.js';\n\nexport type DocumentLabelKind = 'fig' | 'tab' | 'eq';\n\nexport type DocumentLabelEntry = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n /** Block id for fig/tab, or math token id for eq. */\n ownerId: string;\n number: number;\n};\n\nexport type FloatMetaPatch = {\n centered?: boolean;\n captionEnabled?: boolean;\n caption?: string;\n labelEnabled?: boolean;\n label?: string;\n};\n\nexport function defaultFloatMeta(): {\n centered: true;\n captionEnabled: false;\n caption: string;\n captionField: InlineField2;\n labelEnabled: false;\n label: string;\n} {\n return {\n centered: true,\n captionEnabled: false,\n caption: '',\n captionField: {\n id: documentId('field'),\n tokens: [{ id: documentId('text'), kind: 'text', text: '' }],\n },\n labelEnabled: false,\n label: '',\n };\n}\n\nexport function parseFloatMetaFromJson(json: {\n caption?: string;\n label?: string;\n caption_enabled?: boolean;\n label_enabled?: boolean;\n centered?: boolean;\n}): {\n centered: boolean;\n captionEnabled: boolean;\n caption: string;\n labelEnabled: boolean;\n label: string;\n} {\n const caption = typeof json.caption === 'string' ? json.caption : '';\n const label = typeof json.label === 'string' ? json.label : '';\n return {\n centered: json.centered !== false,\n captionEnabled: json.caption_enabled === true || (typeof json.caption_enabled !== 'boolean' && caption.length > 0),\n caption,\n labelEnabled: json.label_enabled === true || (typeof json.label_enabled !== 'boolean' && label.trim().length > 0),\n label,\n };\n}\n\nexport function parseRefKeys(source: string): { keys: string[]; refCommand: 'ref' | 'eqref' } {\n const eqref = /^\\\\eqref\\{([^}]*)\\}$/.exec(source.trim());\n if (eqref) {\n return {\n refCommand: 'eqref',\n keys: (eqref[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0),\n };\n }\n const ref = /^\\\\ref\\{([^}]*)\\}$/.exec(source.trim());\n if (ref) {\n return {\n refCommand: 'ref',\n keys: (ref[1] ?? '')\n .split(',')\n .map((key) => key.trim())\n .filter((key) => key.length > 0),\n };\n }\n return { keys: [], refCommand: 'ref' };\n}\n\nexport function refTokenLatex(keys: string[], refCommand: 'ref' | 'eqref'): string {\n const command = refCommand === 'eqref' ? '\\\\eqref' : '\\\\ref';\n return `${command}{${keys.join(',')}}`;\n}\n\n/** Deterministic, reversible, TeX-safe reference key from a persisted target ID. */\nfunction implicitObjectKey(kind: string, ownerId: string, unitId?: string): string {\n const hex = (value: string): string =>\n Array.from(new TextEncoder().encode(value), (byte) => byte.toString(16).padStart(2, '0')).join('');\n const scope = unitId === undefined ? 'a' : 'u' + hex(unitId);\n return kind + ':butex-auto-' + scope + '-' + hex(ownerId);\n}\n\nexport function implicitReferenceKey(kind: DocumentLabelKind, ownerId: string, unitId?: string): string {\n return implicitObjectKey(kind, ownerId, unitId);\n}\n\nexport function implicitHeadingReferenceKey(kind: 'section' | 'subsection' | 'subsubsection', ownerId: string, unitId: string): string {\n return implicitObjectKey(kind, ownerId, unitId);\n}\n\n/** Single-number display forms supported by the article reference model. */\nexport function supportsSingleEquationNumbering(token: MathToken2): boolean {\n return token.display && (\n token.opening === '\\\\[' || token.opening === String.fromCharCode(36, 36) ||\n token.opening === '\\\\begin{equation}' || token.opening === '\\\\begin{equation*}'\n );\n}\n\n/** Explicit numbering wins; legacy labeled/equation-environment math stays numbered. */\nexport function isNumberedEquation(token: MathToken2): boolean {\n if (!supportsSingleEquationNumbering(token)) return false;\n if (typeof token.numbered === 'boolean') return token.numbered;\n return token.opening === '\\\\begin{equation}' ||\n (Boolean(token.labelEnabled) && Boolean(token.label?.trim()));\n}\n\nexport function isNumberedFloat(block: ImageBlock2 | TableBlock2): boolean {\n return (block.captionEnabled && block.caption.trim().length > 0) ||\n (block.labelEnabled && block.label.trim().length > 0);\n}\n\nexport type DocumentReferenceTarget = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n ownerId: string;\n /** null means a displayed equation that has not been numbered. */\n number: number | null;\n manualKey?: string;\n};\n\n/** Projection of object identities and ordinals; never mutates document state. */\nexport function collectDocumentReferenceTargets(document: DocumentNode): DocumentReferenceTarget[] {\n const targets: DocumentReferenceTarget[] = [];\n const counters: Record<DocumentLabelKind, number> = { fig: 0, tab: 0, eq: 0 };\n function append(kind: DocumentLabelKind, ownerId: string, caption: string, numbered: boolean, manualKey = ''): void {\n if (numbered) counters[kind] += 1;\n targets.push({\n key: implicitReferenceKey(kind, ownerId),\n kind, ownerId, caption,\n number: numbered ? counters[kind] : null,\n ...(manualKey.trim() ? { manualKey: manualKey.trim() } : {}),\n });\n }\n function visitField(field: InlineField2): void {\n for (const token of field.tokens) {\n if (token.kind === 'math' && supportsSingleEquationNumbering(token)) {\n append('eq', token.id, '', isNumberedEquation(token), token.labelEnabled ? token.label ?? '' : '');\n }\n }\n }\n function walk(blocks: DocumentBlock[]): void {\n for (const block of blocks) {\n if (block.kind === 'image' || block.kind === 'table') {\n append(\n block.kind === 'image' ? 'fig' : 'tab',\n block.id, block.captionEnabled ? block.caption : '',\n isNumberedFloat(block), block.labelEnabled ? block.label : '',\n );\n if (block.captionEnabled) visitField(block.captionField);\n if (block.kind === 'table') {\n for (const row of block.rows) for (const cell of row) visitField(cell);\n }\n } else if (block.kind === 'textBlock') {\n visitField(block.field);\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n visitField(item.field);\n walk(item.blocks);\n }\n }\n }\n }\n walk(document.blocks);\n return targets;\n}\n\n/** Author-managed manual labels only; auto keys are not editable author metadata. */\nexport function collectDocumentLabels(document: DocumentNode): DocumentLabelEntry[] {\n return collectDocumentReferenceTargets(document)\n .filter((target): target is DocumentReferenceTarget & { number: number; manualKey: string } =>\n target.number !== null && Boolean(target.manualKey))\n .map(({ manualKey, kind, caption, ownerId, number }) => ({ key: manualKey, kind, caption, ownerId, number }));\n}\n\n/** Key collision checks include generated aliases without adding persistence fields. */\nexport function collectDocumentKeyLabels(document: DocumentNode): Array<Pick<DocumentLabelEntry, 'key' | 'ownerId'>> {\n return collectDocumentReferenceTargets(document).filter((target) => target.number !== null)\n .flatMap((target) => [\n { key: target.key, ownerId: target.ownerId },\n ...(target.manualKey && target.manualKey !== target.key\n ? [{ key: target.manualKey, ownerId: target.ownerId }]\n : []),\n ]);\n}\n\nexport function labelNumberMap(document: DocumentNode): Map<string, { kind: DocumentLabelKind; number: number }> {\n const map = new Map<string, { kind: DocumentLabelKind; number: number }>();\n for (const target of collectDocumentReferenceTargets(document)) {\n if (target.number === null) continue;\n for (const key of [target.key, target.manualKey]) {\n if (key && !map.has(key)) map.set(key, { kind: target.kind, number: target.number });\n }\n }\n return map;\n}\n\nexport type FormatFloatCaptionTitleOptions = {\n uiLocale?: ButexUiLocale;\n documentDirection?: DocumentDirection;\n digitForm?: DigitFormId;\n};\n\nfunction labelKindWord(kind: DocumentLabelKind, uiLocale: ButexUiLocale): string {\n if (kind === 'fig') {\n return uiLocale === 'ar' ? 'الشكل' : 'Figure';\n }\n if (kind === 'tab') {\n return uiLocale === 'ar' ? 'الجدول' : 'Table';\n }\n return uiLocale === 'ar' ? 'المعادلة' : 'Equation';\n}\n\n/** Localized numbered float/equation title: الشكل ١ / Figure 1 / المعادلة ١. */\nexport function formatFloatCaptionTitle(\n kind: DocumentLabelKind,\n number: number,\n options: FormatFloatCaptionTitleOptions = {},\n): string {\n const locale = options.uiLocale ?? 'ar';\n const digits = formatBibliographyNumber(number, {\n documentDirection: options.documentDirection ?? (locale === 'ar' ? 'rtl' : 'ltr'),\n digitForm: options.digitForm ?? (locale === 'ar' ? 'arabicIndic' : 'western'),\n });\n return `${labelKindWord(kind, locale)} ${digits}`;\n}\n\n/** Caption line as shown in document preview: الشكل ١: نص / Figure 1. text. */\nexport function formatFloatCaptionPreview(\n title: string,\n caption: string | undefined,\n uiLocale: ButexUiLocale = 'ar',\n): string {\n const trimmed = caption?.trim() ?? '';\n if (trimmed.length === 0) {\n return title;\n }\n const separator = uiLocale === 'ar' ? ': ' : '. ';\n return `${title}${separator}${trimmed}`;\n}\n\nexport function formatRefLabel(\n keys: string[],\n document: DocumentNode,\n refCommand: 'ref' | 'eqref',\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection: DocumentDirection = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const uiLocale: ButexUiLocale = documentDirection === 'rtl' ? 'ar' : 'en';\n const map = labelNumberMap(document);\n const parts = keys.map((key) => {\n const hit = map.get(key);\n if (!hit) {\n return refCommand === 'eqref' ? '(?)' : '?';\n }\n const digits = formatDigits(String(hit.number), digitForm);\n const numberLabel = refCommand === 'eqref' ? `(${digits})` : digits;\n return `${labelKindWord(hit.kind, uiLocale)} ${numberLabel}`;\n });\n return parts.join(documentDirection === 'rtl' ? '،' : ', ');\n}\n\nexport function stripDisplayMathDelimiters(source: string): string {\n const trimmed = source.trim();\n if (trimmed.startsWith('\\\\[') && trimmed.endsWith('\\\\]')) {\n return trimmed.slice(2, -2).trim();\n }\n if (trimmed.startsWith('$$') && trimmed.endsWith('$$')) {\n return trimmed.slice(2, -2).trim();\n }\n for (const environment of ['equation', 'equation*']) {\n const opening = `\\\\begin{${environment}}`;\n const closing = `\\\\end{${environment}}`;\n if (trimmed.startsWith(opening) && trimmed.endsWith(closing)) {\n return trimmed.slice(opening.length, -closing.length).trim();\n }\n }\n return trimmed;\n}\n\nexport function applyFloatMetaPatch<T extends ImageBlock2 | TableBlock2>(block: T, patch: FloatMetaPatch): void {\n if (typeof patch.centered === 'boolean') {\n block.centered = patch.centered;\n }\n if (typeof patch.captionEnabled === 'boolean') {\n block.captionEnabled = patch.captionEnabled;\n }\n if (typeof patch.caption === 'string') {\n block.caption = patch.caption;\n const existingText = block.captionField.tokens.find((token) => token.kind === 'text');\n block.captionField.tokens = [\n {\n id: existingText?.id ?? documentId('text'),\n kind: 'text',\n text: patch.caption,\n },\n ];\n }\n if (typeof patch.labelEnabled === 'boolean') {\n block.labelEnabled = patch.labelEnabled;\n }\n if (typeof patch.label === 'string') {\n block.label = patch.label;\n }\n}\n","import { citeTokenLatex } from './citations.js';\nimport { documentId } from './ids.js';\nimport { refTokenLatex } from './labels.js';\nimport type {\n DocumentInlineIdsJson,\n DocumentInlineTokenIdJson,\n InlineField2,\n InlineToken2,\n} from './types.js';\n\nexport type DocumentIdentityState = {\n blockIds: Set<string>;\n itemIds: Set<string>;\n fieldIds: Set<string>;\n tokenIds: Set<string>;\n};\n\nexport function createDocumentIdentityState(): DocumentIdentityState {\n return {\n blockIds: new Set<string>(),\n itemIds: new Set<string>(),\n fieldIds: new Set<string>(),\n tokenIds: new Set<string>(),\n };\n}\n\nexport function importedOrGeneratedId(value: unknown, prefix: string, used: Set<string>): string {\n const imported = typeof value === 'string' ? value.trim() : '';\n if (imported.length > 0 && !used.has(imported)) {\n used.add(imported);\n return imported;\n }\n\n let generated = documentId(prefix);\n while (used.has(generated)) {\n generated = documentId(prefix);\n }\n used.add(generated);\n return generated;\n}\n\nexport function inlineTokenSource(token: InlineToken2): string {\n if (token.kind === 'text') {\n return token.text;\n }\n if (token.kind === 'math') {\n return token.source;\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n return refTokenLatex(token.keys, token.refCommand);\n}\n\nexport function inlineIdsFromField(field: InlineField2): DocumentInlineIdsJson {\n let offset = 0;\n const tokens = field.tokens.map((token): DocumentInlineTokenIdJson => {\n const start = offset;\n offset += inlineTokenSource(token).length;\n return { id: token.id, kind: token.kind, start, end: offset };\n });\n return { field_id: field.id, tokens };\n}\n\nfunction isAlignedSidecar(value: unknown, field: InlineField2): value is DocumentInlineIdsJson {\n if (typeof value !== 'object' || value === null || !Array.isArray((value as DocumentInlineIdsJson).tokens)) {\n return false;\n }\n const tokens = (value as DocumentInlineIdsJson).tokens;\n const expected = inlineIdsFromField(field).tokens;\n if (tokens.length !== expected.length) {\n return false;\n }\n return tokens.every((token, index) => {\n const expectedToken = expected[index];\n return (\n typeof token === 'object' &&\n token !== null &&\n expectedToken !== undefined &&\n token.kind === expectedToken.kind &&\n token.start === expectedToken.start &&\n token.end === expectedToken.end\n );\n });\n}\n\nexport function applyImportedInlineIds(\n field: InlineField2,\n sidecar: unknown,\n state: DocumentIdentityState,\n): InlineField2 {\n field.id = importedOrGeneratedId(\n typeof sidecar === 'object' && sidecar !== null ? (sidecar as { field_id?: unknown }).field_id : undefined,\n 'field',\n state.fieldIds,\n );\n\n const aligned = isAlignedSidecar(sidecar, field);\n field.tokens.forEach((token, index) => {\n token.id = importedOrGeneratedId(aligned ? sidecar.tokens[index]?.id : undefined, token.kind, state.tokenIds);\n });\n return field;\n}\n","import type { DetectedInlineSpan2, DetectedMathSpan2 } from './types.js';\nimport { parseCiteKeys } from './citations.js';\nimport { parseRefKeys } from './labels.js';\n\nconst MATH_ENVIRONMENTS = new Set([\n 'equation',\n 'equation*',\n 'align',\n 'align*',\n 'aligned',\n 'gather',\n 'gather*',\n 'multline',\n 'multline*',\n]);\n\nfunction isEscaped(value: string, index: number): boolean {\n let slashCount = 0;\n let i = index - 1;\n while (i >= 0 && value[i] === '\\\\') {\n slashCount += 1;\n i -= 1;\n }\n return slashCount % 2 === 1;\n}\n\nfunction findClosingDollar(value: string, start: number): number {\n let i = start;\n while (i < value.length) {\n if (value[i] === '$' && !isEscaped(value, i)) {\n return i;\n }\n i += 1;\n }\n return -1;\n}\n\nfunction environmentSpan(value: string, start: number): DetectedMathSpan2 | null {\n const match = /^\\\\begin\\{([A-Za-z*]+)\\}/.exec(value.slice(start));\n if (!match) {\n return null;\n }\n\n const envName = match[1] ?? '';\n if (!MATH_ENVIRONMENTS.has(envName)) {\n return null;\n }\n\n const opening = match[0] ?? '';\n const closing = `\\\\end{${envName}}`;\n const closingStart = value.indexOf(closing, start + opening.length);\n if (closingStart < 0) {\n return null;\n }\n\n const end = closingStart + closing.length;\n return { start, end, source: value.slice(start, end), opening, closing, display: true };\n}\n\nfunction citeSpan(value: string, start: number): DetectedInlineSpan2 | null {\n if (!value.startsWith('\\\\cite{', start) || isEscaped(value, start)) {\n return null;\n }\n const openBrace = start + '\\\\cite'.length;\n if (value[openBrace] !== '{') {\n return null;\n }\n let depth = 0;\n for (let i = openBrace; i < value.length; i += 1) {\n const char = value[i];\n if (char === '{' && !isEscaped(value, i)) {\n depth += 1;\n continue;\n }\n if (char === '}' && !isEscaped(value, i)) {\n depth -= 1;\n if (depth === 0) {\n const end = i + 1;\n const source = value.slice(start, end);\n return { kind: 'cite', start, end, source, keys: parseCiteKeys(source) };\n }\n }\n }\n return null;\n}\n\nfunction refSpan(value: string, start: number): DetectedInlineSpan2 | null {\n const eqrefPrefix = '\\\\eqref{';\n const refPrefix = '\\\\ref{';\n const isEqref = value.startsWith(eqrefPrefix, start) && !isEscaped(value, start);\n const isRef = value.startsWith(refPrefix, start) && !isEscaped(value, start);\n if (!isEqref && !isRef) {\n return null;\n }\n const refCommand: 'ref' | 'eqref' = isEqref ? 'eqref' : 'ref';\n const prefix = isEqref ? eqrefPrefix : refPrefix;\n\n const openBrace = start + prefix.length - 1;\n if (value[openBrace] !== '{') {\n return null;\n }\n let depth = 0;\n for (let i = openBrace; i < value.length; i += 1) {\n const char = value[i];\n if (char === '{' && !isEscaped(value, i)) {\n depth += 1;\n continue;\n }\n if (char === '}' && !isEscaped(value, i)) {\n depth -= 1;\n if (depth === 0) {\n const end = i + 1;\n const source = value.slice(start, end);\n const parsed = parseRefKeys(source);\n return { kind: 'ref', start, end, source, keys: parsed.keys, refCommand };\n }\n }\n }\n return null;\n}\n\nfunction mathSpanAt(value: string, i: number): DetectedMathSpan2 | null {\n if (value.startsWith('\\\\begin{', i)) {\n return environmentSpan(value, i);\n }\n\n if (value.startsWith('\\\\(', i)) {\n const close = value.indexOf('\\\\)', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '\\\\(', closing: '\\\\)', display: false };\n }\n }\n\n if (value.startsWith('\\\\[', i)) {\n const close = value.indexOf('\\\\]', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '\\\\[', closing: '\\\\]', display: true };\n }\n }\n\n if (value.startsWith('$$', i) && !isEscaped(value, i)) {\n const close = value.indexOf('$$', i + 2);\n if (close >= 0) {\n const end = close + 2;\n return { start: i, end, source: value.slice(i, end), opening: '$$', closing: '$$', display: true };\n }\n }\n\n if (value[i] === '$' && !isEscaped(value, i)) {\n const close = findClosingDollar(value, i + 1);\n if (close >= 0) {\n const end = close + 1;\n return { start: i, end, source: value.slice(i, end), opening: '$', closing: '$', display: false };\n }\n }\n\n return null;\n}\n\n/** Math-only spans (used for math_objects alignment counts). */\nexport function detectMathSpans(value: string): DetectedMathSpan2[] {\n return detectInlineSpans(value)\n .filter((span): span is DetectedInlineSpan2 & { kind: 'math' } => span.kind === 'math')\n .map((span) => ({\n start: span.start,\n end: span.end,\n source: span.source,\n opening: span.opening,\n closing: span.closing,\n display: span.display,\n }));\n}\n\n/** Left-to-right math + \\\\cite + \\\\ref/\\\\eqref spans without overlap. */\nexport function detectInlineSpans(value: string): DetectedInlineSpan2[] {\n const spans: DetectedInlineSpan2[] = [];\n let i = 0;\n\n while (i < value.length) {\n const cite = citeSpan(value, i);\n if (cite) {\n spans.push(cite);\n i = cite.end;\n continue;\n }\n\n const ref = refSpan(value, i);\n if (ref) {\n spans.push(ref);\n i = ref.end;\n continue;\n }\n\n const math = mathSpanAt(value, i);\n if (math) {\n spans.push({ kind: 'math', ...math });\n i = math.end;\n continue;\n }\n\n i += 1;\n }\n\n return spans;\n}\n","import { fromMathObjectJson } from '../shared/math-document/mathObject.js';\nimport { normalizeDocumentMeta, emptyDocumentMeta } from './articleMeta.js';\nimport { referenceFromJson } from './citations.js';\nimport { documentId } from './ids.js';\nimport {\n applyImportedInlineIds,\n createDocumentIdentityState,\n importedOrGeneratedId,\n type DocumentIdentityState,\n} from './inlineIdentity.js';\nimport { detectInlineSpans, detectMathSpans } from './inlineScanner.js';\nimport { parseFloatMetaFromJson } from './labels.js';\nimport type {\n BibliographyBlock2,\n DocumentBlock,\n DocumentBlockMetadata,\n DocumentBlockJson,\n DocumentDiagnostic,\n DocumentMathObjectJson,\n DocumentListItemJson,\n DocumentNode,\n DocumentParseMode,\n ImageBlock2,\n ImportDocumentOptions,\n InlineField2,\n InlineToken2,\n ListBlock2,\n ListItem2,\n RawBlock2,\n Reference2,\n Reference2Json,\n TableBlock2,\n TextFormatSpan2Json,\n TextStyle2,\n TextBlock2,\n} from './types.js';\n\nconst TEXT_COMMANDS = new Set(['\\\\section', '\\\\subsection', '\\\\subsubsection', '\\\\paragraph']);\nconst LIST_COMMANDS = new Set(['\\\\begin{itemize}', '\\\\begin{enumerate}']);\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction requireString(value: unknown, message: string): string {\n if (typeof value !== 'string') {\n throw new Error(message);\n }\n return value;\n}\n\nfunction isRecordOfStrings(value: unknown): value is Record<string, string> {\n return isObject(value) && Object.values(value).every((entry) => typeof entry === 'string');\n}\n\nfunction asBlockJson(value: unknown): DocumentBlockJson {\n if (!isObject(value)) {\n throw new Error('Document block must be an object');\n }\n if (typeof value.command !== 'string') {\n throw new Error('Document block requires string command');\n }\n return value as DocumentBlockJson;\n}\n\nfunction blockIdFromJson(json: DocumentBlockJson, state: DocumentIdentityState): string {\n return importedOrGeneratedId(json.id, 'block', state.blockIds);\n}\n\nfunction metadataFromJson(value: unknown): { metadata?: DocumentBlockMetadata } {\n if (!isObject(value) || (value.source !== 'agent' && value.source !== 'user')) {\n return {};\n }\n return { metadata: { source: value.source } };\n}\n\nfunction pushDiagnostic(diagnostics: DocumentDiagnostic[], options: ImportDocumentOptions, path: string, message: string): void {\n if (options.strict) {\n throw new Error(message);\n }\n diagnostics.push({ code: 'math_alignment', message, path });\n}\n\nfunction parseReferences(json: unknown): Reference2[] {\n if (!Array.isArray(json)) {\n return [];\n }\n const references: Reference2[] = [];\n for (const entry of json) {\n if (!isObject(entry) || typeof entry.key !== 'string' || entry.key.trim().length === 0) {\n continue;\n }\n references.push(\n referenceFromJson({\n key: entry.key.trim(),\n authors: typeof entry.authors === 'string' ? entry.authors : undefined,\n title: typeof entry.title === 'string' ? entry.title : undefined,\n year: typeof entry.year === 'string' ? entry.year : undefined,\n url: typeof entry.url === 'string' ? entry.url : undefined,\n venue: typeof entry.venue === 'string' ? entry.venue : undefined,\n field_separator:\n entry.field_separator === ',' || entry.field_separator === '،'\n ? entry.field_separator\n : undefined,\n } satisfies Reference2Json),\n );\n }\n return references;\n}\n\nexport function createInlineField(\n value = '',\n mathObjects: Array<DocumentMathObjectJson | null> = [],\n options: ImportDocumentOptions = {},\n path = '$',\n diagnostics: DocumentDiagnostic[] = [],\n formats: TextFormatSpan2Json[] = [],\n): InlineField2 {\n const mode: DocumentParseMode = options.mode ?? 'english';\n const spans = detectInlineSpans(value);\n const mathSpans = spans.filter((span) => span.kind === 'math');\n const tokens: InlineToken2[] = [];\n let index = 0;\n let mathObjectIndex = 0;\n\n if (mathObjects.length > 0 && mathObjects.length !== mathSpans.length) {\n pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathSpans.length)}, got ${String(mathObjects.length)}`);\n }\n\n for (const span of spans) {\n if (span.start > index) {\n pushFormattedTextTokens(tokens, value.slice(index, span.start), index, formats);\n }\n\n if (span.kind === 'cite') {\n tokens.push({\n id: documentId('cite'),\n kind: 'cite',\n keys: span.keys.length > 0 ? span.keys : [],\n });\n index = span.end;\n continue;\n }\n\n if (span.kind === 'ref') {\n tokens.push({\n id: documentId('ref'),\n kind: 'ref',\n keys: span.keys.length > 0 ? span.keys : [],\n refCommand: span.refCommand,\n });\n index = span.end;\n continue;\n }\n\n const mathJson = mathObjects[mathObjectIndex];\n mathObjectIndex += 1;\n const structuredMathJson = mathJson?.node_type === 'MathObject' ? mathJson : null;\n if (structuredMathJson && (structuredMathJson.math_mode !== span.opening || structuredMathJson.closing !== span.closing)) {\n pushDiagnostic(diagnostics, options, path, 'math_objects order mismatch');\n }\n\n if (structuredMathJson && structuredMathJson.math_mode === span.opening && structuredMathJson.closing === span.closing) {\n tokens.push({\n id: documentId('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n sourceSide:\n structuredMathJson.source_side === 'arabic' || structuredMathJson.source_side === 'english'\n ? structuredMathJson.source_side\n : mode,\n math: fromMathObjectJson(structuredMathJson, mode),\n editable: true,\n sourceOwner: structuredMathJson.source_owner === 'editor' ? 'editor' : 'imported-structured',\n ...(typeof structuredMathJson.label_enabled === 'boolean' ? { labelEnabled: structuredMathJson.label_enabled } : {}),\n ...(typeof structuredMathJson.label === 'string' ? { label: structuredMathJson.label } : {}),\n ...(typeof structuredMathJson.numbered === 'boolean' ? { numbered: structuredMathJson.numbered } : {}),\n });\n } else {\n tokens.push({\n id: documentId('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n math: null,\n editable: false,\n reason: 'هذه المعادلة محفوظة كنص خام فقط حاليا',\n sourceOwner: 'raw',\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.label_enabled === 'boolean'\n ? { labelEnabled: mathJson.label_enabled }\n : {}),\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.label === 'string'\n ? { label: mathJson.label }\n : {}),\n ...(mathJson?.node_type === 'RawMathObject' && typeof mathJson.numbered === 'boolean'\n ? { numbered: mathJson.numbered }\n : {}),\n });\n }\n\n index = span.end;\n }\n\n if (index < value.length || tokens.length === 0) {\n pushFormattedTextTokens(tokens, value.slice(index), index, formats);\n }\n\n return { id: documentId('field'), tokens: compactTextTokens(tokens) };\n}\n\nfunction styleFromFormat(format: TextFormatSpan2Json): TextStyle2 | null {\n const style: TextStyle2 = {};\n if (format.bold === true) {\n style.bold = true;\n }\n if (format.italic === true) {\n style.italic = true;\n }\n if (format.underline === true) {\n style.underline = true;\n }\n return style.bold || style.italic || style.underline ? style : null;\n}\n\nfunction mergeTextStyle(base: TextStyle2 | undefined, added: TextStyle2): TextStyle2 {\n return {\n ...(base?.bold ? { bold: true as const } : {}),\n ...(base?.italic ? { italic: true as const } : {}),\n ...(base?.underline ? { underline: true as const } : {}),\n ...(added.bold ? { bold: true as const } : {}),\n ...(added.italic ? { italic: true as const } : {}),\n ...(added.underline ? { underline: true as const } : {}),\n };\n}\n\nfunction textStylesEqual(a: TextStyle2 | undefined, b: TextStyle2 | undefined): boolean {\n return Boolean(a?.bold) === Boolean(b?.bold) && Boolean(a?.italic) === Boolean(b?.italic) && Boolean(a?.underline) === Boolean(b?.underline);\n}\n\nfunction compactTextTokens(tokens: InlineToken2[]): InlineToken2[] {\n const compacted: InlineToken2[] = [];\n for (const token of tokens) {\n const previous = compacted[compacted.length - 1];\n if (previous?.kind === 'text' && token.kind === 'text' && textStylesEqual(previous.style, token.style)) {\n previous.text += token.text;\n } else {\n compacted.push(token);\n }\n }\n return compacted;\n}\n\nfunction styleKey(style: TextStyle2 | undefined): string {\n return `${style?.bold ? 'b' : ''}${style?.italic ? 'i' : ''}${style?.underline ? 'u' : ''}`;\n}\n\nfunction pushFormattedTextTokens(tokens: InlineToken2[], text: string, sourceStart: number, formats: TextFormatSpan2Json[]): void {\n if (text.length === 0) {\n tokens.push({ id: documentId('text'), kind: 'text', text });\n return;\n }\n const styles: Array<TextStyle2 | undefined> = Array.from({ length: text.length });\n for (const format of formats) {\n const style = styleFromFormat(format);\n if (!style || !Number.isFinite(format.start) || !Number.isFinite(format.end)) {\n continue;\n }\n const start = Math.max(0, Math.min(text.length, Math.trunc(format.start) - sourceStart));\n const end = Math.max(0, Math.min(text.length, Math.trunc(format.end) - sourceStart));\n if (end <= start) {\n continue;\n }\n for (let index = start; index < end; index += 1) {\n styles[index] = mergeTextStyle(styles[index], style);\n }\n }\n\n let chunkStart = 0;\n for (let index = 1; index <= text.length; index += 1) {\n if (index < text.length && styleKey(styles[index]) === styleKey(styles[chunkStart])) {\n continue;\n }\n const chunk = text.slice(chunkStart, index);\n const style = styles[chunkStart];\n tokens.push({ id: documentId('text'), kind: 'text', text: chunk, ...(style ? { style } : {}) });\n chunkStart = index;\n }\n}\n\nfunction closingForList(command: '\\\\begin{itemize}' | '\\\\begin{enumerate}'): '\\\\end{itemize}' | '\\\\end{enumerate}' {\n return command === '\\\\begin{itemize}' ? '\\\\end{itemize}' : '\\\\end{enumerate}';\n}\n\nfunction parseTextBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): TextBlock2 {\n const value = requireString(json.value, `${json.command} requires string value`);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'textBlock',\n command: json.command as TextBlock2['command'],\n field: applyImportedInlineIds(\n createInlineField(value, json.math_objects ?? [], options, `${path}.value`, diagnostics, json.command === '\\\\paragraph' ? json.formats ?? [] : []),\n json.inline_ids,\n identities,\n ),\n ...metadataFromJson(json.metadata),\n ...(typeof json.label === 'string' && json.command !== '\\\\paragraph' ? { label: json.label } : {}),\n ...(json.centered === true ? { centered: true } : {}),\n };\n}\n\nfunction parseListItem(\n json: DocumentListItemJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ListItem2 {\n const value = requireString(json.value, 'Document list item requires string value');\n const blocksJson = Array.isArray(json.blocks) ? json.blocks : [];\n return {\n id: importedOrGeneratedId(json.id, 'item', identities.itemIds),\n field: applyImportedInlineIds(\n createInlineField(value, json.math_objects ?? [], options, `${path}.value`, diagnostics, json.formats ?? []),\n json.inline_ids,\n identities,\n ),\n blocks: blocksJson.map((block, index) =>\n parseBlock(asBlockJson(block), options, `${path}.blocks[${String(index)}]`, diagnostics, identities),\n ),\n };\n}\n\nfunction parseListBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ListBlock2 {\n if (!Array.isArray(json.items)) {\n throw new Error(`${json.command} requires items array`);\n }\n const command = json.command as ListBlock2['command'];\n const closing = closingForList(command);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'list',\n command,\n closing,\n items: json.items.map((item, index) =>\n parseListItem(item, options, `${path}.items[${String(index)}]`, diagnostics, identities),\n ),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction captionFieldFromJson(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): InlineField2 {\n const caption = typeof json.caption === 'string' ? json.caption : '';\n return applyImportedInlineIds(\n createInlineField(\n caption,\n json.caption_math_objects ?? [],\n options,\n `${path}.caption`,\n diagnostics,\n json.caption_formats ?? [],\n ),\n json.caption_inline_ids,\n identities,\n );\n}\n\nfunction parseTableBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): TableBlock2 {\n if (!Array.isArray(json.rows)) {\n throw new Error('\\\\begin{tabular} requires rows array');\n }\n\n const mathObjects = json.math_objects ?? [];\n let mathObjectIndex = 0;\n const rows = json.rows.map((row, rowIndex) => {\n if (!Array.isArray(row)) {\n throw new Error('\\\\begin{tabular} rows must be arrays');\n }\n return row.map((cell, columnIndex) => {\n const value = requireString(cell, '\\\\begin{tabular} cells must be strings');\n const spanCount = detectMathSpans(value).length;\n const cellMathObjects = mathObjects.slice(mathObjectIndex, mathObjectIndex + spanCount);\n mathObjectIndex += spanCount;\n const cellFormats = json.cell_formats?.[rowIndex]?.[columnIndex] ?? [];\n return applyImportedInlineIds(\n createInlineField(value, cellMathObjects, options, `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`, diagnostics, cellFormats),\n json.cell_inline_ids?.[rowIndex]?.[columnIndex],\n identities,\n );\n });\n });\n\n if (mathObjects.length > 0 && mathObjects.length !== mathObjectIndex) {\n pushDiagnostic(diagnostics, options, path, `math_objects count mismatch: detected ${String(mathObjectIndex)}, got ${String(mathObjects.length)}`);\n }\n\n const floatMeta = parseFloatMetaFromJson(json);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: typeof json.columns === 'string' ? json.columns : '',\n rows,\n ...floatMeta,\n captionField: captionFieldFromJson(json, options, path, diagnostics, identities),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseImageBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): ImageBlock2 {\n const assetId = typeof json.asset_id === 'string' && json.asset_id.length > 0 ? json.asset_id : undefined;\n const value =\n assetId !== undefined\n ? typeof json.value === 'string'\n ? json.value\n : ''\n : requireString(json.value, '\\\\includegraphics requires string value');\n const floatMeta = parseFloatMetaFromJson(json);\n return {\n id: blockIdFromJson(json, identities),\n kind: 'image',\n command: '\\\\includegraphics',\n value,\n ...(assetId !== undefined ? { assetId } : {}),\n options: isRecordOfStrings(json.options) ? json.options : {},\n ...floatMeta,\n captionField: captionFieldFromJson(json, options, path, diagnostics, identities),\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseRawBlock(json: DocumentBlockJson, identities: DocumentIdentityState): RawBlock2 {\n return {\n id: blockIdFromJson(json, identities),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : '',\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseBibliographyBlock(json: DocumentBlockJson, identities: DocumentIdentityState): BibliographyBlock2 {\n return {\n id: blockIdFromJson(json, identities),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n ...metadataFromJson(json.metadata),\n };\n}\n\nfunction parseBlock(\n json: DocumentBlockJson,\n options: ImportDocumentOptions,\n path: string,\n diagnostics: DocumentDiagnostic[],\n identities: DocumentIdentityState,\n): DocumentBlock {\n if (TEXT_COMMANDS.has(json.command)) {\n return parseTextBlock(json, options, path, diagnostics, identities);\n }\n if (LIST_COMMANDS.has(json.command)) {\n return parseListBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\begin{tabular}') {\n return parseTableBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\includegraphics') {\n return parseImageBlock(json, options, path, diagnostics, identities);\n }\n if (json.command === '\\\\begin{thebibliography}' || json.command === '\\\\bibliography') {\n return parseBibliographyBlock(json, identities);\n }\n if (json.command === '\\\\raw') {\n return parseRawBlock(json, identities);\n }\n return {\n id: blockIdFromJson(json, identities),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : json.command,\n ...metadataFromJson(json.metadata),\n };\n}\n\nexport function fromDocumentJson(json: unknown, options: ImportDocumentOptions = {}): DocumentNode {\n if (!isObject(json) || json.node_type !== 'DocumentObject') {\n throw new Error('DocumentObject requires node_type \"DocumentObject\"');\n }\n if (!Array.isArray(json.blocks)) {\n throw new Error('DocumentObject requires blocks array');\n }\n\n const diagnostics: DocumentDiagnostic[] = [];\n const identities = createDocumentIdentityState();\n return {\n nodeType: 'DocumentObject',\n meta: normalizeDocumentMeta(json.meta),\n references: parseReferences(json.references),\n blocks: json.blocks.map((block, index) =>\n parseBlock(asBlockJson(block), options, `$.blocks[${String(index)}]`, diagnostics, identities),\n ),\n diagnostics,\n };\n}\n\nexport function createEmptyDocument(): DocumentNode {\n return {\n nodeType: 'DocumentObject',\n meta: emptyDocumentMeta(),\n references: [],\n blocks: [],\n diagnostics: [],\n };\n}\n","export type AccentPlacement = 'over' | 'under';\n\nexport const ACCENT_COMMANDS = {\n vec: {\n id: 'vec',\n englishTex: '\\\\vec',\n arabicTex: '\\\\arabvec',\n placement: 'over' as const,\n label: '⃗',\n title: 'سهم فوق',\n },\n hat: {\n id: 'hat',\n englishTex: '\\\\hat',\n arabicTex: '\\\\hat',\n placement: 'over' as const,\n label: 'ˆ',\n title: 'قبعة',\n },\n tilde: {\n id: 'tilde',\n englishTex: '\\\\tilde',\n arabicTex: '\\\\tilde',\n placement: 'over' as const,\n label: '˜',\n title: 'مدة',\n },\n dot: {\n id: 'dot',\n englishTex: '\\\\dot',\n arabicTex: '\\\\dot',\n placement: 'over' as const,\n label: '˙',\n title: 'نقطة فوق',\n },\n ddot: {\n id: 'ddot',\n englishTex: '\\\\ddot',\n arabicTex: '\\\\ddot',\n placement: 'over' as const,\n label: '¨',\n title: 'نقطتان فوق',\n },\n dddot: {\n id: 'dddot',\n englishTex: '\\\\dddot',\n arabicTex: '\\\\dddot',\n placement: 'over' as const,\n label: '⃛',\n title: 'ثلاث نقاط فوق',\n },\n bar: {\n id: 'bar',\n englishTex: '\\\\bar',\n arabicTex: '\\\\bar',\n placement: 'over' as const,\n label: '¯',\n title: 'خط فوق',\n },\n check: {\n id: 'check',\n englishTex: '\\\\check',\n arabicTex: '\\\\check',\n placement: 'over' as const,\n label: 'ˇ',\n title: 'علامة تحقق',\n },\n breve: {\n id: 'breve',\n englishTex: '\\\\breve',\n arabicTex: '\\\\breve',\n placement: 'over' as const,\n label: '˘',\n title: 'قوس قصير',\n },\n acute: {\n id: 'acute',\n englishTex: '\\\\acute',\n arabicTex: '\\\\grave',\n placement: 'over' as const,\n label: '´',\n title: 'نبرة حادة',\n },\n grave: {\n id: 'grave',\n englishTex: '\\\\grave',\n arabicTex: '\\\\acute',\n placement: 'over' as const,\n label: '`',\n title: 'نبرة ثقيلة',\n },\n overline: {\n id: 'overline',\n englishTex: '\\\\overline',\n arabicTex: '\\\\overline',\n placement: 'over' as const,\n label: '‾',\n title: 'خط علوي ممتد',\n },\n underline: {\n id: 'underline',\n englishTex: '\\\\underline',\n arabicTex: '\\\\underline',\n placement: 'under' as const,\n label: '_',\n title: 'خط سفلي',\n },\n overleftarrow: {\n id: 'overleftarrow',\n englishTex: '\\\\overleftarrow',\n arabicTex: '\\\\overrightarrow',\n placement: 'over' as const,\n label: '←',\n title: 'سهم علوي إلى اليسار',\n },\n overrightarrow: {\n id: 'overrightarrow',\n englishTex: '\\\\overrightarrow',\n arabicTex: '\\\\overleftarrow',\n placement: 'over' as const,\n label: '→',\n title: 'سهم علوي إلى اليمين',\n },\n overleftrightarrow: {\n id: 'overleftrightarrow',\n englishTex: '\\\\overleftrightarrow',\n arabicTex: '\\\\overleftrightarrow',\n placement: 'over' as const,\n label: '↔',\n title: 'سهم علوي مزدوج الاتجاه',\n },\n} as const;\n\nexport type AccentCommandId = keyof typeof ACCENT_COMMANDS;\n\nexport type AccentCommandSpec = (typeof ACCENT_COMMANDS)[AccentCommandId] & {\n placement: AccentPlacement;\n};\n\nexport function accentCommandSpec(id: string): AccentCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ACCENT_COMMANDS, id)\n ? ACCENT_COMMANDS[id as AccentCommandId]\n : null;\n}\n\nexport function accentCommandsList(): AccentCommandSpec[] {\n return Object.values(ACCENT_COMMANDS);\n}\n\n/** Resolve accent id from a TeX command name like `\\hat` or `\\arabvec`. */\nexport function accentCommandIdFromTex(tex: string): AccentCommandId | null {\n const normalized = tex.startsWith('\\\\') ? tex : `\\\\${tex}`;\n for (const spec of Object.values(ACCENT_COMMANDS)) {\n if (spec.englishTex === normalized) {\n return spec.id;\n }\n }\n for (const spec of Object.values(ACCENT_COMMANDS)) {\n if (spec.arabicTex === normalized) {\n return spec.id;\n }\n }\n return null;\n}\n","export const ATOMIC_COMMANDS = {\n ///////////////////////// Functions ////////////////////////////////\n\n //////////////// Trigonometric Functions \n cos: {\n id: 'cos',\n category: 'function',\n englishTex: '\\\\cos',\n arabicTex: '\\\\arcos',\n arabicLabel: 'جتا',\n title: 'جيب التمام',\n },\n sin: {\n id: 'sin',\n category: 'function',\n englishTex: '\\\\sin',\n arabicTex: '\\\\arsin',\n arabicLabel: 'جا',\n title: 'جيب',\n },\n tan: {\n id: 'tan',\n category: 'function',\n englishTex: '\\\\tan',\n arabicTex: '\\\\artan',\n arabicLabel: 'ظا',\n title: 'ظل',\n },\n cot: {\n id: 'cot',\n category: 'function',\n englishTex: '\\\\cot',\n arabicTex: '\\\\arcot',\n arabicLabel: 'ظتا',\n title: 'ظل تمام',\n },\n sec: {\n id: 'sec',\n category: 'function',\n englishTex: '\\\\sec',\n arabicTex: '\\\\arsec',\n arabicLabel: 'قا',\n title: 'قاطع',\n },\n csc: {\n id: 'csc',\n category: 'function',\n englishTex: '\\\\csc',\n arabicTex: '\\\\arcsc',\n arabicLabel: 'قتا',\n title: 'قاطع تمام',\n },\n\n\n /////////////////// Arc Trigonometric Functions \n arccos: {\n id: 'arccos',\n category: 'function',\n englishTex: '\\\\arccos',\n arabicTex: '\\\\aracos',\n arabicLabel: 'قجتا',\n title: 'قاطع جيب التمام',\n },\n arcsin: {\n id: 'arcsin',\n category: 'function',\n englishTex: '\\\\arcsin',\n arabicTex: '\\\\arasin',\n arabicLabel: 'قجا',\n title: 'قاطع جيب',\n },\n arctan: {\n id: 'arctan',\n category: 'function',\n englishTex: '\\\\arctan',\n arabicTex: '\\\\aratan',\n arabicLabel: 'قظا',\n title: 'قاطع ظل',\n },\n arccot: {\n id: 'arccot',\n category: 'function',\n englishTex: '\\\\arccot',\n arabicTex: '\\\\aracot',\n arabicLabel: 'قظتا',\n title: 'قاطع ظل التمام',\n },\n arcsec: {\n id: 'arcsec',\n category: 'function',\n englishTex: '\\\\arcsec',\n arabicTex: '\\\\arasec',\n arabicLabel: 'ققا',\n title: 'قاطع القاطع',\n },\n arccsc: {\n id: 'arccsc',\n category: 'function',\n englishTex: '\\\\arccsc',\n arabicTex: '\\\\aracsc',\n arabicLabel: 'ققتا',\n title: 'قاطع القاطع التمام',\n },\n\n ///////////////// Hyperbolic Functions \n cosh: {\n id: 'cosh',\n category: 'function',\n englishTex: '\\\\cosh',\n arabicTex: '\\\\arcosh',\n arabicLabel: 'جتزا',\n title: 'جيب التمام الزائد',\n },\n sinh: {\n id: 'sinh',\n category: 'function',\n englishTex: '\\\\sinh',\n arabicTex: '\\\\arsinh',\n arabicLabel: 'جزا',\n title: 'جيب الزائد',\n },\n tanh: {\n id: 'tanh',\n category: 'function',\n englishTex: '\\\\tanh',\n arabicTex: '\\\\artanh',\n arabicLabel: 'ظزا',\n title: 'ظل الزائد',\n },\n coth: {\n id: 'coth',\n category: 'function',\n englishTex: '\\\\coth',\n arabicTex: '\\\\arcoth',\n arabicLabel: 'ظتزا',\n title: 'ظل تمام الزائد',\n },\n\n ////// These function somehow doesnt exist in LaTeX and therefore MathJax, skip for now. no problem.\n // sech: {\n // id: 'sech',\n // category: 'function',\n // englishTex: '\\\\sech',\n // arabicTex: '\\\\arsech',\n // arabicLabel: 'قزا',\n // title: 'قاطع الزائد',\n // },\n // csch: {\n // id: 'csch',\n // category: 'function',\n // englishTex: '\\\\csch',\n // arabicTex: '\\\\arcsch',\n // arabicLabel: 'قتزا',\n // title: 'قاطع تمام الزائد',\n // },\n\n\n ///////////////// arc Hyperbolic Functions \n ///// Not on MathJax, skip for now, it is okay.\n\n\n\n ////////////////////// Limits & Series ////////////////////////////////\n sum: {\n id: 'sum',\n category: 'limits_series',\n englishTex: '\\\\sum',\n arabicTex: '\\\\arsum',\n arabicLabel: 'مجـــ',\n title: 'مجموع',\n },\n prod: {\n id: 'prod',\n category: 'limits_series',\n englishTex: '\\\\prod',\n arabicTex: '\\\\arprod',\n arabicLabel: 'جـــد',\n title: 'جداء',\n },\n lim: {\n id: 'lim',\n category: 'limits_series',\n englishTex: '\\\\lim',\n arabicTex: '\\\\arlim',\n arabicLabel: 'نـــــها',\n title: 'حد',\n },\n arg: {\n id: 'arg',\n category: 'limits_series',\n englishTex: '\\\\arg',\n arabicTex: '\\\\ararg',\n arabicLabel: 'حج',\n title: 'حجة',\n },\n max: {\n id: 'max',\n category: 'limits_series',\n englishTex: '\\\\max',\n arabicTex: '\\\\armax',\n arabicLabel: 'أكبر',\n title: 'أكبر',\n },\n min: {\n id: 'min',\n category: 'limits_series',\n englishTex: '\\\\min',\n arabicTex: '\\\\armin',\n arabicLabel: 'أصغر',\n title: 'أصغر',\n },\n sup: {\n id: 'sup',\n category: 'limits_series',\n englishTex: '\\\\sup',\n arabicTex: '\\\\arsup',\n arabicLabel: 'أعلى',\n title: 'أعلى',\n },\n inf: {\n id: 'inf',\n category: 'limits_series',\n englishTex: '\\\\inf',\n arabicTex: '\\\\arinf',\n arabicLabel: 'أدنى',\n title: 'أدنى',\n },\n\n ////////////////////// Logarithmic and Exponential and Determinant Functions ////////////////////////////////\n pi: {\n id: 'pi',\n category: 'function2',\n englishTex: '\\\\pi',\n arabicTex: '\\\\arpi',\n arabicLabel: 'ط',\n title: 'نسبة الدائرة',\n },\n exp: {\n id: 'exp',\n category: 'function2',\n englishTex: '\\\\exp',\n arabicTex: '\\\\arexp',\n arabicLabel: 'هـ',\n title: 'أسية',\n },\n ln: {\n id: 'ln',\n category: 'function2',\n englishTex: '\\\\ln',\n arabicTex: '\\\\arln',\n arabicRenderTex: '\\\\prescript{}{\\\\arexp}{\\\\arlog}',\n arabicLabel: 'لو',\n title: 'لوغاريتم طبيعي',\n },\n log: {\n id: 'log',\n category: 'function2',\n englishTex: '\\\\log',\n arabicTex: '\\\\arlog',\n arabicLabel: 'لو',\n title: 'لوغاريتم',\n },\n det: {\n id: 'det',\n category: 'function2',\n englishTex: '\\\\det',\n arabicTex: '\\\\ardet',\n arabicLabel: 'محدد',\n title: 'محدد',\n },\n\n ////////////////////// Derivatives ////////////////////////////////\n ad: {\n id: 'ad',\n category: 'derivative',\n englishTex: '\\\\mathrm{d}',\n englishLabel: 'd',\n arabicTex: '\\\\ad',\n arabicLabel: 'ء',\n title: 'علامة الاشتقاق',\n },\n\n ////////////////////// Groups /////////////////////////////////\n N: {\n id: 'N',\n category: 'groups',\n englishTex: '\\\\mathbb{N}',\n arabicTex: '\\\\arabN',\n arabicLabel: 'ط',\n title: 'أعداد طبيعية',\n },\n Z: {\n id: 'Z',\n category: 'groups',\n englishTex: '\\\\mathbb{Z}',\n arabicTex: '\\\\arabZ',\n arabicLabel: 'ص',\n title: 'أعداد صحيحة',\n },\n Q: {\n id: 'Q',\n category: 'groups',\n englishTex: '\\\\mathbb{Q}',\n arabicTex: '\\\\arabQ',\n arabicLabel: 'ن',\n title: 'أعداد نسبية',\n },\n R: {\n id: 'R',\n category: 'groups',\n englishTex: '\\\\mathbb{R}',\n arabicTex: '\\\\arabR',\n arabicLabel: 'ح',\n title: 'أعداد حقيقية',\n },\n C: {\n id: 'C',\n category: 'groups',\n englishTex: '\\\\mathbb{C}',\n arabicTex: '\\\\arabC',\n arabicLabel: 'ع',\n title: 'أعداد عُقدية',\n },\n H: {\n id: 'H',\n category: 'groups',\n englishTex: '\\\\mathbb{H}',\n arabicTex: '\\\\arabH',\n arabicLabel: 'ر',\n title: 'أعداد رباعية',\n },\n\n ////////////////////// Operations ////////////////////////////\n\n\n ////////////////////// Spacing ////////////////////////////////\n negThinSpace: {\n id: 'negThinSpace',\n category: 'spacing',\n englishTex: '\\\\!',\n arabicTex: '\\\\!',\n arabicLabel: '',\n title: 'فراغ سالب رفيع',\n spacing: { direction: 'negative', level: 1 },\n },\n thinSpace: {\n id: 'thinSpace',\n category: 'spacing',\n englishTex: '\\\\,',\n arabicTex: '\\\\,',\n arabicLabel: '',\n title: 'فراغ رفيع',\n spacing: { direction: 'positive', level: 1 },\n },\n mediumSpace: {\n id: 'mediumSpace',\n category: 'spacing',\n englishTex: '\\\\:',\n arabicTex: '\\\\:',\n arabicLabel: '',\n title: 'فراغ متوسط',\n spacing: { direction: 'positive', level: 1 },\n },\n thickSpace: {\n id: 'thickSpace',\n category: 'spacing',\n englishTex: '\\\\;',\n arabicTex: '\\\\;',\n arabicLabel: '',\n title: 'فراغ عريض',\n spacing: { direction: 'positive', level: 2 },\n },\n quadSpace: {\n id: 'quadSpace',\n category: 'spacing',\n englishTex: '\\\\quad',\n arabicTex: '\\\\quad',\n arabicLabel: '',\n title: 'فراغ كبير',\n spacing: { direction: 'positive', level: 3 },\n },\n qquadSpace: {\n id: 'qquadSpace',\n category: 'spacing',\n englishTex: '\\\\qquad',\n arabicTex: '\\\\qquad',\n arabicLabel: '',\n title: 'فراغ كبير جدا',\n spacing: { direction: 'positive', level: 4 },\n },\n} as const;\n\nexport type AtomicCommandId = keyof typeof ATOMIC_COMMANDS;\nexport type AtomicCommandCategory = 'function' | 'function2' | 'limits_series' | 'groups' | 'spacing' | 'derivative';\nexport type SpacingDirection = 'positive' | 'negative';\n\nexport type AtomicCommandSpec = (typeof ATOMIC_COMMANDS)[AtomicCommandId] & {\n arabicRenderTex?: string;\n englishLabel?: string;\n};\nexport type SpacingCommandSpec = AtomicCommandSpec & {\n category: 'spacing';\n spacing: {\n direction: SpacingDirection;\n level: 1 | 2 | 3 | 4;\n };\n};\n\nexport function atomicCommandsByCategory(category: AtomicCommandCategory): AtomicCommandSpec[] {\n return Object.values(ATOMIC_COMMANDS).filter((command) => command.category === category);\n}\n\nexport function isSpacingCommandSpec(spec: AtomicCommandSpec | null): spec is SpacingCommandSpec {\n return spec?.category === 'spacing';\n}\n\nexport function atomicCommandSpec(id: string): AtomicCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ATOMIC_COMMANDS, id)\n ? ATOMIC_COMMANDS[id as AtomicCommandId]\n : null;\n}\n","export const ATOMIC_OPERATOR_COMMANDS = {\n inf: {\n id: 'inf',\n category: 'operators1',\n Tex: '\\\\infty',\n mirror: true,\n Label: '∞',\n title: 'اللانهاية',\n svg_path: null,\n },\n top: {\n id: 'top',\n category: 'operators1',\n Tex: '\\\\top',\n mirror: false,\n Label: '⊤',\n title: 'المنقول',\n svg_path: null,\n },\n times: {\n id: 'times',\n category: 'operators1',\n Tex: '\\\\times',\n mirror: false,\n Label: '×',\n title: 'ضرب',\n svg_path: null,\n },\n div: {\n id: 'div',\n category: 'operators1',\n Tex: '\\\\div',\n mirror: false,\n Label: '÷',\n title: 'قسمة',\n svg_path: null,\n },\n pm: {\n id: 'pm',\n category: 'operators1',\n Tex: '\\\\pm',\n mirror: false,\n Label: '±',\n title: 'زائد أو ناقص',\n svg_path: null,\n },\n mp: {\n id: 'mp',\n category: 'operators1',\n Tex: '\\\\mp',\n mirror: false,\n Label: '∓',\n title: 'ناقص أو زائد',\n svg_path: null,\n },\n neq: {\n id: 'neq',\n category: 'operators1',\n Tex: '\\\\neq',\n mirror: true,\n compileMirror: true,\n Label: '≠',\n title: 'لا يساوي',\n svg_path: null,\n },\n approx: {\n id: 'approx',\n category: 'operators1',\n Tex: '\\\\approx',\n mirror: false,\n displayMirror: true,\n Label: '≈',\n title: 'تقريبا يساوي',\n svg_path: null,\n },\n sim: {\n id: 'sim',\n category: 'operators1',\n Tex: '\\\\sim',\n mirror: false,\n displayMirror: true,\n Label: '∼',\n title: 'مشابه',\n svg_path: null,\n },\n mid: {\n id: 'mid',\n category: 'operators1',\n Tex: '\\\\mid',\n mirror: false,\n Label: '∣',\n title: 'يقسم',\n svg_path: null,\n },\n leq: {\n id: 'leq',\n category: 'operators1',\n Tex: '\\\\leq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≤',\n title: 'أصغر من أو يساوي',\n svg_path: null,\n },\n geq: {\n id: 'geq',\n category: 'operators1',\n Tex: '\\\\geq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≥',\n title: 'أكبر من أو يساوي',\n svg_path: null,\n },\n coloneqq: {\n id: 'coloneqq',\n category: 'operators1',\n Tex: '\\\\coloneqq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≔',\n title: 'يعرف بأنه يساوي',\n svg_path: null,\n },\n eqqcolon: {\n id: 'eqqcolon',\n category: 'operators1',\n Tex: '\\\\eqqcolon',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '≕',\n title: 'يساوي بالتعريف',\n svg_path: null,\n },\n\n ///// Operators 2\n propto: {\n id: 'propto',\n category: 'operators2',\n Tex: '\\\\propto',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∝',\n title: 'يتناسب مع',\n svg_path: null,\n },\n in: {\n id: 'in',\n category: 'operators2',\n Tex: '\\\\in',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∈',\n title: 'ينتمي إلى',\n svg_path: null,\n },\n notin: {\n id: 'notin',\n category: 'operators2',\n Tex: '\\\\notin',\n mirror: false,\n displayMirror: true,\n Label: '∉',\n title: 'لا ينتمي إلى',\n svg_path: null,\n },\n subset: {\n id: 'subset',\n category: 'operators2',\n Tex: '\\\\subset',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊂',\n title: 'مجموعة جزئية من',\n svg_path: null,\n },\n supset: {\n id: 'supset',\n category: 'operators2',\n Tex: '\\\\supset',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊃',\n title: 'مجموعة شاملة لـ',\n svg_path: null,\n },\n subseteq: {\n id: 'subseteq',\n category: 'operators2',\n Tex: '\\\\subseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊆',\n title: 'مجموعة جزئية أو تساوي',\n svg_path: null,\n },\n supseteq: {\n id: 'supseteq',\n category: 'operators2',\n Tex: '\\\\supseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊇',\n title: 'مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n cap: {\n id: 'cap',\n category: 'operators2',\n Tex: '\\\\cap',\n mirror: false,\n displayMirror: true,\n Label: '∩',\n title: 'تقاطع',\n svg_path: null,\n },\n cup: {\n id: 'cup',\n category: 'operators2',\n Tex: '\\\\cup',\n mirror: false,\n displayMirror: true,\n Label: '∪',\n title: 'اتحاد',\n svg_path: null,\n },\n emptyset: {\n id: 'emptyset',\n category: 'operators2',\n Tex: '\\\\emptyset',\n mirror: false,\n displayMirror: true,\n Label: '∅',\n title: 'المجموعة الخالية',\n svg_path: null,\n },\n nsubseteq: {\n id: 'nsubseteq',\n category: 'operators2',\n Tex: '\\\\nsubseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊈',\n title: 'ليست مجموعة جزئية أو تساوي',\n svg_path: null,\n },\n nsupseteq: {\n id: 'nsupseteq',\n category: 'operators2',\n Tex: '\\\\nsupseteq',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⊉',\n title: 'ليست مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n\n ///// Dots\n ldots: {\n id: 'ldots',\n category: 'dots',\n Tex: '\\\\ldots',\n mirror: false,\n Label: '…',\n title: 'نقاط أفقية',\n svg_path: null,\n },\n cdot: {\n id: 'cdot',\n category: 'dots',\n Tex: '\\\\cdot',\n mirror: false,\n Label: '·',\n title: 'نقطة ضرب',\n svg_path: null,\n },\n cdots: {\n id: 'cdots',\n category: 'dots',\n Tex: '\\\\cdots',\n mirror: false,\n Label: '⋯',\n title: 'نقاط وسطية أفقية',\n svg_path: null,\n },\n vdots: {\n id: 'vdots',\n category: 'dots',\n Tex: '\\\\vdots',\n mirror: false,\n Label: '⋮',\n title: 'نقاط عمودية',\n svg_path: null,\n },\n ddots: {\n id: 'ddots',\n category: 'dots',\n Tex: '\\\\ddots',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⋱',\n title: 'نقاط قطرية',\n svg_path: null,\n },\n\n /// Operators 3\n leftrightarrowDouble: {\n id: 'leftrightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Leftrightarrow',\n mirror: false,\n Label: '⇔',\n title: 'يكافئ',\n svg_path: null,\n },\n implies: {\n id: 'implies',\n category: 'operators3',\n Tex: '\\\\implies',\n mirror: true,\n compileMirror: true,\n Label: '⇒',\n title: 'يستلزم',\n svg_path: null,\n },\n impliedby: {\n id: 'impliedby',\n category: 'operators3',\n Tex: '\\\\impliedby',\n mirror: true,\n compileMirror: true,\n Label: '⇐',\n title: 'مستلزم من',\n svg_path: null,\n },\n iff: {\n id: 'iff',\n category: 'operators3',\n Tex: '\\\\iff',\n mirror: false,\n Label: '⇔',\n title: 'إذا وفقط إذا',\n svg_path: null,\n },\n Longrightarrow: {\n id: 'Longrightarrow',\n category: 'operators3',\n Tex: '\\\\Longrightarrow',\n mirror: true,\n compileMirror: true,\n Label: '⟹',\n title: 'سهم مزدوج طويل إلى اليمين',\n svg_path: null,\n },\n Longleftarrow: {\n id: 'Longleftarrow',\n category: 'operators3',\n Tex: '\\\\Longleftarrow',\n mirror: true,\n compileMirror: true,\n Label: '⟸',\n title: 'سهم مزدوج طويل إلى اليسار',\n svg_path: null,\n },\n to: {\n id: 'to',\n category: 'operators3',\n Tex: '\\\\to',\n mirror: true,\n compileMirror: true,\n Label: '→',\n title: 'يؤول إلى',\n svg_path: null,\n },\n rightleftharpoons: {\n id: 'rightleftharpoons',\n category: 'operators3',\n Tex: '\\\\rightleftharpoons',\n mirror: true,\n compileMirror: true,\n Label: '⇌',\n title: 'اتزان',\n svg_path: null,\n },\n leftarrow: {\n id: 'leftarrow',\n category: 'operators3',\n Tex: '\\\\leftarrow',\n mirror: true,\n compileMirror: true,\n Label: '←',\n title: 'سهم إلى اليسار',\n svg_path: null,\n },\n rightarrow: {\n id: 'rightarrow',\n category: 'operators3',\n Tex: '\\\\rightarrow',\n mirror: true,\n compileMirror: true,\n Label: '→',\n title: 'سهم إلى اليمين',\n svg_path: null,\n },\n leftarrowDouble: {\n id: 'leftarrowDouble',\n category: 'operators3',\n Tex: '\\\\Leftarrow',\n mirror: true,\n compileMirror: true,\n Label: '⇐',\n title: 'سهم مزدوج إلى اليسار',\n svg_path: null,\n },\n rightarrowDouble: {\n id: 'rightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Rightarrow',\n mirror: true,\n compileMirror: true,\n Label: '⇒',\n title: 'سهم مزدوج إلى اليمين',\n svg_path: null,\n },\n leftharpoonup: {\n id: 'leftharpoonup',\n category: 'operators3',\n Tex: '\\\\leftharpoonup',\n mirror: true,\n compileMirror: true,\n Label: '↼',\n title: 'سهم خطافي علوي إلى اليسار',\n svg_path: null,\n },\n rightharpoonup: {\n id: 'rightharpoonup',\n category: 'operators3',\n Tex: '\\\\rightharpoonup',\n mirror: true,\n compileMirror: true,\n Label: '⇀',\n title: 'سهم خطافي علوي إلى اليمين',\n svg_path: null,\n },\n leftharpoondown: {\n id: 'leftharpoondown',\n category: 'operators3',\n Tex: '\\\\leftharpoondown',\n mirror: true,\n compileMirror: true,\n Label: '↽',\n title: 'سهم خطافي سفلي إلى اليسار',\n svg_path: null,\n },\n rightharpoondown: {\n id: 'rightharpoondown',\n category: 'operators3',\n Tex: '\\\\rightharpoondown',\n mirror: true,\n compileMirror: true,\n Label: '⇁',\n title: 'سهم خطافي سفلي إلى اليمين',\n svg_path: null,\n },\n\n // Integrals\n int: {\n id: 'int',\n category: 'integrals',\n Tex: '\\\\int',\n mirror: true,\n compileMirror: true,\n Label: '∫',\n title: 'تكامل',\n svg_path: null,\n },\n iint: {\n id: 'iint',\n category: 'integrals',\n Tex: '\\\\iint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∬',\n title: 'تكامل مزدوج',\n svg_path: null,\n },\n iiint: {\n id: 'iiint',\n category: 'integrals',\n Tex: '\\\\iiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∭',\n title: 'تكامل ثلاثي',\n svg_path: null,\n },\n iiiint: {\n id: 'iiiint',\n category: 'integrals',\n Tex: '\\\\iiiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '⨌',\n title: 'تكامل رباعي',\n svg_path: null,\n },\n oint: {\n id: 'oint',\n category: 'integrals',\n Tex: '\\\\oint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∮',\n title: 'تكامل مغلق',\n svg_path: null,\n },\n oiint: {\n id: 'oiint',\n category: 'integrals',\n Tex: '\\\\oiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∯',\n title: 'تكامل سطحي مغلق',\n svg_path: null,\n },\n oiiint: {\n id: 'oiiint',\n category: 'integrals',\n Tex: '\\\\oiiint',\n mirror: true,\n displayMirror: false,\n compileMirror: true,\n Label: '∰',\n title: 'تكامل حجمي مغلق',\n svg_path: null,\n },\n} as const;\n\nexport type AtomicOperatorCommandId = keyof typeof ATOMIC_OPERATOR_COMMANDS;\n\nexport type AtomicOperatorCommandCategory =\n | 'operators1'\n | 'operators2'\n | 'operators3'\n | 'dots'\n | 'integrals';\n\nexport type AtomicOperatorCommandSpec =\n (typeof ATOMIC_OPERATOR_COMMANDS)[AtomicOperatorCommandId] & {\n displayMirror?: boolean;\n compileMirror?: boolean;\n };\n\nexport function shouldMirrorOperatorDisplay(\n command: AtomicOperatorCommandSpec | null | undefined,\n): boolean {\n return command?.displayMirror ?? command?.mirror ?? false;\n}\n\nconst MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS)\n .filter((command) => command.mirror)\n .map((command) => command.Tex)\n .sort((a, b) => b.length - a.length) as string[];\n\nconst COMPILE_MIRRORED_OPERATOR_TEX = Object.values(ATOMIC_OPERATOR_COMMANDS)\n .filter((command) => 'compileMirror' in command && command.compileMirror)\n .map((command) => command.Tex)\n .sort((a, b) => b.length - a.length) as string[];\n\nfunction matchingMirroredOperatorFrom(tex: string, index: number, operatorTexList: string[]): string | null {\n for (const operatorTex of operatorTexList) {\n if (!tex.startsWith(operatorTex, index)) {\n continue;\n }\n const next = tex[index + operatorTex.length];\n if (next != null && /[A-Za-z]/.test(next)) {\n continue;\n }\n return operatorTex;\n }\n return null;\n}\n\nfunction findMatchingBrace(tex: string, openIndex: number): number {\n let depth = 0;\n for (let index = openIndex; index < tex.length; index += 1) {\n const char = tex[index];\n if (char === '\\\\') {\n index += 1;\n continue;\n }\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n return index;\n }\n }\n }\n return -1;\n}\n\nexport function mirrorBuTeXOperatorsInTex(tex: string, options: { target?: 'preview' | 'compile' } = {}): string {\n const mirroredOperatorTex = options.target === 'compile'\n ? COMPILE_MIRRORED_OPERATOR_TEX\n : MIRRORED_OPERATOR_TEX;\n let result = '';\n let index = 0;\n\n while (index < tex.length) {\n if (tex.startsWith('\\\\butexmirror{', index)) {\n const end = findMatchingBrace(tex, index + '\\\\butexmirror'.length);\n if (end !== -1) {\n const bodyStart = index + '\\\\butexmirror{'.length;\n const body = tex.slice(bodyStart, end);\n if (\n options.target === 'compile' &&\n MIRRORED_OPERATOR_TEX.includes(body) &&\n !mirroredOperatorTex.includes(body)\n ) {\n result += body;\n } else {\n result += tex.slice(index, end + 1);\n }\n index = end + 1;\n continue;\n }\n }\n\n const operatorTex = matchingMirroredOperatorFrom(tex, index, mirroredOperatorTex);\n if (operatorTex) {\n result += `\\\\butexmirror{${operatorTex}}`;\n index += operatorTex.length;\n continue;\n }\n\n result += tex[index];\n index += 1;\n }\n\n return result;\n}\n\nexport function atomicOperatorCommandsByCategory(\n category: AtomicOperatorCommandCategory,\n): AtomicOperatorCommandSpec[] {\n return Object.values(ATOMIC_OPERATOR_COMMANDS).filter(\n (command) => command.category === category,\n );\n}\n\nexport function atomicOperatorCommandSpec(\n id: string,\n): AtomicOperatorCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(ATOMIC_OPERATOR_COMMANDS, id)\n ? ATOMIC_OPERATOR_COMMANDS[id as AtomicOperatorCommandId]\n : null;\n}\n","import type { EditorChain, EditorSession } from './types.js';\n\nexport const STANDARD_COMMANDS = {\n '\\\\alpha': { tex: '\\\\alpha', label: 'α', title: 'alpha' },\n '\\\\beta': { tex: '\\\\beta', label: 'β', title: 'beta' },\n '\\\\gamma': { tex: '\\\\gamma', label: 'γ', title: 'gamma' },\n '\\\\delta': { tex: '\\\\delta', label: 'δ', title: 'delta' },\n '\\\\epsilon': { tex: '\\\\epsilon', label: 'ε', title: 'epsilon' },\n '\\\\eta': { tex: '\\\\eta', label: 'η', title: 'eta' },\n '\\\\theta': { tex: '\\\\theta', label: 'θ', title: 'theta' },\n '\\\\lambda': { tex: '\\\\lambda', label: 'λ', title: 'lambda' },\n '\\\\mu': { tex: '\\\\mu', label: 'μ', title: 'mu' },\n '\\\\rho': { tex: '\\\\rho', label: 'ρ', title: 'rho' },\n '\\\\sigma': { tex: '\\\\sigma', label: 'σ', title: 'sigma' },\n '\\\\tau': { tex: '\\\\tau', label: 'τ', title: 'tau' },\n '\\\\phi': { tex: '\\\\phi', label: 'φ', title: 'phi' },\n '\\\\chi': { tex: '\\\\chi', label: 'χ', title: 'chi' },\n '\\\\psi': { tex: '\\\\psi', label: 'ψ', title: 'psi' },\n '\\\\omega': { tex: '\\\\omega', label: 'ω', title: 'omega' },\n '\\\\zeta': { tex: '\\\\zeta', label: 'ζ', title: 'zeta' },\n '\\\\nabla': { tex: '\\\\nabla', label: '∇', title: 'nabla' },\n '\\\\Delta': { tex: '\\\\Delta', label: 'Δ', title: 'Delta' },\n '\\\\partial': { tex: '\\\\partial', label: '∂', title: 'partial derivative' },\n '\\\\Longleftrightarrow': { tex: '\\\\Longleftrightarrow', label: '⟺', title: 'long equivalence arrow' },\n '\\\\backslash': { tex: '\\\\backslash', label: '∖', title: 'reverse solidus' },\n} as const;\n\nexport type StandardCommandTex = keyof typeof STANDARD_COMMANDS;\nexport type StandardCommandSpec = (typeof STANDARD_COMMANDS)[StandardCommandTex];\n\nexport function standardCommandSpec(tex: string): StandardCommandSpec | null {\n return Object.prototype.hasOwnProperty.call(STANDARD_COMMANDS, tex)\n ? STANDARD_COMMANDS[tex as StandardCommandTex]\n : null;\n}\n\nexport function isStandardCommandTex(tex: string): tex is StandardCommandTex {\n return standardCommandSpec(tex) !== null;\n}\n\nfunction chainHasStandardCommands(chain: EditorChain): boolean {\n for (const node of chain.nodes) {\n if (node.kind === 'standardCommand') {\n return true;\n }\n const childChains = [\n node.superscript,\n node.subscript,\n node.innerExpr,\n node.numerator,\n node.denominator,\n node.radicand,\n node.rootIndex,\n node.overExpr,\n node.underExpr,\n node.baseExpr,\n ];\n if (childChains.some((child) => child && chainHasStandardCommands(child))) {\n return true;\n }\n if (node.matrixRows?.some((row) => row.some(chainHasStandardCommands))) {\n return true;\n }\n }\n return false;\n}\n\nexport function sessionHasStandardCommands(session: EditorSession): boolean {\n return chainHasStandardCommands(session.englishTree) || chainHasStandardCommands(session.arabicTree);\n}\n","import type { EditorChain, EditorNode, EditorSession, EditorSide, EnvColumnAlignment, GridEnvName, MatrixEnvStyle } from './types.js';\nimport type { AccentCommandId } from './accentCommands.js';\nimport type { AtomicCommandId } from './atomicCommands.js';\nimport type { AtomicOperatorCommandId } from './atomicCommandsOperators.js';\n\nlet nextId = 1;\n\nfunction makeId(prefix: string): string {\n const id = `${prefix}_${String(nextId)}`;\n nextId += 1;\n return id;\n}\n\nexport function createEditorChain(nodes: EditorNode[] = []): EditorChain {\n return {\n id: makeId('chain'),\n nodes,\n };\n}\n\nexport function createEditorNode(kind: EditorNode['kind'], expr: string): EditorNode {\n return {\n id: makeId('node'),\n kind,\n expr,\n characterFont: undefined,\n superscript: null,\n subscript: null,\n leftDelimExpr: '',\n rightDelimExpr: '',\n innerExpr: null,\n numerator: null,\n denominator: null,\n radicand: null,\n rootIndex: null,\n overExpr: null,\n underExpr: null,\n baseExpr: null,\n envName: null,\n matrixStyle: null,\n matrixRows: null,\n columnAlignments: null,\n };\n}\n\nexport function createDelimiterNode(leftDelimExpr: string, rightDelimExpr: string): EditorNode {\n return {\n ...createEditorNode('delimiter', ''),\n leftDelimExpr,\n rightDelimExpr,\n innerExpr: createEditorChain(),\n };\n}\n\nexport function createBoxedNode(): EditorNode {\n return {\n ...createEditorNode('boxed', ''),\n innerExpr: createEditorChain(),\n };\n}\n\nexport function createFracNode(): EditorNode {\n return {\n ...createEditorNode('frac', ''),\n numerator: createEditorChain(),\n denominator: createEditorChain(),\n };\n}\n\nexport function createSqrtNode(): EditorNode {\n return {\n ...createEditorNode('sqrt', ''),\n radicand: createEditorChain(),\n rootIndex: createEditorChain(),\n };\n}\n\nexport function createOversetNode(): EditorNode {\n return {\n ...createEditorNode('overset', ''),\n overExpr: createEditorChain(),\n baseExpr: createEditorChain(),\n };\n}\n\nexport function createUndersetNode(): EditorNode {\n return {\n ...createEditorNode('underset', ''),\n underExpr: createEditorChain(),\n baseExpr: createEditorChain(),\n };\n}\n\nexport function createAccentNode(accentId: AccentCommandId): EditorNode {\n return {\n ...createEditorNode('accent', accentId),\n baseExpr: createEditorChain(),\n };\n}\n\nexport function createMatrixEnvNode(style: MatrixEnvStyle, rows: number, columns: number): EditorNode {\n return createGridEnvNode(style, rows, columns);\n}\n\nexport function createGridEnvNode(\n envName: GridEnvName,\n rows: number,\n columns: number,\n columnAlignments?: EnvColumnAlignment[],\n): EditorNode {\n const safeRows = Math.max(1, Math.min(12, Math.trunc(rows)));\n const safeColumns = envName === 'cases' ? 2 : Math.max(1, Math.min(12, Math.trunc(columns)));\n const matrixStyles = new Set<GridEnvName>(['matrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix', 'Vmatrix']);\n const isMatrix = matrixStyles.has(envName) && envName !== 'array' && envName !== 'aligned';\n return {\n ...createEditorNode('env', ''),\n envName,\n matrixStyle: isMatrix ? (envName as MatrixEnvStyle) : null,\n matrixRows: Array.from({ length: safeRows }, () =>\n Array.from({ length: safeColumns }, () => createEditorChain()),\n ),\n columnAlignments: envName === 'array'\n ? Array.from({ length: safeColumns }, (_, index) => columnAlignments?.[index] ?? 'c')\n : null,\n };\n}\n\nexport function createAtomicCommandNode(commandId: AtomicCommandId): EditorNode {\n return createEditorNode('atomicCommand', commandId);\n}\n\nexport function createAtomicOperatorCommandNode(commandId: AtomicOperatorCommandId): EditorNode {\n return createEditorNode('atomicOperatorCommand', commandId);\n}\n\nexport function cloneEditorSession(session: EditorSession): EditorSession {\n return {\n englishTree: structuredClone(session.englishTree),\n arabicTree: structuredClone(session.arabicTree),\n activeSide: session.activeSide,\n splitLeafTyping: session.splitLeafTyping,\n forceSplitNextLeaf: session.forceSplitNextLeaf,\n arabicReverseNumberTyping: session.arabicReverseNumberTyping,\n currentCharacterFont: session.currentCharacterFont ?? 'default',\n currentCharacterWrapper: session.currentCharacterWrapper ?? null,\n currentDigitForm: session.currentDigitForm ?? 'western',\n caret: { ...session.caret },\n selection: session.selection ? { ...session.selection } : null,\n selectedNodeId: session.selectedNodeId,\n selectedStructureNodeId: session.selectedStructureNodeId,\n sync: structuredClone(session.sync),\n debugLog: session.debugLog.slice(),\n };\n}\n\nfunction collectNodeIds(chain: EditorChain, ids: string[]): void {\n for (const node of chain.nodes) {\n ids.push(node.id);\n if (node.superscript) {\n collectNodeIds(node.superscript, ids);\n }\n if (node.subscript) {\n collectNodeIds(node.subscript, ids);\n }\n if (node.innerExpr) {\n collectNodeIds(node.innerExpr, ids);\n }\n if (node.numerator) {\n collectNodeIds(node.numerator, ids);\n }\n if (node.denominator) {\n collectNodeIds(node.denominator, ids);\n }\n if (node.rootIndex) {\n collectNodeIds(node.rootIndex, ids);\n }\n if (node.radicand) {\n collectNodeIds(node.radicand, ids);\n }\n if (node.overExpr) {\n collectNodeIds(node.overExpr, ids);\n }\n if (node.underExpr) {\n collectNodeIds(node.underExpr, ids);\n }\n if (node.baseExpr) {\n collectNodeIds(node.baseExpr, ids);\n }\n if (node.matrixRows) {\n for (const row of node.matrixRows) {\n for (const cell of row) {\n collectNodeIds(cell, ids);\n }\n }\n }\n }\n}\n\nexport function buildInitialSyncMap(englishTree: EditorChain, arabicTree: EditorChain): EditorSession['sync'] {\n const englishIds: string[] = [];\n const arabicIds: string[] = [];\n collectNodeIds(englishTree, englishIds);\n collectNodeIds(arabicTree, arabicIds);\n\n const all = new Set<string>([...englishIds, ...arabicIds]);\n const sync: EditorSession['sync'] = {};\n for (const nodeId of all) {\n sync[nodeId] = { expr: 'synced' };\n }\n return sync;\n}\n\nexport function createEditorSession(englishTree: EditorChain, arabicTree: EditorChain, activeSide: EditorSide = 'arabic'): EditorSession {\n return {\n englishTree,\n arabicTree,\n activeSide,\n splitLeafTyping: false,\n forceSplitNextLeaf: false,\n arabicReverseNumberTyping: true,\n currentCharacterFont: 'default',\n currentCharacterWrapper: null,\n currentDigitForm: 'western',\n caret: {\n chainId: englishTree.id,\n index: 0,\n },\n selection: null,\n selectedNodeId: null,\n selectedStructureNodeId: null,\n sync: buildInitialSyncMap(englishTree, arabicTree),\n debugLog: [],\n };\n}\n","import type { CharacterFontId } from './types.js';\n\nexport type CharacterFontSpec = {\n id: CharacterFontId;\n label: string;\n titleKey:\n | 'defaultFont'\n | 'takweenFont'\n | 'diwaniFont'\n | 'diwaniOutlineFont'\n | 'maghribiFont';\n cssClass?: string;\n mathJaxClass?: string;\n macro?: string;\n latexFontCommand?: string;\n latexFontFamily?: string;\n browserFontStack?: string;\n importAliases?: string[];\n svgLayoutKey?: string;\n};\n\nexport const CHARACTER_FONT_SPECS: CharacterFontSpec[] = [\n {\n id: 'default',\n label: 'س',\n titleKey: 'defaultFont',\n },\n {\n id: 'takween',\n label: 'تك',\n titleKey: 'takweenFont',\n cssClass: 'node-value--takween',\n mathJaxClass: 'butex-takween-text',\n macro: '\\\\butextakween',\n latexFontCommand: '\\\\takween',\n latexFontFamily: 'Takween',\n browserFontStack: '\"BuTeX Takween\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\takween'],\n svgLayoutKey: 'takween',\n },\n {\n id: 'diwani',\n label: 'ديو',\n titleKey: 'diwaniFont',\n cssClass: 'node-value--diwani',\n mathJaxClass: 'butex-diwani-text',\n macro: '\\\\butexdiwani',\n latexFontCommand: '\\\\diwani',\n latexFontFamily: 'Diwani Letter',\n browserFontStack: '\"Diwani Letter\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\diwani'],\n svgLayoutKey: 'diwani',\n },\n {\n id: 'diwaniOutline',\n label: 'ظل',\n titleKey: 'diwaniOutlineFont',\n cssClass: 'node-value--diwani-outline',\n mathJaxClass: 'butex-diwani-outline-text',\n macro: '\\\\butexdiwanioutline',\n latexFontCommand: '\\\\diwanioutlineshaded',\n latexFontFamily: 'Diwani Outline Shaded',\n browserFontStack: '\"BuTeX Diwani Outline\", \"Diwani Letter\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\diwanioutlineshaded'],\n svgLayoutKey: 'diwani-outline',\n },\n {\n id: 'maghribi',\n label: 'مغ',\n titleKey: 'maghribiFont',\n cssClass: 'node-value--maghribi',\n mathJaxClass: 'butex-maghribi-text',\n macro: '\\\\butexmaghribi',\n latexFontCommand: '\\\\maghribi',\n latexFontFamily: 'Almaghribi Warsh Quran',\n browserFontStack: '\"Almaghribi Warsh Quran\", Amiri, \"Segoe UI\", Tahoma, sans-serif',\n importAliases: ['\\\\maghribi'],\n svgLayoutKey: 'maghribi',\n },\n];\n\nexport const CHARACTER_FONT_OPTIONS = CHARACTER_FONT_SPECS.map(({ id, label }) => ({ id, label }));\n\nexport const NON_DEFAULT_CHARACTER_FONT_SPECS = CHARACTER_FONT_SPECS.filter(\n (font): font is CharacterFontSpec & { macro: string } => font.id !== 'default' && typeof font.macro === 'string',\n);\n\nexport function characterFontSpec(fontId: CharacterFontId): CharacterFontSpec {\n return CHARACTER_FONT_SPECS.find((font) => font.id === fontId) ?? CHARACTER_FONT_SPECS[0];\n}\n\nexport function characterFontSpecByMacro(macro: string): CharacterFontSpec | null {\n return NON_DEFAULT_CHARACTER_FONT_SPECS.find(\n (font) => font.macro === macro || font.importAliases?.includes(macro),\n ) ?? null;\n}\n","import type { EditorSide } from './types.js';\n\n/** LTR divide stroke stored on the English tree (reference OperatorObject `/`). */\nexport const DIVIDE_OPERATOR_EN = '/';\n\n/** RTL divide stroke shown on the Arabic editing surface. */\nexport const DIVIDE_OPERATOR_AR = '\\\\';\n\n/** Structured Burhan Arabic AST spelling of the same RTL divide stroke. */\nexport const DIVIDE_OPERATOR_AR_LATEX = '\\\\backslash';\n\nexport function isDivideOperatorExpr(expr: string): boolean {\n return (\n expr === DIVIDE_OPERATOR_EN ||\n expr === DIVIDE_OPERATOR_AR ||\n expr === DIVIDE_OPERATOR_AR_LATEX\n );\n}\n\nexport function divideOperatorSurfaceExpr(expr: string, side: EditorSide): string {\n if (!isDivideOperatorExpr(expr)) {\n return expr;\n }\n return side === 'arabic' ? DIVIDE_OPERATOR_AR : DIVIDE_OPERATOR_EN;\n}\n\nexport function renderDivideOperatorLatex(side: EditorSide): string {\n return side === 'arabic' ? '\\\\backslash' : DIVIDE_OPERATOR_EN;\n}\n","import type { EditorSide } from './types.js';\nimport {\n divideOperatorSurfaceExpr,\n isDivideOperatorExpr,\n renderDivideOperatorLatex,\n} from './divideOperator.js';\n\nconst RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE: Readonly<Record<string, string>> = {\n '<': '>',\n '>': '<',\n};\n\n/**\n * Return the visible glyph for a raw OperatorObject without changing its\n * canonical stored identity. Arabic chains reverse operand order, so\n * directional comparison glyphs must be mirrored at presentation time.\n */\nexport function rawOperatorSurfaceExpr(expr: string, side: EditorSide): string {\n if (isDivideOperatorExpr(expr)) {\n return divideOperatorSurfaceExpr(expr, side);\n }\n if (side === 'arabic') {\n return RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE[expr] ?? expr;\n }\n return expr;\n}\n\n/**\n * Render a raw OperatorObject as LaTeX for one editor side while preserving\n * the operator stored in the structured AST. BuTeX's mirror macro handles\n * directional glyph presentation for Arabic MathJax/XeLaTeX output.\n */\nexport function renderRawOperatorLatex(expr: string, side: EditorSide): string {\n if (isDivideOperatorExpr(expr)) {\n return renderDivideOperatorLatex(side);\n }\n if (\n side === 'arabic' &&\n Object.prototype.hasOwnProperty.call(RTL_DIRECTIONAL_RAW_OPERATOR_SURFACE, expr)\n ) {\n return `\\\\butexmirror{${expr}}`;\n }\n return expr;\n}\n","import type { EditorChain, EditorNode } from './types.js';\n\nexport function isIndexComma(node: EditorNode): boolean {\n return node.kind === 'operator' && (node.expr === ',' || node.expr === '،');\n}\n\n/** Only simple single-character indices and separating commas stay annotated. */\nexport function isValidIndexSequence(chain: EditorChain): boolean {\n let count = 0;\n let afterComma = false;\n for (const node of chain.nodes) {\n if (node.superscript || node.subscript) return false;\n if (isIndexComma(node)) {\n if (count === 0 || afterComma) return false;\n afterComma = true;\n continue;\n }\n const isDigit = node.kind === 'number' && /^[0-9]$/.test(node.expr);\n const identity = node.sourceLatex ?? node.expr;\n const isLetter = node.kind === 'char' &&\n (/^[A-Za-z]$/.test(identity) || (Array.from(identity).length === 1 && /^\\p{L}$/u.test(identity)));\n if (!isDigit && !isLetter) return false;\n count += 1;\n afterComma = false;\n if (count > 64) return false;\n }\n return count >= 2 && !afterComma;\n}\n","import type { DigitFormId, EditorChain, EditorNode, EditorSession, EnvColumnAlignment } from './types.js';\nimport { accentCommandSpec } from './accentCommands.js';\nimport { atomicCommandSpec } from './atomicCommands.js';\nimport { atomicOperatorCommandSpec } from './atomicCommandsOperators.js';\nimport { characterFontSpec } from './characterFonts.js';\nimport { renderRawOperatorLatex } from './rawOperatorPresentation.js';\nimport { formatDigits } from './digits.js';\nimport { isValidIndexSequence, isIndexComma } from './indexSequence.js';\n\ntype RenderOptions = {\n digitForm?: DigitFormId;\n casesPresentation?: boolean;\n};\n\nfunction selectedDigitForm(options?: RenderOptions): DigitFormId {\n return options?.digitForm ?? 'western';\n}\n\nfunction latinScripts(node: EditorNode, options?: RenderOptions): string {\n let scripts = '';\n if (node.superscript) {\n scripts += `^{${renderChainEnglish(node.superscript, options)}}`;\n }\n if (node.subscript) {\n scripts += `_{${renderChainEnglish(node.subscript, options)}}`;\n }\n return scripts;\n}\n\nfunction optionalRootIndexEnglish(node: EditorNode, options?: RenderOptions): string {\n if (!node.rootIndex) {\n return '';\n }\n const rendered = renderChainEnglish(node.rootIndex, options);\n return rendered === '' ? '' : `[${rendered}]`;\n}\n\nfunction optionalRootIndexArabic(node: EditorNode, options?: RenderOptions): string {\n if (!node.rootIndex) {\n return '';\n }\n const rendered = renderChainArabic(node.rootIndex, options);\n return rendered === '' ? '' : `[${rendered}]`;\n}\n\nfunction arabicScripts(node: EditorNode, content: string, options?: RenderOptions): string {\n const sup = node.superscript ? renderChainArabic(node.superscript, options) : '';\n const sub = node.subscript ? renderChainArabic(node.subscript, options) : '';\n if (sup !== '' || sub !== '') {\n return `\\\\prescript{${sup}}{${sub}}{${content}}`;\n }\n return content;\n}\n\nfunction renderMatrixRowsEnglish(node: EditorNode, options?: RenderOptions): string {\n if (!node.matrixRows) {\n return '';\n }\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return '';\n }\n const rows = node.matrixRows.map((row) => row.map((cell) => renderChainEnglish(cell, options)).join(' & '));\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows[0]?.length ?? 0).join('');\n return `\\\\begin{array}{${spec || 'c'}}${rows.join(' \\\\\\\\\\n')}\\\\end{array}`;\n }\n return `\\\\begin{${envName}}${rows.join(' \\\\\\\\\\n')}\\\\end{${envName}}`;\n}\n\nfunction reverseAlignmentForArabic(alignment: EnvColumnAlignment): EnvColumnAlignment {\n if (alignment === 'l') {\n return 'r';\n }\n if (alignment === 'r') {\n return 'l';\n }\n return 'c';\n}\n\nfunction renderMatrixRowsArabic(node: EditorNode, options?: RenderOptions): string {\n if (!node.matrixRows) {\n return '';\n }\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return '';\n }\n const rows = node.matrixRows.map((row) =>\n row\n .slice()\n .reverse()\n .map((cell) => renderChainArabic(cell, options))\n .join(' & '),\n );\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? [])\n .slice(0, node.matrixRows[0]?.length ?? 0)\n .reverse()\n .map(reverseAlignmentForArabic)\n .join('');\n return `\\\\begin{array}{${spec || 'c'}}${rows.join(' \\\\\\\\\\n')}\\\\end{array}`;\n }\n if (envName === 'cases' && options?.casesPresentation) {\n return `\\\\left.\\\\begin{array}{rl}${rows.join(' \\\\\\\\\\n')}\\\\end{array}\\\\right\\\\}`;\n }\n return `\\\\begin{${envName}}${rows.join(' \\\\\\\\\\n')}\\\\end{${envName}}`;\n}\n\nfunction renderAccentEnglish(\n command: 'overset' | 'underset',\n accent: EditorChain | null,\n base: EditorChain | null,\n options?: RenderOptions,\n): string {\n const baseTex = base ? renderChainEnglish(base, options) : '';\n const accentTex = accent ? renderChainEnglish(accent, options) : '';\n if (accentTex === '') {\n return baseTex;\n }\n return `\\\\${command}{${accentTex}}{${baseTex}}`;\n}\n\nfunction renderAccentArabic(\n command: 'overset' | 'underset',\n accent: EditorChain | null,\n base: EditorChain | null,\n options?: RenderOptions,\n): string {\n const baseTex = base ? renderChainArabic(base, options) : '';\n const accentTex = accent ? renderChainArabic(accent, options) : '';\n if (accentTex === '') {\n return baseTex;\n }\n return `\\\\${command}{${accentTex}}{${baseTex}}`;\n}\n\nfunction escapeText(s: string): string {\n return s.replace(/\\\\/g, '\\\\textbackslash{}').replace(/[{}]/g, '\\\\$&');\n}\n\n// Imported literal spans can contain already-escaped LaTeX punctuation.\n// Normalize these before escaping newly authored text, without double-escaping.\nfunction escapeAtomicLiteral(text: string): string {\n const unescaped = text.replace(/\\\\([%_&#{}$])/g, '$1');\n return escapeText(unescaped).replace(/[%_&#$]/g, '\\\\$&');\n}\n\nfunction renderCharContent(node: EditorNode, options?: RenderOptions): string {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const font = node.characterFont ?? 'default';\n const macro = characterFontSpec(font).macro;\n if (macro) {\n return `${macro}{${escapeText(expr)}}`;\n }\n return expr;\n}\n\nfunction renderNodeEnglish(node: EditorNode, options?: RenderOptions): string {\n if (node.kind === 'delimiter' && node.innerExpr) {\n return `${node.leftDelimExpr} ${renderChainEnglish(node.innerExpr, options)}${node.rightDelimExpr}${latinScripts(node, options)}`;\n }\n if (node.kind === 'boxed' && node.innerExpr) {\n const body = `\\\\boxed{${renderChainEnglish(node.innerExpr, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'frac' && node.numerator && node.denominator) {\n const body = `\\\\frac{${renderChainEnglish(node.numerator, options)}}{${renderChainEnglish(node.denominator, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'sqrt' && node.radicand) {\n const body = `\\\\sqrt${optionalRootIndexEnglish(node, options)}{${renderChainEnglish(node.radicand, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'overset' && node.baseExpr) {\n const body = renderAccentEnglish('overset', node.overExpr, node.baseExpr, options);\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'underset' && node.baseExpr) {\n const body = renderAccentEnglish('underset', node.underExpr, node.baseExpr, options);\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'accent' && node.baseExpr) {\n const cmd = accentCommandSpec(node.expr)?.englishTex ?? `\\\\${node.expr}`;\n const body = `${cmd}{${renderChainEnglish(node.baseExpr, options)}}`;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'env') {\n return `${renderMatrixRowsEnglish(node, options)}${latinScripts(node, options)}`;\n }\n if (node.kind === 'atomicCommand') {\n const body = atomicCommandSpec(node.expr)?.englishTex ?? node.expr;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'atomicOperatorCommand') {\n const body = node.sourceLatex === '\\\\le' || node.sourceLatex === '\\\\ge'\n ? node.sourceLatex : atomicOperatorCommandSpec(node.expr)?.Tex ?? node.expr;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'standardCommand') {\n return `${node.expr}${latinScripts(node, options)}`;\n }\n if (node.kind === 'char') {\n if (node.sourceLatex) {\n // Burhan's mapped bold Arabic character records the underlying English\n // variable on the inner text node. Keep the original variable identity\n // *and* its enclosing bold style when emitting interoperable English TeX.\n if (node.wrapperCommand === '\\\\boldarabic' || node.wrapperCommand === '\\\\mathbf') {\n const boldSource = node.sourceLatex.startsWith('\\\\mathbf{')\n ? node.sourceLatex\n : `\\\\mathbf{${node.sourceLatex}}`;\n return `${boldSource}${latinScripts(node, options)}`;\n }\n return `${node.sourceLatex}${latinScripts(node, options)}`;\n }\n if (node.wrapperCommand) {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const wrapper = node.wrapperCommand === '\\\\boldarabic' ? '\\\\mathbf' : node.wrapperCommand;\n const escaped = wrapper === '\\\\operatorname' || wrapper === '\\\\text'\n ? escapeAtomicLiteral(expr) : escapeText(expr);\n return `${wrapper}{${escaped}}${latinScripts(node, options)}`;\n }\n return `${renderCharContent(node, options)}${latinScripts(node, options)}`;\n }\n if (node.kind === 'operator') {\n return `${renderRawOperatorLatex(node.expr, 'english')}${latinScripts(node, options)}`;\n }\n return `${formatDigits(node.expr, selectedDigitForm(options))}${latinScripts(node, options)}`;\n}\n\nfunction renderNodeArabic(node: EditorNode, options?: RenderOptions): string {\n if (node.kind === 'delimiter' && node.innerExpr) {\n const content = `${node.leftDelimExpr}${renderChainArabic(node.innerExpr, options)}${node.rightDelimExpr}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'boxed' && node.innerExpr) {\n const content = `\\\\boxed{${renderChainArabic(node.innerExpr, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'frac' && node.numerator && node.denominator) {\n const content = `\\\\frac{${renderChainArabic(node.numerator, options)}}{${renderChainArabic(node.denominator, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'sqrt' && node.radicand) {\n const content = `\\\\arsqrt${optionalRootIndexArabic(node, options)}{${renderChainArabic(node.radicand, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'overset' && node.baseExpr) {\n const content = renderAccentArabic('overset', node.overExpr, node.baseExpr, options);\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'underset' && node.baseExpr) {\n const content = renderAccentArabic('underset', node.underExpr, node.baseExpr, options);\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'accent' && node.baseExpr) {\n const cmd = accentCommandSpec(node.expr)?.arabicTex ?? `\\\\${node.expr}`;\n const content = `${cmd}{${renderChainArabic(node.baseExpr, options)}}`;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'env') {\n return arabicScripts(node, renderMatrixRowsArabic(node, options), options);\n }\n if (node.kind === 'atomicCommand') {\n const spec = atomicCommandSpec(node.expr);\n const content = spec?.arabicRenderTex ?? spec?.arabicTex ?? node.expr;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'atomicOperatorCommand') {\n const spec = atomicOperatorCommandSpec(node.expr);\n const tex = spec?.Tex ?? node.expr;\n const content = spec?.mirror ? `\\\\butexmirror{${tex}}` : tex;\n return arabicScripts(node, content, options);\n }\n if (node.kind === 'standardCommand') {\n return arabicScripts(node, node.expr, options);\n }\n if (node.kind === 'char') {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const content = renderCharContent(node, options);\n if (node.wrapperCommand) {\n const wrapper = node.wrapperCommand === '\\\\mathbf' ? '\\\\boldarabic' : node.wrapperCommand;\n const literal = wrapper === '\\\\operatorname' || wrapper === '\\\\text'\n ? escapeAtomicLiteral(expr) : content;\n return arabicScripts(node, `${wrapper}{${literal}}`, options);\n }\n return arabicScripts(node, (node.characterFont ?? 'default') === 'default'\n ? `\\\\text{${escapeText(expr)}}`\n : content, options);\n }\n if (node.kind === 'operator') {\n return arabicScripts(node, renderRawOperatorLatex(node.expr, 'arabic'), options);\n }\n return arabicScripts(node, formatDigits(node.expr, selectedDigitForm(options)), options);\n}\n\nexport function renderChainEnglish(chain: EditorChain, options?: RenderOptions): string {\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n const atoms = chain.nodes.map((node) => isIndexComma(node) ? ',' : renderNodeEnglish(node, options));\n return '\\\\mathnormal{' + atoms.join('') + '}';\n }\n return chain.nodes.map((node) => renderNodeEnglish(node, options)).join(' ');\n}\n\nexport function renderChainArabic(chain: EditorChain, options?: RenderOptions): string {\n const rendered = chain.nodes.slice().reverse().map((node) => renderNodeArabic(node, options));\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n return '\\\\mathnormal{' + rendered.join('\\\\,') + '}';\n }\n return rendered.join(' ');\n}\n\nexport function renderEnglishLatexFromSession(session: EditorSession): string {\n return renderChainEnglish(session.englishTree, { digitForm: session.currentDigitForm ?? 'western' });\n}\n\nexport function renderArabicLatexFromSession(session: EditorSession): string {\n return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? 'western' });\n}\n\n/** Render-only RTL cases; never use this for source or stored MathObjects. */\nexport function renderArabicPreviewLatexFromSession(session: EditorSession): string {\n return renderChainArabic(session.arabicTree, { digitForm: session.currentDigitForm ?? 'western', casesPresentation: true });\n}\n","import { caretStep } from './caretOrder.js';\nimport {\n type EditorFragment,\n regenerateFragmentIds,\n serializeSelection,\n} from './clipboard.js';\nimport {\n cloneEditorSession,\n createDelimiterNode,\n createEditorChain,\n createEditorNode,\n createFracNode,\n createSqrtNode,\n createAccentNode,\n createOversetNode,\n createUndersetNode,\n createGridEnvNode,\n createAtomicCommandNode,\n createAtomicOperatorCommandNode,\n} from './factory.js';\nimport { renderArabicLatexFromSession, renderEnglishLatexFromSession } from './render.js';\nimport { formatDigits } from './digits.js';\nimport { buildFirstDerivativeFrac, buildSecondDerivativeFrac, derivativeTemplateInitialCaret } from './derivativeTemplates.js';\nimport {\n buildLimitsSeriesTemplate,\n limitsSeriesTemplateInitialCaret,\n buildAccentPairTemplate,\n accentPairTemplateInitialCaret,\n} from './limitsTemplates.js';\nimport { DIVIDE_OPERATOR_AR, DIVIDE_OPERATOR_EN } from './divideOperator.js';\nimport { coveredNodeIds, isSelectionActive, nodeChildChains, normalizeSelection } from './selection.js';\nimport { activeTreeKey, findChainById, findNodeById, passiveTreeKey } from './traversal.js';\nimport type {\n CharacterFontId,\n DigitFormId,\n EditorChain,\n EditorDebugEntry,\n EditorNode,\n EditorSession,\n EditorSide,\n EnvColumnAlignment,\n GridEnvName,\n MatrixEnvStyle,\n} from './types.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport { equationEditorMessages } from './uiLocale.js';\nimport type { AccentCommandId } from './accentCommands.js';\nimport type { AtomicCommandId } from './atomicCommands.js';\nimport type { AtomicOperatorCommandId } from './atomicCommandsOperators.js';\n\nfunction ensureSyncEntry(session: EditorSession, nodeId: string): void {\n if (!session.sync[nodeId]) {\n session.sync[nodeId] = { expr: 'synced' };\n }\n}\n\nfunction markExprSync(session: EditorSession, nodeId: string): void {\n const english = findNodeById(session.englishTree, nodeId);\n const arabic = findNodeById(session.arabicTree, nodeId);\n ensureSyncEntry(session, nodeId);\n if (!english || !arabic) {\n session.sync[nodeId].expr = 'diverged';\n return;\n }\n session.sync[nodeId].expr = english.node.expr === arabic.node.expr ? 'synced' : 'diverged';\n}\n\nfunction clearSourceIdentity(session: EditorSession, nodeId: string): void {\n const english = findNodeById(session.englishTree, nodeId);\n const arabic = findNodeById(session.arabicTree, nodeId);\n // An Arabic label edit changes presentation, not the canonical source.\n // English-side edits still replace the source, as before.\n if (session.activeSide === 'arabic' && english?.node.kind === 'char' &&\n ['\\\\mathtt', '\\\\operatorname', '\\\\text'].includes(english.node.wrapperCommand ?? '') &&\n english.node.sourceLatex) {\n return;\n }\n if (english) {\n delete english.node.sourceLatex;\n }\n if (arabic) {\n delete arabic.node.sourceLatex;\n }\n}\n\n\n/** Keep highlighted node aligned with caret (keyboard + programmatic caret moves). */\nexport function syncSelectionToCaret(session: EditorSession): void {\n const activeKey = activeTreeKey(session.activeSide);\n const tree = session[activeKey];\n const { chainId, index } = session.caret;\n const located = findChainById(tree, chainId);\n if (!located) {\n session.selectedNodeId = null;\n return;\n }\n if (index > 0) {\n session.selectedNodeId = located.chain.nodes[index - 1].id;\n return;\n }\n if (located.relation.kind === 'superscript' || located.relation.kind === 'subscript') {\n session.selectedNodeId = located.relation.ownerNodeId;\n return;\n }\n if (\n located.relation.kind === 'inner' ||\n located.relation.kind === 'numerator' ||\n located.relation.kind === 'denominator' ||\n located.relation.kind === 'radicand' ||\n located.relation.kind === 'rootIndex' ||\n located.relation.kind === 'overExpr' ||\n located.relation.kind === 'underExpr' ||\n located.relation.kind === 'baseExpr' ||\n located.relation.kind === 'matrixCell'\n ) {\n session.selectedNodeId = located.relation.ownerNodeId;\n return;\n }\n session.selectedNodeId = null;\n}\n\nfunction appendDebug(session: EditorSession, command: string, note: string): void {\n const entry: EditorDebugEntry = {\n timestamp: new Date().toISOString(),\n command,\n activeSide: session.activeSide,\n englishLatex: renderEnglishLatexFromSession(session),\n arabicLatex: renderArabicLatexFromSession(session),\n renderOk: true,\n renderError: null,\n note,\n };\n const nextLog = session.debugLog.concat(entry);\n session.debugLog = nextLog.slice(-120);\n}\n\nfunction insertMirroredNode(session: EditorSession, chainId: string, index: number, englishNode: EditorNode, arabicNode: EditorNode): void {\n const englishLocated = findChainById(session.englishTree, chainId);\n const arabicLocated = findChainById(session.arabicTree, chainId);\n if (!englishLocated || !arabicLocated) {\n return;\n }\n const safeIndex = Math.max(0, Math.min(index, englishLocated.chain.nodes.length));\n englishLocated.chain.nodes.splice(safeIndex, 0, englishNode);\n arabicLocated.chain.nodes.splice(safeIndex, 0, arabicNode);\n ensureSyncEntry(session, englishNode.id);\n markExprSync(session, englishNode.id);\n}\n\nfunction syncMatrixCellChainIds(englishNode: EditorNode, arabicNode: EditorNode): void {\n const englishRows = englishNode.matrixRows ?? [];\n const arabicRows = arabicNode.matrixRows ?? [];\n const rowLimit = Math.min(englishRows.length, arabicRows.length);\n for (let rowIndex = 0; rowIndex < rowLimit; rowIndex += 1) {\n const englishRow = englishRows[rowIndex];\n const arabicRow = arabicRows[rowIndex];\n const columnLimit = Math.min(englishRow.length, arabicRow.length);\n for (let columnIndex = 0; columnIndex < columnLimit; columnIndex += 1) {\n arabicRow[columnIndex].id = englishRow[columnIndex].id;\n }\n }\n}\n\nfunction createMatrixRow(columnCount: number): EditorChain[] {\n return Array.from({ length: columnCount }, () => createEditorChain());\n}\n\nfunction findSelectedMatrixPair(session: EditorSession): { english: EditorNode; arabic: EditorNode } | null {\n const targetNodeId = session.selectedStructureNodeId ?? session.selectedNodeId;\n if (!targetNodeId) {\n return null;\n }\n const englishLocated = findNodeById(session.englishTree, targetNodeId);\n const arabicLocated = findNodeById(session.arabicTree, targetNodeId);\n if (!englishLocated || !arabicLocated) {\n return null;\n }\n if (englishLocated.node.kind !== 'env' || arabicLocated.node.kind !== 'env') {\n return null;\n }\n return { english: englishLocated.node, arabic: arabicLocated.node };\n}\n\nfunction normalizeArrayAlignments(node: EditorNode): void {\n if ((node.envName ?? node.matrixStyle) !== 'array' || !node.matrixRows) {\n return;\n }\n const columnCount = Math.max(1, node.matrixRows[0]?.length ?? 1);\n const current = node.columnAlignments ?? [];\n node.columnAlignments = Array.from({ length: columnCount }, (_, index) => current[index] ?? 'c');\n}\n\nfunction removeMirroredNodeById(session: EditorSession, nodeId: string): boolean {\n const englishLocated = findNodeById(session.englishTree, nodeId);\n const arabicLocated = findNodeById(session.arabicTree, nodeId);\n if (!englishLocated || !arabicLocated) {\n return false;\n }\n englishLocated.chain.nodes.splice(englishLocated.index, 1);\n arabicLocated.chain.nodes.splice(arabicLocated.index, 1);\n delete session.sync[nodeId];\n return true;\n}\n\n/**\n * Mutates `next` to remove every node covered by its current selection (mirrored\n * across EN/AR), parks the caret at selection.start, and clears the selection.\n * Returns true when something was removed.\n */\nfunction applyDeleteSelectionRange(next: EditorSession): boolean {\n if (!isSelectionActive(next.selection)) {\n next.selection = null;\n return false;\n }\n const ids = coveredNodeIds(next);\n if (ids.length === 0) {\n next.selection = null;\n return false;\n }\n const sel = next.selection;\n if (!sel) {\n return false;\n }\n const start = Math.min(sel.anchorIndex, sel.focusIndex);\n const chainId = sel.chainId;\n for (const id of ids) {\n removeMirroredNodeById(next, id);\n }\n next.caret = { chainId, index: start };\n next.selection = null;\n next.selectedStructureNodeId = null;\n return true;\n}\n\n/** Recursively ensure sync entries for an inserted mirrored subtree (top + nested). */\nfunction syncSubtreeRecursive(session: EditorSession, eng: EditorNode, ar: EditorNode): void {\n ensureSyncEntry(session, eng.id);\n markExprSync(session, eng.id);\n const engChains = nodeChildChains(eng);\n const arChains = nodeChildChains(ar);\n const limit = Math.min(engChains.length, arChains.length);\n for (let c = 0; c < limit; c += 1) {\n const ec = engChains[c];\n const ac = arChains[c];\n const innerLimit = Math.min(ec.nodes.length, ac.nodes.length);\n for (let j = 0; j < innerLimit; j += 1) {\n syncSubtreeRecursive(session, ec.nodes[j], ac.nodes[j]);\n }\n }\n}\n\nexport function switchSide(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n next.activeSide = next.activeSide === 'english' ? 'arabic' : 'english';\n next.selection = null;\n appendDebug(next, 'switchSide', `active=${next.activeSide}`);\n return next;\n}\n\nexport function setSplitLeafTyping(session: EditorSession, enabled: boolean): EditorSession {\n const next = cloneEditorSession(session);\n next.splitLeafTyping = enabled;\n appendDebug(next, 'setSplitLeafTyping', enabled ? 'on' : 'off');\n return next;\n}\n\nexport function setArabicReverseNumberTyping(session: EditorSession, enabled: boolean): EditorSession {\n const next = cloneEditorSession(session);\n next.arabicReverseNumberTyping = enabled;\n appendDebug(next, 'setArabicReverseNumberTyping', enabled ? 'on' : 'off');\n return next;\n}\n\nexport function setCaret(session: EditorSession, chainId: string, index: number): EditorSession {\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findChainById(next[activeKey], chainId);\n if (!located) {\n return session;\n }\n next.caret = {\n chainId,\n index: Math.max(0, Math.min(index, located.chain.nodes.length)),\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n return next;\n}\n\nexport function moveCaret(session: EditorSession, delta: -1 | 1): EditorSession {\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const tree = next[activeKey];\n const located = findChainById(tree, next.caret.chainId);\n if (!located) {\n return session;\n }\n next.caret = caretStep(tree, next.caret, delta);\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaret', `delta=${String(delta)} dfs`);\n return next;\n}\n\nexport function horizontalCaretDelta(session: EditorSession, direction: 'left' | 'right'): -1 | 1 {\n const activeKey = activeTreeKey(session.activeSide);\n const tree = session[activeKey];\n const located = findChainById(tree, session.caret.chainId);\n const inMatrixCell = located?.relation.kind === 'matrixCell';\n const canMoveInsideCell =\n inMatrixCell &&\n session.activeSide === 'arabic' &&\n ((direction === 'left' && session.caret.index < located.chain.nodes.length) ||\n (direction === 'right' && session.caret.index > 0));\n if (session.activeSide === 'arabic' && (!inMatrixCell || canMoveInsideCell)) {\n return direction === 'left' ? 1 : -1;\n }\n return direction === 'left' ? -1 : 1;\n}\n\nexport function moveCaretHorizontal(session: EditorSession, direction: 'left' | 'right'): EditorSession {\n const activeKey = activeTreeKey(session.activeSide);\n const tree = session[activeKey];\n const located = findChainById(tree, session.caret.chainId);\n if (!located || located.relation.kind !== 'matrixCell') {\n return moveCaret(session, horizontalCaretDelta(session, direction));\n }\n\n const textDelta = session.activeSide === 'arabic'\n ? direction === 'left' ? 1 : -1\n : direction === 'left' ? -1 : 1;\n const nextIndex = session.caret.index + textDelta;\n if (nextIndex >= 0 && nextIndex <= located.chain.nodes.length) {\n return moveCaret(session, textDelta);\n }\n\n const ownerLocated =\n located.relation.ownerNodeId !== null ? findNodeById(tree, located.relation.ownerNodeId) : null;\n const ownerNode = ownerLocated?.node ?? null;\n if (!ownerLocated || !ownerNode?.matrixRows) {\n return session;\n }\n\n const rowIndex = located.relation.rowIndex ?? 0;\n const columnIndex = located.relation.columnIndex ?? 0;\n const row = ownerNode.matrixRows[rowIndex];\n if (!row) {\n return session;\n }\n\n const toVisualIndex = (column: number, columnCount: number): number =>\n session.activeSide === 'arabic' ? columnCount - 1 - column : column;\n const fromVisualIndex = (visualColumn: number, columnCount: number): number =>\n session.activeSide === 'arabic' ? columnCount - 1 - visualColumn : visualColumn;\n const entryIndex = (cell: EditorChain): number => {\n if (session.activeSide === 'arabic') {\n return direction === 'left' ? 0 : cell.nodes.length;\n }\n return direction === 'left' ? cell.nodes.length : 0;\n };\n\n const visualDelta = direction === 'left' ? -1 : 1;\n const currentVisualIndex = toVisualIndex(columnIndex, row.length);\n let targetRowIndex = rowIndex;\n let targetVisualIndex = currentVisualIndex + visualDelta;\n\n if (targetVisualIndex < 0 || targetVisualIndex >= row.length) {\n if (direction === 'left') {\n if (session.activeSide === 'arabic') {\n targetRowIndex = rowIndex + 1;\n const targetRow = ownerNode.matrixRows[targetRowIndex];\n if (targetRow) {\n targetVisualIndex = targetRow.length - 1;\n }\n } else {\n targetRowIndex = rowIndex - 1;\n const targetRow = ownerNode.matrixRows[targetRowIndex];\n if (targetRow) {\n targetVisualIndex = targetRow.length - 1;\n }\n }\n } else if (session.activeSide === 'arabic') {\n targetRowIndex = rowIndex - 1;\n targetVisualIndex = 0;\n } else {\n targetRowIndex = rowIndex + 1;\n targetVisualIndex = 0;\n }\n }\n\n const targetRow = ownerNode.matrixRows[targetRowIndex];\n if (targetRow && targetVisualIndex >= 0 && targetVisualIndex < targetRow.length) {\n const targetColumnIndex = fromVisualIndex(targetVisualIndex, targetRow.length);\n const targetCell = targetRow[targetColumnIndex];\n if (targetCell) {\n const next = cloneEditorSession(session);\n next.caret = { chainId: targetCell.id, index: entryIndex(targetCell) };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretHorizontal', `matrix-${direction}`);\n return next;\n }\n }\n\n const next = cloneEditorSession(session);\n const exitsAfter =\n (session.activeSide === 'english' && direction === 'right') ||\n (session.activeSide === 'arabic' && direction === 'left');\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: exitsAfter ? ownerLocated.index + 1 : ownerLocated.index,\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretHorizontal', `matrix-${direction}-exit`);\n return next;\n}\n\nexport function moveCaretVertical(session: EditorSession, direction: 'up' | 'down'): EditorSession {\n const next = cloneEditorSession(session);\n next.selection = null;\n const activeKey = activeTreeKey(next.activeSide);\n const tree = next[activeKey];\n const located = findChainById(tree, next.caret.chainId);\n if (!located) {\n return session;\n }\n\n const ownerLocated =\n located.relation.ownerNodeId !== null ? findNodeById(tree, located.relation.ownerNodeId) : null;\n const ownerNode = ownerLocated?.node ?? null;\n\n if (located.relation.kind === 'numerator' && ownerLocated && ownerNode && ownerNode.denominator) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.denominator.id,\n index: ownerNode.denominator.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-num->den');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-num-up-exit');\n return next;\n }\n\n if (located.relation.kind === 'denominator' && ownerLocated && ownerNode && ownerNode.numerator) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.numerator.id,\n index: ownerNode.numerator.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-den->num');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'frac-den-down-exit');\n return next;\n }\n\n if (located.relation.kind === 'rootIndex' && ownerLocated && ownerNode && ownerNode.radicand) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.radicand.id,\n index: ownerNode.radicand.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-root->radicand');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-root-up-exit');\n return next;\n }\n\n if (located.relation.kind === 'radicand' && ownerLocated && ownerNode && ownerNode.rootIndex) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.rootIndex.id,\n index: ownerNode.rootIndex.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-radicand->root');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sqrt-radicand-down-exit');\n return next;\n }\n\n if (located.relation.kind === 'overExpr' && ownerLocated && ownerNode && ownerNode.baseExpr) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.baseExpr.id,\n index: ownerNode.baseExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-over->base');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-over-up-exit');\n return next;\n }\n\n if (\n located.relation.kind === 'baseExpr' &&\n ownerLocated &&\n ownerNode &&\n ownerNode.kind === 'overset' &&\n ownerNode.overExpr\n ) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.overExpr.id,\n index: ownerNode.overExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-base->over');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'overset-base-down-exit');\n return next;\n }\n\n if (\n located.relation.kind === 'baseExpr' &&\n ownerLocated &&\n ownerNode &&\n ownerNode.kind === 'underset' &&\n ownerNode.underExpr\n ) {\n if (direction === 'down') {\n next.caret = {\n chainId: ownerNode.underExpr.id,\n index: ownerNode.underExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-base->under');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-base-up-exit');\n return next;\n }\n\n if (located.relation.kind === 'underExpr' && ownerLocated && ownerNode && ownerNode.baseExpr) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerNode.baseExpr.id,\n index: ownerNode.baseExpr.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-under->base');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'underset-under-down-exit');\n return next;\n }\n\n if (\n located.relation.kind === 'baseExpr' &&\n ownerLocated &&\n ownerNode &&\n ownerNode.kind === 'accent'\n ) {\n if (direction === 'up') {\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'accent-base-up-exit');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'accent-base-down-exit');\n return next;\n }\n\n if (located.relation.kind === 'matrixCell' && ownerLocated && ownerNode?.matrixRows) {\n const rowIndex = located.relation.rowIndex ?? 0;\n const columnIndex = located.relation.columnIndex ?? 0;\n const nextRowIndex = direction === 'up' ? rowIndex - 1 : rowIndex + 1;\n if (nextRowIndex >= 0 && nextRowIndex < ownerNode.matrixRows.length) {\n const nextRow = ownerNode.matrixRows[nextRowIndex];\n const nextCell = nextRow[Math.min(columnIndex, nextRow.length - 1)];\n if (nextCell) {\n next.caret = {\n chainId: nextCell.id,\n index: nextCell.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'matrix-cell');\n return next;\n }\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: direction === 'up' ? ownerLocated.index : ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', `matrix-${direction}-exit`);\n return next;\n }\n\n if (located.relation.kind === 'superscript' && ownerLocated && ownerNode) {\n if (direction === 'down') {\n if (ownerNode.subscript) {\n next.caret = {\n chainId: ownerNode.subscript.id,\n index: ownerNode.subscript.nodes.length,\n };\n } else {\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sup->down');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sup->up-exit');\n return next;\n }\n\n if (located.relation.kind === 'subscript' && ownerLocated && ownerNode) {\n if (direction === 'up') {\n if (ownerNode.superscript) {\n next.caret = {\n chainId: ownerNode.superscript.id,\n index: ownerNode.superscript.nodes.length,\n };\n } else {\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index,\n };\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sub->up');\n return next;\n }\n next.caret = {\n chainId: ownerLocated.chain.id,\n index: ownerLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', 'sub->down-exit');\n return next;\n }\n\n if (located.relation.kind !== 'root' && located.relation.kind !== 'inner') {\n return session;\n }\n\n const caretIdx = next.caret.index;\n if (caretIdx <= 0) {\n return session;\n }\n const nodeBeforeCaret = located.chain.nodes[caretIdx - 1];\n if (!nodeBeforeCaret) {\n return session;\n }\n\n const targetChain =\n direction === 'up'\n ? nodeBeforeCaret.superscript ?? nodeBeforeCaret.subscript\n : nodeBeforeCaret.subscript ?? nodeBeforeCaret.superscript;\n\n if (!targetChain) {\n return session;\n }\n next.caret = {\n chainId: targetChain.id,\n index: targetChain.nodes.length,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'moveCaretVertical', `base->script:${direction}`);\n return next;\n}\n\nfunction insertLeaf(session: EditorSession, kind: 'char' | 'number' | 'operator', expr: string): EditorSession {\n const next = cloneEditorSession(session);\n const englishNode = createEditorNode(kind, expr);\n const arabicNode = createEditorNode(kind, expr);\n if (kind === 'char' && next.currentCharacterWrapper === '\\\\boldarabic') {\n englishNode.wrapperCommand = '\\\\boldarabic';\n arabicNode.wrapperCommand = '\\\\boldarabic';\n } else if (kind === 'char' && (next.currentCharacterFont ?? 'default') !== 'default') {\n englishNode.characterFont = next.currentCharacterFont;\n arabicNode.characterFont = next.currentCharacterFont;\n }\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertLeaf', `${kind}:${expr}`);\n return next;\n}\n\n/** When Arabic active and flag on, number fragments prepend on both mirrored exprs (same printed string on EN/AR). */\nfunction shouldReverseArabicNumber(session: EditorSession): boolean {\n return session.activeSide === 'arabic' && session.arabicReverseNumberTyping;\n}\n\nfunction characterTypingStyleOf(node: EditorNode): string {\n if (node.kind !== 'char') return 'none';\n return node.wrapperCommand\n ? `wrapper:${node.wrapperCommand}`\n : `font:${node.characterFont ?? 'default'}`;\n}\n\nfunction currentCharacterTypingStyle(session: EditorSession): string {\n return session.currentCharacterWrapper\n ? `wrapper:${session.currentCharacterWrapper}`\n : `font:${session.currentCharacterFont ?? 'default'}`;\n}\n\n/** When split mode is off: merge into adjacent same-kind leaf (append after node at index-1, else prepend node at index). */\nfunction tryMergeLeafTyping(session: EditorSession, kind: 'char' | 'number', fragment: string): boolean {\n const engLocated = findChainById(session.englishTree, session.caret.chainId);\n if (!engLocated) {\n return false;\n }\n // Index digits are individual atoms, never merge them into an integer.\n if (engLocated.chain.indexSequence) return false;\n const nodes = engLocated.chain.nodes;\n const i = session.caret.index;\n let targetId: string | null = null;\n let prepend = false;\n if (i > 0) {\n const prev = nodes[i - 1];\n if (prev.kind === kind && (kind !== 'char' || characterTypingStyleOf(prev) === currentCharacterTypingStyle(session))) {\n targetId = prev.id;\n prepend = false;\n }\n }\n if (!targetId && i < nodes.length) {\n const fwd = nodes[i];\n if (fwd.kind === kind && (kind !== 'char' || characterTypingStyleOf(fwd) === currentCharacterTypingStyle(session))) {\n targetId = fwd.id;\n prepend = true;\n }\n }\n if (!targetId) {\n return false;\n }\n const englishHit = findNodeById(session.englishTree, targetId);\n const arabicHit = findNodeById(session.arabicTree, targetId);\n if (!englishHit || !arabicHit) {\n return false;\n }\n const prependBoth = kind === 'number' && shouldReverseArabicNumber(session) ? true : prepend;\n if (prependBoth) {\n englishHit.node.expr = `${fragment}${englishHit.node.expr}`;\n arabicHit.node.expr = `${fragment}${arabicHit.node.expr}`;\n } else {\n englishHit.node.expr = `${englishHit.node.expr}${fragment}`;\n arabicHit.node.expr = `${arabicHit.node.expr}${fragment}`;\n }\n clearSourceIdentity(session, targetId);\n markExprSync(session, targetId);\n return true;\n}\n\n/**\n * Replace any active selection with a freshly-cleared range, then return a base\n * session ready for the actual insert. Mutating helper so reducers stay short.\n */\nfunction replaceSelectionFirst(session: EditorSession): EditorSession {\n if (!isSelectionActive(session.selection)) {\n return session;\n }\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n return next;\n}\n\n/** Returns true when the node before the caret is a pure-digit number leaf (no existing dot). */\nfunction precedingIsExtendableNumber(session: EditorSession): boolean {\n const located = findChainById(session.englishTree, session.caret.chainId);\n if (!located || session.caret.index <= 0) {\n return false;\n }\n const prev = located.chain.nodes[session.caret.index - 1];\n if (!prev || prev.kind !== 'number') {\n return false;\n }\n if (prev.expr.includes('.')) {\n return false;\n }\n return /^\\d+$/.test(prev.expr);\n}\n\n/** One-shot: forces the next insertChar/insertNumber to start a new leaf instead of merging. No-op in split mode. */\nexport function breakLeafTyping(session: EditorSession): EditorSession {\n if (session.splitLeafTyping) {\n return session;\n }\n const next = cloneEditorSession(session);\n next.forceSplitNextLeaf = true;\n appendDebug(next, 'breakLeafTyping', 'split-next');\n return next;\n}\n\nexport function setCurrentCharacterFont(session: EditorSession, fontId: CharacterFontId): EditorSession {\n const next = cloneEditorSession(session);\n next.currentCharacterFont = fontId;\n next.currentCharacterWrapper = null;\n appendDebug(next, 'setCurrentCharacterFont', fontId);\n return next;\n}\n\nexport function setCurrentBoldCharacterStyle(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n next.currentCharacterFont = 'default';\n next.currentCharacterWrapper = '\\\\boldarabic';\n appendDebug(next, 'setCurrentBoldCharacterStyle', '\\\\boldarabic');\n return next;\n}\n\nexport function toggleTakweenCharacterFont(session: EditorSession): EditorSession {\n return setCurrentCharacterFont(session, (session.currentCharacterFont ?? 'default') === 'takween' ? 'default' : 'takween');\n}\n\nexport function setCurrentDigitForm(session: EditorSession, digitForm: DigitFormId): EditorSession {\n const next = cloneEditorSession(session);\n next.currentDigitForm = digitForm;\n appendDebug(next, 'setCurrentDigitForm', digitForm);\n return next;\n}\n\nexport function insertChar(session: EditorSession, expr: string): EditorSession {\n // Treat Western, Arabic-Indic, and Persian-Indic keyboard digits as numbers.\n const digit = formatDigits(expr, 'western');\n if (/^[0-9]$/.test(digit)) return insertNumber(session, digit);\n const base = replaceSelectionFirst(session);\n if (!base.splitLeafTyping && !base.forceSplitNextLeaf) {\n const next = cloneEditorSession(base);\n if (tryMergeLeafTyping(next, 'char', expr)) {\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'mergeLeaf', `char:${expr}`);\n return next;\n }\n }\n const inserted = insertLeaf(base, 'char', expr);\n inserted.forceSplitNextLeaf = false;\n return inserted;\n}\n\nexport function insertNumber(session: EditorSession, expr: string): EditorSession {\n const digit = formatDigits(expr, 'western');\n const base = replaceSelectionFirst(session);\n if (!base.splitLeafTyping && !base.forceSplitNextLeaf) {\n const next = cloneEditorSession(base);\n if (tryMergeLeafTyping(next, 'number', digit)) {\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'mergeLeaf', `number:${expr}`);\n return next;\n }\n }\n const inserted = insertLeaf(base, 'number', digit);\n inserted.forceSplitNextLeaf = false;\n return inserted;\n}\n\nexport function insertDivideOperator(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createEditorNode('operator', DIVIDE_OPERATOR_EN);\n const arabicNode = createEditorNode('operator', DIVIDE_OPERATOR_AR);\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n markExprSync(next, englishNode.id);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertDivideOperator', '');\n return next;\n}\n\nexport function insertOperator(session: EditorSession, expr: string): EditorSession {\n if (expr === '.' && !session.splitLeafTyping && precedingIsExtendableNumber(session)) {\n return insertNumber(session, '.');\n }\n if (expr === DIVIDE_OPERATOR_EN || expr === DIVIDE_OPERATOR_AR) {\n return insertDivideOperator(session);\n }\n const base = replaceSelectionFirst(session);\n return insertLeaf(base, 'operator', expr);\n}\n\nexport function insertAtomicCommand(session: EditorSession, commandId: AtomicCommandId): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createAtomicCommandNode(commandId);\n const arabicNode = createAtomicCommandNode(commandId);\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAtomicCommand', commandId);\n return next;\n}\n\nexport function insertAtomicOperatorCommand(session: EditorSession, commandId: AtomicOperatorCommandId): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createAtomicOperatorCommandNode(commandId);\n const arabicNode = createAtomicOperatorCommandNode(commandId);\n arabicNode.id = englishNode.id;\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret.index += 1;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAtomicOperatorCommand', commandId);\n return next;\n}\n\nexport function insertDelimiterPair(session: EditorSession, leftDelimExpr: string, rightDelimExpr: string): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createDelimiterNode(leftDelimExpr, rightDelimExpr);\n const arabicNode = createDelimiterNode(leftDelimExpr, rightDelimExpr);\n arabicNode.id = englishNode.id;\n if (arabicNode.innerExpr && englishNode.innerExpr) {\n arabicNode.innerExpr.id = englishNode.innerExpr.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.innerExpr ? englishNode.innerExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertDelimiterPair', `${leftDelimExpr}${rightDelimExpr}`);\n return next;\n}\n\nexport function insertFraction(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createFracNode();\n const arabicNode = createFracNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.numerator && englishNode.numerator) {\n arabicNode.numerator.id = englishNode.numerator.id;\n }\n if (arabicNode.denominator && englishNode.denominator) {\n arabicNode.denominator.id = englishNode.denominator.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.numerator ? englishNode.numerator.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertFraction', '');\n return next;\n}\n\nfunction insertDerivativeFrac(\n session: EditorSession,\n build: () => { english: EditorNode; arabic: EditorNode },\n debugLabel: string,\n): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const { english, arabic } = build();\n insertMirroredNode(next, next.caret.chainId, next.caret.index, english, arabic);\n syncSubtreeRecursive(next, english, arabic);\n next.caret = derivativeTemplateInitialCaret(english);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, debugLabel, '');\n return next;\n}\n\nexport function insertFirstDerivative(session: EditorSession): EditorSession {\n return insertDerivativeFrac(session, buildFirstDerivativeFrac, 'insertFirstDerivative');\n}\n\nexport function insertSecondDerivative(session: EditorSession): EditorSession {\n return insertDerivativeFrac(session, buildSecondDerivativeFrac, 'insertSecondDerivative');\n}\n\nexport function insertSqrt(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createSqrtNode();\n const arabicNode = createSqrtNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.radicand && englishNode.radicand) {\n arabicNode.radicand.id = englishNode.radicand.id;\n }\n if (arabicNode.rootIndex && englishNode.rootIndex) {\n arabicNode.rootIndex.id = englishNode.rootIndex.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.radicand ? englishNode.radicand.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertSqrt', '');\n return next;\n}\n\nexport function insertOverset(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createOversetNode();\n const arabicNode = createOversetNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.overExpr && englishNode.overExpr) {\n arabicNode.overExpr.id = englishNode.overExpr.id;\n }\n if (arabicNode.baseExpr && englishNode.baseExpr) {\n arabicNode.baseExpr.id = englishNode.baseExpr.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.overExpr ? englishNode.overExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertOverset', '');\n return next;\n}\n\nexport function insertUnderset(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createUndersetNode();\n const arabicNode = createUndersetNode();\n arabicNode.id = englishNode.id;\n if (arabicNode.underExpr && englishNode.underExpr) {\n arabicNode.underExpr.id = englishNode.underExpr.id;\n }\n if (arabicNode.baseExpr && englishNode.baseExpr) {\n arabicNode.baseExpr.id = englishNode.baseExpr.id;\n }\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.underExpr ? englishNode.underExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertUnderset', '');\n return next;\n}\n\nexport function insertLimitsSeriesTemplate(\n session: EditorSession,\n commandId: AtomicCommandId,\n): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const { english, arabic } = buildLimitsSeriesTemplate(commandId);\n insertMirroredNode(next, next.caret.chainId, next.caret.index, english, arabic);\n syncSubtreeRecursive(next, english, arabic);\n next.caret = limitsSeriesTemplateInitialCaret(english);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertLimitsSeriesTemplate', commandId);\n return next;\n}\n\nexport function insertAccentPair(session: EditorSession): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const { english, arabic } = buildAccentPairTemplate();\n insertMirroredNode(next, next.caret.chainId, next.caret.index, english, arabic);\n syncSubtreeRecursive(next, english, arabic);\n next.caret = accentPairTemplateInitialCaret(english);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAccentPair', '');\n return next;\n}\n\n/**\n * Insert a one-argument math accent. When a selection is active in one chain,\n * wrap the selected nodes into the accent base; otherwise insert an empty base\n * and place the caret inside it.\n */\nexport function insertAccent(session: EditorSession, accentId: AccentCommandId): EditorSession {\n const next = cloneEditorSession(session);\n const englishNode = createAccentNode(accentId);\n const arabicNode = createAccentNode(accentId);\n arabicNode.id = englishNode.id;\n if (arabicNode.baseExpr && englishNode.baseExpr) {\n arabicNode.baseExpr.id = englishNode.baseExpr.id;\n }\n\n if (isSelectionActive(next.selection) && next.selection) {\n const sel = next.selection;\n const { start, end } = normalizeSelection(sel);\n const englishLocated = findChainById(next.englishTree, sel.chainId);\n const arabicLocated = findChainById(next.arabicTree, sel.chainId);\n if (englishLocated && arabicLocated && end > start) {\n const count = end - start;\n const englishWrapped = englishLocated.chain.nodes.splice(start, count);\n const arabicWrapped = arabicLocated.chain.nodes.splice(start, count);\n englishNode.baseExpr!.nodes = englishWrapped;\n arabicNode.baseExpr!.nodes = arabicWrapped;\n englishLocated.chain.nodes.splice(start, 0, englishNode);\n arabicLocated.chain.nodes.splice(start, 0, arabicNode);\n syncSubtreeRecursive(next, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.baseExpr!.id,\n index: englishWrapped.length,\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAccent', `${accentId}:wrap`);\n return next;\n }\n }\n\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n syncSubtreeRecursive(next, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.baseExpr ? englishNode.baseExpr.id : next.caret.chainId,\n index: 0,\n };\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertAccent', `${accentId}:empty`);\n return next;\n}\n\nexport function insertMatrixEnv(\n session: EditorSession,\n style: MatrixEnvStyle,\n rows: number,\n columns: number,\n): EditorSession {\n return insertGridEnv(session, style, rows, columns);\n}\n\nexport function insertArrayEnv(\n session: EditorSession,\n rows: number,\n columns: number,\n columnAlignments?: EnvColumnAlignment[],\n): EditorSession {\n return insertGridEnv(session, 'array', rows, columns, columnAlignments);\n}\n\nexport function insertAlignedEnv(\n session: EditorSession,\n rows: number,\n columns: number,\n): EditorSession {\n return insertGridEnv(session, 'aligned', rows, columns);\n}\n\nexport function insertCasesEnv(session: EditorSession, rows: number): EditorSession {\n return insertGridEnv(session, 'cases', rows, 2);\n}\n\nfunction insertGridEnv(\n session: EditorSession,\n envName: GridEnvName,\n rows: number,\n columns: number,\n columnAlignments?: EnvColumnAlignment[],\n): EditorSession {\n const base = replaceSelectionFirst(session);\n const next = cloneEditorSession(base);\n const englishNode = createGridEnvNode(envName, rows, columns, columnAlignments);\n const arabicNode = createGridEnvNode(envName, rows, columns, columnAlignments);\n arabicNode.id = englishNode.id;\n syncMatrixCellChainIds(englishNode, arabicNode);\n insertMirroredNode(next, next.caret.chainId, next.caret.index, englishNode, arabicNode);\n next.caret = {\n chainId: englishNode.matrixRows?.[0]?.[0]?.id ?? next.caret.chainId,\n index: 0,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'insertGridEnv', `${envName}:${String(rows)}x${String(columns)}`);\n return next;\n}\n\nexport function setMatrixEnvStyle(session: EditorSession, style: MatrixEnvStyle): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || pair.english.envName === 'cases') {\n return session;\n }\n pair.english.envName = style;\n pair.arabic.envName = style;\n pair.english.matrixStyle = style;\n pair.arabic.matrixStyle = style;\n pair.english.columnAlignments = null;\n pair.arabic.columnAlignments = null;\n appendDebug(next, 'setMatrixEnvStyle', style);\n return next;\n}\n\nexport function setArrayColumnAlignment(\n session: EditorSession,\n columnIndex: number,\n alignment: EnvColumnAlignment,\n): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || (pair.english.envName ?? pair.english.matrixStyle) !== 'array') {\n return session;\n }\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n const columnCount = pair.english.columnAlignments?.length ?? 0;\n const safeIndex = Math.max(0, Math.min(columnIndex, Math.max(0, columnCount - 1)));\n if (pair.english.columnAlignments && pair.arabic.columnAlignments && columnCount > 0) {\n pair.english.columnAlignments[safeIndex] = alignment;\n pair.arabic.columnAlignments[safeIndex] = alignment;\n }\n appendDebug(next, 'setArrayColumnAlignment', `${String(safeIndex)}:${alignment}`);\n return next;\n}\n\nexport function addMatrixRow(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.matrixRows.length >= 12) {\n return session;\n }\n const columnCount = Math.max(1, pair.english.matrixRows[0]?.length ?? 1);\n const englishRow = createMatrixRow(columnCount);\n const arabicRow = createMatrixRow(columnCount);\n for (let i = 0; i < columnCount; i += 1) {\n arabicRow[i].id = englishRow[i].id;\n }\n pair.english.matrixRows.push(englishRow);\n pair.arabic.matrixRows.push(arabicRow);\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'addMatrixRow', pair.english.id);\n return next;\n}\n\nexport function removeMatrixRow(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.matrixRows.length <= 1) {\n return session;\n }\n pair.english.matrixRows.pop();\n pair.arabic.matrixRows.pop();\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'removeMatrixRow', pair.english.id);\n return next;\n}\n\nexport function addMatrixColumn(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.envName === 'cases') {\n return session;\n }\n const columnCount = pair.english.matrixRows[0]?.length ?? 0;\n if (columnCount >= 12) {\n return session;\n }\n for (let rowIndex = 0; rowIndex < pair.english.matrixRows.length; rowIndex += 1) {\n const englishCell = createEditorChain();\n const arabicCell = createEditorChain();\n arabicCell.id = englishCell.id;\n pair.english.matrixRows[rowIndex].push(englishCell);\n pair.arabic.matrixRows[rowIndex].push(arabicCell);\n }\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'addMatrixColumn', pair.english.id);\n return next;\n}\n\nexport function removeMatrixColumn(session: EditorSession): EditorSession {\n const next = cloneEditorSession(session);\n const pair = findSelectedMatrixPair(next);\n if (!pair || !pair.english.matrixRows || !pair.arabic.matrixRows || pair.english.envName === 'cases') {\n return session;\n }\n const columnCount = pair.english.matrixRows[0]?.length ?? 0;\n if (columnCount <= 1) {\n return session;\n }\n for (let rowIndex = 0; rowIndex < pair.english.matrixRows.length; rowIndex += 1) {\n pair.english.matrixRows[rowIndex].pop();\n pair.arabic.matrixRows[rowIndex].pop();\n }\n normalizeArrayAlignments(pair.english);\n normalizeArrayAlignments(pair.arabic);\n appendDebug(next, 'removeMatrixColumn', pair.english.id);\n return next;\n}\n\nfunction addScript(session: EditorSession, type: 'superscript' | 'subscript'): EditorSession {\n const targetNodeId = session.selectedNodeId;\n if (!targetNodeId) {\n return session;\n }\n const next = cloneEditorSession(session);\n const englishLocated = findNodeById(next.englishTree, targetNodeId);\n const arabicLocated = findNodeById(next.arabicTree, targetNodeId);\n if (!englishLocated || !arabicLocated) {\n return session;\n }\n const englishNode = englishLocated.node;\n const arabicNode = arabicLocated.node;\n if (!englishNode[type]) {\n englishNode[type] = createEditorChain();\n }\n if (!arabicNode[type]) {\n arabicNode[type] = createEditorChain();\n }\n if (englishNode[type] && arabicNode[type]) {\n arabicNode[type].id = englishNode[type].id;\n next.caret = {\n chainId: englishNode[type].id,\n index: englishNode[type].nodes.length,\n };\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, `add${type === 'superscript' ? 'Sup' : 'Sub'}`, targetNodeId);\n return next;\n}\n\nfunction removeScript(session: EditorSession, type: 'superscript' | 'subscript'): EditorSession {\n const targetNodeId = session.selectedNodeId;\n if (!targetNodeId) {\n return session;\n }\n const next = cloneEditorSession(session);\n const englishLocated = findNodeById(next.englishTree, targetNodeId);\n const arabicLocated = findNodeById(next.arabicTree, targetNodeId);\n if (!englishLocated || !arabicLocated) {\n return session;\n }\n englishLocated.node[type] = null;\n arabicLocated.node[type] = null;\n next.caret = {\n chainId: englishLocated.chain.id,\n index: englishLocated.index + 1,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, `remove${type === 'superscript' ? 'Sup' : 'Sub'}`, targetNodeId);\n return next;\n}\n\nexport function addSup(session: EditorSession): EditorSession {\n return addScript(session, 'superscript');\n}\n\nexport function addSub(session: EditorSession): EditorSession {\n return addScript(session, 'subscript');\n}\n\nexport function removeSup(session: EditorSession): EditorSession {\n return removeScript(session, 'superscript');\n}\n\nexport function removeSub(session: EditorSession): EditorSession {\n return removeScript(session, 'subscript');\n}\n\nexport function selectNode(session: EditorSession, nodeId: string | null): EditorSession {\n const next = cloneEditorSession(session);\n next.selectedNodeId = nodeId;\n next.selectedStructureNodeId = null;\n return next;\n}\n\nexport function deleteStructure(session: EditorSession): EditorSession {\n const targetNodeId = session.selectedStructureNodeId ?? session.selectedNodeId;\n if (!targetNodeId) {\n return session;\n }\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findNodeById(next[activeKey], targetNodeId);\n if (!located) {\n return session;\n }\n const removed = removeMirroredNodeById(next, targetNodeId);\n if (!removed) {\n return session;\n }\n next.caret = {\n chainId: located.chain.id,\n index: located.index,\n };\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteStructure', targetNodeId);\n return next;\n}\n\nexport function deleteBackward(session: EditorSession): EditorSession {\n if (isSelectionActive(session.selection)) {\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteBackward', 'deleted range');\n return next;\n }\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findChainById(next[activeKey], next.caret.chainId);\n if (!located) {\n return session;\n }\n if (next.caret.index <= 0) {\n return session;\n }\n const previousNode = located.chain.nodes[next.caret.index - 1];\n if (!previousNode) {\n return session;\n }\n if (\n (previousNode.kind === 'delimiter' || previousNode.kind === 'frac' || previousNode.kind === 'sqrt' || previousNode.kind === 'overset' || previousNode.kind === 'underset' || previousNode.kind === 'accent' || previousNode.kind === 'env') &&\n next.selectedStructureNodeId !== previousNode.id\n ) {\n next.selectedStructureNodeId = previousNode.id;\n next.selectedNodeId = previousNode.id;\n appendDebug(next, 'deleteBackward', 'selected structure');\n return next;\n }\n if (\n !next.splitLeafTyping &&\n (previousNode.kind === 'char' || previousNode.kind === 'number') &&\n previousNode.expr.length > 1\n ) {\n const id = previousNode.id;\n const englishHit = findNodeById(next.englishTree, id);\n const arabicHit = findNodeById(next.arabicTree, id);\n if (englishHit && arabicHit) {\n if (previousNode.kind === 'number' && shouldReverseArabicNumber(next)) {\n englishHit.node.expr = englishHit.node.expr.slice(1);\n arabicHit.node.expr = arabicHit.node.expr.slice(1);\n } else {\n englishHit.node.expr = englishHit.node.expr.slice(0, -1);\n arabicHit.node.expr = arabicHit.node.expr.slice(0, -1);\n }\n clearSourceIdentity(next, id);\n markExprSync(next, id);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteBackward', 'trimmed leaf');\n return next;\n }\n }\n const removed = removeMirroredNodeById(next, previousNode.id);\n if (!removed) {\n return session;\n }\n next.caret.index = Math.max(0, next.caret.index - 1);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteBackward', 'removed node');\n return next;\n}\n\nexport function deleteForward(session: EditorSession): EditorSession {\n if (isSelectionActive(session.selection)) {\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteForward', 'deleted range');\n return next;\n }\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const located = findChainById(next[activeKey], next.caret.chainId);\n if (!located) {\n return session;\n }\n if (next.caret.index >= located.chain.nodes.length) {\n return session;\n }\n const node = located.chain.nodes[next.caret.index];\n if (!node) {\n return session;\n }\n if (!next.splitLeafTyping && (node.kind === 'char' || node.kind === 'number') && node.expr.length > 1) {\n const englishHit = findNodeById(next.englishTree, node.id);\n const arabicHit = findNodeById(next.arabicTree, node.id);\n if (englishHit && arabicHit) {\n if (node.kind === 'number' && shouldReverseArabicNumber(next)) {\n englishHit.node.expr = englishHit.node.expr.slice(0, -1);\n arabicHit.node.expr = arabicHit.node.expr.slice(0, -1);\n } else {\n englishHit.node.expr = englishHit.node.expr.slice(1);\n arabicHit.node.expr = arabicHit.node.expr.slice(1);\n }\n clearSourceIdentity(next, node.id);\n markExprSync(next, node.id);\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteForward', 'trimmed leaf');\n return next;\n }\n }\n const removed = removeMirroredNodeById(next, node.id);\n if (!removed) {\n return session;\n }\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'deleteForward', 'removed node');\n return next;\n}\n\nexport function setExpr(session: EditorSession, nodeId: string, expr: string): EditorSession {\n const next = cloneEditorSession(session);\n const activeKey = activeTreeKey(next.activeSide);\n const passiveKey = passiveTreeKey(next.activeSide);\n const activeNode = findNodeById(next[activeKey], nodeId);\n const passiveNode = findNodeById(next[passiveKey], nodeId);\n if (!activeNode || !passiveNode) {\n return session;\n }\n activeNode.node.expr = expr;\n // An atomic label is one authored expression: persist the same edited\n // value in both mirrors, including when the Arabic side was active.\n if (['\\\\mathtt', '\\\\operatorname', '\\\\text'].includes(activeNode.node.wrapperCommand ?? '')) {\n passiveNode.node.expr = expr;\n }\n clearSourceIdentity(next, nodeId);\n markExprSync(next, nodeId);\n appendDebug(next, 'setExpr', nodeId);\n return next;\n}\n\nexport function createStarterSession(): EditorSession {\n const englishRoot = createEditorChain([createEditorNode('char', 'x')]);\n const arabicRoot = createEditorChain([createEditorNode('char', 'س')]);\n arabicRoot.id = englishRoot.id;\n arabicRoot.nodes[0].id = englishRoot.nodes[0].id;\n const session: EditorSession = {\n englishTree: englishRoot,\n arabicTree: arabicRoot,\n activeSide: 'arabic',\n splitLeafTyping: false,\n forceSplitNextLeaf: false,\n arabicReverseNumberTyping: true,\n currentCharacterFont: 'default',\n currentCharacterWrapper: null,\n currentDigitForm: 'western',\n caret: {\n chainId: englishRoot.id,\n index: 1,\n },\n selection: null,\n selectedNodeId: englishRoot.nodes[0].id,\n selectedStructureNodeId: null,\n sync: {\n [englishRoot.nodes[0].id]: { expr: 'diverged' },\n },\n debugLog: [],\n };\n appendDebug(session, 'createStarterSession', 'initialized');\n return session;\n}\n\nexport function syncStateSummary(session: EditorSession, uiLocale: ButexUiLocale = 'ar'): string {\n const messages = equationEditorMessages(uiLocale);\n const diverged = Object.values(session.sync).filter((entry) => entry.expr === 'diverged').length;\n if (diverged === 0) {\n return messages.synced;\n }\n return uiLocale === 'ar' ? `يوجد ${String(diverged)} ${messages.differentItems}` : `${String(diverged)} ${messages.differentItems}`;\n}\n\nexport function setRenderError(session: EditorSession, message: string | null): EditorSession {\n const next = cloneEditorSession(session);\n if (next.debugLog.length === 0) {\n appendDebug(next, 'render', 'init');\n }\n const last = next.debugLog[next.debugLog.length - 1];\n next.debugLog[next.debugLog.length - 1] = {\n ...last,\n renderOk: message === null,\n renderError: message,\n };\n return next;\n}\n\nexport function activeSideLabel(side: EditorSide, uiLocale: ButexUiLocale = 'ar'): string {\n const messages = equationEditorMessages(uiLocale);\n return side === 'arabic' ? messages.arabicSide : messages.englishSide;\n}\n\nconst PASTE_OPERATORS = new Set(['+', '-', '*', '/', '=', '<', '>', '.']);\n\n/** Read-only: build a fragment from the active selection (or null when collapsed). */\nexport function copySelection(session: EditorSession): EditorFragment | null {\n return serializeSelection(session);\n}\n\n/** Cut: removes the selection and returns both the cleaned session and the fragment. */\nexport function cutSelection(\n session: EditorSession,\n): { session: EditorSession; fragment: EditorFragment | null } {\n const fragment = serializeSelection(session);\n if (!fragment) {\n return { session, fragment: null };\n }\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n syncSelectionToCaret(next);\n appendDebug(next, 'cutSelection', `count=${String(fragment.english.length)}`);\n return { session: next, fragment };\n}\n\n/**\n * Insert a structured fragment at the caret in the active chain. The fragment\n * is re-id'd so it can't collide with the live tree, mirrored EN/AR ids are\n * preserved, and sync entries are populated for every nested node.\n */\nexport function pasteFragment(session: EditorSession, fragment: EditorFragment): EditorSession {\n if (!fragment || !fragment.english.length || !fragment.arabic.length) {\n return session;\n }\n const next = cloneEditorSession(session);\n applyDeleteSelectionRange(next);\n\n const fresh = regenerateFragmentIds(fragment);\n const limit = Math.min(fresh.english.length, fresh.arabic.length);\n for (let i = 0; i < limit; i += 1) {\n const eng = fresh.english[i];\n const ar = fresh.arabic[i];\n insertMirroredNode(next, next.caret.chainId, next.caret.index, eng, ar);\n syncSubtreeRecursive(next, eng, ar);\n next.caret = { chainId: next.caret.chainId, index: next.caret.index + 1 };\n }\n next.selection = null;\n next.selectedStructureNodeId = null;\n syncSelectionToCaret(next);\n appendDebug(next, 'pasteFragment', `count=${String(limit)}`);\n return next;\n}\n\n/**\n * Plain-text fallback paste. Each character is dispatched through the existing\n * typing path so split/merge mode and selection-replace behave the same as\n * keyboard input. Whitespace is silently skipped in this MVP.\n */\nexport function pasteText(session: EditorSession, text: string): EditorSession {\n if (!text) {\n return session;\n }\n // A selected atomic label is edited as ONE span, not pasted as math\n // characters (which would otherwise discard the spaces in a sentence).\n const selection = session.selection;\n if (selection && Math.abs(selection.anchorIndex - selection.focusIndex) === 1) {\n const selectedChain = findChainById(session[activeTreeKey(session.activeSide)], selection.chainId);\n const selected = selectedChain?.chain.nodes[Math.min(selection.anchorIndex, selection.focusIndex)];\n if (selected?.kind === 'char' &&\n ['\\\\mathtt', '\\\\operatorname', '\\\\text'].includes(selected.wrapperCommand ?? '')) {\n return setExpr(session, selected.id, text);\n }\n }\n let s = session;\n let i = 0;\n while (i < text.length) {\n const ch = text[i]!;\n if (ch === '\\n' || ch === '\\r' || ch === '\\t' || ch === ' ') {\n if (!s.splitLeafTyping) {\n s = breakLeafTyping(s);\n }\n i += 1;\n continue;\n }\n if (/^[0-9]$/.test(ch)) {\n let j = i + 1;\n let sawDot = false;\n while (j < text.length) {\n const c = text[j]!;\n if (/^[0-9]$/.test(c)) {\n j += 1;\n continue;\n }\n if (c === '.' && !sawDot && j + 1 < text.length && /^[0-9]$/.test(text[j + 1]!)) {\n sawDot = true;\n j += 1;\n continue;\n }\n break;\n }\n s = insertNumber(s, text.slice(i, j));\n i = j;\n continue;\n }\n if (PASTE_OPERATORS.has(ch)) {\n s = insertOperator(s, ch);\n i += 1;\n continue;\n }\n if (ch === DIVIDE_OPERATOR_AR) {\n s = insertDivideOperator(s);\n i += 1;\n continue;\n }\n s = insertChar(s, ch);\n i += 1;\n }\n return s;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const DELIMITER_CSS = `\n.delim-pair {\n display: inline-flex;\n align-items: stretch;\n min-height: 1.85em;\n}\n\n.delim-inner {\n display: inline-flex;\n align-items: center;\n}\n\n.delim {\n display: inline-flex;\n align-self: stretch;\n align-items: center;\n justify-content: center;\n color: var(--butex-delim-color, #475569);\n padding: 0 1px;\n min-height: 100%;\n}\n\n.delim-glyph {\n display: inline-flex;\n align-items: center;\n line-height: 1;\n font-size: clamp(20px, 1.08em + 0.8vh, 36px);\n transform: translateY(-20%) scaleY(var(--butex-delim-scale, 1));\n transform-origin: center;\n}\n`.trim();\n\nfunction escapeDelimiterExpr(value: string): string {\n return value.replace(/[.*+?^$()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction buildDelimiterExpr(prefixes: string[], delimiters: string[]): RegExp {\n const prefixExpr = prefixes.map(escapeDelimiterExpr).join('|');\n const delimiterExpr = delimiters.map(escapeDelimiterExpr).join('|');\n return new RegExp(`^(?:(?:${prefixExpr}))?(?:${delimiterExpr})$`);\n}\n\nexport const leftDelimExpr = buildDelimiterExpr(\n ['\\\\left', '\\\\bigl', '\\\\Bigl', '\\\\biggl', '\\\\Biggl'],\n ['(', '[', '\\\\{', '\\\\lfloor', '\\\\lceil', '\\\\langle', '`', '|', '\\\\|', '\\\\lvert', '\\\\vert', '\\\\lVert', '\\\\Vert'],\n);\nexport const rightDelimExpr = buildDelimiterExpr(\n ['\\\\right', '\\\\bigr', '\\\\Bigr', '\\\\biggr', '\\\\Biggr'],\n [')', ']', '\\\\}', '\\\\rfloor', '\\\\rceil', '\\\\rangle', '`', '|', '\\\\|', '\\\\rvert', '\\\\vert', '\\\\rVert', '\\\\Vert'],\n);\n\nconst DELIMITER_BASE_HEIGHT_PX = 18;\nconst DELIMITER_MAX_SCALE = 4.8;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applyDelimiterScale(pair: HTMLElement, inner: HTMLElement): void {\n const innerHeight = Math.max(inner.getBoundingClientRect().height, DELIMITER_BASE_HEIGHT_PX);\n const scale = clamp((innerHeight / DELIMITER_BASE_HEIGHT_PX) * 1.18, 1.18, DELIMITER_MAX_SCALE);\n pair.style.setProperty('--butex-delim-scale', scale.toFixed(3));\n}\n\nfunction visibleDelimiter(expr: string): string {\n return expr\n .replace(/\\\\(?:left|right|bigl|Bigl|biggl|Biggl|bigr|Bigr|biggr|Biggr)/, '')\n .replace('\\\\{', '{')\n .replace('\\\\}', '}')\n .replace(/\\\\(?:lvert|rvert|vert)/, '|')\n .replace(/\\\\(?:lVert|rVert|Vert)/, '‖')\n .replace('\\\\|', '‖');\n}\n\nexport function buildDelimiterNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const pair = document.createElement('span');\n pair.className = 'delim-pair';\n\n const left = document.createElement('span');\n left.className = 'delim delim--left';\n const leftGlyph = document.createElement('span');\n leftGlyph.className = 'delim-glyph';\n leftGlyph.textContent = visibleDelimiter(node.leftDelimExpr);\n left.appendChild(leftGlyph);\n pair.appendChild(left);\n\n const inner = document.createElement('span');\n inner.className = 'delim-inner';\n if (node.innerExpr) {\n inner.appendChild(buildChain(node.innerExpr));\n }\n pair.appendChild(inner);\n\n const right = document.createElement('span');\n right.className = 'delim delim--right';\n const rightGlyph = document.createElement('span');\n rightGlyph.className = 'delim-glyph';\n rightGlyph.textContent = visibleDelimiter(node.rightDelimExpr);\n right.appendChild(rightGlyph);\n pair.appendChild(right);\n\n applyDelimiterScale(pair, inner);\n requestAnimationFrame(() => applyDelimiterScale(pair, inner));\n\n return pair;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const BOXED_CSS = `\n.boxed-command {\n display: inline-flex;\n align-items: center;\n border: 1.5px solid currentColor;\n padding: 0.12em 0.22em;\n min-height: 1.25em;\n}\n\n.boxed-command > .chain {\n min-height: auto;\n}\n`.trim();\n\nexport function buildBoxedNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const box = document.createElement('span');\n box.className = 'boxed-command';\n if (node.innerExpr) {\n box.appendChild(buildChain(node.innerExpr));\n }\n return box;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const FRAC_CSS = `\n.frac {\n display: inline-flex;\n flex-direction: column;\n align-items: stretch;\n justify-content: center;\n vertical-align: middle;\n margin: 0 3px;\n min-width: 1.5em;\n}\n\n.frac-num,\n.frac-den {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.1em;\n padding: 0 4px;\n}\n\n.frac-bar {\n align-self: stretch;\n height: 1px;\n background: var(--butex-frac-bar, currentColor);\n opacity: 0.88;\n}\n`.trim();\n\nexport function buildFracNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'frac';\n\n const num = document.createElement('span');\n num.className = 'frac-num';\n if (node.numerator) {\n num.appendChild(buildChain(node.numerator));\n }\n\n const bar = document.createElement('span');\n bar.className = 'frac-bar';\n bar.setAttribute('aria-hidden', 'true');\n\n const den = document.createElement('span');\n den.className = 'frac-den';\n if (node.denominator) {\n den.appendChild(buildChain(node.denominator));\n }\n\n wrap.appendChild(num);\n wrap.appendChild(bar);\n wrap.appendChild(den);\n\n return wrap;\n}\n","import type { EditorChain, EditorNode, EditorSide } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const SQRT_CSS = `\n.sqrt {\n display: inline-flex;\n align-items: stretch;\n position: relative;\n vertical-align: middle;\n margin: 0 2px;\n min-height: 2.1em;\n direction: ltr;\n --butex-sqrt-scale: 1;\n}\n\n.sqrt.sqrt--english .sqrt-root {\n order: 1;\n}\n\n.sqrt.sqrt--english .sqrt-sign {\n order: 2;\n}\n\n.sqrt.sqrt--english .sqrt-radicand {\n order: 3;\n}\n\n.sqrt.sqrt--arabic .sqrt-radicand {\n order: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-sign {\n order: 2;\n}\n\n.sqrt.sqrt--arabic .sqrt-root {\n order: 3;\n}\n\n.sqrt.sqrt--arabic .sqrt-root,\n.sqrt.sqrt--arabic .sqrt-radicand {\n direction: rtl;\n}\n\n.sqrt-root {\n align-self: flex-start;\n min-width: 0.9em;\n min-height: 1em;\n margin-inline-end: -0.18em;\n transform: translate(0.16em, 0.02em);\n font-size: 0.64em;\n line-height: 1;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n position: relative;\n z-index: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-root {\n margin-inline-start: -0.22em;\n margin-inline-end: 0;\n transform: translate(-0.16em, 0.02em);\n}\n\n.sqrt-root .chain {\n min-height: auto;\n}\n\n.sqrt-sign {\n display: inline-flex;\n align-items: flex-end;\n justify-content: center;\n align-self: stretch;\n line-height: 0.78;\n font-size: 2em;\n color: var(--butex-sqrt-color, currentColor);\n transform: scaleY(var(--butex-sqrt-scale));\n transform-origin: center bottom;\n margin-inline-end: -0.24em;\n min-height: 100%;\n position: relative;\n z-index: 1;\n}\n\n.sqrt.sqrt--arabic .sqrt-sign {\n transform: scaleX(-1) scaleY(var(--butex-sqrt-scale));\n margin-inline-start: -0.24em;\n margin-inline-end: 0;\n}\n\n.sqrt-radicand {\n display: inline-flex;\n align-items: center;\n min-width: 1.35em;\n min-height: 1.35em;\n padding: 0.06em 0.24em 0;\n border-top: 2px solid var(--butex-sqrt-bar, currentColor);\n transform: translateY(-0.08em);\n position: relative;\n}\n\n.sqrt-radicand .chain {\n min-height: auto;\n}\n`.trim();\n\nconst SQRT_BASE_HEIGHT_PX = 32;\nconst SQRT_MAX_SCALE = 3.8;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applySqrtScale(wrap: HTMLElement, radicand: HTMLElement): void {\n const radicandHeight = Math.max(radicand.getBoundingClientRect().height, SQRT_BASE_HEIGHT_PX);\n const scale = clamp(radicandHeight / SQRT_BASE_HEIGHT_PX, 1, SQRT_MAX_SCALE);\n wrap.style.setProperty('--butex-sqrt-scale', scale.toFixed(3));\n}\n\nexport function buildSqrtNodeBody(node: EditorNode, buildChain: BuildChain, side: EditorSide): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = `sqrt sqrt--${side}`;\n\n const root = document.createElement('span');\n root.className = 'sqrt-root';\n if (node.rootIndex) {\n root.appendChild(buildChain(node.rootIndex));\n }\n\n const sign = document.createElement('span');\n sign.className = 'sqrt-sign';\n sign.setAttribute('aria-hidden', 'true');\n sign.textContent = '\\u221a';\n\n const radicand = document.createElement('span');\n radicand.className = 'sqrt-radicand';\n if (node.radicand) {\n radicand.appendChild(buildChain(node.radicand));\n }\n\n wrap.appendChild(root);\n wrap.appendChild(sign);\n wrap.appendChild(radicand);\n\n applySqrtScale(wrap, radicand);\n requestAnimationFrame(() => applySqrtScale(wrap, radicand));\n\n return wrap;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const OVERSET_CSS = `\n.overset {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.2em;\n}\n\n.overset-over {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.85em;\n padding: 0 2px;\n font-size: 0.72em;\n line-height: 1.1;\n}\n\n.overset-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n`.trim();\n\nexport function buildOversetNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'overset';\n\n const over = document.createElement('span');\n over.className = 'overset-over';\n if (node.overExpr) {\n over.appendChild(buildChain(node.overExpr));\n }\n\n const base = document.createElement('span');\n base.className = 'overset-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n wrap.appendChild(over);\n wrap.appendChild(base);\n return wrap;\n}\n","import type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const UNDERSET_CSS = `\n.underset {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.2em;\n}\n\n.underset-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n\n.underset-under {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.85em;\n padding: 0 2px;\n font-size: 0.72em;\n line-height: 1.1;\n}\n`.trim();\n\nexport function buildUndersetNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = 'underset';\n\n const base = document.createElement('span');\n base.className = 'underset-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n const under = document.createElement('span');\n under.className = 'underset-under';\n if (node.underExpr) {\n under.appendChild(buildChain(node.underExpr));\n }\n\n wrap.appendChild(base);\n wrap.appendChild(under);\n return wrap;\n}\n","import { accentCommandSpec } from '../accentCommands.js';\nimport type { EditorChain, EditorNode } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nexport const ACCENT_CSS = `\n.math-accent {\n display: inline-flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n vertical-align: middle;\n margin: 0 2px;\n min-width: 1.1em;\n}\n\n.math-accent-chrome {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 0.7em;\n padding: 0 2px;\n font-size: 0.85em;\n line-height: 1;\n color: var(--butex-script-color, #475569);\n user-select: none;\n}\n\n.math-accent-base {\n display: inline-flex;\n justify-content: center;\n align-items: center;\n min-height: 1.05em;\n padding: 0 2px;\n}\n\n.math-accent--under .math-accent-chrome {\n min-height: 0.45em;\n border-top: 1.5px solid currentColor;\n width: 100%;\n font-size: 0;\n color: var(--butex-surface-fg, #0f172a);\n}\n`.trim();\n\nexport function buildAccentNodeBody(node: EditorNode, buildChain: BuildChain): HTMLElement {\n const wrap = document.createElement('span');\n const spec = accentCommandSpec(node.expr);\n const placement = spec?.placement ?? 'over';\n wrap.className = placement === 'under' ? 'math-accent math-accent--under' : 'math-accent math-accent--over';\n\n const chrome = document.createElement('span');\n chrome.className = 'math-accent-chrome';\n chrome.setAttribute('aria-hidden', 'true');\n if (placement === 'over') {\n chrome.textContent = spec?.label ?? 'ˆ';\n }\n\n const base = document.createElement('span');\n base.className = 'math-accent-base';\n if (node.baseExpr) {\n base.appendChild(buildChain(node.baseExpr));\n }\n\n if (placement === 'under') {\n wrap.appendChild(base);\n wrap.appendChild(chrome);\n } else {\n wrap.appendChild(chrome);\n wrap.appendChild(base);\n }\n return wrap;\n}\n","import type { EditorChain, EditorNode, EditorSide, MatrixEnvStyle } from '../types.js';\n\ntype BuildChain = (chain: EditorChain) => HTMLElement;\n\nconst WRAPPERS: Record<MatrixEnvStyle, { left: string; right: string }> = {\n matrix: { left: '', right: '' },\n pmatrix: { left: '(', right: ')' },\n bmatrix: { left: '[', right: ']' },\n Bmatrix: { left: '{', right: '}' },\n vmatrix: { left: '|', right: '|' },\n Vmatrix: { left: '||', right: '||' },\n};\n\nexport const MATRIX_ENV_CSS = `\n.matrix-env {\n display: inline-flex;\n align-items: stretch;\n vertical-align: middle;\n margin: 0 3px;\n --butex-matrix-delim-scale: 1.25;\n}\n\n.matrix-env__wrapper {\n display: inline-flex;\n align-self: stretch;\n align-items: center;\n justify-content: center;\n min-width: 0.42em;\n padding: 0 2px;\n color: var(--butex-delim-color, currentColor);\n font-family: ui-serif, \"Cambria Math\", \"Times New Roman\", serif;\n font-size: clamp(22px, 1.35em + 0.8vh, 42px);\n line-height: 1;\n transform: scaleY(var(--butex-matrix-delim-scale));\n transform-origin: center;\n}\n\n.matrix-env--cases .matrix-env__wrapper:empty {\n min-width: 0;\n padding: 0;\n}\n\n.matrix-env__grid {\n display: inline-grid;\n direction: ltr;\n gap: 2px 5px;\n align-items: center;\n justify-items: center;\n padding: 2px 3px;\n}\n\n.matrix-env__cell {\n min-width: 1.35em;\n min-height: 1.45em;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n border-radius: 5px;\n border: 1px dashed rgba(148, 163, 184, 0.48);\n padding: 1px 3px;\n}\n\n.matrix-env__cell .chain {\n min-height: auto;\n}\n\n.matrix-env--arabic .matrix-env__cell {\n direction: rtl;\n}\n\n.matrix-env--english .matrix-env__cell {\n direction: ltr;\n}\n`.trim();\n\nconst MATRIX_DELIMITER_BASE_HEIGHT_PX = 20;\nconst MATRIX_DELIMITER_MAX_SCALE = 5.2;\n\nfunction clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n}\n\nfunction applyMatrixDelimiterScale(wrap: HTMLElement, grid: HTMLElement): void {\n const gridHeight = Math.max(grid.getBoundingClientRect().height, MATRIX_DELIMITER_BASE_HEIGHT_PX);\n const scale = clamp((gridHeight / MATRIX_DELIMITER_BASE_HEIGHT_PX) * 1.22, 1.25, MATRIX_DELIMITER_MAX_SCALE);\n wrap.style.setProperty('--butex-matrix-delim-scale', scale.toFixed(3));\n}\n\nexport function buildMatrixEnvNodeBody(node: EditorNode, buildChain: BuildChain, side: EditorSide): HTMLElement {\n const wrap = document.createElement('span');\n wrap.className = `matrix-env matrix-env--${side}${node.envName === 'cases' ? ' matrix-env--cases' : ''}`;\n if (node.envName === 'cases') wrap.dir = 'ltr';\n\n const style = node.envName ?? node.matrixStyle ?? 'matrix';\n const glyphs = style === 'cases'\n ? (side === 'arabic' ? { left: '', right: '}' } : { left: '{', right: '' })\n : style === 'array' || style === 'aligned' ? undefined : WRAPPERS[style];\n\n const left = document.createElement('span');\n left.className = 'matrix-env__wrapper matrix-env__wrapper--left';\n left.textContent = glyphs?.left ?? '';\n\n const grid = document.createElement('span');\n grid.className = 'matrix-env__grid';\n\n const rows = node.matrixRows ?? [];\n const columnCount = Math.max(1, ...rows.map((row) => row.length));\n grid.style.gridTemplateColumns = `repeat(${String(columnCount)}, minmax(1.35em, auto))`;\n\n const displayRows = side === 'arabic' ? rows.map((row) => row.slice().reverse()) : rows;\n for (const row of displayRows) {\n for (const cellChain of row) {\n const cell = document.createElement('span');\n cell.className = 'matrix-env__cell';\n cell.dir = side === 'arabic' ? 'rtl' : 'ltr';\n cell.appendChild(buildChain(cellChain));\n grid.appendChild(cell);\n }\n }\n\n const right = document.createElement('span');\n right.className = 'matrix-env__wrapper matrix-env__wrapper--right';\n right.textContent = glyphs?.right ?? '';\n\n wrap.appendChild(left);\n wrap.appendChild(grid);\n wrap.appendChild(right);\n\n applyMatrixDelimiterScale(wrap, grid);\n requestAnimationFrame(() => applyMatrixDelimiterScale(wrap, grid));\n\n return wrap;\n}\n","import diwaniLetterUrl from './fonts/Diwani Letter Regular.ttf';\nimport diwaniOutlineUrl from './fonts/DWNOUTSH.TTF';\nimport maghribiUrl from './fonts/Almaghribi-Warsh-Quran.otf';\nimport takweenUrl from './fonts/Takween.otf';\n\n\nexport const BUTEX_DIWANI_FONT_FAMILY = 'Diwani Letter';\nexport const BUTEX_DIWANI_OUTLINE_FONT_FAMILY = 'BuTeX Diwani Outline';\nexport const BUTEX_MAGHRIBI_FONT_FAMILY = 'Almaghribi Warsh Quran';\nexport const BUTEX_TAKWEEN_FONT_FAMILY = 'BuTeX Takween';\n\nexport const BUTEX_DIWANI_FONT_STACK = `\"${BUTEX_DIWANI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_DIWANI_OUTLINE_FONT_STACK = `\"${BUTEX_DIWANI_OUTLINE_FONT_FAMILY}\", \"${BUTEX_DIWANI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_MAGHRIBI_FONT_STACK = `\"${BUTEX_MAGHRIBI_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\nexport const BUTEX_TAKWEEN_FONT_STACK = `\"${BUTEX_TAKWEEN_FONT_FAMILY}\", Amiri, \"Segoe UI\", Tahoma, sans-serif`;\n\nexport const BUTEX_DIWANI_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_DIWANI_FONT_FAMILY}\";\n src: url(\"${diwaniLetterUrl}\") format(\"truetype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_TAKWEEN_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_TAKWEEN_FONT_FAMILY}\";\n src: url(\"${takweenUrl}\") format(\"opentype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_DIWANI_OUTLINE_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_DIWANI_OUTLINE_FONT_FAMILY}\";\n src: url(\"${diwaniOutlineUrl}\") format(\"truetype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_MAGHRIBI_FONT_FACE_CSS = `\n@font-face {\n font-family: \"${BUTEX_MAGHRIBI_FONT_FAMILY}\";\n src: url(\"${maghribiUrl}\") format(\"opentype\");\n font-weight: 400;\n font-style: normal;\n font-display: swap;\n}\n`.trim();\n\nexport const BUTEX_FONT_FACE_CSS = `\n${BUTEX_DIWANI_FONT_FACE_CSS}\n\n${BUTEX_DIWANI_OUTLINE_FONT_FACE_CSS}\n\n${BUTEX_TAKWEEN_FONT_FACE_CSS}\n\n${BUTEX_MAGHRIBI_FONT_FACE_CSS}\n`.trim();\n","import { atomicCommandSpec, isSpacingCommandSpec, type AtomicCommandSpec, type SpacingCommandSpec } from '../atomicCommands.js';\nimport { BUTEX_DIWANI_FONT_STACK, BUTEX_DIWANI_OUTLINE_FONT_STACK } from '../../diwani-font.js';\nimport type { EditorNode, EditorSide } from '../types.js';\nimport type { ButexUiLocale } from '../../uiLocale.js';\nimport { atomicCommandTitle } from '../uiLocale.js';\n\nexport const ATOMIC_COMMAND_CSS = `\n/* Shared atomic-command display */\n.atomic-command {\n display: inline-flex;\n align-items: center;\n font-weight: 600;\n line-height: 1;\n}\n\n/* Function-style commands: sin/cos/tan families. */\n.atomic-command--arabic {\n font-family: ${BUTEX_DIWANI_FONT_STACK};\n font-size: 1.15em;\n direction: rtl;\n}\n\n.atomic-command--diwani-outline {\n font-family: ${BUTEX_DIWANI_OUTLINE_FONT_STACK};\n}\n\n.atomic-command--english {\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 0.96em;\n}\n\n.atomic-command-label-with-sub {\n position: relative;\n display: inline-block;\n padding-inline-end: 0.45em;\n padding-block-end: 0.22em;\n line-height: 1;\n}\n\n.atomic-command-label-with-sub__sub {\n position: absolute;\n inset-inline-end: 0;\n inset-block-end: 0;\n font-size: 0.62em;\n line-height: 1;\n}\n\n/* Spacing commands: tiny selectable marker, real spacing remains in LaTeX preview. */\n.atomic-spacing {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n width: 3px;\n min-width: 3px;\n height: 1em;\n color: var(--butex-accent, currentColor);\n opacity: 0.62;\n}\n\n.atomic-spacing__marker {\n display: inline-block;\n width: 3px;\n height: 0.85em;\n border-radius: 999px;\n background: currentColor;\n}\n\n.atomic-spacing--negative {\n color: var(--butex-danger, #dc2626);\n}\n`.trim();\n\nfunction spacingArrowForSide(spec: SpacingCommandSpec, side: EditorSide): string {\n const pointsWithFlow = spec.spacing.direction === 'positive';\n if (pointsWithFlow) {\n return side === 'arabic' ? '\\u2190' : '\\u2192';\n }\n return side === 'arabic' ? '\\u2192' : '\\u2190';\n}\n\nexport function spacingTooltipForSide(spec: SpacingCommandSpec, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): string {\n return `${atomicCommandTitle(spec, uiLocale)} ${spacingArrowForSide(spec, side).repeat(spec.spacing.level)}`;\n}\n\nfunction buildFunctionAtomicCommandBody(node: EditorNode, side: EditorSide, spec: AtomicCommandSpec | null): HTMLElement {\n const value = document.createElement('span');\n value.className = `atomic-command atomic-command--${side}`;\n if (side === 'arabic' && spec?.category === 'groups') {\n value.classList.add('atomic-command--diwani-outline');\n }\n if (side === 'arabic' && node.expr === 'ln') {\n const label = document.createElement('span');\n label.className = 'atomic-command-label-with-sub';\n const base = document.createElement('span');\n base.className = 'atomic-command-label-with-sub__base';\n base.textContent = spec?.arabicLabel ?? node.expr;\n const sub = document.createElement('span');\n sub.className = 'atomic-command-label-with-sub__sub';\n sub.textContent = 'هـ';\n label.append(base, sub);\n value.appendChild(label);\n return value;\n }\n value.textContent = side === 'arabic'\n ? spec?.arabicLabel ?? node.expr\n : spec?.englishLabel ?? spec?.englishTex.replace(/^\\\\/, '') ?? node.expr;\n return value;\n}\n\nfunction buildSpacingAtomicCommandBody(spec: SpacingCommandSpec, side: EditorSide, uiLocale: ButexUiLocale): HTMLElement {\n const value = document.createElement('span');\n value.className = `atomic-spacing atomic-spacing--${spec.spacing.direction} atomic-spacing--level-${String(spec.spacing.level)}`;\n value.title = spacingTooltipForSide(spec, side, uiLocale);\n const marker = document.createElement('span');\n marker.className = 'atomic-spacing__marker';\n value.appendChild(marker);\n return value;\n}\n\nexport function buildAtomicCommandNodeBody(node: EditorNode, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): HTMLElement {\n const spec = atomicCommandSpec(node.expr);\n if (isSpacingCommandSpec(spec)) {\n return buildSpacingAtomicCommandBody(spec, side, uiLocale);\n }\n return buildFunctionAtomicCommandBody(node, side, spec);\n}\n","import { atomicOperatorCommandSpec, shouldMirrorOperatorDisplay, type AtomicOperatorCommandSpec } from '../atomicCommandsOperators.js';\nimport type { EditorNode, EditorSide } from '../types.js';\nimport type { ButexUiLocale } from '../../uiLocale.js';\nimport { atomicOperatorCommandTitle } from '../uiLocale.js';\n\nexport const ATOMIC_OPERATOR_COMMAND_CSS = `\n.atomic-operator-command {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 0.9em;\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 1.05em;\n font-weight: 600;\n line-height: 1;\n}\n\n.atomic-operator-command--mirrored {\n transform: scaleX(-1);\n}\n\n.atomic-operator-command__svg {\n width: 1em;\n height: 1em;\n background: currentColor;\n}\n`.trim();\n\nfunction buildOperatorLabel(spec: AtomicOperatorCommandSpec): HTMLElement {\n const value = document.createElement('span');\n value.className = 'atomic-operator-command__label';\n value.textContent = spec.Label;\n return value;\n}\n\nexport function buildAtomicOperatorCommandNodeBody(node: EditorNode, side: EditorSide, uiLocale: ButexUiLocale = 'ar'): HTMLElement {\n const spec = atomicOperatorCommandSpec(node.expr);\n const value = document.createElement('span');\n value.className = 'atomic-operator-command';\n value.title = spec ? atomicOperatorCommandTitle(spec, uiLocale) : node.expr;\n if (side === 'arabic' && shouldMirrorOperatorDisplay(spec)) {\n value.classList.add('atomic-operator-command--mirrored');\n }\n\n if (spec?.svg_path) {\n const icon = document.createElement('span');\n icon.className = 'atomic-operator-command__svg';\n icon.style.mask = `url(\"${spec.svg_path}\") center / contain no-repeat`;\n icon.style.webkitMask = `url(\"${spec.svg_path}\") center / contain no-repeat`;\n value.appendChild(icon);\n return value;\n }\n\n if (spec) {\n value.appendChild(buildOperatorLabel(spec));\n } else {\n const label = document.createElement('span');\n label.className = 'atomic-operator-command__label';\n label.textContent = node.expr;\n value.appendChild(label);\n }\n return value;\n}\n","import { standardCommandSpec } from '../standardCommands.js';\nimport type { EditorNode } from '../types.js';\n\nexport const STANDARD_COMMAND_CSS = `\n.standard-command {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n min-width: 0.9em;\n font-family: \"Cambria Math\", \"Times New Roman\", serif;\n font-size: 1.05em;\n line-height: 1;\n}\n`.trim();\n\nexport function buildStandardCommandNodeBody(node: EditorNode): HTMLElement {\n const spec = standardCommandSpec(node.expr);\n const value = document.createElement('span');\n value.className = 'standard-command';\n value.title = spec?.title ?? node.expr;\n value.textContent = spec?.label ?? node.expr;\n return value;\n}\n","import { DELIMITER_CSS } from './display/delimiter.js';\nimport { BOXED_CSS } from './display/boxed.js';\nimport { FRAC_CSS } from './display/frac.js';\nimport { SQRT_CSS } from './display/sqrt.js';\nimport { OVERSET_CSS } from './display/overset.js';\nimport { UNDERSET_CSS } from './display/underset.js';\nimport { ACCENT_CSS } from './display/accent.js';\nimport { MATRIX_ENV_CSS } from './display/env.js';\nimport { ATOMIC_COMMAND_CSS } from './display/atomicCommand.js';\nimport { ATOMIC_OPERATOR_COMMAND_CSS } from './display/atomicCommandsOperators.js';\nimport { STANDARD_COMMAND_CSS } from './display/standardCommand.js';\nimport { BUTEX_FONT_FACE_CSS } from '../diwani-font.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from './characterFonts.js';\n\nconst CHARACTER_FONT_CSS = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.cssClass && font.browserFontStack)\n .map((font) => `.${font.cssClass} {\\n font-family: ${font.browserFontStack};\\n}`)\n .join('\\n\\n');\n\nexport const BUTEX_EDITOR_CSS = `\n${BUTEX_FONT_FACE_CSS}\n\n.surface {\n background: var(--butex-surface-bg, linear-gradient(180deg, #ffffff 0%, #fafbfc 100%));\n border: 1px solid var(--butex-border, #e2e8f0);\n border-radius: 12px;\n color: var(--butex-surface-fg, #0f172a);\n cursor: text;\n max-width: 100%;\n min-height: 100px;\n min-width: 0;\n outline: none;\n overflow-x: auto;\n overflow-y: hidden;\n overscroll-behavior-inline: contain;\n padding: 8px 10px;\n touch-action: pan-x pan-y;\n transition: box-shadow 0.15s ease, border-color 0.15s ease;\n}\n\n.surface:focus,\n.surface.surface--typing-focus {\n border-color: var(--butex-focus-border, rgba(13, 148, 136, 0.45));\n box-shadow: 0 0 0 3px var(--butex-focus-shadow, rgba(13, 148, 136, 0.12));\n}\n\n.surface.surface--arabic {\n direction: rtl;\n}\n\n.surface.surface--english {\n direction: ltr;\n}\n\n${CHARACTER_FONT_CSS}\n\n.node-value--bold {\n font-family: var(--font-display-ar, Amiri), \"Noto Serif Arabic\", serif;\n font-weight: 700;\n}\n\n.node-value--unit {\n font-style: normal;\n text-decoration-line: underline;\n text-decoration-style: dotted;\n text-underline-offset: 0.2em;\n}\n\n.chain {\n display: inline-flex;\n align-items: center;\n gap: 0;\n min-height: 28px;\n flex-wrap: wrap;\n row-gap: 2px;\n}\n\n.slot {\n width: 5px;\n min-height: 28px;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n border-radius: 3px;\n}\n\n.slot:hover {\n background: var(--butex-slot-hover, rgba(13, 148, 136, 0.08));\n}\n\n.slot.range-highlight {\n background: var(--butex-selection-bg, rgba(13, 148, 136, 0.34));\n width: 11px;\n min-height: 42px;\n border: 2px solid var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n position: relative;\n z-index: 1;\n}\n\n.caret {\n display: inline-block;\n width: 2px;\n height: 20px;\n background: var(--butex-caret, #0f172a);\n border-radius: 1px;\n animation: butex-editor-blink 1s step-end infinite;\n}\n\n@keyframes butex-editor-blink {\n 50% { opacity: 0; }\n}\n\n@media (prefers-reduced-motion: reduce) {\n .surface {\n scroll-behavior: auto;\n transition: none;\n }\n\n .caret {\n animation: none;\n }\n}\n\n.node {\n display: inline-flex;\n align-items: stretch;\n gap: 3px;\n border-radius: 8px;\n padding: 2px 4px;\n cursor: pointer;\n border: 1px solid transparent;\n user-select: none;\n}\n\n.node.node--atomic-spacing {\n padding-inline: 0;\n margin-inline: -2px;\n border-color: transparent;\n}\n\n.node:hover {\n border-color: var(--butex-border, #e2e8f0);\n background: var(--butex-node-hover, rgba(148, 163, 184, 0.08));\n}\n\n.node.selected {\n background: var(--butex-node-selected-bg, rgba(13, 148, 136, 0.14));\n border-color: var(--butex-node-selected-border, rgba(13, 148, 136, 0.45));\n}\n\n.node.range-highlight {\n background: var(--butex-selection-bg, rgba(13, 148, 136, 0.34));\n border-color: var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n box-shadow: inset 0 0 0 3px var(--butex-selection-border, rgba(15, 118, 110, 0.9)),\n 0 0 0 1px var(--butex-selection-border, rgba(15, 118, 110, 0.9));\n position: relative;\n z-index: 2;\n}\n\n.chain .slot.range-highlight + .node.range-highlight,\n.chain .node.range-highlight + .slot.range-highlight {\n margin-inline: -1px;\n}\n\n.node-body {\n display: inline-flex;\n align-items: stretch;\n gap: 0;\n min-height: 1.6em;\n}\n\n.node-value {\n font-size: 16px;\n font-weight: 500;\n line-height: 1.25;\n display: inline-flex;\n align-items: center;\n}\n\n.scripts {\n display: flex;\n flex-direction: column;\n flex-shrink: 0;\n justify-content: space-between;\n align-items: center;\n padding: 1px 0;\n min-width: 0.75em;\n}\n\n.scripts.scripts--sup-only {\n justify-content: flex-start;\n padding-bottom: 2px;\n}\n\n.scripts.scripts--sub-only {\n justify-content: flex-end;\n padding-top: 2px;\n}\n\n.script-box {\n min-height: 12px;\n min-width: 10px;\n border-radius: 4px;\n border: 1px dashed var(--butex-script-border, #cbd5e1);\n padding: 0 2px;\n font-size: 0.68em;\n line-height: 1.15;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n background: var(--butex-script-bg, rgba(248, 250, 252, 0.95));\n color: var(--butex-script-color, #475569);\n}\n\n.script-box .chain {\n min-height: auto;\n}\n\n${DELIMITER_CSS}\n\n${BOXED_CSS}\n\n${FRAC_CSS}\n\n${SQRT_CSS}\n\n${OVERSET_CSS}\n\n${UNDERSET_CSS}\n\n${ACCENT_CSS}\n\n${MATRIX_ENV_CSS}\n\n${ATOMIC_COMMAND_CSS}\n\n${ATOMIC_OPERATOR_COMMAND_CSS}\n\n${STANDARD_COMMAND_CSS}\n`.trim();\n\n/**\n * Injects BuTeX editor surface styles into `document.head` if not already present.\n * Browser-only; no-op if `document` is undefined (Node).\n */\nexport function injectBuTeXEditorStyles(doc?: Document): void {\n const d = doc ?? (typeof document !== 'undefined' ? document : undefined);\n if (!d) {\n return;\n }\n const id = 'butex-editor-styles';\n const existing = d.getElementById(id);\n if (existing) {\n existing.textContent = BUTEX_EDITOR_CSS;\n return;\n }\n const style = d.createElement('style');\n style.id = id;\n style.textContent = BUTEX_EDITOR_CSS;\n d.head.appendChild(style);\n}\n","import type { CharacterFontId } from '../../editor/types.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../../editor/characterFonts.js';\n\nexport type NormalizedCharImport = {\n expr: string;\n characterFont: CharacterFontId;\n};\n\ntype WrapperSpec = {\n prefix: string;\n font?: CharacterFontId;\n};\n\nconst WRAPPER_SPECS: WrapperSpec[] = [\n ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [\n { prefix: font.macro, font: font.id },\n ...(font.importAliases ?? []).map((alias) => ({ prefix: alias, font: font.id })),\n ]),\n { prefix: '\\\\text' },\n];\n\nfunction readBracedArg(source: string, openBraceIndex: number): { inner: string; end: number } | null {\n if (source[openBraceIndex] !== '{') {\n return null;\n }\n\n let depth = 0;\n for (let index = openBraceIndex; index < source.length; index += 1) {\n const char = source[index];\n if (char === '{') {\n depth += 1;\n } else if (char === '}') {\n depth -= 1;\n if (depth === 0) {\n return { inner: source.slice(openBraceIndex + 1, index), end: index + 1 };\n }\n }\n }\n\n return null;\n}\n\nfunction peelWrapper(source: string): { inner: string; font?: CharacterFontId } | null {\n for (const wrapper of WRAPPER_SPECS) {\n if (!source.startsWith(wrapper.prefix)) {\n continue;\n }\n\n const braced = readBracedArg(source, wrapper.prefix.length);\n if (!braced || braced.end !== source.length) {\n continue;\n }\n\n return { inner: braced.inner, font: wrapper.font };\n }\n\n return null;\n}\n\nexport function normalizeCharImportExpr(expr: string): NormalizedCharImport {\n const original = expr;\n let current = expr;\n let characterFont: CharacterFontId = 'default';\n let changed = false;\n\n while (true) {\n const peeled = peelWrapper(current);\n if (!peeled) {\n break;\n }\n\n current = peeled.inner;\n if (peeled.font) {\n characterFont = peeled.font;\n }\n changed = true;\n }\n\n if (!changed) {\n return { expr: original, characterFont: 'default' };\n }\n\n if (current.includes('\\\\')) {\n return { expr: original, characterFont: 'default' };\n }\n\n return { expr: current, characterFont };\n}\n","import {\n BaseAstNode,\n ChainNode,\n CharNode,\n CommandNode,\n DelimiterNode,\n EnvNode,\n NumberNode,\n OperatorNode,\n} from '../../ast/arabic_ast.js';\nimport {\n accentCommandIdFromTex,\n accentCommandSpec,\n} from '../../editor/accentCommands.js';\nimport {\n ATOMIC_COMMANDS,\n atomicCommandSpec,\n type AtomicCommandId,\n} from '../../editor/atomicCommands.js';\nimport {\n ATOMIC_OPERATOR_COMMANDS,\n atomicOperatorCommandSpec,\n type AtomicOperatorCommandId,\n} from '../../editor/atomicCommandsOperators.js';\nimport { isStandardCommandTex } from '../../editor/standardCommands.js';\nimport {\n buildInitialSyncMap,\n cloneEditorSession,\n createAccentNode,\n createDelimiterNode,\n createBoxedNode,\n createEditorChain,\n createEditorNode,\n createEditorSession,\n createFracNode,\n createGridEnvNode,\n createSqrtNode,\n createOversetNode,\n createUndersetNode,\n renderArabicLatexFromSession,\n} from '../../editor/index.js';\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../../editor/characterFonts.js';\nimport type {\n CharacterFontId,\n EditorChain,\n EditorNode,\n EditorSession,\n EnvColumnAlignment,\n GridEnvName,\n MatrixEnvStyle,\n} from '../../editor/index.js';\nimport { normalizeCharImportExpr } from './normalizeCharImport.js';\nimport { isValidIndexSequence } from '../../editor/indexSequence.js';\nimport type { MathNode } from './types.js';\n\ntype CommandFontPolicy = CharacterFontId | 'infer';\n\nconst COMMAND_FONT_MAP: Record<string, CommandFontPolicy> = Object.fromEntries([\n ['\\\\text', 'infer'],\n ...NON_DEFAULT_CHARACTER_FONT_SPECS.flatMap((font) => [\n [font.macro, font.id],\n ...(font.importAliases ?? []).map((alias) => [alias, font.id]),\n ]),\n]) as Record<string, CommandFontPolicy>;\n\nconst CHAR_FONT_EXPORT_TEX: Record<Exclude<CharacterFontId, 'default'>, string> = Object.fromEntries(\n NON_DEFAULT_CHARACTER_FONT_SPECS.map((font) => [font.id, font.macro]),\n) as Record<Exclude<CharacterFontId, 'default'>, string>;\n\nfunction hasBareBoldCharSource(node: EditorNode): boolean {\n return node.kind === 'char'\n && (node.wrapperCommand === '\\\\boldarabic' || node.wrapperCommand === '\\\\mathbf')\n && typeof node.sourceLatex === 'string'\n && node.sourceLatex.length > 0\n && !node.sourceLatex.startsWith('\\\\mathbf{');\n}\n\nfunction charEditorNodeToAstNode(node: EditorNode): BaseAstNode {\n const font = node.characterFont ?? 'default';\n const charNode = new CharNode(node.expr);\n if (node.wrapperCommand) {\n const wrapper = node.wrapperCommand === '\\\\boldarabic' ? '\\\\mathbf' : node.wrapperCommand;\n // Burhan's nested boldarabic{text{س}} supplies 'x' as source identity\n // for the inner character. Keep it on that character, not the enclosing\n // \\\\mathbf command: reverse conversion would otherwise replace the entire\n // styled command with an unstyled x.\n if (hasBareBoldCharSource(node)) {\n charNode.sourceLatex = node.sourceLatex!;\n }\n return new CommandNode(wrapper, [], [new ChainNode([charNode])]);\n }\n if (font === 'default') {\n return charNode;\n }\n return new CommandNode(CHAR_FONT_EXPORT_TEX[font], [], [new ChainNode([charNode])]);\n}\n\nexport type MathEditorAdapterResult =\n | { editable: true; session: EditorSession }\n | { editable: false; reason: string };\n\ntype NodeAdapterResult =\n | { editable: true; node: EditorNode }\n | { editable: false; reason: string };\n\ntype UnsupportedAdapterResult = { editable: false; reason: string };\n\nexport type MathNodeFromEditorResult =\n | { ok: true; math: MathNode }\n | { ok: false; reason: string };\n\nfunction commandIdForTex(tex: string): AtomicCommandId | null {\n for (const spec of Object.values(ATOMIC_COMMANDS)) {\n const renderTex = (spec as { arabicRenderTex?: string }).arabicRenderTex;\n if (spec.englishTex === tex || spec.arabicTex === tex || renderTex === tex) {\n return spec.id as AtomicCommandId;\n }\n }\n return null;\n}\n\nfunction operatorCommandIdForTex(tex: string): AtomicOperatorCommandId | null {\n const normalized = tex === '\\\\le' ? '\\\\leq' : tex === '\\\\ge' ? '\\\\geq' : tex;\n for (const spec of Object.values(ATOMIC_OPERATOR_COMMANDS)) {\n if (spec.Tex === normalized) {\n return spec.id as AtomicOperatorCommandId;\n }\n }\n return null;\n}\n\nfunction cloneChainWithFreshIds(chain: EditorChain): EditorChain {\n return structuredClone(chain);\n}\n\nfunction attachScripts(astNode: BaseAstNode, editorNode: EditorNode): UnsupportedAdapterResult | null {\n if (astNode.sourceLatex) {\n editorNode.sourceLatex = astNode.sourceLatex;\n }\n if (astNode.superscript) {\n const sup = chainToEditorChain(astNode.superscript, true);\n if (!sup.editable) {\n return sup;\n }\n editorNode.superscript = sup.chain;\n }\n if (astNode.subscript) {\n const sub = chainToEditorChain(astNode.subscript, true);\n if (!sub.editable) {\n return sub;\n }\n editorNode.subscript = sub.chain;\n }\n return null;\n}\n\ntype ChainAdapterResult =\n | { editable: true; chain: EditorChain }\n | { editable: false; reason: string };\n\nconst MATRIX_ENV_NAMES = new Set<GridEnvName>(['matrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix', 'Vmatrix']);\n\nfunction isGridEnvName(value: string): value is GridEnvName {\n return MATRIX_ENV_NAMES.has(value as GridEnvName) || value === 'array' || value === 'aligned' || value === 'cases';\n}\n\nfunction isMatrixEnvName(value: GridEnvName): value is MatrixEnvStyle {\n return MATRIX_ENV_NAMES.has(value);\n}\n\nfunction parseEnvOpening(opening: string): { envName: GridEnvName; alignments?: EnvColumnAlignment[] } | null {\n const match = /^\\\\begin\\{([^}]+)\\}(?:\\{([lcr]+)\\})?$/.exec(opening);\n if (!match) {\n return null;\n }\n\n const envName = match[1] ?? '';\n if (!isGridEnvName(envName)) {\n return null;\n }\n\n if (envName === 'array') {\n const spec = match[2] ?? 'c';\n return {\n envName,\n alignments: spec.split('').map((alignment) => alignment as EnvColumnAlignment),\n };\n }\n\n return { envName };\n}\n\nfunction splitEnvLine(line: ChainNode): ChainNode[] {\n const cells: ChainNode[] = [];\n let current: BaseAstNode[] = [];\n for (const node of line.chain) {\n if (node instanceof OperatorNode && node.expr === '&') {\n cells.push(new ChainNode(current));\n current = [];\n } else {\n current.push(node);\n }\n }\n cells.push(new ChainNode(current));\n return cells;\n}\n\nfunction envToEditorNode(node: EnvNode): NodeAdapterResult {\n const parsed = parseEnvOpening(node.opening);\n if (!parsed) {\n return { editable: false, reason: `بيئة رياضية غير مدعومة حاليا: ${node.opening}` };\n }\n\n const expectedClosing = `\\\\end{${parsed.envName}}`;\n if (node.closing !== expectedClosing) {\n return { editable: false, reason: `إغلاق بيئة رياضية غير مدعوم حاليا: ${node.closing}` };\n }\n\n const rowCells = node.lines.map(splitEnvLine);\n if (parsed.envName === 'cases' && (rowCells.length === 0 || rowCells.length > 12 || rowCells.some((row) => row.length !== 2))) {\n return { editable: false, reason: 'بيئة cases تتطلب تعبيرا وشرطا في كل صف (عمودان)' };\n }\n const rows = Math.max(1, rowCells.length);\n const columns = Math.max(1, ...rowCells.map((row) => row.length));\n const env = createGridEnvNode(parsed.envName, rows, columns, parsed.alignments);\n\n for (let rowIndex = 0; rowIndex < rows; rowIndex += 1) {\n const row = rowCells[rowIndex] ?? [];\n for (let columnIndex = 0; columnIndex < columns; columnIndex += 1) {\n const cell = chainToEditorChain(row[columnIndex] ?? new ChainNode());\n if (!cell.editable) {\n return cell;\n }\n env.matrixRows![rowIndex]![columnIndex] = cell.chain;\n }\n }\n\n if (parsed.envName === 'array') {\n env.columnAlignments = Array.from(\n { length: columns },\n (_, index) => parsed.alignments?.[index] ?? 'c',\n );\n }\n if (isMatrixEnvName(parsed.envName)) {\n env.matrixStyle = parsed.envName;\n }\n\n const scripts = attachScripts(node, env);\n return scripts ?? { editable: true, node: env };\n}\n\nfunction charFromTextLikeCommand(node: CommandNode): NodeAdapterResult | null {\n const commandFont = COMMAND_FONT_MAP[node.name];\n if (commandFont === undefined) {\n return null;\n }\n if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {\n return null;\n }\n\n const arg = node.mandatoryArgs[0]!;\n if (arg.chain.length !== 1) {\n return null;\n }\n\n const child = arg.chain[0]!;\n if (child instanceof CommandNode) {\n const nested = charFromTextLikeCommand(child);\n if (!nested?.editable) {\n return null;\n }\n if (commandFont !== 'infer') {\n nested.node.characterFont = commandFont;\n }\n const scripts = attachScripts(node, nested.node);\n return scripts ?? nested;\n }\n\n if (!(child instanceof CharNode)) {\n return null;\n }\n\n const normalized = normalizeCharImportExpr(child.expr);\n const characterFont = commandFont === 'infer' ? normalized.characterFont : commandFont;\n const editorNode = createEditorNode('char', normalized.expr);\n if (characterFont !== 'default') {\n editorNode.characterFont = characterFont;\n }\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n}\n\nfunction singleCommandChar(node: CommandNode): CharNode | null {\n if (node.optionalArgs.length > 0 || node.mandatoryArgs.length !== 1) {\n return null;\n }\n const arg = node.mandatoryArgs[0]!;\n if (arg.chain.length !== 1 || !(arg.chain[0] instanceof CharNode)) {\n return null;\n }\n return arg.chain[0];\n}\n\nfunction wrappedAtomicCommandId(node: CommandNode): AtomicCommandId | null {\n if (node.name !== '\\\\mathbb' && node.name !== '\\\\mathrm') {\n return null;\n }\n const child = singleCommandChar(node);\n if (!child) {\n return null;\n }\n return commandIdForTex(`${node.name}{${child.expr}}`);\n}\n\nfunction editableWrapperCommand(node: CommandNode): NodeAdapterResult | null {\n if (\n node.name !== '\\\\mathtt' &&\n node.name !== '\\\\operatorname' &&\n node.name !== '\\\\text' &&\n node.name !== '\\\\mathsf' &&\n node.name !== '\\\\unit' &&\n node.name !== '\\\\mathbf' &&\n node.name !== '\\\\boldarabic'\n ) {\n return null;\n }\n // A mapped legacy variable may be represented as \\text{س}, sourced from x.\n // Only a canonical \\text invocation (or edited literal) is a text wrapper.\n if (node.name === '\\\\text' && node.sourceLatex && !node.sourceLatex.startsWith('\\\\text{')) {\n return null;\n }\n const child = singleCommandChar(node);\n if (node.name === '\\\\text' && child?.sourceLatex && !node.sourceLatex) return null;\n let editorNode: EditorNode;\n if (child) {\n const normalized = normalizeCharImportExpr(child.expr);\n editorNode = createEditorNode('char', normalized.expr);\n // Keep source identity when reopening an editor-exported wrapped CharObject.\n // Without it, reopening \\mathbf{س} loses the original English x.\n if (child.sourceLatex) editorNode.sourceLatex = child.sourceLatex;\n if (normalized.characterFont !== 'default') {\n editorNode.characterFont = normalized.characterFont;\n }\n } else {\n // Burhan represents mapped mathbf characters as boldarabic{text{Arabic}}\n // with source_latex on the inner text node, not as a single CharObject.\n // Import that existing supported character without discarding its identity.\n if (node.optionalArgs.length || node.mandatoryArgs.length !== 1) return null;\n const nodes = node.mandatoryArgs[0]?.chain;\n if (!nodes || nodes.length !== 1 || !(nodes[0] instanceof CommandNode)) return null;\n const nested = charFromTextLikeCommand(nodes[0]);\n if (!nested?.editable) return null;\n editorNode = nested.node;\n }\n\n editorNode.wrapperCommand = node.name === '\\\\mathsf' ? '\\\\unit'\n : node.name as NonNullable<EditorNode['wrapperCommand']>;\n\n const scripts = attachScripts(node, editorNode);\n if (scripts) {\n return scripts;\n }\n if (!editorNode.sourceLatex && node.name === '\\\\mathsf' && child) {\n editorNode.sourceLatex = `\\\\mathsf{${child.expr}}`;\n }\n return { editable: true, node: editorNode };\n}\n\nfunction commandToEditorNode(node: CommandNode): NodeAdapterResult {\n if (node.name === '\\\\frac' && node.mandatoryArgs.length >= 2) {\n const frac = createFracNode();\n const numerator = chainToEditorChain(node.mandatoryArgs[0]!);\n const denominator = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!numerator.editable) {\n return numerator;\n }\n if (!denominator.editable) {\n return denominator;\n }\n frac.numerator = numerator.chain;\n frac.denominator = denominator.chain;\n const scripts = attachScripts(node, frac);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: frac };\n }\n\n if (\n (node.name === '\\\\sqrt' || node.name === '\\\\arabsqrt' || node.name === '\\\\arsqrt') &&\n node.mandatoryArgs.length >= 1\n ) {\n const sqrt = createSqrtNode();\n const radicand = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!radicand.editable) {\n return radicand;\n }\n sqrt.radicand = radicand.chain;\n if (node.optionalArgs[0]) {\n const rootIndex = chainToEditorChain(node.optionalArgs[0]);\n if (!rootIndex.editable) {\n return rootIndex;\n }\n sqrt.rootIndex = rootIndex.chain;\n }\n const scripts = attachScripts(node, sqrt);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: sqrt };\n }\n\n if (node.name === '\\\\boxed' && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 1) {\n const boxed = createBoxedNode();\n const inner = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!inner.editable) {\n return inner;\n }\n boxed.innerExpr = inner.chain;\n const scripts = attachScripts(node, boxed);\n return scripts ?? { editable: true, node: boxed };\n }\n\n if (node.name === '\\\\overset' && node.mandatoryArgs.length >= 2) {\n const overset = createOversetNode();\n const overExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!overExpr.editable) {\n return overExpr;\n }\n if (!baseExpr.editable) {\n return baseExpr;\n }\n overset.overExpr = overExpr.chain;\n overset.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, overset);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: overset };\n }\n\n if (node.name === '\\\\underset' && node.mandatoryArgs.length >= 2) {\n const underset = createUndersetNode();\n const underExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[1]!);\n if (!underExpr.editable) {\n return underExpr;\n }\n if (!baseExpr.editable) {\n return baseExpr;\n }\n underset.underExpr = underExpr.chain;\n underset.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, underset);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: underset };\n }\n\n const accentId = accentCommandIdFromTex(node.name);\n if (accentId && node.mandatoryArgs.length >= 1) {\n const accent = createAccentNode(accentId);\n const baseExpr = chainToEditorChain(node.mandatoryArgs[0]!);\n if (!baseExpr.editable) {\n return baseExpr;\n }\n accent.baseExpr = baseExpr.chain;\n const scripts = attachScripts(node, accent);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: accent };\n }\n\n const wrappedAtomicId = wrappedAtomicCommandId(node);\n if (wrappedAtomicId) {\n const atomic = createEditorNode('atomicCommand', wrappedAtomicId);\n const scripts = attachScripts(node, atomic);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomic };\n }\n\n const wrapper = editableWrapperCommand(node);\n if (wrapper) {\n return wrapper;\n }\n\n const atomicId = commandIdForTex(node.name);\n if (atomicId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const atomic = createEditorNode('atomicCommand', atomicId);\n const scripts = attachScripts(node, atomic);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomic };\n }\n\n const operatorId = operatorCommandIdForTex(node.name);\n if (operatorId && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const atomicOperator = createEditorNode('atomicOperatorCommand', operatorId);\n if (node.name === '\\\\le' || node.name === '\\\\ge') atomicOperator.sourceLatex = node.name;\n const scripts = attachScripts(node, atomicOperator);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomicOperator };\n }\n\n if (isStandardCommandTex(node.name) && node.optionalArgs.length === 0 && node.mandatoryArgs.length === 0) {\n const standard = createEditorNode('standardCommand', node.name);\n const scripts = attachScripts(node, standard);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: standard };\n }\n\n const textLike = charFromTextLikeCommand(node);\n if (textLike) {\n return textLike;\n }\n\n return { editable: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.name}` };\n}\n\nfunction astNodeToEditorNode(node: ChainNode['chain'][number]): NodeAdapterResult {\n if (node instanceof CharNode) {\n const normalized = normalizeCharImportExpr(node.expr);\n const editorNode = createEditorNode('char', normalized.expr);\n if (normalized.characterFont !== 'default') {\n editorNode.characterFont = normalized.characterFont;\n }\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof NumberNode) {\n const editorNode = createEditorNode('number', node.expr);\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof OperatorNode) {\n return { editable: true, node: createEditorNode('operator', node.expr) };\n }\n if (node instanceof DelimiterNode) {\n const editorNode = createDelimiterNode(node.leftDelimExpr, node.rightDelimExpr);\n const inner = chainToEditorChain(node.innerExpr);\n if (!inner.editable) {\n return inner;\n }\n editorNode.innerExpr = inner.chain;\n const scripts = attachScripts(node, editorNode);\n return scripts ?? { editable: true, node: editorNode };\n }\n if (node instanceof CommandNode) {\n return commandToEditorNode(node);\n }\n if (node instanceof EnvNode) {\n return envToEditorNode(node);\n }\n return { editable: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.nodeType}` };\n}\n\nconst VERTICAL_DELIMITER_COMMAND_PAIRS: Readonly<Record<string, string>> = {\n '\\\\vert': '\\\\vert',\n '\\\\lvert': '\\\\rvert',\n '\\\\Vert': '\\\\Vert',\n '\\\\lVert': '\\\\rVert',\n '\\\\|': '\\\\|',\n};\n\nfunction isBareCommand(node: BaseAstNode, name: string): node is CommandNode {\n return node instanceof CommandNode &&\n node.name === name &&\n node.optionalArgs.length === 0 &&\n node.mandatoryArgs.length === 0;\n}\n\nfunction normalizeVerticalDelimiterCommands(chain: ChainNode): ChainNode {\n const normalized: BaseAstNode[] = [];\n\n for (let index = 0; index < chain.chain.length; index += 1) {\n const left = chain.chain[index]!;\n if (!(left instanceof CommandNode) || left.superscript || left.subscript) {\n normalized.push(left);\n continue;\n }\n\n const rightName = VERTICAL_DELIMITER_COMMAND_PAIRS[left.name];\n if (!rightName || left.optionalArgs.length > 0 || left.mandatoryArgs.length > 0) {\n normalized.push(left);\n continue;\n }\n\n let rightIndex = -1;\n for (let candidate = index + 1; candidate < chain.chain.length; candidate += 1) {\n if (isBareCommand(chain.chain[candidate]!, rightName)) {\n rightIndex = candidate;\n break;\n }\n }\n\n if (rightIndex < 0) {\n normalized.push(left);\n continue;\n }\n\n const right = chain.chain[rightIndex]! as CommandNode;\n const delimiter = new DelimiterNode(\n left.name,\n new ChainNode(chain.chain.slice(index + 1, rightIndex)),\n right.name,\n );\n delimiter.superscript = right.superscript;\n delimiter.subscript = right.subscript;\n normalized.push(delimiter);\n index = rightIndex;\n }\n\n return new ChainNode(normalized);\n}\n\nfunction chainToEditorChain(chain: ChainNode, script = false): ChainAdapterResult {\n // Only a complete script wrapper is semantic; ordinary \\mathnormal font use\n // elsewhere is not silently reinterpreted as ordered indices.\n if (script && chain.chain.length === 1) {\n const wrapper = chain.chain[0]!;\n if (wrapper instanceof CommandNode && wrapper.name === '\\\\mathnormal') {\n if (wrapper.optionalArgs.length || wrapper.mandatoryArgs.length !== 1) {\n return { editable: false, reason: 'صيغة مجموعة الفهارس غير مدعومة' };\n }\n const imported = chainToEditorChain(wrapper.mandatoryArgs[0]!);\n if (!imported.editable) return imported;\n // Be compatible with older Burhan versions that stored \"23\" as one NumberObject.\n const atoms: EditorNode[] = [];\n for (const node of imported.chain.nodes) {\n if (node.kind === 'number' && /^[0-9]{2,}$/.test(node.expr)) {\n atoms.push(...node.expr.split('').map((digit) => createEditorNode('number', digit)));\n } else if (node.kind === 'char' && !node.sourceLatex && /^[A-Za-z]{2,}$/.test(node.expr)) {\n atoms.push(...node.expr.split('').map((letter) => createEditorNode('char', letter)));\n } else {\n atoms.push(node);\n }\n }\n imported.chain.nodes = atoms;\n if (!isValidIndexSequence(imported.chain)) {\n return { editable: false, reason: 'محتوى مجموعة الفهارس غير مدعوم' };\n }\n imported.chain.indexSequence = true;\n return imported;\n }\n }\n const nodes: EditorNode[] = [];\n for (const astNode of normalizeVerticalDelimiterCommands(chain).chain) {\n const converted = astNodeToEditorNode(astNode);\n if (!converted.editable) {\n return converted;\n }\n nodes.push(converted.node);\n }\n return { editable: true, chain: createEditorChain(nodes) };\n}\n\nexport function mathObjectToEditorSession(math: MathNode): MathEditorAdapterResult {\n if (math.lines.length !== 1) {\n return { editable: false, reason: 'تحرير المعادلات متعددة الأسطر داخل المستند غير مدعوم بعد' };\n }\n\n const english = chainToEditorChain(math.lines[0]!);\n if (!english.editable) {\n return english;\n }\n\n const arabic = cloneChainWithFreshIds(english.chain);\n const session = createEditorSession(english.chain, arabic, 'english');\n session.sync = buildInitialSyncMap(session.englishTree, session.arabicTree);\n return { editable: true, session: cloneEditorSession(session) };\n}\n\ntype AstNodeResult =\n | { ok: true; node: BaseAstNode }\n | { ok: false; reason: string };\n\ntype AstChainResult =\n | { ok: true; chain: ChainNode }\n | { ok: false; reason: string };\n\nfunction attachAstScripts(editorNode: EditorNode, astNode: BaseAstNode): AstNodeResult | null {\n if (editorNode.superscript) {\n const sup = editorChainToAstChain(editorNode.superscript);\n if (!sup.ok) {\n return sup;\n }\n astNode.superscript = sup.chain;\n }\n if (editorNode.subscript) {\n const sub = editorChainToAstChain(editorNode.subscript);\n if (!sub.ok) {\n return sub;\n }\n astNode.subscript = sub.chain;\n }\n return null;\n}\n\nfunction editorEnvOpening(node: EditorNode): { opening: string; closing: string } | null {\n const envName = node.envName ?? node.matrixStyle;\n if (!envName) {\n return null;\n }\n if (envName === 'array') {\n const spec = (node.columnAlignments ?? []).slice(0, node.matrixRows?.[0]?.length ?? 0).join('') || 'c';\n return { opening: `\\\\begin{array}{${spec}}`, closing: '\\\\end{array}' };\n }\n return { opening: `\\\\begin{${envName}}`, closing: `\\\\end{${envName}}` };\n}\n\nfunction editorEnvToAstNode(node: EditorNode): AstNodeResult {\n const wrapper = editorEnvOpening(node);\n if (!wrapper || !node.matrixRows) {\n return { ok: false, reason: 'بيئة رياضية غير مدعومة حاليا' };\n }\n const lines: ChainNode[] = [];\n for (const row of node.matrixRows) {\n const lineNodes: BaseAstNode[] = [];\n for (let columnIndex = 0; columnIndex < row.length; columnIndex += 1) {\n if (columnIndex > 0) {\n lineNodes.push(new OperatorNode('&'));\n }\n const cell = editorChainToAstChain(row[columnIndex]!);\n if (!cell.ok) {\n return cell;\n }\n lineNodes.push(...cell.chain.chain);\n }\n lines.push(new ChainNode(lineNodes));\n }\n const env = new EnvNode(wrapper.opening, lines, wrapper.closing);\n const scripts = attachAstScripts(node, env);\n return scripts ?? { ok: true, node: env };\n}\n\nfunction accentChainForExport(accent: EditorChain | null): AstChainResult {\n if (!accent) {\n return { ok: true, chain: new ChainNode([]) };\n }\n return editorChainToAstChain(accent);\n}\n\nfunction nodeFromAccentBase(\n command: '\\\\overset' | '\\\\underset',\n accent: ChainNode,\n base: ChainNode,\n): BaseAstNode {\n if (accent.chain.length > 0) {\n return new CommandNode(command, [], [accent, base]);\n }\n if (base.chain.length === 1) {\n return base.chain[0]!;\n }\n return new DelimiterNode('', base, '');\n}\n\nfunction editorNodeToAstNode(node: EditorNode): AstNodeResult {\n let astNode: BaseAstNode;\n\n if (node.kind === 'char') {\n astNode = charEditorNodeToAstNode(node);\n } else if (node.kind === 'number') {\n astNode = new NumberNode(node.expr);\n } else if (node.kind === 'operator') {\n astNode = new OperatorNode(node.expr);\n } else if (node.kind === 'delimiter' && node.innerExpr) {\n const inner = editorChainToAstChain(node.innerExpr);\n if (!inner.ok) {\n return inner;\n }\n astNode = new DelimiterNode(node.leftDelimExpr, inner.chain, node.rightDelimExpr);\n } else if (node.kind === 'boxed' && node.innerExpr) {\n const inner = editorChainToAstChain(node.innerExpr);\n if (!inner.ok) {\n return inner;\n }\n astNode = new CommandNode('\\\\boxed', [], [inner.chain]);\n } else if (node.kind === 'frac' && node.numerator && node.denominator) {\n const numerator = editorChainToAstChain(node.numerator);\n const denominator = editorChainToAstChain(node.denominator);\n if (!numerator.ok) {\n return numerator;\n }\n if (!denominator.ok) {\n return denominator;\n }\n astNode = new CommandNode('\\\\frac', [], [numerator.chain, denominator.chain]);\n } else if (node.kind === 'sqrt' && node.radicand) {\n const radicand = editorChainToAstChain(node.radicand);\n if (!radicand.ok) {\n return radicand;\n }\n const optionalArgs: ChainNode[] = [];\n if (node.rootIndex && node.rootIndex.nodes.length > 0) {\n const rootIndex = editorChainToAstChain(node.rootIndex);\n if (!rootIndex.ok) {\n return rootIndex;\n }\n optionalArgs.push(rootIndex.chain);\n }\n astNode = new CommandNode('\\\\sqrt', optionalArgs, [radicand.chain]);\n } else if (node.kind === 'overset' && node.baseExpr) {\n const accent = accentChainForExport(node.overExpr);\n if (!accent.ok) {\n return accent;\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = nodeFromAccentBase('\\\\overset', accent.chain, baseExpr.chain);\n } else if (node.kind === 'underset' && node.baseExpr) {\n const accent = accentChainForExport(node.underExpr);\n if (!accent.ok) {\n return accent;\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = nodeFromAccentBase('\\\\underset', accent.chain, baseExpr.chain);\n } else if (node.kind === 'accent' && node.baseExpr) {\n const tex = accentCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `لكنة رياضية غير مدعومة حاليا: ${node.expr}` };\n }\n const baseExpr = editorChainToAstChain(node.baseExpr);\n if (!baseExpr.ok) {\n return baseExpr;\n }\n astNode = new CommandNode(tex, [], [baseExpr.chain]);\n } else if (node.kind === 'atomicCommand') {\n const tex = atomicCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n if (node.expr === 'ad') {\n astNode = new CommandNode('\\\\mathrm', [], [new ChainNode([new CharNode('d')])]);\n } else if (['N', 'Z', 'Q', 'R', 'C', 'H'].includes(node.expr)) {\n astNode = new CommandNode('\\\\mathbb', [], [new ChainNode([new CharNode(node.expr)])]);\n } else {\n astNode = new CommandNode(tex);\n }\n } else if (node.kind === 'atomicOperatorCommand') {\n const tex = atomicOperatorCommandSpec(node.expr)?.Tex;\n if (!tex) {\n return { ok: false, reason: `رمز رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(node.sourceLatex === '\\\\le' || node.sourceLatex === '\\\\ge' ? node.sourceLatex : tex);\n } else if (node.kind === 'standardCommand') {\n if (!isStandardCommandTex(node.expr)) {\n return { ok: false, reason: `أمر رياضي قياسي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(node.expr);\n } else if (node.kind === 'env') {\n return editorEnvToAstNode(node);\n } else {\n return { ok: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.kind}` };\n }\n\n if (node.sourceLatex && !hasBareBoldCharSource(node)) {\n astNode.sourceLatex = node.sourceLatex;\n }\n const scripts = attachAstScripts(node, astNode);\n return scripts ?? { ok: true, node: astNode };\n}\n\nfunction editorChainToAstChain(chain: EditorChain): AstChainResult {\n const nodes: BaseAstNode[] = [];\n for (const editorNode of chain.nodes) {\n const converted = editorNodeToAstNode(editorNode);\n if (!converted.ok) {\n return converted;\n }\n nodes.push(converted.node);\n }\n const content = new ChainNode(nodes);\n if (chain.indexSequence && isValidIndexSequence(chain)) {\n return { ok: true, chain: new ChainNode([new CommandNode('\\\\mathnormal', [], [content])]) };\n }\n return { ok: true, chain: content };\n}\n\nexport function mathNodeFromEditorSession(\n session: EditorSession,\n mathMode = '$',\n closing = '$',\n): MathNodeFromEditorResult {\n const converted = editorChainToAstChain(session.englishTree);\n if (!converted.ok) {\n return converted;\n }\n return {\n ok: true,\n math: {\n nodeType: 'MathObject',\n mathMode,\n lines: [converted.chain],\n closing,\n },\n };\n}\n\nexport function mathSourceFromEditorSession(\n session: EditorSession,\n mathMode = '$',\n closing = '$',\n): string {\n const inner = renderArabicLatexFromSession(session);\n if (mathMode === '$' || mathMode === '\\\\(') {\n return mathMode + inner + closing;\n }\n if (mathMode === '$$' || mathMode === '\\\\[') {\n if (!inner.includes('\\n')) {\n return `${mathMode}\\n${inner}\\n${closing}`;\n }\n return `${mathMode}\\n${inner.split('\\n').map((line) => ` ${line}`).join(' \\\\\\\\\\n')}\\n${closing}`;\n }\n return `${mathMode}\\n ${inner}\\n${closing}`;\n}\n\nexport function mathSourceWithReplacement(source: string, replacementInnerLatex: string): string {\n if (source.startsWith('$$') && source.endsWith('$$')) {\n return `$$${replacementInnerLatex}$$`;\n }\n if (source.startsWith('$') && source.endsWith('$')) {\n return `$${replacementInnerLatex}$`;\n }\n if (source.startsWith('\\\\(') && source.endsWith('\\\\)')) {\n return `\\\\(${replacementInnerLatex}\\\\)`;\n }\n if (source.startsWith('\\\\[') && source.endsWith('\\\\]')) {\n return `\\\\[${replacementInnerLatex}\\\\]`;\n }\n const begin = /^\\\\begin\\{([A-Za-z*]+)\\}/.exec(source);\n if (begin) {\n const opening = begin[0] ?? '';\n const closing = `\\\\end{${begin[1] ?? ''}}`;\n if (source.endsWith(closing)) {\n return `${opening}${replacementInnerLatex}${closing}`;\n }\n }\n return replacementInnerLatex;\n}\n","import { mathNodeFromEditorSession, mathObjectToEditorSession } from '../shared/math-document/mathEditorAdapter.js';\nimport type { MathNode } from '../shared/math-document/types.js';\nimport {\n buildInitialSyncMap,\n createEditorChain,\n createEditorSession,\n renderArabicLatexFromSession,\n renderArabicPreviewLatexFromSession,\n renderEnglishLatexFromSession,\n setCurrentDigitForm,\n type DigitFormId,\n type EditorSide,\n type EditorSession,\n} from '../editor/index.js';\nimport type { MathToken2 } from './types.js';\n\nexport type DocumentMathBridgeResult =\n | { editable: true; session: EditorSession }\n | { editable: false; reason: string };\n\nexport function createEmptyEquationSession(side: EditorSide = 'arabic'): EditorSession {\n const english = createEditorChain();\n const arabic = createEditorChain();\n arabic.id = english.id;\n const session = createEditorSession(english, arabic, side);\n session.sync = buildInitialSyncMap(session.englishTree, session.arabicTree);\n return session;\n}\n\nexport function createEmptyArabicEquationSession(): EditorSession {\n return createEmptyEquationSession('arabic');\n}\n\nexport function mathTokenToEditorSession(math: MathNode | null, side: EditorSide = 'arabic'): DocumentMathBridgeResult {\n if (!math) {\n return { editable: false, reason: 'هذه المعادلة محفوظة كنص خام فقط حاليا' };\n }\n const result = mathObjectToEditorSession(math);\n if (!result.editable) {\n return result;\n }\n result.session.activeSide = side;\n result.session.sync = buildInitialSyncMap(result.session.englishTree, result.session.arabicTree);\n return result;\n}\n\nexport function mathTokenToArabicEditorSession(math: MathNode | null): DocumentMathBridgeResult {\n return mathTokenToEditorSession(math, 'arabic');\n}\n\nexport function mathSourceFromSession(\n session: EditorSession,\n side: EditorSide,\n opening = '$',\n closing = '$',\n presentation = false,\n): string {\n const inner = side === 'english'\n ? renderEnglishLatexFromSession(session)\n : presentation ? renderArabicPreviewLatexFromSession(session) : renderArabicLatexFromSession(session);\n if (opening === '$' || opening === '\\\\(') {\n return opening + inner + closing;\n }\n if (opening === '$$' || opening === '\\\\[') {\n return `${opening}\\n${inner}\\n${closing}`;\n }\n return `${opening}\\n ${inner}\\n${closing}`;\n}\n\nexport function mathSourceFromArabicSession(session: EditorSession, opening = '$', closing = '$'): string {\n return mathSourceFromSession(session, 'arabic', opening, closing);\n}\n\nexport function mathNodeFromSession(session: EditorSession, opening = '$', closing = '$'): MathNode {\n const converted = mathNodeFromEditorSession(session, opening, closing);\n if (converted.ok) {\n return converted.math;\n }\n return { nodeType: 'MathObject', mathMode: opening, lines: [], closing };\n}\n\nexport function mathNodeFromArabicSession(session: EditorSession, opening = '$', closing = '$'): MathNode {\n return mathNodeFromSession(session, opening, closing);\n}\n\nexport function mathTokenSourceForSide(token: MathToken2, side: EditorSide, digitForm?: DigitFormId, presentation = false): string {\n if (!token.math || token.sourceOwner === 'raw') {\n return token.source;\n }\n if (!presentation && token.sourceSide === side && digitForm === undefined) {\n return token.source;\n }\n const result = mathTokenToEditorSession(token.math, side);\n if (!result.editable) {\n return token.source;\n }\n const session = digitForm === undefined\n ? result.session\n : setCurrentDigitForm(result.session, digitForm);\n return mathSourceFromSession(session, side, token.opening, token.closing, presentation);\n}\n","import type { DocumentLabelEntry } from './labels.js';\nimport type { Reference2 } from './types.js';\n\nexport type DocumentKeyError = 'empty' | 'invalid' | 'duplicate';\n\nconst DOCUMENT_KEY_PATTERN = /^[\\p{L}\\p{M}\\p{Nd}:._-]+$/u;\n\n/** NFC-normalize and trim a document key (label or bibliography). */\nexport function normalizeDocumentKey(key: string): string {\n return key.normalize('NFC').trim();\n}\n\n/** True when key matches Unicode letters/marks, decimal digits, and :._- with no spaces. */\nexport function isValidDocumentKey(key: string): boolean {\n const normalized = normalizeDocumentKey(key);\n return normalized.length > 0 && DOCUMENT_KEY_PATTERN.test(normalized);\n}\n\nexport type DocumentKeyNamespace = {\n references?: Array<Pick<Reference2, 'id' | 'key'>>;\n labels?: Array<Pick<DocumentLabelEntry, 'ownerId' | 'key'>>;\n /** Skip this reference id when checking (editing that entry). */\n excludeReferenceId?: string;\n /** Skip this label owner id when checking (editing that float/eq). */\n excludeOwnerId?: string;\n};\n\n/** Returns true if another reference or label already uses this key (NFC match). */\nexport function isDuplicateDocumentKey(key: string, namespace: DocumentKeyNamespace): boolean {\n const normalized = normalizeDocumentKey(key);\n if (normalized.length === 0) {\n return false;\n }\n for (const reference of namespace.references ?? []) {\n if (namespace.excludeReferenceId && reference.id === namespace.excludeReferenceId) {\n continue;\n }\n if (normalizeDocumentKey(reference.key) === normalized) {\n return true;\n }\n }\n for (const label of namespace.labels ?? []) {\n if (namespace.excludeOwnerId && label.ownerId === namespace.excludeOwnerId) {\n continue;\n }\n if (normalizeDocumentKey(label.key) === normalized) {\n return true;\n }\n }\n return false;\n}\n\n/** Classify a key for UI messaging: empty, invalid charset, or duplicate. */\nexport function documentKeyError(key: string, namespace: DocumentKeyNamespace = {}): DocumentKeyError | null {\n const normalized = normalizeDocumentKey(key);\n if (normalized.length === 0) {\n return 'empty';\n }\n if (!DOCUMENT_KEY_PATTERN.test(normalized)) {\n return 'invalid';\n }\n if (isDuplicateDocumentKey(normalized, namespace)) {\n return 'duplicate';\n }\n return null;\n}\n","import { diffJson } from 'diff';\nimport { fromDocumentJson } from './importJson.js';\nimport { toDocumentJson } from './exportJson.js';\nimport type { DocumentJson } from './types.js';\n\nexport type DocumentDiffChunkKind = 'added' | 'removed' | 'context';\n\nexport type DocumentDiffChunk = {\n kind: DocumentDiffChunkKind;\n text: string;\n};\n\nexport type DocumentDiff = {\n version: 1;\n changed: boolean;\n truncated: boolean;\n chunks: DocumentDiffChunk[];\n};\n\ntype JsonDiffPart = {\n value: string;\n added?: boolean;\n removed?: boolean;\n};\n\nconst MAX_TOTAL_TEXT_CHARS = 16_000;\nconst MAX_CHANGED_CHUNK_CHARS = 4_000;\nconst MAX_CONTEXT_CHUNK_CHARS = 600;\nconst TRUNCATION_MARKER = '\\n…\\n';\nconst IDENTITY_KEYS = new Set(['id', 'inline_ids', 'caption_inline_ids', 'cell_inline_ids']);\n\ntype SliceMode = 'head' | 'tail' | 'both';\n\nfunction comparisonValue(value: unknown, key?: string): unknown {\n if (key && IDENTITY_KEYS.has(key)) {\n return undefined;\n }\n if (Array.isArray(value)) {\n return value.map((entry) => comparisonValue(entry));\n }\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const childKey of Object.keys(value as Record<string, unknown>).sort()) {\n const child = comparisonValue((value as Record<string, unknown>)[childKey], childKey);\n if (child !== undefined) {\n result[childKey] = child;\n }\n }\n return result;\n }\n return value;\n}\n\nfunction normalizedComparisonDocument(document: DocumentJson): Record<string, unknown> {\n return comparisonValue(toDocumentJson(fromDocumentJson(document))) as Record<string, unknown>;\n}\n\nfunction withoutFinalNewline(value: string): string {\n return value.endsWith('\\n') ? value.slice(0, -1) : value;\n}\n\nfunction shorten(text: string, limit: number, mode: SliceMode): { text: string; truncated: boolean } {\n if (text.length <= limit) {\n return { text, truncated: false };\n }\n if (limit <= TRUNCATION_MARKER.length) {\n return { text: text.slice(0, Math.max(0, limit)), truncated: true };\n }\n const available = limit - TRUNCATION_MARKER.length;\n if (mode === 'head') {\n return { text: `${text.slice(0, available)}${TRUNCATION_MARKER}`, truncated: true };\n }\n if (mode === 'tail') {\n return { text: `${TRUNCATION_MARKER}${text.slice(text.length - available)}`, truncated: true };\n }\n const head = Math.ceil(available / 2);\n const tail = available - head;\n return {\n text: `${text.slice(0, head)}${TRUNCATION_MARKER}${text.slice(text.length - tail)}`,\n truncated: true,\n };\n}\n\n/**\n * Compare two persisted Document documents using canonical Document import/export\n * semantics and jsdiff's maintained JSON diff implementation.\n *\n * Generated editor identity sidecars are intentionally excluded so equivalent\n * legacy documents do not differ merely because normalization assigned new IDs.\n */\nexport function diffDocument(before: DocumentJson, after: DocumentJson): DocumentDiff {\n const beforeComparable = normalizedComparisonDocument(before);\n const afterComparable = normalizedComparisonDocument(after);\n const parts = diffJson(beforeComparable, afterComparable) as JsonDiffPart[];\n const changed = parts.some((part) => part.added === true || part.removed === true);\n\n if (!changed) {\n return { version: 1, changed: false, truncated: false, chunks: [] };\n }\n\n const chunks: DocumentDiffChunk[] = [];\n let truncated = false;\n let totalTextChars = 0;\n\n const append = (kind: DocumentDiffChunkKind, rawText: string, limit: number, mode: SliceMode): void => {\n const cleaned = withoutFinalNewline(rawText);\n if (cleaned.length === 0) return;\n\n const perChunk = shorten(cleaned, limit, mode);\n truncated ||= perChunk.truncated;\n const remaining = MAX_TOTAL_TEXT_CHARS - totalTextChars;\n if (remaining <= 0) {\n truncated = true;\n return;\n }\n\n const withinBudget = shorten(perChunk.text, remaining, mode);\n truncated ||= withinBudget.truncated;\n if (withinBudget.text.length === 0) return;\n chunks.push({ kind, text: withinBudget.text });\n totalTextChars += withinBudget.text.length;\n };\n\n parts.forEach((part, index) => {\n if (part.added) {\n append('added', part.value, MAX_CHANGED_CHUNK_CHARS, 'both');\n return;\n }\n if (part.removed) {\n append('removed', part.value, MAX_CHANGED_CHUNK_CHARS, 'both');\n return;\n }\n\n const previousChanged = index > 0 && (parts[index - 1]?.added === true || parts[index - 1]?.removed === true);\n const nextChanged = index + 1 < parts.length && (parts[index + 1]?.added === true || parts[index + 1]?.removed === true);\n if (!previousChanged && !nextChanged) return;\n\n const mode: SliceMode = previousChanged && nextChanged ? 'both' : previousChanged ? 'head' : 'tail';\n append('context', part.value, MAX_CONTEXT_CHUNK_CHARS, mode);\n });\n\n return { version: 1, changed: true, truncated, chunks };\n}\n","import { collectDocumentLabels, collectDocumentReferenceTargets, labelNumberMap, type DocumentLabelKind } from './labels.js';\nimport type {\n DocumentBlock,\n DocumentNode,\n InlineField2,\n Reference2Json,\n} from './types.js';\n\nexport type DocumentCitationIndexEntry = {\n kind: 'cite';\n block_id: string;\n field_id: string;\n token_id: string;\n keys: string[];\n unresolved_keys: string[];\n};\n\nexport type DocumentCrossReferenceIndexEntry = {\n kind: 'ref';\n ref_command: 'ref' | 'eqref';\n block_id: string;\n field_id: string;\n token_id: string;\n keys: string[];\n unresolved_keys: string[];\n};\n\nexport type DocumentIndexedLabel = {\n key: string;\n kind: DocumentLabelKind;\n caption: string;\n number: number;\n block_id?: string;\n field_id?: string;\n token_id?: string;\n};\n\nexport type DocumentReferenceIndex = {\n citations: DocumentCitationIndexEntry[];\n cross_references: DocumentCrossReferenceIndexEntry[];\n labels: DocumentIndexedLabel[];\n reference_targets: Array<Omit<DocumentIndexedLabel, 'number'> & { number: number | null; manual_key?: string }>;\n unresolved: {\n citation_keys: string[];\n cross_reference_keys: string[];\n };\n};\n\ntype TokenLocation = {\n block_id: string;\n field_id: string;\n};\n\nfunction appendUnique(target: string[], seen: Set<string>, values: string[]): void {\n for (const value of values) {\n if (!seen.has(value)) {\n seen.add(value);\n target.push(value);\n }\n }\n}\n\n/** Return a detached, read-only view of the registered bibliography catalog. */\nexport function getDocumentReferences(document: DocumentNode): Reference2Json[] {\n return document.references.map((reference) => ({\n key: reference.key,\n authors: reference.authors,\n title: reference.title,\n year: reference.year,\n venue: reference.venue,\n url: reference.url,\n field_separator: reference.fieldSeparator,\n }));\n}\n\n/**\n * Return semantic citation, cross-reference, and label relationships without\n * changing the document. Entries follow document/token order and preserve the\n * stable IDs already present in the live Document node.\n */\nexport function getDocumentReferenceIndex(document: DocumentNode): DocumentReferenceIndex {\n const referenceKeys = new Set(document.references.map((reference) => reference.key));\n const labelEntries = collectDocumentLabels(document);\n const labelKeys = new Set(labelNumberMap(document).keys());\n const citations: DocumentCitationIndexEntry[] = [];\n const crossReferences: DocumentCrossReferenceIndexEntry[] = [];\n const tokenLocations = new Map<string, TokenLocation>();\n const unresolvedCitationKeys: string[] = [];\n const unresolvedCrossReferenceKeys: string[] = [];\n const seenCitationKeys = new Set<string>();\n const seenCrossReferenceKeys = new Set<string>();\n\n function visitField(blockId: string, field: InlineField2): void {\n for (const token of field.tokens) {\n tokenLocations.set(token.id, { block_id: blockId, field_id: field.id });\n if (token.kind === 'cite') {\n const unresolvedKeys = token.keys.filter((key) => !referenceKeys.has(key));\n citations.push({\n kind: 'cite',\n block_id: blockId,\n field_id: field.id,\n token_id: token.id,\n keys: [...token.keys],\n unresolved_keys: unresolvedKeys,\n });\n appendUnique(unresolvedCitationKeys, seenCitationKeys, unresolvedKeys);\n } else if (token.kind === 'ref') {\n const unresolvedKeys = token.keys.filter((key) => !labelKeys.has(key));\n crossReferences.push({\n kind: 'ref',\n ref_command: token.refCommand,\n block_id: blockId,\n field_id: field.id,\n token_id: token.id,\n keys: [...token.keys],\n unresolved_keys: unresolvedKeys,\n });\n appendUnique(unresolvedCrossReferenceKeys, seenCrossReferenceKeys, unresolvedKeys);\n }\n }\n }\n\n function visitBlocks(blocks: DocumentBlock[]): void {\n for (const block of blocks) {\n if (block.kind === 'textBlock') {\n visitField(block.id, block.field);\n } else if (block.kind === 'table') {\n visitField(block.id, block.captionField);\n for (const row of block.rows) {\n for (const cell of row) {\n visitField(block.id, cell);\n }\n }\n } else if (block.kind === 'image') {\n visitField(block.id, block.captionField);\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n visitField(block.id, item.field);\n visitBlocks(item.blocks);\n }\n }\n }\n }\n\n visitBlocks(document.blocks);\n\n const labels: DocumentIndexedLabel[] = labelEntries.map((entry) => {\n if (entry.kind !== 'eq') {\n return {\n key: entry.key,\n kind: entry.kind,\n caption: entry.caption,\n number: entry.number,\n block_id: entry.ownerId,\n };\n }\n const location = tokenLocations.get(entry.ownerId);\n return {\n key: entry.key,\n kind: entry.kind,\n caption: entry.caption,\n number: entry.number,\n ...(location ? { block_id: location.block_id, field_id: location.field_id } : {}),\n token_id: entry.ownerId,\n };\n });\n\n return {\n citations,\n cross_references: crossReferences,\n labels,\n reference_targets: collectDocumentReferenceTargets(document).map((target) => ({\n key: target.key,\n kind: target.kind,\n caption: target.caption,\n number: target.number,\n ...(target.kind === 'eq' ? { token_id: target.ownerId } : { block_id: target.ownerId }),\n ...(target.manualKey ? { manual_key: target.manualKey } : {}),\n })),\n unresolved: {\n citation_keys: unresolvedCitationKeys,\n cross_reference_keys: unresolvedCrossReferenceKeys,\n },\n };\n}\n","/** Arabic XeLaTeX preamble fragments for full-document export. */\nimport { NON_DEFAULT_CHARACTER_FONT_SPECS } from '../editor/characterFonts.js';\n\nexport type ArabicDigitsMapping = 'arabicdigits' | 'farsidigits' | 'digits';\n\nexport type ArabicXeLatexPreambleOptions = {\n digitsMapping?: ArabicDigitsMapping;\n /** When true, add the article class twocolumn option. Default false. */\n twocolumn?: boolean;\n};\n\nfunction fontOptions(digitsMapping: ArabicDigitsMapping, includeScript = true): string {\n const parts: string[] = [];\n if (includeScript) {\n parts.push('Script=Arabic');\n }\n if (digitsMapping !== 'digits') {\n parts.push(`Mapping=${digitsMapping}`);\n }\n if (parts.length === 0) {\n return '';\n }\n return `[${parts.join(',')}]`;\n}\n\nexport function arabicXeLatexPreamblePkg(twocolumn = false): string {\n const classOptions = twocolumn\n ? '12pt,a4paper,notitlepage,twocolumn'\n : '12pt,a4paper,notitlepage';\n return (\n `\n\\\\documentclass[${classOptions}]{article}\n` +\n String.raw`\\usepackage{amsmath,amsfonts,amssymb,mathrsfs,tikz,fancyhdr, mathtools}\n\\usepackage{fontspec} % For loading OpenType fonts\n\\usepackage{unicode-math} % For setting the math font\n\\usepackage{polyglossia} % For Arabic support\n\\usepackage{array}\n\\usepackage{cancel}\n\\usepackage{bidi}\n\\usepackage{multirow}\n\\usepackage{booktabs}\n\\usepackage{graphicx} % For \\reflectbox\n\\usepackage{xcolor}\n\\usepackage{tikz}\n\\usepackage{tcolorbox} % For tcolorbox environment\n\\usepackage{textcomp} % For \\textrightarrow command\n\\usepackage{url}\n\n\n% visit : https://www.symbolcopy.com/punctuation-symbol.html\n% for inversed punctuation\n\n% save inverted comma for use - copy paste -> ،\n% save back tick for use - copy paste -> ` + '`'\n );\n}\n\nexport function arabicXeLatexPreambleFont(digitsMapping: ArabicDigitsMapping = 'arabicdigits'): string {\n const customFonts = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.latexFontCommand && font.latexFontFamily)\n .map((font) => `\\\\newfontfamily${font.latexFontCommand}${fontOptions(digitsMapping)}{${font.latexFontFamily}}`)\n .join('\\n');\n const mathFontOptions = fontOptions(digitsMapping, false);\n return `\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Persian digits: Mapping=farsidigits\n% Arabic-Indic digits: Mapping=arabicdigits\n% Western digits: omit Mapping entirely\n\\\\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia\n\\\\setmainfont${fontOptions(digitsMapping)}{Amiri}\n${customFonts}\n\\\\newfontfamily\\\\boldarabic${fontOptions(digitsMapping)}{Amiri Bold}\n\\\\newfontfamily\\\\italicarabic${fontOptions(digitsMapping)}{Amiri Italic}\n\n% for polyglossia url I dont know, sugggested by cursor\n\\\\newfontfamily\\\\arabicfonttt${fontOptions(digitsMapping)}{Amiri}\n\\\\newfontfamily\\\\arabicfontsf${fontOptions(digitsMapping)}{Amiri}\n\n\n% Explicitly set math font to XITS Math\n\\\\setmathfont${mathFontOptions}{XITS Math} % Ensure XITS Math is correctly installed and available\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n`;\n}\n\nexport function arabicXeLatexPreambleCmd(): string {\n const fontCommands = NON_DEFAULT_CHARACTER_FONT_SPECS\n .filter((font) => font.macro && font.latexFontCommand)\n .map((font) => `\\\\newcommand{${font.macro}}[1]{\\\\text{${font.latexFontCommand}{#1}}}`)\n .join('\\n');\n return String.raw`\n% Run with XeLaTeX compiler\n${fontCommands}\n\\newcommand{\\butexmirror}[1]{\\reflectbox{\\(#1\\)}}\n\n\\newcommand{\\arabN}{\\text{\\diwanioutlineshaded{ط}}}\n\\newcommand{\\arabZ}{\\text{\\diwanioutlineshaded{ص}}}\n\\newcommand{\\arabQ}{\\text{\\diwanioutlineshaded{ن}}}\n\\newcommand{\\arabR}{\\text{\\diwanioutlineshaded{ح}}}\n\\newcommand{\\arabC}{\\text{\\diwanioutlineshaded{ع}}}\n\\newcommand{\\arabH}{\\text{\\diwanioutlineshaded{ر}}}\n\n\n\\newcommand{\\lowerscript}[1]{\\raisebox{-4pt}{\\scriptsize #1}}\n\\newcommand{\\llowerscript}[1]{\\raisebox{-8pt}{\\scriptsize #1}}\n\\newcommand{\\lllowerscript}[2]{\\raisebox{#2pt}{\\scriptsize #1}}\n\n\\newcommand{\\arabdsub}[3]{\\prescript{}{#1}{\\prescript{}{#2}{#3}}} % arabic double subscript\n\\newcommand{\\arabsub}[2]{\\prescript{}{#1}{#2}} % arabic single subscript\n\n\n\n\\newcommand{\\upperscript}[1]{\\raisebox{8pt}{\\scriptsize #1}}\n\\newcommand{\\uupperscript}[2]{\\raisebox{#2pt}{\\scriptsize #1}}\n\\newcommand{\\vertbar}{\\rule[-1ex]{0.5pt}{2.5ex}}\n\\newcommand{\\horzbar}{\\rule[.5ex]{2.5ex}{0.5pt}}\n\n\n\\newcommand{\\arsqrt}[2][]{\\reflectbox{\\(\\sqrt[\\reflectbox{\\(#1\\)}]{\\reflectbox{\\(#2\\)}}\\)}}\n\\newcommand{\\arabsqrt}[2][]{\\arsqrt[#1]{#2}}\n\\newcommand{\\arabvec}[1]{\\reflectbox{$\\vec{\\reflectbox{$#1$}}$}}\n\n\\newcommand{\\arabexp}[1]{{}^{#1}\\!\\raisebox{-4.5pt}{\\text{\\diwani{ه}}}}\n\\newcommand{\\arablog}[2]{\\left(\\text{#2}\\right)\\!\\prescript{}{\\text{#1}}{\\text{\\diwani{لو}}}}\n\\newcommand{\\arabnlog}[1]{\\left(\\text{#1}\\right)\\!\\prescript{}{\\text{\\diwani{ه}}}{\\text{\\diwani{لو}}}}\n\n\\newcommand{\\arabcos}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جتا}}}}\n\\newcommand{\\arabsin}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جا}}}}\n\\newcommand{\\arabtan}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظا}}}}\n\\newcommand{\\arabcot}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظتا}}}}\n\\newcommand{\\arabsec}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قا}}}}\n\\newcommand{\\arabcsc}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قتا}}}}\n\n\\newcommand{\\arabacos}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجتا}}}}\n\\newcommand{\\arabasin}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجا}}}}\n\\newcommand{\\arabatan}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظا}}}}\n\\newcommand{\\arabacot}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظتا}}}}\n\\newcommand{\\arabasec}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققا}}}}\n\\newcommand{\\arabacsc}[1]{\\left(#1\\right)\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققتا}}}}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% summation\n\\newcommand{\\arablim}[2]{\\underset{#2 \\leftarrow #1}{\\text{نـــــها}}}\n\\newcommand{\\arabsum}[2]{\\underset{#1}{\\overset{#2}{\\text{مجـــ}}}}\n\\newcommand{\\arabprod}[2]{\\underset{#1}{\\overset{#2}{\\text{جـــذ}}}}\n\\newcommand{\\arabint}[2]{\\prescript{#2}{#1\\!\\!\\!}\\int}\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% we define this command to make it ease for change of notation later\n\\newcommand{\\ad}[0]{\\text{ء}} % \"ad\" for arabic differentiation or derivative (ء\" لإشتقاق\")\n\\newcommand{\\arpi}[0]{\\!\\text{\\diwani{ط}}}\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% differentials\n\n\\newcommand{\\arabdiff}[2]{\\frac{#1\\ad}{#2\\ad}} % arabic differential\n\\newcommand{\\arabddiff}[2]{\\frac{#1{}^{2}\\ad}{{}^{2}#2\\ad}} % arabic second differential\n\n\\newcommand{\\arabode}[2][-5pt]{\\stackrel{\\raisebox{#1}{$\\cdot$}}{\\text{#2}}}\n\\newcommand{\\arabodde}[2][-5pt]{\\stackrel{\\raisebox{#1}{$\\vcenter{\\hbox{$\\cdot\\!\\cdot$}}$}}{\\text{#2}}}\n\\newcommand{\\araboddde}[2][-5pt]{\\stackrel{\\raisebox{#1}{$\\vcenter{\\hbox{$\\cdot\\!\\cdot\\!\\cdot$}}$}}{\\text{#2}}}\n\\newcommand{\\arabpde}[1]{\\prescript{}{#1\\!\\!}{\\nabla}} % arabic partial differential equation (PDE)\n\n\\newcommand{\\arabprime}[0]{\\reflectbox{$\\prime$}\\!} % arabic prime notation\n\\newcommand{\\arabpprime}[0]{\\reflectbox{$\\prime$}\\reflectbox{$\\prime$}\\!} % arabic prime notation\n\\newcommand{\\arabppprime}[0]{\\reflectbox{$\\prime$}\\reflectbox{$\\prime$}\\reflectbox{$\\prime$}\\!} % arabic prime notation\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% probability\n\\newcommand{\\ap}[0]{\\!\\text{\\diwani{حـ}}} % arabic Probability - used a lot so short form\n\\newcommand{\\arabExpct}[0]{\\text{\\diwani{توقـ}}} % arabic Expectation\n\\newcommand{\\arabVar}[0]{\\!\\text{\\diwani{با}}} % arabic Variance\n\\newcommand{\\arabCov}[0]{\\!\\text{\\diwani{ت}}} % arabic Covariance\n\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% custom commands specific to lesson\n\\newcommand{\\lagrange}[2]{\\left(#2\\right)\\!\\prescript{}{#1}{\\text{\\diwani{لا}}}}\n\\newcommand{\\xii}[0]{\\left(\\prescript{}{\\text{يـ}}{\\text{س}}\\right)\\!}\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n\n\\newcommand{\\arexp}[0]{\\!\\raisebox{-4.5pt}{\\text{\\diwani{ه}}}}\n\\newcommand{\\arlog}[0]{\\!\\!\\text{\\diwani{لو}}}\n\\newcommand{\\arln}[0]{\\!\\!\\prescript{}{\\text{\\diwani{ه}}}{\\text{\\diwani{لو}}}}\n\\newcommand{\\ardet}[0]{\\!\\!\\text{\\diwani{محدد}}}\n\n\\newcommand{\\arsum}[0]{\\text{مجـــ}}\n\\newcommand{\\arprod}[0]{\\text{جـــذ}}\n\n\\newcommand{\\arlim}[0]{\\text{نـــــها}}\n\\newcommand{\\ararg}[0]{\\text{حج}}\n\\newcommand{\\armax}[0]{\\text{أكبر}}\n\\newcommand{\\armin}[0]{\\text{أصغر}}\n\\newcommand{\\arsup}[0]{\\text{أعلى}}\n\\newcommand{\\arinf}[0]{\\text{أدنى}}\n\n\\newcommand{\\arsin}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جا}}}}\n\\newcommand{\\arcos}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جتا}}}}\n\\newcommand{\\artan}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظا}}}}\n\\newcommand{\\arcot}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظتا}}}}\n\\newcommand{\\arsec}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قا}}}}\n\\newcommand{\\arcsc}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قتا}}}} \n\n\\newcommand{\\arasin}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجا}}}}\n\\newcommand{\\aracos}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجتا}}}}\n\\newcommand{\\aratan}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظا}}}}\n\\newcommand{\\aracot}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظتا}}}}\n\\newcommand{\\arasec}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققا}}}}\n\\newcommand{\\aracsc}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققتا}}}}\n\n\\newcommand{\\arsinh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جزا}}}}\n\\newcommand{\\arcosh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{جتزا}}}}\n\\newcommand{\\artanh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظزا}}}}\n\\newcommand{\\arcoth}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ظتزا}}}}\n\\newcommand{\\arsech}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قزا}}}}\n\\newcommand{\\arcsch}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قتزا}}}}\n\n\\newcommand{\\arasinh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجزا}}}}\n\\newcommand{\\aracosh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قجتزا}}}} \n\\newcommand{\\aratanh}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظزا}}}}\n\\newcommand{\\aracoth}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{قظتزا}}}}\n\\newcommand{\\arasech}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققزا}}}}\n\\newcommand{\\aracsch}[0]{\\!\\!\\raisebox{-2.5pt}{\\text{\\diwani{ققتزا}}}}\n\n\\newcommand{\\unit}[1]{\\text{#1}}\n\\newcommand{\\idx}[1]{#1}\n\\newcommand{\\arbinom}[2]{\\left(\\begin{array}{c} #1 \\\\ #2 \\end{array} \\right)}\n`;\n}\n\nexport function getArabicXeLatexPreamble(\n digitsMappingOrOptions: ArabicDigitsMapping | ArabicXeLatexPreambleOptions = 'arabicdigits',\n): string {\n const options: ArabicXeLatexPreambleOptions =\n typeof digitsMappingOrOptions === 'string'\n ? { digitsMapping: digitsMappingOrOptions }\n : digitsMappingOrOptions;\n const digitsMapping = options.digitsMapping ?? 'arabicdigits';\n const twocolumn = options.twocolumn === true;\n return (\n arabicXeLatexPreamblePkg(twocolumn) +\n arabicXeLatexPreambleFont(digitsMapping) +\n arabicXeLatexPreambleCmd()\n );\n}\n","import { renderMathNodeLatex } from '../shared/math-document/mathObject.js';\nimport { mathTokenSourceForSide } from './mathBridge.js';\nimport { mirrorBuTeXOperatorsInTex } from '../editor/atomicCommandsOperators.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport {\n getArabicXeLatexPreamble,\n type ArabicDigitsMapping,\n} from './arabicPreamble.js';\nimport {\n BUTEX_CLOSING_HAMDALA,\n butexBasmalaDisplayLatex,\n butexBasmalaTitlingPreamble,\n documentHasAbstract,\n documentHasMaketitle,\n emptyDocumentMeta,\n formatHijriDate,\n} from './articleMeta.js';\nimport { bibliographyEntryLatex, citeTokenLatex } from './citations.js';\nimport {\n implicitReferenceKey,\n implicitHeadingReferenceKey,\n isNumberedEquation,\n labelNumberMap,\n refTokenLatex,\n stripDisplayMathDelimiters,\n type DocumentLabelKind,\n} from './labels.js';\nimport type { DocumentBookContext } from './bookContent.js';\nimport type {\n DocumentBlock,\n DocumentMeta,\n DocumentNode,\n ImageBlock2,\n InlineField2,\n InlineToken2,\n ListBlock2,\n MathToken2,\n TableBlock2,\n TextStyle2,\n TextBlock2,\n} from './types.js';\n\nexport type DocumentLatexOptions = {\n /**\n * When true (default), emit a complete Arabic XeLaTeX file:\n * preamble + \\\\begin{document} + body + \\\\end{document}.\n * Pass false for body-only blocks.\n */\n wrapDocument?: boolean;\n /** Font digit Mapping when wrapping. Default 'arabicdigits'. */\n digitsMapping?: ArabicDigitsMapping;\n /** Document-level digit form for XeLaTeX font Mapping. Ignored when digitsMapping is set. */\n digitForm?: DigitFormId;\n /** When true, use article class option twocolumn. Default false. */\n twocolumn?: boolean;\n};\n\ntype LabelKindMap = ReadonlyMap<string, DocumentLabelKind>;\n\nfunction digitsMappingFromDigitForm(digitForm: DigitFormId | undefined): ArabicDigitsMapping {\n if (digitForm === 'western') {\n return 'digits';\n }\n if (digitForm === 'persianIndic') {\n return 'farsidigits';\n }\n return 'arabicdigits';\n}\n\nfunction editorMathLatexForCompile(token: MathToken2): string {\n // Presentation only: retain the saved canonical cases source for editing/readback.\n const source = token.math && token.sourceSide === 'arabic' && token.source.includes('\\\\begin{cases}')\n ? mathTokenSourceForSide(token, 'arabic', undefined, true)\n : token.source;\n return mirrorBuTeXOperatorsInTex(source, { target: 'compile' });\n}\n\nfunction mathBodyLatex(token: MathToken2): string {\n if (token.sourceOwner === 'editor') {\n return stripDisplayMathDelimiters(editorMathLatexForCompile(token));\n }\n if (!token.math || token.sourceOwner === 'raw') {\n return stripDisplayMathDelimiters(token.source);\n }\n const rendered = renderMathNodeLatex(token.math);\n return stripDisplayMathDelimiters(rendered);\n}\n\nfunction styledTextLatex(text: string, style: TextStyle2 | undefined): string {\n let output = text;\n if (style?.bold) {\n output = `\\\\textbf{${output}}`;\n }\n if (style?.italic) {\n output = `\\\\textit{${output}}`;\n }\n if (style?.underline) {\n output = `\\\\underline{${output}}`;\n }\n return output;\n}\n\nfunction semanticRefPrefix(kind: DocumentLabelKind): string {\n if (kind === 'fig') {\n return 'الشكل';\n }\n if (kind === 'tab') {\n return 'الجدول';\n }\n return 'المعادلة';\n}\n\nfunction semanticRefNames(kind: DocumentLabelKind): string[] {\n if (kind === 'fig') {\n return ['الشكل', 'شكل', 'Figure', 'figure'];\n }\n if (kind === 'tab') {\n return ['الجدول', 'جدول', 'Table', 'table'];\n }\n return ['المعادلة', 'معادلة', 'Equation', 'equation'];\n}\n\nfunction previousTextAlreadyNamesKind(previousToken: InlineToken2 | undefined, kind: DocumentLabelKind): boolean {\n if (previousToken?.kind !== 'text') {\n return false;\n }\n const text = previousToken.text.trimEnd();\n return semanticRefNames(kind).some((name) => text.endsWith(name));\n}\n\nfunction refTokenLatexForDocument(\n token: Extract<InlineToken2, { kind: 'ref' }>,\n labelKinds: LabelKindMap | undefined,\n previousToken: InlineToken2 | undefined,\n): string {\n const reference = refTokenLatex(token.keys, token.refCommand);\n if (!labelKinds || token.keys.length !== 1) {\n return reference;\n }\n const kind = labelKinds.get(token.keys[0]!);\n if (!kind || previousTextAlreadyNamesKind(previousToken, kind)) {\n return reference;\n }\n return `${semanticRefPrefix(kind)}~${reference}`;\n}\n\nfunction tokenLatex(\n token: InlineToken2,\n labelKinds?: LabelKindMap,\n previousToken?: InlineToken2,\n unitId?: string,\n): string {\n if (token.kind === 'text') {\n return styledTextLatex(token.text, token.style);\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n if (token.kind === 'ref') {\n return refTokenLatexForDocument(token, labelKinds, previousToken);\n }\n if (isNumberedEquation(token)) {\n const body = mathBodyLatex(token);\n const autoKey = implicitReferenceKey('eq', token.id, unitId);\n const aliases = [autoKey];\n if (token.labelEnabled && token.label?.trim() && token.label.trim() !== autoKey) aliases.push(token.label.trim());\n return '\\\\begin{equation}\\n' + body + '\\n' +\n aliases.map((key) => '\\\\label{' + key + '}').join('\\n') + '\\n\\\\end{equation}';\n }\n if (token.display && token.numbered === false && token.opening === '\\\\begin{equation}') {\n return '\\\\[' + mathBodyLatex(token) + '\\\\]';\n }\n if (token.sourceOwner === 'editor') {\n return editorMathLatexForCompile(token);\n }\n if (!token.math || token.sourceOwner === 'raw') {\n return token.source;\n }\n return renderMathNodeLatex(token.math);\n}\n\nfunction inlineFieldLatexWithLabelKinds(field: InlineField2, labelKinds?: LabelKindMap, unitId?: string): string {\n return field.tokens\n .map((token, index) => tokenLatex(token, labelKinds, field.tokens[index - 1], unitId))\n .join('');\n}\n\nexport function inlineFieldLatex(field: InlineField2): string {\n return inlineFieldLatexWithLabelKinds(field);\n}\n\nfunction textBlockLatex(block: TextBlock2, labelKinds: LabelKindMap, unitId?: string): string {\n const content = inlineFieldLatexWithLabelKinds(block.field, labelKinds, unitId);\n const body = block.command === '\\\\paragraph' ? `\\\\par\\n${content}` : `${block.command}{${content}}`;\n if (block.command !== '\\\\paragraph') {\n const keys = unitId ? [implicitHeadingReferenceKey(block.command.slice(1) as 'section' | 'subsection' | 'subsubsection', block.id, unitId)] : [];\n if (block.label?.trim() && !keys.includes(block.label.trim())) keys.push(block.label.trim());\n return [body, ...keys.map((key) => `\\\\label{${key}}`)].join('\\n');\n }\n if (block.command === '\\\\paragraph' && block.centered) {\n return `\\\\begin{center}\\n${body}\\n\\\\end{center}`;\n }\n return body;\n}\n\nfunction indent(value: string): string {\n return value\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n');\n}\n\nfunction listBlockLatex(\n block: ListBlock2,\n references: DocumentNode['references'],\n labelKinds: LabelKindMap,\n fixedFloats: boolean,\n unitId?: string,\n): string {\n const items = block.items\n .map((item) => {\n const nested = item.blocks\n .map((child) => '\\n' + indent(blockLatex(child, references, labelKinds, fixedFloats, unitId)))\n .join('');\n return ` \\\\item ${inlineFieldLatexWithLabelKinds(item.field, labelKinds, unitId)}${nested}`;\n })\n .join('\\n');\n return `${block.command}\\n${items}\\n${block.closing}`;\n}\n\nfunction defaultGridColumnSpec(block: TableBlock2): string | null {\n const compact = block.columns.replace(/\\s+/g, '');\n const columnCount = block.rows[0]?.length ?? 0;\n if (columnCount === 0 || compact.length !== columnCount || !/^[lcr]+$/.test(compact)) {\n return null;\n }\n return `|${compact.split('').join('|')}|`;\n}\n\nfunction tabularInnerLatex(block: TableBlock2, labelKinds: LabelKindMap, unitId?: string): string {\n const rows = block.rows.map((row) =>\n ` ${row.map((cell) => inlineFieldLatexWithLabelKinds(cell, labelKinds, unitId)).join(' & ')}`,\n );\n const gridColumns = defaultGridColumnSpec(block);\n if (gridColumns) {\n const griddedRows = rows.map((row) => `${row} \\\\\\\\ \\\\hline`).join('\\n');\n return `${block.command}{${gridColumns}}\\n \\\\hline\\n${griddedRows}\\n${block.closing}`;\n }\n return `${block.command}{${block.columns}}\\n${rows.join(' \\\\\\\\' + '\\n')}\\n${block.closing}`;\n}\n\nfunction floatCaptionLabelLines(\n block: ImageBlock2 | TableBlock2,\n counter: 'figure' | 'table',\n labelKinds: LabelKindMap,\n unitId?: string,\n): string[] {\n const lines: string[] = [];\n const caption = inlineFieldLatexWithLabelKinds(block.captionField, labelKinds, unitId).trim();\n const hasCaption = block.captionEnabled && caption.length > 0;\n if (hasCaption) {\n lines.push(` \\\\caption{${caption}}`);\n }\n const hasManualLabel = block.labelEnabled && block.label.trim().length > 0;\n if (hasCaption || hasManualLabel) {\n if (!hasCaption) lines.push(' \\\\refstepcounter{' + counter + '}');\n const autoKey = implicitReferenceKey(counter === 'figure' ? 'fig' : 'tab', block.id, unitId);\n lines.push(' \\\\label{' + autoKey + '}');\n if (hasManualLabel && block.label.trim() !== autoKey) lines.push(' \\\\label{' + block.label.trim() + '}');\n }\n return lines;\n}\n\nfunction tableBlockLatex(block: TableBlock2, labelKinds: LabelKindMap, fixedFloats: boolean, unitId?: string): string {\n const placement = fixedFloats ? 'H' : 'htbp';\n const lines = [`\\\\begin{table}[${placement}]`];\n if (block.centered) {\n lines.push(' \\\\centering');\n }\n lines.push(...floatCaptionLabelLines(block, 'table', labelKinds, unitId));\n lines.push(indent(tabularInnerLatex(block, labelKinds, unitId)));\n lines.push('\\\\end{table}');\n return lines.join('\\n');\n}\n\n/** Prefer \\\\columnwidth so figures fit a column (equals \\\\textwidth in one-column). */\nfunction remapImageWidthForColumns(value: string): string {\n return value.replace(/\\\\textwidth\\b/g, '\\\\columnwidth');\n}\n\nfunction imageOptionsLatex(block: ImageBlock2, constrainToColumn: boolean): string {\n const entries = Object.entries(block.options).map(([key, value]) => {\n if (constrainToColumn && key === 'width') {\n return [key, remapImageWidthForColumns(value)] as const;\n }\n return [key, value] as const;\n });\n if (entries.length === 0) {\n return '';\n }\n return `[${entries.map(([key, value]) => `${key}=${value}`).join(',')}]`;\n}\n\nfunction imageBlockLatex(block: ImageBlock2, labelKinds: LabelKindMap, fixedFloats: boolean, unitId?: string): string {\n const placement = fixedFloats ? 'H' : 'htbp';\n const lines = [`\\\\begin{figure}[${placement}]`];\n if (block.centered) {\n lines.push(' \\\\centering');\n }\n // Remap textwidth→columnwidth: safe in one-column, required in twocolumn.\n lines.push(` ${block.command}${imageOptionsLatex(block, true)}{${block.value}}`);\n lines.push(...floatCaptionLabelLines(block, 'figure', labelKinds, unitId));\n lines.push('\\\\end{figure}');\n return lines.join('\\n');\n}\n\nfunction blockLatex(\n block: DocumentBlock,\n references: DocumentNode['references'],\n labelKinds: LabelKindMap,\n fixedFloats: boolean,\n unitId?: string,\n): string {\n if (block.kind === 'textBlock') {\n return textBlockLatex(block, labelKinds, unitId);\n }\n if (block.kind === 'list') {\n return listBlockLatex(block, references, labelKinds, fixedFloats, unitId);\n }\n if (block.kind === 'table') {\n return tableBlockLatex(block, labelKinds, fixedFloats, unitId);\n }\n if (block.kind === 'image') {\n return imageBlockLatex(block, labelKinds, fixedFloats, unitId);\n }\n if (block.kind === 'bibliography') {\n const width = String(Math.max(references.length, 9));\n const items = references.map((reference) => ` ${bibliographyEntryLatex(reference)}`).join('\\n');\n return `${block.command}{${width}}\\n${items}\\n${block.closing}`;\n }\n return block.value;\n}\n\nfunction authorLatex(authors: string): string {\n return authors\n .split(/\\n+/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .join(' \\\\\\\\ ');\n}\n\n/** Title metadata + titling hooks for the XeLaTeX preamble (before \\\\begin{document}). */\nfunction articleMaketitlePreamble(meta: DocumentMeta, twocolumn = false): string {\n if (!documentHasMaketitle(meta)) {\n return '';\n }\n const parts: string[] = [butexBasmalaTitlingPreamble({ twocolumn })];\n if (meta.title.trim().length > 0) {\n parts.push(`\\\\title{${meta.title.trim()}}`);\n }\n if (meta.authors.trim().length > 0) {\n parts.push(`\\\\author{${authorLatex(meta.authors)}}`);\n }\n parts.push(`\\\\date{${formatHijriDate(meta.date, { locale: 'ar', digitForm: 'western' })}}`);\n return parts.join('\\n');\n}\n\nfunction articleFrontMatterLatex(meta: DocumentMeta): string[] {\n const parts: string[] = [];\n if (documentHasMaketitle(meta)) {\n parts.push('\\\\maketitle');\n } else {\n parts.push(butexBasmalaDisplayLatex());\n }\n if (documentHasAbstract(meta)) {\n parts.push(`\\\\begin{abstract}\\n${meta.abstract.trim()}\\n\\\\end{abstract}`);\n }\n return parts;\n}\n\nfunction documentLabelKindMap(document: DocumentNode): Map<string, DocumentLabelKind> {\n const map = new Map<string, DocumentLabelKind>();\n for (const [key, entry] of labelNumberMap(document)) {\n map.set(key, entry.kind);\n }\n return map;\n}\n\nfunction closingHamdalaLatex(): string {\n // Use the font family directly: the math-oriented \\\\butexmaghribi wrapper uses\n // \\\\text/\\\\mbox and would keep the whole sentence in one unbreakable box.\n return `\\\\begin{center}\\n\\\\maghribi{${BUTEX_CLOSING_HAMDALA}}\\n\\\\end{center}`;\n}\n\n/** A book unit is content, not an article. Never emit article chrome or a bibliography. */\nexport function documentContentLatex(document: DocumentNode, context?: DocumentBookContext): string {\n if (!context?.unitId?.trim()) throw new Error('book-content export requires a stable unitId');\n const labelKinds = documentLabelKindMap(document);\n for (const target of context?.targets ?? []) {\n if (target.kind === 'fig' || target.kind === 'tab' || target.kind === 'eq') {\n labelKinds.set(target.key, target.kind);\n if (target.manualKey) labelKinds.set(target.manualKey, target.kind);\n }\n }\n return document.blocks.filter((block) => block.kind !== 'bibliography')\n .map((block) => blockLatex(block, document.references, labelKinds, false, context?.unitId))\n .filter((part) => part.length > 0).join('\\n\\n');\n}\n\nexport function documentLatex(\n document: DocumentNode,\n options: DocumentLatexOptions = {},\n): string {\n const meta = document.meta ?? emptyDocumentMeta();\n const twocolumn = options.twocolumn === true;\n const front = articleFrontMatterLatex(meta);\n const labelKinds = documentLabelKindMap(document);\n const bodyBlocks = document.blocks.map((block) =>\n blockLatex(block, document.references, labelKinds, twocolumn),\n );\n const closing = closingHamdalaLatex();\n const body = [...front, ...bodyBlocks, closing].filter((part) => part.length > 0).join('\\n\\n');\n const wrapDocument = options.wrapDocument !== false;\n if (!wrapDocument) {\n // Body-only: include title metadata so callers still see \\\\title / titling when present.\n const metaPreamble = articleMaketitlePreamble(meta, twocolumn);\n return metaPreamble.length > 0 ? `${metaPreamble}\\n\\n${body}` : body;\n }\n const floatPackage = twocolumn ? '\\n\\\\usepackage{float}\\n' : '\\n';\n const preamble =\n getArabicXeLatexPreamble({\n digitsMapping: options.digitsMapping ?? digitsMappingFromDigitForm(options.digitForm),\n twocolumn,\n }) +\n floatPackage +\n articleMaketitlePreamble(meta, twocolumn);\n return `${preamble}\\n\\\\begin{document}\\n\\n${body}\\n\\n\\\\end{document}\\n`;\n}\n","/** Pure JSON and stable-identity helpers shared by book adapters. */\nconst ID = /^[A-Za-z0-9_-]{1,128}$/;\nexport function safeId(id: string): boolean {\n return ID.test(id) && !['__proto__', 'prototype', 'constructor'].includes(id);\n}\n\nexport function object(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\nexport function copy<T>(value: T): T { return JSON.parse(JSON.stringify(value)) as T; }\n","import { isValidDocumentKey } from '../document/index.js';\nimport type { BookSnapshotJson } from './contracts.js';\nimport { copy, object, safeId } from './utils.js';\n\nexport class BookContractError extends Error {\n readonly code = 'invalid_book';\n constructor(message: string) { super(message); this.name = 'BookContractError'; }\n}\n\nconst KEYS = new Set(['title-page', 'table-of-contents', 'list-of-figures', 'list-of-tables', 'bibliography']);\nconst UNIT_TYPES = new Set(['abstract', 'dedication', 'acknowledgements', 'preface', 'abbreviations', 'chapter', 'appendix', 'backmatter']);\n\n/** Structural validation is deterministic and preserves every authored title and key. */\nexport function normalizeBookSnapshot(value: unknown): BookSnapshotJson {\n if (!object(value) || !object(value.manifest) || !object(value.references) || !object(value.documents)) {\n throw new BookContractError('Book snapshot requires manifest, references and documents');\n }\n const manifest = value.manifest;\n const meta = manifest.meta;\n if (manifest.node_type !== 'BookManifest' || manifest.schema_version !== 1 ||\n typeof manifest.id !== 'string' || !safeId(manifest.id) ||\n manifest.references_path !== 'references.json' || !Array.isArray(manifest.entries) ||\n !object(meta) || typeof meta.title !== 'string' || !Array.isArray(meta.authors) ||\n !meta.authors.every(x => typeof x === 'string') || meta.language !== 'ar' || meta.direction !== 'rtl' ||\n (meta.numbering !== undefined && (!object(meta.numbering) ||\n (meta.numbering.digit_form !== undefined && !['arabicIndic', 'western'].includes(String(meta.numbering.digit_form))) ||\n (meta.numbering.chapter_heading !== undefined && !['ordinal-words', 'digits'].includes(String(meta.numbering.chapter_heading))) ||\n (meta.numbering.appendix_heading !== undefined && !['letters', 'digits'].includes(String(meta.numbering.appendix_heading)))))) {\n throw new BookContractError('Invalid BookManifest v1');\n }\n if (value.references.node_type !== 'BookReferences' || value.references.schema_version !== 1 ||\n !Array.isArray(value.references.references)) {\n throw new BookContractError('Invalid BookReferences v1');\n }\n const ids = new Set<string>();\n const generated = new Set<string>();\n const unitIds = new Set<string>();\n for (const entry of manifest.entries as unknown[]) {\n if (!object(entry) || typeof entry.id !== 'string' || !safeId(entry.id) || ids.has(entry.id)) {\n throw new BookContractError('Duplicate or unsafe book entry ID');\n }\n ids.add(entry.id);\n if (entry.kind === 'generated') {\n if (typeof entry.generated !== 'string' || !KEYS.has(entry.generated) || generated.has(entry.generated)) {\n throw new BookContractError('Invalid or repeated generated entry');\n }\n generated.add(entry.generated);\n } else if (entry.kind === 'document') {\n if (typeof entry.type !== 'string' || !UNIT_TYPES.has(entry.type) ||\n typeof entry.title !== 'string' || typeof entry.numbered !== 'boolean' ||\n typeof entry.include_in_toc !== 'boolean' ||\n entry.document_path !== 'content/units/' + entry.id + '/document.json') {\n throw new BookContractError('Invalid or unsafe unit entry');\n }\n unitIds.add(entry.id);\n } else {\n throw new BookContractError('Unknown book entry kind');\n }\n }\n const documents = value.documents;\n if (Object.keys(documents).length !== unitIds.size || Object.keys(documents).some(id => !unitIds.has(id))) {\n throw new BookContractError('Unit documents must exactly match manifest');\n }\n for (const id of unitIds) {\n const doc = documents[id];\n if (!object(doc) || doc.node_type !== 'DocumentObject' || !Array.isArray(doc.blocks)) {\n throw new BookContractError('Invalid unit DocumentJson for ' + id);\n }\n }\n for (const ref of value.references.references) {\n if (!object(ref) || typeof ref.key !== 'string' || !isValidDocumentKey(ref.key)) {\n throw new BookContractError('Invalid shared bibliography entry');\n }\n }\n return copy(value as BookSnapshotJson);\n}\n","import type { DocumentJson, Reference2Json } from '../document/index.js';\nimport type { BookEntry, BookMetaJson, BookSnapshotJson } from './contracts.js';\nimport { copy, object, safeId } from './utils.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookCommand =\n | { op: 'reorder_entries'; entry_ids: string[] }\n | { op: 'update_entry'; entry_id: string; title?: string; numbered?: boolean; include_in_toc?: boolean; label?: string | null }\n | { op: 'set_meta'; meta: BookMetaJson }\n | { op: 'set_references'; references: Reference2Json[] }\n | { op: 'insert_entry'; entry: BookEntry; document?: DocumentJson; index: number }\n | { op: 'remove_entry'; entry_id: string };\n\n/** Validate untrusted book-command JSON before it reaches the typed reducer. */\nexport function parseBookCommand(value: unknown): BookCommand {\n if (!object(value) || typeof value.op !== 'string') {\n throw new BookContractError('Book command requires an operation');\n }\n const rules: Record<string, string[]> = {\n reorder_entries: ['entry_ids'],\n update_entry: ['entry_id', 'title', 'numbered', 'include_in_toc', 'label'],\n set_meta: ['meta'],\n set_references: ['references'],\n insert_entry: ['entry', 'document', 'index'],\n remove_entry: ['entry_id'],\n };\n const allowed = rules[value.op];\n if (!allowed || Object.keys(value).some(key => key !== 'op' && !allowed.includes(key))) {\n throw new BookContractError('Unsupported book command fields');\n }\n if (value.op === 'reorder_entries' &&\n (!Array.isArray(value.entry_ids) || !value.entry_ids.every(id => typeof id === 'string'))) {\n throw new BookContractError('Reorder requires entry ID list');\n }\n if (value.op === 'update_entry' &&\n (typeof value.entry_id !== 'string' || !safeId(value.entry_id) ||\n !['title', 'numbered', 'include_in_toc', 'label'].some(key => key in value) ||\n (value.title !== undefined && typeof value.title !== 'string') ||\n (value.numbered !== undefined && typeof value.numbered !== 'boolean') ||\n (value.include_in_toc !== undefined && typeof value.include_in_toc !== 'boolean') ||\n (value.label !== undefined && value.label !== null && typeof value.label !== 'string'))) {\n throw new BookContractError('Invalid book entry patch');\n }\n if (value.op === 'set_meta' && !object(value.meta)) {\n throw new BookContractError('Book metadata must be an object');\n }\n if (value.op === 'set_references' &&\n (!Array.isArray(value.references) || !value.references.every(entry => object(entry)))) {\n throw new BookContractError('Shared bibliography must be an array of entries');\n }\n if (value.op === 'insert_entry' &&\n (!object(value.entry) || !Number.isInteger(value.index) ||\n ((value.entry.kind !== 'document') && (value.entry.kind !== 'generated')) ||\n (value.entry.kind === 'document' && !object(value.document)) ||\n (value.entry.kind === 'generated' && value.document !== undefined))) {\n throw new BookContractError('Invalid book insertion command');\n }\n if (value.op === 'remove_entry' && (typeof value.entry_id !== 'string' || !safeId(value.entry_id))) {\n throw new BookContractError('Removal requires stable entry ID');\n }\n return value as BookCommand;\n}\n\n/** Commands only edit a manifest/catalog; individual Document commands remain on /v1/document. */\nexport function applyBookCommand(raw: unknown, command: BookCommand): BookSnapshotJson {\n const snapshot = normalizeBookSnapshot(raw);\n command = parseBookCommand(command);\n if (command.op === 'reorder_entries') {\n const actual = snapshot.manifest.entries.map(e => e.id);\n if (command.entry_ids.length !== actual.length ||\n new Set(command.entry_ids).size !== actual.length ||\n actual.some(id => !command.entry_ids.includes(id))) {\n throw new BookContractError('Reorder must contain every existing entry exactly once');\n }\n const byId = new Map(snapshot.manifest.entries.map(e => [e.id, e]));\n snapshot.manifest.entries = command.entry_ids.map(id => byId.get(id)!);\n } else if (command.op === 'update_entry') {\n const entry = snapshot.manifest.entries.find(e => e.id === command.entry_id);\n if (!entry || entry.kind !== 'document') throw new BookContractError('Unknown document unit');\n if (command.title !== undefined) entry.title = command.title;\n if (command.numbered !== undefined) entry.numbered = command.numbered;\n if (command.include_in_toc !== undefined) entry.include_in_toc = command.include_in_toc;\n if (command.label !== undefined) {\n if (command.label === null) delete entry.label;\n else entry.label = command.label;\n }\n } else if (command.op === 'set_meta') {\n snapshot.manifest.meta = copy(command.meta);\n } else if (command.op === 'set_references') {\n snapshot.references.references = copy(command.references);\n } else if (command.op === 'insert_entry') {\n if (!Number.isInteger(command.index) || command.index < 0 || command.index > snapshot.manifest.entries.length) {\n throw new BookContractError('Invalid insertion index');\n }\n snapshot.manifest.entries.splice(command.index, 0, copy(command.entry));\n if (command.entry.kind === 'document') {\n if (!command.document) throw new BookContractError('New document unit needs a separate DocumentJson');\n snapshot.documents[command.entry.id] = copy(command.document);\n }\n } else if (command.op === 'remove_entry') {\n const at = snapshot.manifest.entries.findIndex(e => e.id === command.entry_id);\n if (at < 0) throw new BookContractError('Unknown book entry');\n const [removed] = snapshot.manifest.entries.splice(at, 1);\n if (removed?.kind === 'document') delete snapshot.documents[removed.id];\n } else {\n throw new BookContractError('Unknown book structure operation');\n }\n return normalizeBookSnapshot(snapshot);\n}\n","import {\n collectDocumentReferenceTargets,\n fromDocumentJson,\n getDocumentReferenceIndex,\n implicitHeadingReferenceKey,\n implicitReferenceKey,\n isValidDocumentKey,\n} from '../document/index.js';\nimport type { DocumentBlockJson, DocumentBookContext, DocumentBookTarget } from '../document/index.js';\nimport type { BookSnapshotJson } from './contracts.js';\nimport { copy } from './utils.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookIssue = {\n code: 'invalid_snapshot' | 'invalid_entry' | 'missing_document' | 'duplicate_entry' |\n 'duplicate_generated' | 'local_bibliography' | 'unstable_block_id' |\n 'duplicate_key' | 'invalid_key' | 'missing_citation' | 'missing_reference' |\n 'invalid_reference_kind';\n path: string;\n severity: 'error' | 'warning';\n unit_id?: string;\n block_id?: string;\n token_id?: string;\n key?: string;\n};\n\nexport type BookOutlineEntry = {\n id: string;\n kind: 'chapter' | 'appendix' | 'unit' | 'generated' | 'section' | 'subsection' | 'subsubsection';\n title: string;\n display_label: string;\n level: number;\n unit_id?: string;\n parent_unit_id?: string;\n numbered: boolean;\n include_in_toc: boolean;\n};\n\nexport type BookTarget = DocumentBookTarget & {\n numbered: boolean;\n ordinal?: string;\n};\n\nexport type BookResolution = {\n manifest_id: string;\n outline: BookOutlineEntry[];\n targets: BookTarget[];\n citations: Array<{ key: string; number: number; display_label: string }>;\n issues: BookIssue[];\n};\n\nconst LETTERS = ['أ', 'ب', 'ج', 'د', 'هـ', 'و', 'ز', 'ح', 'ط', 'ي', 'ك', 'ل', 'م', 'ن', 'س', 'ع', 'ف', 'ص', 'ق', 'ر', 'ش', 'ت', 'ث', 'خ', 'ذ', 'ض', 'ظ', 'غ'];\nconst ORDINALS = ['الأول', 'الثاني', 'الثالث', 'الرابع', 'الخامس', 'السادس', 'السابع', 'الثامن', 'التاسع', 'العاشر',\n 'الحادي عشر', 'الثاني عشر', 'الثالث عشر', 'الرابع عشر', 'الخامس عشر', 'السادس عشر', 'السابع عشر', 'الثامن عشر', 'التاسع عشر', 'العشرون'];\n\nfunction digits(value: number | string, form: 'arabicIndic' | 'western'): string {\n return form === 'western' ? String(value) : String(value).replace(/[0-9]/g, ch => '٠١٢٣٤٥٦٧٨٩'[Number(ch)]!);\n}\nfunction ordinal(number: number, form: 'arabicIndic' | 'western', style: 'ordinal-words' | 'digits'): string {\n return style === 'digits' ? digits(number, form) : ORDINALS[number - 1] ?? digits(number, form);\n}\nfunction appendix(number: number, form: 'arabicIndic' | 'western', style: 'letters' | 'digits'): string {\n return style === 'digits' ? digits(number, form) : LETTERS[number - 1] ?? digits(number, form);\n}\nfunction unitAlias(kind: 'chapter' | 'appendix', unitId: string): string {\n const hex = Array.from(new TextEncoder().encode(unitId), byte => byte.toString(16).padStart(2, '0')).join('');\n return kind + ':butex-auto-u' + hex + '-' + hex;\n}\nfunction issue(code: BookIssue['code'], path: string, extra: Partial<BookIssue> = {}): BookIssue {\n return { code, path, severity: code === 'missing_citation' || code === 'missing_reference' ? 'warning' : 'error', ...extra };\n}\n\nfunction headingKind(block: DocumentBlockJson): 'section' | 'subsection' | 'subsubsection' | null {\n if (block.command === '\\\\section') return 'section';\n if (block.command === '\\\\subsection') return 'subsection';\n if (block.command === '\\\\subsubsection') return 'subsubsection';\n return null;\n}\nfunction headingLevel(kind: 'section' | 'subsection' | 'subsubsection'): number {\n return kind === 'section' ? 1 : kind === 'subsection' ? 2 : 3;\n}\n\n/** One global, read-only catalog; no ordinals or shared bibliography are written into chapter JSON. */\nexport function resolveBookSnapshot(raw: unknown): BookResolution {\n const snapshot = normalizeBookSnapshot(raw);\n const { manifest, references, documents } = snapshot;\n const digitForm = manifest.meta.numbering?.digit_form ?? 'arabicIndic';\n const chapterStyle = manifest.meta.numbering?.chapter_heading ?? 'ordinal-words';\n const appendixStyle = manifest.meta.numbering?.appendix_heading ?? 'letters';\n const outline: BookOutlineEntry[] = [];\n const targets: BookTarget[] = [];\n const issues: BookIssue[] = [];\n const aliasOwners = new Map<string, { unitId?: string; ownerId?: string }>();\n const citationKeys = new Set<string>();\n const unnumbered = { fig: 0, tab: 0, eq: 0 };\n let chapterCount = 0;\n let appendixCount = 0;\n\n function register(key: string | undefined, unitId?: string, ownerId?: string): void {\n if (!key) return;\n if (!isValidDocumentKey(key)) {\n issues.push(issue('invalid_key', '$.references', { unit_id: unitId, block_id: ownerId, key }));\n }\n if (aliasOwners.has(key)) {\n issues.push(issue('duplicate_key', '$.references', { unit_id: unitId, block_id: ownerId, key }));\n } else {\n aliasOwners.set(key, { unitId, ownerId });\n }\n }\n for (let n = 0; n < references.references.length; n++) {\n const ref = references.references[n]!;\n citationKeys.add(ref.key);\n register(ref.key);\n }\n const citations = references.references.map((ref, i) => ({\n key: ref.key, number: i + 1, display_label: '[' + digits(i + 1, digitForm) + ']',\n }));\n\n for (const entry of manifest.entries) {\n if (entry.kind === 'generated') {\n outline.push({ id: entry.id, kind: 'generated', title: entry.generated,\n display_label: entry.generated, level: 0, numbered: false, include_in_toc: false });\n continue;\n }\n const unitId = entry.id;\n const isChapter = entry.type === 'chapter';\n const isAppendix = entry.type === 'appendix';\n if (isChapter && entry.numbered) chapterCount++;\n if (isAppendix && entry.numbered) appendixCount++;\n const chapterNumber = isChapter && entry.numbered ? chapterCount : null;\n const appendixNumber = isAppendix && entry.numbered ? appendixCount : null;\n const prefix = chapterNumber !== null ? digits(chapterNumber, digitForm)\n : appendixNumber !== null ? appendix(appendixNumber, digitForm, appendixStyle) : '';\n const generatedTitle = chapterNumber !== null ? 'الفصل ' + ordinal(chapterNumber, digitForm, chapterStyle)\n : appendixNumber !== null ? 'الملحق ' + prefix : '';\n const displayTitle = generatedTitle ? generatedTitle + ': ' + entry.title : entry.title;\n outline.push({\n id: unitId, unit_id: unitId, kind: isChapter ? 'chapter' : isAppendix ? 'appendix' : 'unit',\n title: entry.title, display_label: displayTitle, level: 0, numbered: entry.numbered,\n include_in_toc: entry.include_in_toc,\n });\n if (isChapter || isAppendix) {\n const kind = isChapter ? 'chapter' : 'appendix';\n const key = unitAlias(kind, unitId);\n targets.push({ unitId, ownerId: unitId, key, kind, caption: entry.title,\n displayLabel: generatedTitle || entry.title, numbered: entry.numbered,\n ...(prefix ? { ordinal: prefix } : {}), ...(entry.label ? { manualKey: entry.label } : {}) });\n register(key, unitId, unitId);\n register(entry.label, unitId, unitId);\n } else {\n register(entry.label, unitId, unitId);\n }\n\n const doc = documents[unitId]!;\n const seenBlocks = new Set<string>();\n const headingNumbers = { section: 0, subsection: 0, subsubsection: 0 };\n for (let b = 0; b < doc.blocks.length; b++) {\n const block = doc.blocks[b]!;\n if (!block.id || seenBlocks.has(block.id)) {\n issues.push(issue('unstable_block_id', '$.documents.' + unitId + '.blocks[' + b + ']',\n { unit_id: unitId, block_id: block.id }));\n } else seenBlocks.add(block.id);\n if (block.command === '\\\\begin{thebibliography}' || block.command === '\\\\bibliography') {\n issues.push(issue('local_bibliography', '$.documents.' + unitId + '.blocks[' + b + ']',\n { unit_id: unitId, block_id: block.id }));\n }\n const kind = headingKind(block);\n if (kind && block.id) {\n // Chapter-aware heading numbers are a projection; never persist them\n // in a unit's canonical DocumentJson or overwrite authored titles.\n if (kind === 'section') {\n headingNumbers.section++;\n headingNumbers.subsection = 0;\n headingNumbers.subsubsection = 0;\n } else if (kind === 'subsection') {\n headingNumbers.subsection++;\n headingNumbers.subsubsection = 0;\n } else {\n headingNumbers.subsubsection++;\n }\n const levels = kind === 'section' ? [headingNumbers.section]\n : kind === 'subsection' ? [headingNumbers.section, headingNumbers.subsection]\n : [headingNumbers.section, headingNumbers.subsection, headingNumbers.subsubsection];\n const ordinalLabel = [...(prefix ? [prefix] : []),\n ...levels.map(number => digits(number, digitForm))].join('.');\n const visible = 'القسم ' + ordinalLabel;\n const key = implicitHeadingReferenceKey(kind, block.id, unitId);\n const label = block.value ?? '';\n outline.push({ id: block.id, parent_unit_id: unitId, unit_id: unitId, kind,\n title: label, display_label: visible + ': ' + label, level: headingLevel(kind), numbered: true,\n include_in_toc: entry.include_in_toc });\n targets.push({ unitId, ownerId: block.id, key, kind, caption: label,\n displayLabel: visible, ordinal: ordinalLabel, numbered: true,\n ...(block.label ? { manualKey: block.label } : {}) });\n register(key, unitId, block.id);\n register(block.label, unitId, block.id);\n }\n }\n const resolved = fromDocumentJson(doc);\n const localCounts = { fig: 0, tab: 0, eq: 0 };\n for (const target of collectDocumentReferenceTargets(resolved)) {\n const key = implicitReferenceKey(target.kind, target.ownerId, unitId);\n const numbered = target.number !== null;\n if (numbered) {\n if (prefix) localCounts[target.kind]++;\n else unnumbered[target.kind]++;\n }\n const index = prefix ? localCounts[target.kind] : unnumbered[target.kind];\n const displayOrdinal = numbered ? (prefix ? prefix + '.' : '') + digits(index, digitForm) : '';\n const name = target.kind === 'fig' ? 'الشكل' : target.kind === 'tab' ? 'الجدول' : 'المعادلة';\n const displayLabel = numbered ? (target.kind === 'eq' ? name + ' (' + displayOrdinal + ')' : name + ' ' + displayOrdinal) : '';\n targets.push({ unitId, ownerId: target.ownerId, key, kind: target.kind,\n caption: target.caption, numbered, ...(displayOrdinal ? { ordinal: displayOrdinal, displayLabel } : {}),\n ...(target.manualKey ? { manualKey: target.manualKey } : {}) });\n if (numbered) {\n register(key, unitId, target.ownerId);\n register(target.manualKey, unitId, target.ownerId);\n }\n }\n }\n // Validate relationships only after seeing all units: references may point forward.\n for (const entry of manifest.entries) {\n if (entry.kind !== 'document') continue;\n const doc = fromDocumentJson(documents[entry.id]!);\n const refs = getDocumentReferenceIndex(doc);\n for (const citation of refs.citations) {\n for (const key of citation.keys) {\n if (!citationKeys.has(key)) {\n issues.push(issue('missing_citation', '$.documents.' + entry.id + '.citations', {\n unit_id: entry.id, block_id: citation.block_id, token_id: citation.token_id, key,\n }));\n }\n }\n }\n for (const reference of refs.cross_references) {\n for (const key of reference.keys) {\n const hit = targets.find(t => t.key === key || t.manualKey === key);\n if (!hit || (!hit.numbered && (hit.kind === 'fig' || hit.kind === 'tab' || hit.kind === 'eq'))) {\n issues.push(issue('missing_reference', '$.documents.' + entry.id + '.references', {\n unit_id: entry.id, block_id: reference.block_id, token_id: reference.token_id, key,\n }));\n } else if (reference.ref_command === 'eqref' && hit.kind !== 'eq') {\n issues.push(issue('invalid_reference_kind', '$.documents.' + entry.id + '.references', {\n unit_id: entry.id, block_id: reference.block_id, token_id: reference.token_id, key,\n }));\n }\n }\n }\n }\n return { manifest_id: manifest.id, outline, targets, citations, issues };\n}\n\nexport function bookContextForUnit(snapshot: BookSnapshotJson, unitId: string): DocumentBookContext {\n if (!Object.prototype.hasOwnProperty.call(snapshot.documents, unitId)) {\n throw new BookContractError('Unknown book unit: ' + unitId);\n }\n const projection = resolveBookSnapshot(snapshot);\n return { unitId, references: copy(snapshot.references.references), targets: projection.targets.map(t => ({\n unitId: t.unitId, ownerId: t.ownerId, key: t.key, kind: t.kind,\n ...(t.caption !== undefined ? { caption: t.caption } : {}),\n ...(t.displayLabel !== undefined ? { displayLabel: t.displayLabel } : {}),\n ...(t.ordinal !== undefined ? { ordinal: t.ordinal } : {}),\n ...(t.manualKey !== undefined ? { manualKey: t.manualKey } : {}),\n })) };\n}\n\nexport function bookOutline(snapshot: unknown): BookOutlineEntry[] {\n return resolveBookSnapshot(snapshot).outline;\n}\nexport function getBookReferenceIndex(snapshot: unknown): BookResolution {\n return resolveBookSnapshot(snapshot);\n}\nexport function validateBookSnapshot(snapshot: unknown): { valid: boolean; issues: BookIssue[] } {\n const resolution = resolveBookSnapshot(snapshot);\n return { valid: resolution.issues.every(x => x.severity !== 'error'), issues: resolution.issues };\n}\n","/** Deterministic, pure multi-file XeLaTeX Book export. No ZIP, filesystem or S3. */\nimport {\n bibliographyEntryLatex, documentContentLatex, fromDocumentJson,\n getArabicXeLatexPreamble, referenceFromJson,\n} from '../document/index.js';\nimport type { DocumentBlockJson, DocumentBookContext } from '../document/index.js';\nimport type { BookSnapshotJson, BookUnitEntry } from './contracts.js';\nimport type { BookIssue, BookResolution } from './introspection.js';\nimport { resolveBookSnapshot } from './introspection.js';\nimport { BookContractError, normalizeBookSnapshot } from './validation.js';\n\nexport type BookLatexAsset = { asset_id: string; output_path: string };\nexport type BookLatexBundle = {\n main_file: 'main.tex';\n files: Record<string, string>;\n assets: BookLatexAsset[];\n diagnostics: BookIssue[];\n /** Stable source fingerprint; Al-Bayan computes SHA-256 for stored artifacts. */\n fingerprint: string;\n};\nexport type BookLatexOptions = { include_toc_if_missing?: boolean };\n\nconst SAFE_PATH = /^[A-Za-z0-9][A-Za-z0-9._-]*(\\/[A-Za-z0-9][A-Za-z0-9._-]*){0,3}$/;\nconst IMAGE_EXT = /\\.(?:png|jpe?g|pdf)$/i;\n\nfunction escapeLatex(value: string): string {\n return value.replace(/[\\\\{}%#$&_~^]/g, (char) => ({\n '\\\\': '\\\\textbackslash{}', '{': '\\\\{', '}': '\\\\}', '%': '\\\\%',\n '#': '\\\\#', '$': '\\\\$', '&': '\\\\&', '_': '\\\\_',\n '~': '\\\\textasciitilde{}', '^': '\\\\textasciicircum{}',\n })[char] ?? char);\n}\n\nfunction visitAssets(blocks: DocumentBlockJson[], collect: (assetId: string, path: string) => void): void {\n for (const block of blocks) {\n if (block.command === '\\\\includegraphics') {\n if (!block.asset_id || typeof block.value !== 'string') {\n throw new BookContractError('Book images require an asset_id and relative image path');\n }\n collect(block.asset_id, block.value);\n }\n for (const item of block.items ?? []) {\n visitAssets(item.blocks ?? [], collect);\n }\n }\n}\n\nfunction fingerprint(files: Record<string, string>, assets: BookLatexAsset[]): string {\n // Browser-safe deterministic FNV-1a (source fingerprint only; not a security hash).\n let value = 2166136261;\n const payload = JSON.stringify({ files, assets });\n for (const byte of new TextEncoder().encode(payload)) {\n value = Math.imul(value ^ byte, 16777619) >>> 0;\n }\n return 'fnv1a32:' + value.toString(16).padStart(8, '0');\n}\n\nfunction heading(entry: BookUnitEntry, resolution: BookResolution): string {\n return resolution.outline.find(item => item.id === entry.id)?.display_label ?? entry.title;\n}\n\nfunction unitBoundary(entry: BookUnitEntry, projection: BookResolution, unnumbered: { fig: number; tab: number; eq: number }): string {\n const numbered = (entry.type === 'chapter' || entry.type === 'appendix') && entry.numbered;\n const lines: string[] = [];\n if (numbered) {\n const target = projection.targets.find(t => t.unitId === entry.id && t.ownerId === entry.id);\n if (!target?.ordinal) throw new BookContractError('Missing Book numbering projection for ' + entry.id);\n lines.push(\n '\\\\renewcommand{\\\\thechapter}{' + target.ordinal + '}',\n '\\\\refstepcounter{chapter}',\n '\\\\renewcommand{\\\\thesection}{\\\\thechapter.\\\\arabic{section}}',\n );\n } else {\n lines.push(\n '\\\\setcounter{section}{0}',\n '\\\\renewcommand{\\\\thesection}{\\\\arabic{section}}',\n );\n }\n for (const [kind, counter] of [['fig', 'figure'], ['tab', 'table'], ['eq', 'equation']] as const) {\n lines.push('\\\\setcounter{' + counter + '}{' + (numbered ? '0' : String(unnumbered[kind])) + '}');\n lines.push('\\\\renewcommand{\\\\the' + counter + '}{' + (numbered ? '\\\\thechapter.' : '') + '\\\\arabic{' + counter + '}}');\n }\n\n const title = escapeLatex(heading(entry, projection));\n lines.push('\\\\chapter*{' + title + '}');\n if (entry.include_in_toc) {\n lines.push('\\\\addcontentsline{toc}{chapter}{' + title + '}');\n }\n if (numbered) {\n const target = projection.targets.find(t => t.unitId === entry.id && t.ownerId === entry.id);\n if (target) lines.push('\\\\label{' + target.key + '}');\n if (entry.label && entry.label !== target?.key) lines.push('\\\\label{' + entry.label + '}');\n } else if (entry.label) {\n lines.push('\\\\label{' + entry.label + '}');\n }\n return lines.join('\\n');\n}\n\nfunction bookPreamble(snapshot: BookSnapshotJson): string {\n const arabicDigits = snapshot.manifest.meta.numbering?.digit_form !== 'western';\n const articlePreamble = getArabicXeLatexPreamble({\n digitsMapping: arabicDigits ? 'arabicdigits' : 'digits',\n });\n const withoutClass = articlePreamble.replace(/\\\\documentclass\\[[^\\]]*\\]\\{article\\}/, '');\n if (withoutClass === articlePreamble) throw new BookContractError('Arabic preamble class seam has changed');\n return [\n '\\\\NeedsTeXFormat{LaTeX2e}',\n '\\\\ProvidesPackage{book}[2026/11/14 BuTeX Arabic Book]',\n withoutClass.replace(/\\\\usepackage/g, '\\\\RequirePackage'),\n '\\\\renewcommand{\\\\figurename}{الشكل}',\n '\\\\renewcommand{\\\\tablename}{الجدول}',\n '\\\\renewcommand{\\\\contentsname}{المحتويات}',\n ].join('\\n');\n}\n\n\n/**\n * amsmath permits only one \\\\label inside an equation. Keep the stable\n * auto-label as the compiled identity and resolve author labels as aliases in\n * book cross-references. The saved Document and Book projection are unchanged.\n */\nfunction normalizeBookEquationLabels(content: string, unitId: string, projection: BookResolution): string {\n const aliases = new Map<string, string>();\n let latex = content;\n for (const target of projection.targets) {\n if (target.kind !== 'eq' || !target.manualKey || target.manualKey === target.key) continue;\n aliases.set(target.manualKey, target.key);\n if (target.unitId === unitId) {\n const automatic = '\\\\label{' + target.key + '}';\n const manual = '\\\\label{' + target.manualKey + '}';\n latex = latex.replace(automatic + '\\n' + manual, automatic);\n }\n }\n if (!aliases.size) return latex;\n return latex.replace(/\\\\(eqref|ref)\\{([^}]*)\\}/g, (_whole, command: string, keys: string) =>\n '\\\\' + command + '{' +\n keys.split(',').map(key => aliases.get(key.trim()) ?? key).join(',') + '}');\n}\n\nexport function book2Latex(raw: unknown, _options: BookLatexOptions = {}): BookLatexBundle {\n const snapshot = normalizeBookSnapshot(raw);\n const projection = resolveBookSnapshot(snapshot);\n const fatal = projection.issues.filter(issue => issue.severity === 'error');\n if (fatal.length) {\n throw new BookContractError('Book export blocked: ' + fatal[0]!.code + ' at ' + fatal[0]!.path);\n }\n const files: Record<string, string> = {};\n const assets: BookLatexAsset[] = [];\n const paths = new Map<string, string>();\n const addAsset = (assetId: string, path: string): void => {\n const tail = path.split('/').at(-1) ?? '';\n const extensionless = !tail.includes('.');\n if (!SAFE_PATH.test(path) || path.split('/').some(part => part.startsWith('.')) ||\n !(IMAGE_EXT.test(path) || extensionless)) {\n throw new BookContractError('Unsafe or unsupported Book image path: ' + path);\n }\n const alias = path.toLowerCase();\n const prior = paths.get(alias);\n if (prior && prior !== assetId) {\n throw new BookContractError('Multiple Book assets claim the same image path: ' + path);\n }\n paths.set(alias, assetId);\n if (!assets.some(a => a.asset_id === assetId && a.output_path === path)) {\n assets.push({ asset_id: assetId, output_path: path });\n }\n };\n const meta = snapshot.manifest.meta;\n const main = [\n '\\\\documentclass[12pt,a4paper]{book}',\n '\\\\usepackage{book}',\n '\\\\begin{document}',\n ];\n const unnumbered = { fig: 0, tab: 0, eq: 0 };\n let hasBibliography = false;\n let hasToc = false;\n\n for (const entry of snapshot.manifest.entries) {\n if (entry.kind === 'generated') {\n if (entry.generated === 'title-page') {\n main.push('\\\\begin{titlepage}\\\\centering',\n '{\\\\Huge ' + escapeLatex(meta.title) + '\\\\par}',\n '\\\\vspace{2cm}', ...meta.authors.map(author => escapeLatex(author) + '\\\\par'),\n ...(meta.date ? [escapeLatex(meta.date) + '\\\\par'] : []), '\\\\end{titlepage}');\n } else if (entry.generated === 'table-of-contents') {\n hasToc = true;\n main.push('\\\\tableofcontents');\n } else if (entry.generated === 'list-of-figures') {\n main.push('\\\\listoffigures');\n } else if (entry.generated === 'list-of-tables') {\n main.push('\\\\listoftables');\n } else if (entry.generated === 'bibliography') {\n hasBibliography = true;\n main.push('\\\\input{references.tex}');\n }\n continue;\n }\n\n const unitPath = 'units/' + entry.id + '.tex';\n const doc = snapshot.documents[entry.id]!;\n visitAssets(doc.blocks, addAsset);\n const context: DocumentBookContext = {\n unitId: entry.id, references: snapshot.references.references,\n targets: projection.targets,\n };\n const content = normalizeBookEquationLabels(documentContentLatex(fromDocumentJson(doc), context), entry.id, projection);\n files[unitPath] = [unitBoundary(entry, projection, unnumbered), content, ''].join('\\n\\n');\n main.push('\\\\input{' + unitPath + '}');\n if (!((entry.type === 'chapter' || entry.type === 'appendix') && entry.numbered)) {\n for (const kind of ['fig', 'tab', 'eq'] as const) {\n unnumbered[kind] += projection.targets.filter(t =>\n t.unitId === entry.id && t.kind === kind && t.numbered).length;\n }\n }\n }\n if (!hasToc && _options.include_toc_if_missing) {\n main.splice(3, 0, '\\\\tableofcontents');\n }\n if (snapshot.references.references.length) {\n const entries = snapshot.references.references.map(ref => ' ' + bibliographyEntryLatex(referenceFromJson(ref)));\n files['references.tex'] = ['\\\\begin{thebibliography}{' + String(Math.max(9, entries.length)) + '}',\n ...entries, '\\\\end{thebibliography}', ''].join('\\n');\n if (!hasBibliography) main.push('\\\\input{references.tex}');\n } else if (hasBibliography) {\n files['references.tex'] = '% No shared references\\n';\n }\n main.push('\\\\end{document}', '');\n files['main.tex'] = main.join('\\n\\n');\n files['book.sty'] = bookPreamble(snapshot);\n const ordered = Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))) as Record<string, string>;\n return { main_file: 'main.tex', files: ordered, assets,\n diagnostics: projection.issues, fingerprint: fingerprint(ordered, assets) };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAI,SAAS;AACb,IAAM,aAAa,GAAG,KAAK,IAAI,EAAE,SAAS,EAAE,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,EAAE,CAAC;AAEjF,SAAS,WAAW,QAAwB;AACjD,QAAM,KAAK,GAAG,MAAM,IAAI,UAAU,IAAI,OAAO,MAAM,CAAC;AACpD,YAAU;AACV,SAAO;AACT;;;ACLA,IAAM,UAAU;AAChB,IAAM,eAAe;AACrB,IAAM,gBAAgB;AAEtB,IAAM,YAAyC;AAAA,EAC7C,SAAS;AAAA,EACT,aAAa;AAAA,EACb,cAAc;AAChB;AAEA,SAAS,WAAW,MAAsB;AACxC,QAAM,UAAU,QAAQ,QAAQ,IAAI;AACpC,MAAI,WAAW,GAAG;AAChB,WAAO;AAAA,EACT;AACA,QAAM,cAAc,aAAa,QAAQ,IAAI;AAC7C,MAAI,eAAe,GAAG;AACpB,WAAO;AAAA,EACT;AACA,SAAO,cAAc,QAAQ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,MAAM,EAAE,SAAS,QAAQ,EAAE,QAAQ,EAAE;AAAA,MAC5D;AAAA,IACF;AAAA,EACF;AACA,MAAI,CAAC,UAAU,SAAS,wBAAwB;AAC9C,SAAK,OAAO,GAAG,GAAG,mBAAmB;AAAA,EACvC;AACA,MAAI,SAAS,WAAW,WAAW,QAAQ;AACzC,UAAM,UAAU,SAAS,WAAW,WAAW,IAAI,SAAO,OAAO,uBAAuB,kBAAkB,GAAG,CAAC,CAAC;AAC/G,UAAM,gBAAgB,IAAI;AAAA,MAAC,8BAA8B,OAAO,KAAK,IAAI,GAAG,QAAQ,MAAM,CAAC,IAAI;AAAA,MAC7F,GAAG;AAAA,MAAS;AAAA,MAA0B;AAAA,IAAE,EAAE,KAAK,IAAI;AACrD,QAAI,CAAC,gBAAiB,MAAK,KAAK,yBAAyB;AAAA,EAC3D,WAAW,iBAAiB;AAC1B,UAAM,gBAAgB,IAAI;AAAA,EAC5B;AACA,OAAK,KAAK,mBAAmB,EAAE;AAC/B,QAAM,UAAU,IAAI,KAAK,KAAK,MAAM;AACpC,QAAM,UAAU,IAAI,aAAa,QAAQ;AACzC,QAAM,UAAU,OAAO,YAAY,OAAO,QAAQ,KAAK,EAAE,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AAC/F,SAAO;AAAA,IAAE,WAAW;AAAA,IAAY,OAAO;AAAA,IAAS;AAAA,IAC9C,aAAa,WAAW;AAAA,IAAQ,aAAa,YAAY,SAAS,MAAM;AAAA,EAAE;AAC9E;","names":["value","leftDelimExpr","rightDelimExpr","node","parseChain","document","document","isObject","nextId","leftDelimExpr","rightDelimExpr","scripts","document","document","document","issue"]}
|