@drghaliasri/butex 5.3.2 → 5.3.3
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/document.js +25 -1
- package/dist/document.js.map +1 -1
- package/dist/document.mjs +25 -1
- package/dist/document.mjs.map +1 -1
- package/dist/document2.js +25 -1
- package/dist/document2.js.map +1 -1
- package/dist/document2.mjs +25 -1
- package/dist/document2.mjs.map +1 -1
- package/dist/index.d.mts +25 -1
- package/dist/index.d.ts +25 -1
- package/dist/index.global.js +61 -9
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +61 -9
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +61 -9
- package/dist/index.mjs.map +1 -1
- package/dist/react-document.js +57 -3
- package/dist/react-document.js.map +1 -1
- package/dist/react-document.mjs +57 -3
- package/dist/react-document.mjs.map +1 -1
- package/dist/react-document2.js +57 -3
- package/dist/react-document2.js.map +1 -1
- package/dist/react-document2.mjs +57 -3
- package/dist/react-document2.mjs.map +1 -1
- package/dist/react.d.mts +25 -1
- package/dist/react.d.ts +25 -1
- package/dist/react.js +57 -3
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +57 -3
- package/dist/react.mjs.map +1 -1
- package/package.json +1 -1
package/dist/document2.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/document2/ids.ts","../src/editor/digits.ts","../src/document2/articleMeta.ts","../src/document2/citations.ts","../src/ast/commands/index.ts","../src/ast/arabic_ast.ts","../src/document/mathObject.ts","../src/document2/labels.ts","../src/document2/inlineScanner.ts","../src/document2/importJson.ts","../src/editor/atomicCommands.ts","../src/editor/atomicCommandsOperators.ts","../src/editor/factory.ts","../src/editor/divideOperator.ts","../src/editor/render.ts","../src/editor/display/delimiter.ts","../src/editor/display/frac.ts","../src/editor/display/sqrt.ts","../src/editor/display/env.ts","../src/diwani-font.ts","../src/editor/display/atomicCommand.ts","../src/editor/display/atomicCommandsOperators.ts","../src/editor/styles.ts","../src/document/normalizeCharImport.ts","../src/document/mathEditorAdapter.ts","../src/document2/mathBridge.ts","../src/document2/commands.ts","../src/document2/keys.ts","../src/document2/arabicPreamble.ts","../src/document2/exportLatex.ts","../src/document2/history.ts","../src/document2/blockSelection.ts","../src/document2/previewModel.ts"],"sourcesContent":["let nextId = 1;\n\nexport function document2Id(prefix: string): string {\n const id = `${prefix}_${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 { Document2HijriDate, Document2Meta, 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\n/** Display-math body using BuTeX Diwani (for MathJax preview islands). */\nexport function butexDiwaniDisplayTex(text: string): string {\n return `\\\\butexdiwani{${escapeButexTextArg(text)}}`;\n}\n\n/** Full display equation for XeLaTeX export. */\nexport function butexDiwaniDisplayLatex(text: string): string {\n return `\\\\[\\n${butexDiwaniDisplayTex(text)}\\n\\\\]`;\n}\n\nconst BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT] as const;\n\n/** Three-line Diwani body for MathJax basmala islands. */\nexport function butexBasmalaDisplayTex(): string {\n return BASMALA_LINES.map((line) => butexDiwaniDisplayTex(line)).join(' \\\\\\\\ ');\n}\n\n/** Standalone display equation when there is no \\\\maketitle (title-less docs). */\nexport function butexBasmalaDisplayLatex(): string {\n return `\\\\[\\n${butexBasmalaDisplayTex()}\\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 ` ${butexDiwaniDisplayTex(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: Document2HijriDate = {\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 emptyDocument2Meta(): Document2Meta {\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 normalizeDocument2HijriDate(value: unknown): Document2HijriDate {\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 normalizeDocument2Meta(value: unknown): Document2Meta {\n if (typeof value !== 'object' || value === null) {\n return emptyDocument2Meta();\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: normalizeDocument2HijriDate(raw.date),\n abstract: typeof raw.abstract === 'string' ? raw.abstract : '',\n };\n}\n\nexport type Document2MetaProp = Partial<Omit<Document2Meta, 'date'>> & {\n date?: Partial<Document2HijriDate>;\n};\n\n/** Prop fills gaps; JSON wins only when the key is present on the JSON object. */\nexport function mergeDocument2Meta(fromJson: unknown, fromProp?: Document2MetaProp): Document2Meta {\n const fromPropMeta: Document2Meta = {\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 ? normalizeDocument2HijriDate({ ...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 ? normalizeDocument2HijriDate(json.date) : fromPropMeta.date,\n };\n}\n\n/** For live Document2Node meta: prop fills empty title/authors/abstract; date patch merges. */\nexport function fillDocument2MetaGaps(current: Document2Meta, fromProp?: Document2MetaProp): Document2Meta {\n if (!fromProp) {\n return cloneDocument2Meta(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 ? normalizeDocument2HijriDate({ ...current.date, ...fromProp.date })\n : { ...current.date },\n };\n}\n\nexport function document2HasMaketitle(meta: Document2Meta): boolean {\n return meta.title.trim().length > 0 || meta.authors.trim().length > 0;\n}\n\nexport function document2HasAbstract(meta: Document2Meta): boolean {\n return meta.abstract.trim().length > 0;\n}\n\nexport function document2HasTitleStack(meta: Document2Meta): boolean {\n return document2HasMaketitle(meta) || document2HasAbstract(meta);\n}\n\nexport type FormatHijriDateOptions = {\n locale?: ButexUiLocale;\n digitForm?: DigitFormId;\n};\n\nexport function formatHijriDate(date: Document2HijriDate, 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 cloneDocument2Meta(meta: Document2Meta): Document2Meta {\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 { document2Id } 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: document2Id('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 createEmptyReference2(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};\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\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 }\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 = this.name === '\\\\sqrt' ? '\\\\arabsqrt' : 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 const fullContent = `${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 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 { ChainNode, fromArabicJson, fromEnglishJson } 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\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 type {\n Document2Block,\n Document2Direction,\n Document2Node,\n FormatCiteLabelOptions,\n ImageBlock2,\n InlineField2,\n MathToken2,\n TableBlock2,\n} from './types.js';\n\nexport type Document2LabelKind = 'fig' | 'tab' | 'eq';\n\nexport type Document2LabelEntry = {\n key: string;\n kind: Document2LabelKind;\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: '';\n labelEnabled: false;\n label: '';\n} {\n return {\n centered: true,\n captionEnabled: false,\n caption: '',\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/** Collect enabled labels in document order, numbering per kind. */\nexport function collectDocument2Labels(document: Document2Node): Document2LabelEntry[] {\n const entries: Document2LabelEntry[] = [];\n const counters: Record<Document2LabelKind, number> = { fig: 0, tab: 0, eq: 0 };\n\n function pushEqFromField(tokens: MathToken2[] | InlineField2['tokens']): void {\n for (const token of tokens) {\n if (token.kind !== 'math') {\n continue;\n }\n if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {\n counters.eq += 1;\n entries.push({\n key: token.label.trim(),\n kind: 'eq',\n caption: '',\n ownerId: token.id,\n number: counters.eq,\n });\n }\n }\n }\n\n function walk(blocks: Document2Block[]): void {\n for (const block of blocks) {\n if (block.kind === 'image' && block.labelEnabled && block.label.trim().length > 0) {\n counters.fig += 1;\n entries.push({\n key: block.label.trim(),\n kind: 'fig',\n caption: block.captionEnabled ? block.caption : '',\n ownerId: block.id,\n number: counters.fig,\n });\n }\n if (block.kind === 'table') {\n if (block.labelEnabled && block.label.trim().length > 0) {\n counters.tab += 1;\n entries.push({\n key: block.label.trim(),\n kind: 'tab',\n caption: block.captionEnabled ? block.caption : '',\n ownerId: block.id,\n number: counters.tab,\n });\n }\n for (const row of block.rows) {\n for (const cell of row) {\n pushEqFromField(cell.tokens);\n }\n }\n }\n if (block.kind === 'textBlock') {\n pushEqFromField(block.field.tokens);\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n pushEqFromField(item.field.tokens);\n walk(item.blocks);\n }\n }\n }\n }\n\n walk(document.blocks);\n return entries;\n}\n\nexport function labelNumberMap(document: Document2Node): Map<string, { kind: Document2LabelKind; number: number }> {\n const map = new Map<string, { kind: Document2LabelKind; number: number }>();\n for (const entry of collectDocument2Labels(document)) {\n if (!map.has(entry.key)) {\n map.set(entry.key, { kind: entry.kind, number: entry.number });\n }\n }\n return map;\n}\n\nexport type FormatFloatCaptionTitleOptions = {\n uiLocale?: ButexUiLocale;\n documentDirection?: Document2Direction;\n digitForm?: DigitFormId;\n};\n\n/** Localized numbered float/equation title: الشكل ١ / Figure 1 / المعادلة ١. */\nexport function formatFloatCaptionTitle(\n kind: Document2LabelKind,\n number: number,\n options: FormatFloatCaptionTitleOptions = {},\n): string {\n const locale = options.uiLocale ?? 'ar';\n const kindWord =\n kind === 'fig'\n ? locale === 'ar'\n ? 'الشكل'\n : 'Figure'\n : kind === 'tab'\n ? locale === 'ar'\n ? 'الجدول'\n : 'Table'\n : locale === 'ar'\n ? 'المعادلة'\n : 'Equation';\n const digits = formatBibliographyNumber(number, {\n documentDirection: options.documentDirection ?? (locale === 'ar' ? 'rtl' : 'ltr'),\n digitForm: options.digitForm ?? (locale === 'ar' ? 'arabicIndic' : 'western'),\n });\n return `${kindWord} ${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: Document2Node,\n refCommand: 'ref' | 'eqref',\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection: Document2Direction = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const map = labelNumberMap(document);\n const parts = keys.map((key) => {\n const hit = map.get(key);\n if (!hit) {\n return '?';\n }\n return formatDigits(String(hit.number), digitForm);\n });\n const body = parts.join(documentDirection === 'rtl' ? '،' : ', ');\n if (refCommand === 'eqref') {\n return `(${body})`;\n }\n return body;\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 if (trimmed.startsWith('\\\\begin{equation}') && trimmed.endsWith('\\\\end{equation}')) {\n return trimmed.slice('\\\\begin{equation}'.length, -'\\\\end{equation}'.length).trim();\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 }\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 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 let refCommand: 'ref' | 'eqref' = 'ref';\n let prefix = refPrefix;\n if (value.startsWith(eqrefPrefix, start) && !isEscaped(value, start)) {\n refCommand = 'eqref';\n prefix = eqrefPrefix;\n } else if (value.startsWith(refPrefix, start) && !isEscaped(value, start)) {\n refCommand = 'ref';\n prefix = refPrefix;\n } else {\n return null;\n }\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 detectMathSpans2(value: string): DetectedMathSpan2[] {\n return detectInlineSpans2(value)\n .filter((span): span is DetectedInlineSpan2 & { kind: 'math' } => span.kind === 'math')\n .map(({ kind: _kind, ...span }) => span);\n}\n\n/** Left-to-right math + \\\\cite + \\\\ref/\\\\eqref spans without overlap. */\nexport function detectInlineSpans2(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 '../document/mathObject.js';\nimport { normalizeDocument2Meta, emptyDocument2Meta } from './articleMeta.js';\nimport { referenceFromJson } from './citations.js';\nimport { document2Id } from './ids.js';\nimport { detectInlineSpans2, detectMathSpans2 } from './inlineScanner.js';\nimport { parseFloatMetaFromJson } from './labels.js';\nimport type {\n BibliographyBlock2,\n Document2Block,\n Document2BlockJson,\n Document2Diagnostic,\n Document2ListItemJson,\n Document2Node,\n Document2ParseMode,\n ImageBlock2,\n ImportDocument2Options,\n InlineField2,\n InlineToken2,\n ListBlock2,\n ListItem2,\n MathObject2Json,\n RawBlock2,\n Reference2,\n Reference2Json,\n TableBlock2,\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): Document2BlockJson {\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 Document2BlockJson;\n}\n\nfunction pushDiagnostic(diagnostics: Document2Diagnostic[], options: ImportDocument2Options, 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 createInlineField2(\n value = '',\n mathObjects: MathObject2Json[] = [],\n options: ImportDocument2Options = {},\n path = '$',\n diagnostics: Document2Diagnostic[] = [],\n): InlineField2 {\n const mode: Document2ParseMode = options.mode ?? 'english';\n const spans = detectInlineSpans2(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 tokens.push({ id: document2Id('text'), kind: 'text', text: value.slice(index, span.start) });\n }\n\n if (span.kind === 'cite') {\n tokens.push({\n id: document2Id('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: document2Id('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 if (mathJson && (mathJson.math_mode !== span.opening || mathJson.closing !== span.closing)) {\n pushDiagnostic(diagnostics, options, path, 'math_objects order mismatch');\n }\n\n if (mathJson && mathJson.math_mode === span.opening && mathJson.closing === span.closing) {\n tokens.push({\n id: document2Id('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n sourceSide: mode,\n math: fromMathObjectJson(mathJson, mode),\n editable: true,\n sourceOwner: 'imported-structured',\n });\n } else {\n tokens.push({\n id: document2Id('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 });\n }\n\n index = span.end;\n }\n\n if (index < value.length || tokens.length === 0) {\n tokens.push({ id: document2Id('text'), kind: 'text', text: value.slice(index) });\n }\n\n return { id: document2Id('field'), tokens };\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(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): TextBlock2 {\n const value = requireString(json.value, `${json.command} requires string value`);\n return {\n id: document2Id('block'),\n kind: 'textBlock',\n command: json.command as TextBlock2['command'],\n field: createInlineField2(value, json.math_objects ?? [], options, `${path}.value`, diagnostics),\n ...(json.centered === true ? { centered: true } : {}),\n };\n}\n\nfunction parseListItem(json: Document2ListItemJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): 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: document2Id('item'),\n field: createInlineField2(value, json.math_objects ?? [], options, `${path}.value`, diagnostics),\n blocks: blocksJson.map((block, index) => parseBlock(asBlockJson(block), options, `${path}.blocks[${String(index)}]`, diagnostics)),\n };\n}\n\nfunction parseListBlock(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): 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: document2Id('block'),\n kind: 'list',\n command,\n closing,\n items: json.items.map((item, index) => parseListItem(item, options, `${path}.items[${String(index)}]`, diagnostics)),\n };\n}\n\nfunction parseTableBlock(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): 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 = detectMathSpans2(value).length;\n const cellMathObjects = mathObjects.slice(mathObjectIndex, mathObjectIndex + spanCount);\n mathObjectIndex += spanCount;\n return createInlineField2(value, cellMathObjects, options, `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`, diagnostics);\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 return {\n id: document2Id('block'),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: typeof json.columns === 'string' ? json.columns : '',\n rows,\n ...parseFloatMetaFromJson(json),\n };\n}\n\nfunction parseImageBlock(json: Document2BlockJson): 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 return {\n id: document2Id('block'),\n kind: 'image',\n command: '\\\\includegraphics',\n value,\n ...(assetId !== undefined ? { assetId } : {}),\n options: isRecordOfStrings(json.options) ? json.options : {},\n ...parseFloatMetaFromJson(json),\n };\n}\n\nfunction parseRawBlock(json: Document2BlockJson): RawBlock2 {\n return {\n id: document2Id('block'),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : '',\n };\n}\n\nfunction parseBibliographyBlock(): BibliographyBlock2 {\n return {\n id: document2Id('block'),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n };\n}\n\nfunction parseBlock(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): Document2Block {\n if (TEXT_COMMANDS.has(json.command)) {\n return parseTextBlock(json, options, path, diagnostics);\n }\n if (LIST_COMMANDS.has(json.command)) {\n return parseListBlock(json, options, path, diagnostics);\n }\n if (json.command === '\\\\begin{tabular}') {\n return parseTableBlock(json, options, path, diagnostics);\n }\n if (json.command === '\\\\includegraphics') {\n return parseImageBlock(json);\n }\n if (json.command === '\\\\begin{thebibliography}' || json.command === '\\\\bibliography') {\n return parseBibliographyBlock();\n }\n if (json.command === '\\\\raw') {\n return parseRawBlock(json);\n }\n return {\n id: document2Id('block'),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : json.command,\n };\n}\n\nexport function fromDocumentJson2(json: unknown, options: ImportDocument2Options = {}): Document2Node {\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: Document2Diagnostic[] = [];\n return {\n nodeType: 'DocumentObject',\n meta: normalizeDocument2Meta(json.meta),\n references: parseReferences(json.references),\n blocks: json.blocks.map((block, index) => parseBlock(asBlockJson(block), options, `$.blocks[${String(index)}]`, diagnostics)),\n diagnostics,\n };\n}\n\nexport function createEmptyDocument2(): Document2Node {\n return {\n nodeType: 'DocumentObject',\n meta: emptyDocument2Meta(),\n references: [],\n blocks: [],\n diagnostics: [],\n };\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 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 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 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: false,\n Label: '≠',\n title: 'لا يساوي',\n svg_path: null,\n },\n approx: {\n id: 'approx',\n category: 'operators1',\n Tex: '\\\\approx',\n mirror: false,\n Label: '≈',\n title: 'تقريبا يساوي',\n svg_path: null,\n },\n sim: {\n id: 'sim',\n category: 'operators1',\n Tex: '\\\\sim',\n mirror: false,\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 Label: '≤',\n title: 'أصغر من أو يساوي',\n svg_path: null,\n },\n geq: {\n id: 'geq',\n category: 'operators1',\n Tex: '\\\\geq',\n mirror: 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 Label: '≔',\n title: 'يعرف بأنه يساوي',\n svg_path: null,\n },\n eqqcolon: {\n id: 'eqqcolon',\n category: 'operators1',\n Tex: '\\\\eqqcolon',\n mirror: 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 Label: '∝',\n title: 'يتناسب مع',\n svg_path: null,\n },\n in: {\n id: 'in',\n category: 'operators2',\n Tex: '\\\\in',\n mirror: 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 Label: '∉',\n title: 'لا ينتمي إلى',\n svg_path: null,\n },\n subset: {\n id: 'subset',\n category: 'operators2',\n Tex: '\\\\subset',\n mirror: 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 Label: '⊃',\n title: 'مجموعة شاملة لـ',\n svg_path: null,\n },\n subseteq: {\n id: 'subseteq',\n category: 'operators2',\n Tex: '\\\\subseteq',\n mirror: 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 Label: '⊇',\n title: 'مجموعة شاملة أو تساوي',\n svg_path: null,\n },\n cap: {\n id: 'cap',\n category: 'operators2',\n Tex: '\\\\cap',\n mirror: false,\n Label: '∩',\n title: 'تقاطع',\n svg_path: null,\n },\n cup: {\n id: 'cup',\n category: 'operators2',\n Tex: '\\\\cup',\n mirror: false,\n Label: '∪',\n title: 'اتحاد',\n svg_path: null,\n },\n emptyset: {\n id: 'emptyset',\n category: 'operators2',\n Tex: '\\\\emptyset',\n mirror: false,\n Label: '∅',\n title: 'المجموعة الخالية',\n svg_path: null,\n },\n nsubseteq: {\n id: 'nsubseteq',\n category: 'operators2',\n Tex: '\\\\nsubseteq',\n mirror: 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 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 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 Label: '⇒',\n title: 'يستلزم',\n svg_path: null,\n },\n impliedby: {\n id: 'impliedby',\n category: 'operators3',\n Tex: '\\\\impliedby',\n mirror: 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 Label: '⟹',\n title: 'سهم مزدوج طويل إلى اليمين',\n svg_path: null,\n },\n Longleftarrow: {\n id: 'Longleftarrow',\n category: 'operators3',\n Tex: '\\\\Longleftarrow',\n mirror: 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 Label: '→',\n title: 'يؤول إلى',\n svg_path: null,\n },\n rightleftharpoons: {\n id: 'rightleftharpoons',\n category: 'operators3',\n Tex: '\\\\rightleftharpoons',\n mirror: 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 Label: '←',\n title: 'سهم إلى اليسار',\n svg_path: null,\n },\n rightarrow: {\n id: 'rightarrow',\n category: 'operators3',\n Tex: '\\\\rightarrow',\n mirror: 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 Label: '⇐',\n title: 'سهم مزدوج إلى اليسار',\n svg_path: null,\n },\n rightarrowDouble: {\n id: 'rightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Rightarrow',\n mirror: 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 Label: '↼',\n title: 'سهم خطافي علوي إلى اليسار',\n svg_path: null,\n },\n rightharpoonup: {\n id: 'rightharpoonup',\n category: 'operators3',\n Tex: '\\\\rightharpoonup',\n mirror: 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 Label: '↽',\n title: 'سهم خطافي سفلي إلى اليسار',\n svg_path: null,\n },\n rightharpoondown: {\n id: 'rightharpoondown',\n category: 'operators3',\n Tex: '\\\\rightharpoondown',\n mirror: 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 Label: '∫',\n title: 'تكامل',\n svg_path: null,\n },\n iint: {\n id: 'iint',\n category: 'integrals',\n Tex: '\\\\iint',\n mirror: 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 Label: '∭',\n title: 'تكامل ثلاثي',\n svg_path: null,\n },\n iiiint: {\n id: 'iiiint',\n category: 'integrals',\n Tex: '\\\\iiiint',\n mirror: 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 Label: '∮',\n title: 'تكامل مغلق',\n svg_path: null,\n },\n oiint: {\n id: 'oiint',\n category: 'integrals',\n Tex: '\\\\oiint',\n mirror: 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 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 };\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);\n\nfunction matchingMirroredOperator(tex: string, index: number): string | null {\n for (const operatorTex of MIRRORED_OPERATOR_TEX) {\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): string {\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 result += tex.slice(index, end + 1);\n index = end + 1;\n continue;\n }\n }\n\n const operatorTex = matchingMirroredOperator(tex, index);\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, EditorNode, EditorSession, EditorSide, EnvColumnAlignment, GridEnvName, MatrixEnvStyle } from './types.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 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 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 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 = 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 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.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 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 { 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\nexport function isDivideOperatorExpr(expr: string): boolean {\n return expr === DIVIDE_OPERATOR_EN || expr === DIVIDE_OPERATOR_AR;\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 { DigitFormId, EditorChain, EditorNode, EditorSession, EnvColumnAlignment } from './types.js';\nimport { atomicCommandSpec } from './atomicCommands.js';\nimport { atomicOperatorCommandSpec } from './atomicCommandsOperators.js';\nimport { isDivideOperatorExpr, renderDivideOperatorLatex } from './divideOperator.js';\nimport { formatDigits } from './digits.js';\n\ntype RenderOptions = {\n digitForm?: DigitFormId;\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 return `\\\\begin{${envName}}${rows.join(' \\\\\\\\\\n')}\\\\end{${envName}}`;\n}\n\nfunction escapeText(s: string): string {\n return s.replace(/\\\\/g, '\\\\textbackslash{}').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 if (font === 'takween') {\n return `\\\\butextakween{${escapeText(expr)}}`;\n }\n if (font === 'diwani') {\n return `\\\\butexdiwani{${escapeText(expr)}}`;\n }\n if (font === 'diwaniOutline') {\n return `\\\\butexdiwanioutline{${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 === '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 === '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 = atomicOperatorCommandSpec(node.expr)?.Tex ?? node.expr;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'char') {\n return `${renderCharContent(node, options)}${latinScripts(node, options)}`;\n }\n if (node.kind === 'operator' && isDivideOperatorExpr(node.expr)) {\n return `${renderDivideOperatorLatex('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 === '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 = `\\\\arabsqrt${optionalRootIndexArabic(node, options)}{${renderChainArabic(node.radicand, 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 === 'char') {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const content = renderCharContent(node, options);\n return arabicScripts(node, (node.characterFont ?? 'default') === 'default'\n ? `\\\\text{${escapeText(expr)}}`\n : content, options);\n }\n if (node.kind === 'operator' && isDivideOperatorExpr(node.expr)) {\n return arabicScripts(node, renderDivideOperatorLatex('arabic'), options);\n }\n return arabicScripts(node, formatDigits(node.expr, selectedDigitForm(options)), options);\n}\n\nexport function renderChainEnglish(chain: EditorChain, options?: RenderOptions): string {\n return chain.nodes.map((node) => renderNodeEnglish(node, options)).join(' ');\n}\n\nexport function renderChainArabic(chain: EditorChain, options?: RenderOptions): string {\n return chain.nodes\n .slice()\n .reverse()\n .map((node) => renderNodeArabic(node, options))\n .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","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\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', '')\n .replace('\\\\right', '')\n .replace('\\\\{', '{')\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 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, 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__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}`;\n\n const style = node.envName ?? node.matrixStyle ?? 'matrix';\n const glyphs = 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 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_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_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_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`.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 { DELIMITER_CSS } from './display/delimiter.js';\nimport { FRAC_CSS } from './display/frac.js';\nimport { SQRT_CSS } from './display/sqrt.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 {\n BUTEX_DIWANI_FONT_STACK,\n BUTEX_DIWANI_OUTLINE_FONT_STACK,\n BUTEX_FONT_FACE_CSS,\n BUTEX_TAKWEEN_FONT_STACK,\n} from '../diwani-font.js';\n\nexport const BUTEX_EDITOR_CSS = `\n${BUTEX_FONT_FACE_CSS}\n\n.surface {\n border: 1px solid var(--butex-border, #e2e8f0);\n border-radius: 12px;\n min-height: 100px;\n padding: 8px 10px;\n background: var(--butex-surface-bg, linear-gradient(180deg, #ffffff 0%, #fafbfc 100%));\n color: var(--butex-surface-fg, #0f172a);\n outline: none;\n cursor: text;\n transition: box-shadow 0.15s ease, border-color 0.15s ease;\n}\n\n.surface: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.node-value--takween {\n font-family: ${BUTEX_TAKWEEN_FONT_STACK};\n}\n\n.node-value--diwani {\n font-family: ${BUTEX_DIWANI_FONT_STACK};\n}\n\n.node-value--diwani-outline {\n font-family: ${BUTEX_DIWANI_OUTLINE_FONT_STACK};\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.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${FRAC_CSS}\n\n${SQRT_CSS}\n\n${MATRIX_ENV_CSS}\n\n${ATOMIC_COMMAND_CSS}\n\n${ATOMIC_OPERATOR_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';\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 { prefix: '\\\\butexdiwanioutline', font: 'diwaniOutline' },\n { prefix: '\\\\diwanioutlineshaded', font: 'diwaniOutline' },\n { prefix: '\\\\butexdiwani', font: 'diwani' },\n { prefix: '\\\\butextakween', font: 'takween' },\n { prefix: '\\\\diwani', font: 'diwani' },\n { prefix: '\\\\takween', font: 'takween' },\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 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 {\n buildInitialSyncMap,\n cloneEditorSession,\n createDelimiterNode,\n createEditorChain,\n createEditorNode,\n createEditorSession,\n createFracNode,\n createGridEnvNode,\n createSqrtNode,\n renderArabicLatexFromSession,\n} from '../editor/index.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 type { MathNode } from './types.js';\n\ntype CommandFontPolicy = CharacterFontId | 'infer';\n\nconst COMMAND_FONT_MAP: Record<string, CommandFontPolicy> = {\n '\\\\text': 'infer',\n '\\\\butextakween': 'takween',\n '\\\\takween': 'takween',\n '\\\\butexdiwani': 'diwani',\n '\\\\diwani': 'diwani',\n '\\\\butexdiwanioutline': 'diwaniOutline',\n '\\\\diwanioutlineshaded': 'diwaniOutline',\n};\n\nconst CHAR_FONT_EXPORT_TEX: Record<Exclude<CharacterFontId, 'default'>, string> = {\n takween: '\\\\butextakween',\n diwani: '\\\\butexdiwani',\n diwaniOutline: '\\\\butexdiwanioutline',\n};\n\nfunction charEditorNodeToAstNode(node: EditorNode): BaseAstNode {\n const font = node.characterFont ?? 'default';\n const charNode = new CharNode(node.expr);\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 for (const spec of Object.values(ATOMIC_OPERATOR_COMMANDS)) {\n if (spec.Tex === tex) {\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: { superscript: ChainNode | null; subscript: ChainNode | null }, editorNode: EditorNode): UnsupportedAdapterResult | null {\n if (astNode.superscript) {\n const sup = chainToEditorChain(astNode.superscript);\n if (!sup.editable) {\n return sup;\n }\n editorNode.superscript = sup.chain;\n }\n if (astNode.subscript) {\n const sub = chainToEditorChain(astNode.subscript);\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';\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 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 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 ((node.name === '\\\\sqrt' || node.name === '\\\\arabsqrt') && node.mandatoryArgs.length >= 1) {\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 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 const scripts = attachScripts(node, atomicOperator);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomicOperator };\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\nfunction chainToEditorChain(chain: ChainNode): ChainAdapterResult {\n const nodes: EditorNode[] = [];\n for (const astNode of 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 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 === '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 === 'atomicCommand') {\n const tex = atomicCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(tex);\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(tex);\n } else if (node.kind === 'env') {\n return editorEnvToAstNode(node);\n } else {\n return { ok: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.kind}` };\n }\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 return { ok: true, chain: new ChainNode(nodes) };\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\n/** Delimited Arabic TeX for document text/preview — matches `<ButexEditor />` arabic output. */\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 '../document/mathEditorAdapter.js';\nimport type { MathNode } from '../document/types.js';\nimport {\n buildInitialSyncMap,\n createEditorChain,\n createEditorSession,\n renderArabicLatexFromSession,\n renderEnglishLatexFromSession,\n type EditorSide,\n type EditorSession,\n} from '../editor/index.js';\nimport type { MathToken2 } from './types.js';\n\nexport type Document2MathBridgeResult =\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'): Document2MathBridgeResult {\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): Document2MathBridgeResult {\n return mathTokenToEditorSession(math, 'arabic');\n}\n\nexport function mathSourceFromSession(\n session: EditorSession,\n side: EditorSide,\n opening = '$',\n closing = '$',\n): string {\n const inner = side === 'english'\n ? renderEnglishLatexFromSession(session)\n : 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): string {\n if (!token.math || token.sourceOwner === 'raw') {\n return token.source;\n }\n if (token.sourceSide === side) {\n return token.source;\n }\n const result = mathTokenToEditorSession(token.math, side);\n if (!result.editable) {\n return token.source;\n }\n return mathSourceFromSession(result.session, side, token.opening, token.closing);\n}\n","import { document2Id } from './ids.js';\nimport { cloneDocument2Meta, emptyDocument2Meta, normalizeDocument2HijriDate } from './articleMeta.js';\nimport { createEmptyReference2 } from './citations.js';\nimport { createInlineField2 } from './importJson.js';\nimport { applyFloatMetaPatch, defaultFloatMeta, type FloatMetaPatch } from './labels.js';\nimport { mathNodeFromSession, mathSourceFromSession } from './mathBridge.js';\nimport type {\n BibliographyBlock2,\n CiteToken2,\n Document2Block,\n Document2Node,\n ImageBlock2,\n InlineField2,\n InlineToken2,\n ListBlock2,\n MathToken2,\n Reference2,\n Reference2Json,\n RefToken2,\n TableBlock2,\n TextToken2,\n} from './types.js';\nimport type { Document2MetaProp } from './articleMeta.js';\nimport type { EditorSession, EditorSide } from '../editor/index.js';\n\nfunction cloneToken(token: InlineToken2): InlineToken2 {\n return token.kind === 'text' ? { ...token } : { ...token };\n}\n\nfunction cloneField(field: InlineField2): InlineField2 {\n return { id: field.id, tokens: field.tokens.map(cloneToken) };\n}\n\nfunction cloneBlock(block: Document2Block): Document2Block {\n if (block.kind === 'textBlock') {\n return { ...block, field: cloneField(block.field) };\n }\n if (block.kind === 'list') {\n return {\n ...block,\n items: block.items.map((item) => ({\n ...item,\n field: cloneField(item.field),\n blocks: item.blocks.map(cloneBlock),\n })),\n };\n }\n if (block.kind === 'table') {\n return { ...block, rows: block.rows.map((row) => row.map(cloneField)) };\n }\n if (block.kind === 'image') {\n return { ...block, options: { ...block.options } };\n }\n return { ...block };\n}\n\nfunction cloneDocument(document: Document2Node): Document2Node {\n return {\n nodeType: 'DocumentObject',\n meta: cloneDocument2Meta(document.meta ?? emptyDocument2Meta()),\n references: document.references.map((reference) => ({ ...reference })),\n blocks: document.blocks.map(cloneBlock),\n diagnostics: document.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n}\n\nfunction visitFields(blocks: Document2Block[], visitor: (field: InlineField2) => boolean): boolean {\n for (const block of blocks) {\n if (block.kind === 'textBlock') {\n if (visitor(block.field)) {\n return true;\n }\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n if (visitor(item.field) || visitFields(item.blocks, visitor)) {\n return true;\n }\n }\n } else if (block.kind === 'table') {\n for (const row of block.rows) {\n for (const cell of row) {\n if (visitor(cell)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n}\n\nexport function findFirstInlineField(document: Document2Node): InlineField2 | null {\n let found: InlineField2 | null = null;\n visitFields(document.blocks, (field) => {\n found = field;\n return true;\n });\n return found;\n}\n\nexport function updateTextToken(document: Document2Node, fieldId: string, tokenId: string, text: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n const token = field.tokens.find((entry): entry is TextToken2 => entry.id === tokenId && entry.kind === 'text');\n if (!token) {\n return true;\n }\n token.text = text;\n return true;\n });\n return next;\n}\n\nfunction mathTokenFromSession(session: EditorSession, opening = '$', closing = '$', side: EditorSide = 'arabic'): MathToken2 {\n return {\n id: document2Id('math'),\n kind: 'math',\n display: opening === '$$' || opening === '\\\\[' || opening.startsWith('\\\\begin{'),\n opening,\n closing,\n source: mathSourceFromSession(session, side, opening, closing),\n sourceSide: side,\n math: mathNodeFromSession(session, opening, closing),\n editable: true,\n sourceOwner: 'editor',\n };\n}\n\nfunction splitTextForInsertion(token: TextToken2): InlineToken2[] | null {\n const gap = token.text.indexOf(' ');\n if (gap < 0) {\n return null;\n }\n return [\n { id: token.id, kind: 'text', text: token.text.slice(0, gap + 1) },\n { id: document2Id('text'), kind: 'text', text: token.text.slice(gap + 1) },\n ];\n}\n\nexport function cloneDocument2Node(document: Document2Node): Document2Node {\n return cloneDocument(document);\n}\n\nfunction insertBlockAfter(blocks: Document2Block[], afterBlockId: string | null | undefined, block: Document2Block): void {\n if (!afterBlockId) {\n blocks.push(block);\n return;\n }\n const index = blocks.findIndex((entry) => entry.id === afterBlockId);\n if (index < 0) {\n blocks.push(block);\n return;\n }\n blocks.splice(index + 1, 0, block);\n}\n\nexport function insertDocument2BlockAfter(\n document: Document2Node,\n afterBlockId: string | null | undefined,\n block: Document2Block,\n): Document2Node {\n const next = cloneDocument(document);\n insertBlockAfter(next.blocks, afterBlockId, block);\n return next;\n}\n\nexport function moveDocument2BlockById(document: Document2Node, blockId: string, direction: -1 | 1): Document2Node {\n const next = cloneDocument(document);\n const index = next.blocks.findIndex((block) => block.id === blockId);\n const targetIndex = index + direction;\n if (index < 0 || targetIndex < 0 || targetIndex >= next.blocks.length) {\n return document;\n }\n const [block] = next.blocks.splice(index, 1);\n if (!block) {\n return document;\n }\n next.blocks.splice(targetIndex, 0, block);\n return next;\n}\n\nexport function moveDocument2BlockRange(\n document: Document2Node,\n from: number,\n to: number,\n direction: -1 | 1,\n): Document2Node {\n const count = document.blocks.length;\n if (from < 0 || to < 0 || from >= count || to >= count || from > to) {\n return document;\n }\n const insertAt = from + direction;\n if (insertAt < 0 || to + direction >= count) {\n return document;\n }\n const next = cloneDocument(document);\n const slice = next.blocks.splice(from, to - from + 1);\n next.blocks.splice(insertAt, 0, ...slice);\n return next;\n}\n\nexport function removeDocument2BlockRange(document: Document2Node, from: number, to: number): Document2Node {\n const count = document.blocks.length;\n if (from < 0 || to < 0 || from >= count || to >= count || from > to) {\n return document;\n }\n const next = cloneDocument(document);\n next.blocks = [...next.blocks.slice(0, from), ...next.blocks.slice(to + 1)];\n return next;\n}\n\nfunction normalizeFieldTokens(tokens: InlineToken2[]): InlineToken2[] {\n if (tokens.length === 0) {\n return [{ id: document2Id('text'), kind: 'text', text: '' }];\n }\n return tokens;\n}\n\nfunction stitchTextAroundRemovedToken(tokens: InlineToken2[], index: number): InlineToken2[] {\n const before = tokens[index - 1];\n const after = tokens[index + 1];\n if (before?.kind === 'text' && after?.kind === 'text') {\n return [\n ...tokens.slice(0, index - 1),\n { ...before, text: before.text + after.text },\n ...tokens.slice(index + 2),\n ];\n }\n return [...tokens.slice(0, index), ...tokens.slice(index + 1)];\n}\n\nexport function removeMathTokenById(document: Document2Node, tokenId: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'math');\n if (index < 0) {\n return false;\n }\n field.tokens = normalizeFieldTokens(stitchTextAroundRemovedToken(field.tokens, index));\n return true;\n });\n return next;\n}\n\nfunction splitTextTokenAt(token: TextToken2, offset: number): [TextToken2, TextToken2] {\n const safeOffset = Math.max(0, Math.min(offset, token.text.length));\n return [\n { id: token.id, kind: 'text', text: token.text.slice(0, safeOffset) },\n { id: document2Id('text'), kind: 'text', text: token.text.slice(safeOffset) },\n ];\n}\n\nexport function insertMathTokenAtCaret(\n document: Document2Node,\n fieldId: string,\n textTokenId: string | null,\n caretOffset: number,\n session: EditorSession,\n opening = '$',\n closing = '$',\n side: EditorSide = 'arabic',\n): Document2Node {\n const next = cloneDocument(document);\n const mathToken = mathTokenFromSession(session, opening, closing, side);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n const textIndex = textTokenId\n ? field.tokens.findIndex((token) => token.id === textTokenId && token.kind === 'text')\n : field.tokens.findIndex((token) => token.kind === 'text');\n\n if (textIndex < 0) {\n field.tokens.push(mathToken);\n field.tokens.push({ id: document2Id('text'), kind: 'text', text: '' });\n return true;\n }\n\n const current = field.tokens[textIndex] as TextToken2;\n const [before, after] = splitTextTokenAt(current, caretOffset);\n const parts: InlineToken2[] = [...field.tokens.slice(0, textIndex)];\n if (before.text.length > 0) {\n parts.push(before);\n }\n parts.push(mathToken);\n parts.push(after);\n parts.push(...field.tokens.slice(textIndex + 1));\n field.tokens = normalizeFieldTokens(parts);\n return true;\n });\n return next;\n}\n\nexport function insertMathToken(\n document: Document2Node,\n fieldId: string,\n insertIndex: number,\n session: EditorSession,\n opening = '$',\n closing = '$',\n side: EditorSide = 'arabic',\n): Document2Node {\n const next = cloneDocument(document);\n const mathToken = mathTokenFromSession(session, opening, closing, side);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n if (field.tokens.length === 1 && field.tokens[0]?.kind === 'text') {\n const split = splitTextForInsertion(field.tokens[0]);\n if (split) {\n field.tokens = [split[0]!, mathToken, split[1]!];\n return true;\n }\n }\n\n const safeIndex = Math.max(0, Math.min(insertIndex, field.tokens.length));\n field.tokens.splice(safeIndex, 0, mathToken);\n return true;\n });\n return next;\n}\n\nexport function replaceMathTokenFromSession(\n document: Document2Node,\n tokenId: string,\n session: EditorSession,\n opening?: string,\n closing?: string,\n side: EditorSide = 'arabic',\n): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'math');\n if (index < 0) {\n return false;\n }\n const current = field.tokens[index] as MathToken2;\n const open = opening ?? current.opening;\n const close = closing ?? current.closing;\n const replaced = mathTokenFromSession(session, open, close, side);\n replaced.id = current.id;\n if (current.labelEnabled !== undefined) {\n replaced.labelEnabled = current.labelEnabled;\n }\n if (current.label !== undefined) {\n replaced.label = current.label;\n }\n field.tokens[index] = replaced;\n return true;\n });\n return next;\n}\n\nexport function addDocument2TextBlock(\n document: Document2Node,\n command: '\\\\section' | '\\\\subsection' | '\\\\subsubsection' | '\\\\paragraph' = '\\\\paragraph',\n afterBlockId?: string | null,\n): Document2Node {\n const block = {\n id: document2Id('block'),\n kind: 'textBlock' as const,\n command,\n field: createInlineField2(''),\n ...(command === '\\\\paragraph' ? { centered: false } : {}),\n };\n return insertDocument2BlockAfter(document, afterBlockId, block);\n}\n\nexport function updateDocument2TextBlockCentered(\n document: Document2Node,\n blockId: string,\n centered: boolean,\n): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'textBlock' && block.command === '\\\\paragraph') {\n block.centered = centered;\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function removeDocument2BlockById(document: Document2Node, blockId: string): Document2Node {\n const next = cloneDocument(document);\n next.blocks = next.blocks.filter((block) => block.id !== blockId);\n return next;\n}\n\nfunction newListBlock(ordered: boolean): ListBlock2 {\n const command: ListBlock2['command'] = ordered ? '\\\\begin{enumerate}' : '\\\\begin{itemize}';\n const closing = ordered ? '\\\\end{enumerate}' : '\\\\end{itemize}';\n return {\n id: document2Id('block'),\n kind: 'list',\n command,\n closing,\n items: [{ id: document2Id('item'), field: createInlineField2(''), blocks: [] }],\n };\n}\n\nexport function addDocument2ListBlock(document: Document2Node, ordered: boolean, afterBlockId?: string | null): Document2Node {\n return insertDocument2BlockAfter(document, afterBlockId, newListBlock(ordered));\n}\n\nexport function addDocument2TableBlock(\n document: Document2Node,\n columns = 'lll',\n rowCount = 3,\n colCount = 3,\n afterBlockId?: string | null,\n): Document2Node {\n const rows = Math.max(1, rowCount);\n const cols = Math.max(1, colCount);\n const tableRows: InlineField2[][] = [];\n for (let r = 0; r < rows; r += 1) {\n const row: InlineField2[] = [];\n for (let c = 0; c < cols; c += 1) {\n row.push(createInlineField2(''));\n }\n tableRows.push(row);\n }\n const block: TableBlock2 = {\n id: document2Id('block'),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: columns || 'l'.repeat(cols),\n rows: tableRows,\n ...defaultFloatMeta(),\n };\n return insertDocument2BlockAfter(document, afterBlockId, block);\n}\n\nexport function addDocument2ImageBlock(document: Document2Node, src = '', afterBlockId?: string | null): Document2Node {\n const block: ImageBlock2 = {\n id: document2Id('block'),\n kind: 'image',\n command: '\\\\includegraphics',\n value: src,\n options: { width: '0.8\\\\columnwidth' },\n ...defaultFloatMeta(),\n };\n return insertDocument2BlockAfter(document, afterBlockId, block);\n}\n\nexport function updateDocument2ImageValue(document: Document2Node, blockId: string, value: string): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'image') {\n block.value = value;\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function updateDocument2ImageMeta(document: Document2Node, blockId: string, patch: FloatMetaPatch): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'image') {\n applyFloatMetaPatch(block, patch);\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function updateDocument2TableMeta(document: Document2Node, blockId: string, patch: FloatMetaPatch): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'table') {\n applyFloatMetaPatch(block, patch);\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function updateMathTokenLabel(\n document: Document2Node,\n tokenId: string,\n patch: { labelEnabled?: boolean; label?: string },\n): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const token = field.tokens.find((entry): entry is MathToken2 => entry.id === tokenId && entry.kind === 'math');\n if (!token) {\n return false;\n }\n if (typeof patch.labelEnabled === 'boolean') {\n token.labelEnabled = patch.labelEnabled;\n }\n if (typeof patch.label === 'string') {\n token.label = patch.label;\n }\n return true;\n });\n return next;\n}\n\nfunction refTokenFromKeys(keys: string[], refCommand: 'ref' | 'eqref'): RefToken2 {\n return { id: document2Id('ref'), kind: 'ref', keys: [...keys], refCommand };\n}\n\nexport function insertRefTokenAtCaret(\n document: Document2Node,\n fieldId: string,\n textTokenId: string | null,\n caretOffset: number,\n keys: string[],\n refCommand: 'ref' | 'eqref' = 'ref',\n): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n const refToken = refTokenFromKeys(keys, refCommand);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n const textIndex = textTokenId\n ? field.tokens.findIndex((token) => token.id === textTokenId && token.kind === 'text')\n : field.tokens.findIndex((token) => token.kind === 'text');\n\n if (textIndex < 0) {\n field.tokens.push(refToken);\n field.tokens.push({ id: document2Id('text'), kind: 'text', text: '' });\n return true;\n }\n\n const current = field.tokens[textIndex] as TextToken2;\n const [before, after] = splitTextTokenAt(current, caretOffset);\n const parts: InlineToken2[] = [...field.tokens.slice(0, textIndex)];\n if (before.text.length > 0) {\n parts.push(before);\n }\n parts.push(refToken);\n parts.push(after);\n parts.push(...field.tokens.slice(textIndex + 1));\n field.tokens = normalizeFieldTokens(parts);\n return true;\n });\n return next;\n}\n\nexport function updateRefTokenKeys(\n document: Document2Node,\n tokenId: string,\n keys: string[],\n refCommand?: 'ref' | 'eqref',\n): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const token = field.tokens.find((entry): entry is RefToken2 => entry.id === tokenId && entry.kind === 'ref');\n if (!token) {\n return false;\n }\n token.keys = [...keys];\n if (refCommand) {\n token.refCommand = refCommand;\n }\n return true;\n });\n return next;\n}\n\nexport function removeRefTokenById(document: Document2Node, tokenId: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'ref');\n if (index < 0) {\n return false;\n }\n field.tokens = normalizeFieldTokens(stitchTextAroundRemovedToken(field.tokens, index));\n return true;\n });\n return next;\n}\n\nfunction mutateListBlockById(blocks: Document2Block[], listBlockId: string, mutator: (list: ListBlock2) => void): boolean {\n for (const block of blocks) {\n if (block.id === listBlockId && block.kind === 'list') {\n mutator(block);\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (mutateListBlockById(item.blocks, listBlockId, mutator)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nexport function addDocument2ListItem(document: Document2Node, listBlockId: string): Document2Node {\n const next = cloneDocument(document);\n mutateListBlockById(next.blocks, listBlockId, (list) => {\n list.items.push({ id: document2Id('item'), field: createInlineField2(''), blocks: [] });\n });\n return next;\n}\n\nexport function removeDocument2ListItem(document: Document2Node, listBlockId: string, itemId: string): Document2Node {\n const next = cloneDocument(document);\n mutateListBlockById(next.blocks, listBlockId, (list) => {\n if (list.items.length < 2) {\n return;\n }\n const index = list.items.findIndex((item) => item.id === itemId);\n if (index >= 0) {\n list.items.splice(index, 1);\n }\n });\n return next;\n}\n\nfunction citeTokenFromKeys(keys: string[]): CiteToken2 {\n return { id: document2Id('cite'), kind: 'cite', keys: [...keys] };\n}\n\nexport function insertCiteTokenAtCaret(\n document: Document2Node,\n fieldId: string,\n textTokenId: string | null,\n caretOffset: number,\n keys: string[],\n): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n const citeToken = citeTokenFromKeys(keys);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n const textIndex = textTokenId\n ? field.tokens.findIndex((token) => token.id === textTokenId && token.kind === 'text')\n : field.tokens.findIndex((token) => token.kind === 'text');\n\n if (textIndex < 0) {\n field.tokens.push(citeToken);\n field.tokens.push({ id: document2Id('text'), kind: 'text', text: '' });\n return true;\n }\n\n const current = field.tokens[textIndex] as TextToken2;\n const [before, after] = splitTextTokenAt(current, caretOffset);\n const parts: InlineToken2[] = [...field.tokens.slice(0, textIndex)];\n if (before.text.length > 0) {\n parts.push(before);\n }\n parts.push(citeToken);\n parts.push(after);\n parts.push(...field.tokens.slice(textIndex + 1));\n field.tokens = normalizeFieldTokens(parts);\n return true;\n });\n return next;\n}\n\nexport function updateCiteTokenKeys(document: Document2Node, tokenId: string, keys: string[]): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const token = field.tokens.find((entry): entry is CiteToken2 => entry.id === tokenId && entry.kind === 'cite');\n if (!token) {\n return false;\n }\n token.keys = [...keys];\n return true;\n });\n return next;\n}\n\nexport function removeCiteTokenById(document: Document2Node, tokenId: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'cite');\n if (index < 0) {\n return false;\n }\n field.tokens = normalizeFieldTokens(stitchTextAroundRemovedToken(field.tokens, index));\n return true;\n });\n return next;\n}\n\nexport function ensureDocument2BibliographyBlock(document: Document2Node, afterBlockId?: string | null): Document2Node {\n if (document.blocks.some((block) => block.kind === 'bibliography')) {\n return document;\n }\n const block: BibliographyBlock2 = {\n id: document2Id('block'),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n };\n return insertDocument2BlockAfter(document, afterBlockId ?? null, block);\n}\n\nexport function addDocument2Reference(document: Document2Node, partial: Partial<Reference2Json> = {}): Document2Node {\n const next = cloneDocument(document);\n next.references.push(createEmptyReference2(partial));\n return next;\n}\n\nexport function updateDocument2Reference(document: Document2Node, referenceId: string, patch: Partial<Reference2Json>): Document2Node {\n const next = cloneDocument(document);\n const reference = next.references.find((entry) => entry.id === referenceId);\n if (!reference) {\n return document;\n }\n if (typeof patch.key === 'string' && patch.key.trim().length > 0) {\n reference.key = patch.key.trim();\n }\n if (typeof patch.authors === 'string') {\n reference.authors = patch.authors;\n }\n if (typeof patch.title === 'string') {\n reference.title = patch.title;\n }\n if (typeof patch.year === 'string') {\n reference.year = patch.year;\n }\n if (typeof patch.url === 'string') {\n reference.url = patch.url;\n }\n if (typeof patch.venue === 'string') {\n reference.venue = patch.venue;\n }\n if (patch.field_separator === ',' || patch.field_separator === '،') {\n reference.fieldSeparator = patch.field_separator;\n }\n return next;\n}\n\nexport function removeDocument2Reference(document: Document2Node, referenceId: string): Document2Node {\n const next = cloneDocument(document);\n next.references = next.references.filter((reference) => reference.id !== referenceId);\n return next;\n}\n\nexport function moveDocument2Reference(document: Document2Node, referenceId: string, direction: -1 | 1): Document2Node {\n const next = cloneDocument(document);\n const index = next.references.findIndex((reference) => reference.id === referenceId);\n const targetIndex = index + direction;\n if (index < 0 || targetIndex < 0 || targetIndex >= next.references.length) {\n return document;\n }\n const [reference] = next.references.splice(index, 1);\n if (!reference) {\n return document;\n }\n next.references.splice(targetIndex, 0, reference);\n return next;\n}\n\nexport function setDocument2References(document: Document2Node, references: Reference2[]): Document2Node {\n const next = cloneDocument(document);\n next.references = references.map((reference) => ({ ...reference }));\n return next;\n}\n\nexport function updateDocument2Meta(document: Document2Node, patch: Document2MetaProp): Document2Node {\n const next = cloneDocument(document);\n const current = next.meta ?? emptyDocument2Meta();\n next.meta = {\n title: typeof patch.title === 'string' ? patch.title : current.title,\n authors: typeof patch.authors === 'string' ? patch.authors : current.authors,\n abstract: typeof patch.abstract === 'string' ? patch.abstract : current.abstract,\n date: patch.date\n ? normalizeDocument2HijriDate({ ...current.date, ...patch.date })\n : { ...current.date },\n };\n return next;\n}\n","import type { Document2LabelEntry } from './labels.js';\nimport type { Reference2 } from './types.js';\n\nexport type Document2KeyError = 'empty' | 'invalid' | 'duplicate';\n\nconst DOCUMENT2_KEY_PATTERN = /^[\\p{L}\\p{M}0-9:._-]+$/u;\n\n/** NFC-normalize and trim a document key (label or bibliography). */\nexport function normalizeDocument2Key(key: string): string {\n return key.normalize('NFC').trim();\n}\n\n/** True when key matches Unicode letters/marks, ASCII digits, and :._- with no spaces. */\nexport function isValidDocument2Key(key: string): boolean {\n const normalized = normalizeDocument2Key(key);\n return normalized.length > 0 && DOCUMENT2_KEY_PATTERN.test(normalized);\n}\n\nexport type Document2KeyNamespace = {\n references?: Array<Pick<Reference2, 'id' | 'key'>>;\n labels?: Array<Pick<Document2LabelEntry, '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 isDuplicateDocument2Key(key: string, namespace: Document2KeyNamespace): boolean {\n const normalized = normalizeDocument2Key(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 (normalizeDocument2Key(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 (normalizeDocument2Key(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 document2KeyError(key: string, namespace: Document2KeyNamespace = {}): Document2KeyError | null {\n const normalized = normalizeDocument2Key(key);\n if (normalized.length === 0) {\n return 'empty';\n }\n if (!DOCUMENT2_KEY_PATTERN.test(normalized)) {\n return 'invalid';\n }\n if (isDuplicateDocument2Key(normalized, namespace)) {\n return 'duplicate';\n }\n return null;\n}\n","/** Arabic XeLaTeX preamble fragments for full-document export. */\n\nexport type ArabicDigitsMapping = 'arabicdigits' | 'digits';\n\nexport type ArabicXeLatexPreambleOptions = {\n digitsMapping?: ArabicDigitsMapping;\n /** When true, add the article class twocolumn option. Default false. */\n twocolumn?: boolean;\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} % For bidirectional text handling\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\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 return `\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Toggle between eastern and western digits by changing the Mapping in the below fonts (inside math font as well) between \"arabicdigits\" and \"digits\"\n\\\\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia\n\\\\setmainfont[Script=Arabic , Mapping=${digitsMapping}]{Amiri}\n\\\\newfontfamily\\\\diwani[Script=Arabic,Mapping=${digitsMapping}]{Diwani Letter}\n\\\\newfontfamily\\\\diwanioutlineshaded[Script=Arabic,Mapping=${digitsMapping}]{Diwani Outline Shaded}\n\\\\newfontfamily\\\\takween[Script=Arabic,Mapping=${digitsMapping}]{Takween}\n\\\\newfontfamily\\\\boldarabic[Script=Arabic,Mapping=${digitsMapping}]{Amiri Bold}\n\\\\newfontfamily\\\\italicarabic[Script=Arabic,Mapping=${digitsMapping}]{Amiri Italic}\n\n% Explicitly set math font to XITS Math\n% Remove \"Script=Arabic\" to cancel reflected symbols and other RTL symbols\n\\\\setmathfont[Script=Arabic , Mapping=${digitsMapping}]{XITS Math} % Ensure XITS Math is correctly installed and available\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n`;\n}\n\nexport function arabicXeLatexPreambleCmd(): string {\n return String.raw`\n% Run with XeLaTeX compiler\n\\newcommand{\\butextakween}[1]{\\text{\\takween{#1}}}\n\\newcommand{\\butexdiwani}[1]{\\text{\\diwani{#1}}}\n\\newcommand{\\butexdiwanioutline}[1]{\\text{\\diwanioutlineshaded{#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\\newcommand{\\arabsqrt}[2]{\\reflectbox{\\(\\sqrt[\\reflectbox{\\(#1\\)}]{\\reflectbox{\\(#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{\\arsqrt}[2][]{\\reflectbox{\\(\\sqrt[\\reflectbox{\\(#1\\)}]{\\reflectbox{\\(#2\\)}}\\)}}\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{\\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 '../document/mathObject.js';\nimport {\n getArabicXeLatexPreamble,\n type ArabicDigitsMapping,\n} from './arabicPreamble.js';\nimport {\n BUTEX_CLOSING_HAMDALA,\n butexBasmalaDisplayLatex,\n butexBasmalaTitlingPreamble,\n butexDiwaniDisplayLatex,\n document2HasAbstract,\n document2HasMaketitle,\n emptyDocument2Meta,\n formatHijriDate,\n} from './articleMeta.js';\nimport { bibliographyEntryLatex, citeTokenLatex } from './citations.js';\nimport { refTokenLatex, stripDisplayMathDelimiters } from './labels.js';\nimport type {\n Document2Block,\n Document2Meta,\n Document2Node,\n ImageBlock2,\n InlineField2,\n InlineToken2,\n ListBlock2,\n MathToken2,\n TableBlock2,\n TextBlock2,\n} from './types.js';\n\nexport type Document2LatexOptions = {\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 /** When true, use article class option twocolumn. Default false. */\n twocolumn?: boolean;\n};\n\nfunction mathBodyLatex(token: MathToken2): string {\n if (!token.math || token.sourceOwner === 'raw' || token.sourceOwner === 'editor') {\n return stripDisplayMathDelimiters(token.source);\n }\n const rendered = renderMathNodeLatex(token.math);\n return stripDisplayMathDelimiters(rendered);\n}\n\nfunction tokenLatex(token: InlineToken2): string {\n if (token.kind === 'text') {\n return token.text;\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n if (token.kind === 'ref') {\n return refTokenLatex(token.keys, token.refCommand);\n }\n if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {\n const body = mathBodyLatex(token);\n return `\\\\begin{equation}\\n${body}\\n\\\\label{${token.label.trim()}}\\n\\\\end{equation}`;\n }\n if (!token.math || token.sourceOwner === 'raw' || token.sourceOwner === 'editor') {\n return token.source;\n }\n return renderMathNodeLatex(token.math);\n}\n\nexport function inlineFieldLatex(field: InlineField2): string {\n return field.tokens.map((token) => tokenLatex(token)).join('');\n}\n\nfunction textBlockLatex(block: TextBlock2): string {\n const body = `${block.command}{${inlineFieldLatex(block.field)}}`;\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(block: ListBlock2, references: Document2Node['references']): string {\n const items = block.items\n .map((item) => {\n const nested = item.blocks.map((child) => '\\n' + indent(blockLatex(child, references))).join('');\n return ` \\\\item ${inlineFieldLatex(item.field)}${nested}`;\n })\n .join('\\n');\n return `${block.command}\\n${items}\\n${block.closing}`;\n}\n\nfunction tabularInnerLatex(block: TableBlock2): string {\n const rows = block.rows\n .map((row) => ` ${row.map((cell) => inlineFieldLatex(cell)).join(' & ')}`)\n .join(' \\\\\\\\\\n');\n return `${block.command}{${block.columns}}\\n${rows}\\n${block.closing}`;\n}\n\nfunction floatCaptionLabelLines(block: ImageBlock2 | TableBlock2): string[] {\n const lines: string[] = [];\n if (block.captionEnabled && block.caption.trim().length > 0) {\n lines.push(` \\\\caption{${block.caption.trim()}}`);\n }\n if (block.labelEnabled && block.label.trim().length > 0) {\n lines.push(` \\\\label{${block.label.trim()}}`);\n }\n return lines;\n}\n\nfunction tableBlockLatex(block: TableBlock2): string {\n const lines = ['\\\\begin{table}[htbp]'];\n if (block.centered) {\n lines.push(' \\\\centering');\n }\n lines.push(...floatCaptionLabelLines(block));\n lines.push(indent(tabularInnerLatex(block)));\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): string {\n const lines = ['\\\\begin{figure}[htbp]'];\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));\n lines.push('\\\\end{figure}');\n return lines.join('\\n');\n}\n\nfunction blockLatex(block: Document2Block, references: Document2Node['references']): string {\n if (block.kind === 'textBlock') {\n return textBlockLatex(block);\n }\n if (block.kind === 'list') {\n return listBlockLatex(block, references);\n }\n if (block.kind === 'table') {\n return tableBlockLatex(block);\n }\n if (block.kind === 'image') {\n return imageBlockLatex(block);\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: Document2Meta, twocolumn = false): string {\n if (!document2HasMaketitle(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: 'arabicIndic' })}}`);\n return parts.join('\\n');\n}\n\nfunction articleFrontMatterLatex(meta: Document2Meta): string[] {\n const parts: string[] = [];\n if (document2HasMaketitle(meta)) {\n parts.push('\\\\maketitle');\n } else {\n parts.push(butexBasmalaDisplayLatex());\n }\n if (document2HasAbstract(meta)) {\n parts.push(`\\\\begin{abstract}\\n${meta.abstract.trim()}\\n\\\\end{abstract}`);\n }\n return parts;\n}\n\nexport function document2Latex(\n document: Document2Node,\n options: Document2LatexOptions = {},\n): string {\n const meta = document.meta ?? emptyDocument2Meta();\n const twocolumn = options.twocolumn === true;\n const front = articleFrontMatterLatex(meta);\n const bodyBlocks = document.blocks.map((block) => blockLatex(block, document.references));\n const closing = butexDiwaniDisplayLatex(BUTEX_CLOSING_HAMDALA);\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 preamble =\n getArabicXeLatexPreamble({\n digitsMapping: options.digitsMapping ?? 'arabicdigits',\n twocolumn,\n }) +\n '\\n' +\n articleMaketitlePreamble(meta, twocolumn);\n return `${preamble}\\n\\\\begin{document}\\n\\n${body}\\n\\n\\\\end{document}\\n`;\n}\n","import type { Document2Node } from './types.js';\nimport { cloneDocument2Node } from './commands.js';\n\nexport const DEFAULT_DOCUMENT2_HISTORY_MAX_DEPTH = 100;\n\nexport type Document2HistoryStacks = {\n past: Document2Node[];\n future: Document2Node[];\n maxDepth: number;\n};\n\nexport function createDocument2History(maxDepth: number = DEFAULT_DOCUMENT2_HISTORY_MAX_DEPTH): Document2HistoryStacks {\n return { past: [], future: [], maxDepth };\n}\n\nexport function pushDocument2Snapshot(stacks: Document2HistoryStacks, documentBeforeEdit: Document2Node): void {\n stacks.past.push(cloneDocument2Node(documentBeforeEdit));\n if (stacks.past.length > stacks.maxDepth) {\n stacks.past.splice(0, stacks.past.length - stacks.maxDepth);\n }\n stacks.future = [];\n}\n\nexport function restoreDocument2Undo(stacks: Document2HistoryStacks, documentNow: Document2Node): Document2Node | null {\n if (stacks.past.length === 0) {\n return null;\n }\n stacks.future.push(cloneDocument2Node(documentNow));\n return stacks.past.pop() ?? null;\n}\n\nexport function restoreDocument2Redo(stacks: Document2HistoryStacks, documentNow: Document2Node): Document2Node | null {\n if (stacks.future.length === 0) {\n return null;\n }\n stacks.past.push(cloneDocument2Node(documentNow));\n return stacks.future.pop() ?? null;\n}\n\nexport function document2HistoryCanUndo(stacks: Document2HistoryStacks): boolean {\n return stacks.past.length > 0;\n}\n\nexport function document2HistoryCanRedo(stacks: Document2HistoryStacks): boolean {\n return stacks.future.length > 0;\n}\n","export type BlockSelectionRange = { from: number; to: number };\n\nexport type BlockSelectionState = {\n selection: BlockSelectionRange | null;\n anchor: number | null;\n};\n\nexport function emptyBlockSelection(): BlockSelectionState {\n return { selection: null, anchor: null };\n}\n\nexport function normalizeBlockSelection(\n selection: BlockSelectionRange | null,\n blockCount: number,\n): BlockSelectionRange | null {\n if (!selection) {\n return null;\n }\n const { from, to } = selection;\n if (\n blockCount <= 0 ||\n from < 0 ||\n to < 0 ||\n from >= blockCount ||\n to >= blockCount ||\n from > to\n ) {\n return null;\n }\n return { from, to };\n}\n\nfunction inRange(selection: BlockSelectionRange, index: number): boolean {\n return index >= selection.from && index <= selection.to;\n}\n\n/** Checkbox click without Shift */\nexport function toggleBlockInSelection(\n state: BlockSelectionState,\n index: number,\n blockCount: number,\n): BlockSelectionState {\n if (index < 0 || index >= blockCount) {\n return state;\n }\n\n const selection = normalizeBlockSelection(state.selection, blockCount);\n if (!selection) {\n return { selection: { from: index, to: index }, anchor: index };\n }\n\n if (inRange(selection, index)) {\n if (selection.from === selection.to) {\n return emptyBlockSelection();\n }\n if (index === selection.from) {\n return { selection: { from: selection.from + 1, to: selection.to }, anchor: state.anchor };\n }\n if (index === selection.to) {\n return { selection: { from: selection.from, to: selection.to - 1 }, anchor: state.anchor };\n }\n return emptyBlockSelection();\n }\n\n if (index === selection.from - 1) {\n return { selection: { from: index, to: selection.to }, anchor: state.anchor ?? index };\n }\n if (index === selection.to + 1) {\n return { selection: { from: selection.from, to: index }, anchor: state.anchor ?? index };\n }\n\n return { selection: { from: index, to: index }, anchor: index };\n}\n\n/** Shift+click on checkbox or header label */\nexport function extendBlockSelectionFromAnchor(\n state: BlockSelectionState,\n index: number,\n blockCount: number,\n): BlockSelectionState {\n if (index < 0 || index >= blockCount) {\n return state;\n }\n\n const anchor = state.anchor ?? index;\n const from = Math.min(anchor, index);\n const to = Math.max(anchor, index);\n return {\n selection: { from, to },\n anchor: state.anchor ?? index,\n };\n}\n\nexport function remapSelectionAfterRangeMove(\n selection: BlockSelectionRange,\n direction: -1 | 1,\n): BlockSelectionRange {\n return { from: selection.from + direction, to: selection.to + direction };\n}\n","import { formatBibliographyNumber, formatCiteLabel } from './citations.js';\nimport {\n BUTEX_BASMALA,\n BUTEX_CLOSING_HAMDALA,\n butexBasmalaDisplayTex,\n butexDiwaniDisplayTex,\n document2HasAbstract,\n document2HasMaketitle,\n emptyDocument2Meta,\n formatHijriDate,\n} from './articleMeta.js';\nimport { formatFloatCaptionTitle, formatRefLabel, labelNumberMap } from './labels.js';\nimport { mathTokenSourceForSide } from './mathBridge.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { EditorSide } from '../editor/index.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport type {\n Document2Block,\n Document2Direction,\n Document2MathOutput,\n Document2Node,\n Document2Preview,\n InlineField2,\n MathIsland2,\n PreviewBlock2,\n PreviewInline2,\n TextBlock2,\n} from './types.js';\n\nexport type Document2PreviewOptions = {\n documentDirection?: Document2Direction;\n digitForm?: DigitFormId;\n uiLocale?: ButexUiLocale;\n};\n\nfunction mathTex(token: Extract<InlineField2['tokens'][number], { kind: 'math' }>, equationSide: EditorSide): string {\n return mathTokenSourceForSide(token, equationSide);\n}\n\nfunction previewInlines(\n field: InlineField2,\n islands: MathIsland2[],\n output: Document2MathOutput,\n equationSide: EditorSide,\n document: Document2Node,\n previewOptions: Document2PreviewOptions,\n): PreviewInline2[] {\n return field.tokens.map((token) => {\n if (token.kind === 'text') {\n return { kind: 'text', text: token.text };\n }\n if (token.kind === 'cite') {\n return {\n kind: 'cite',\n id: token.id,\n keys: [...token.keys],\n label: formatCiteLabel(token.keys, document.references, {\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n }),\n };\n }\n if (token.kind === 'ref') {\n return {\n kind: 'ref',\n id: token.id,\n keys: [...token.keys],\n refCommand: token.refCommand,\n label: formatRefLabel(token.keys, document, token.refCommand, {\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n }),\n };\n }\n const island = {\n id: token.id,\n tex: mathTex(token, equationSide),\n display: token.display,\n output,\n editable: token.editable,\n };\n islands.push(island);\n return { kind: 'math', ...island };\n });\n}\n\nfunction textBlockPreview(\n block: TextBlock2,\n islands: MathIsland2[],\n output: Document2MathOutput,\n equationSide: EditorSide,\n document: Document2Node,\n previewOptions: Document2PreviewOptions,\n): PreviewBlock2 {\n const inlines = previewInlines(block.field, islands, output, equationSide, document, previewOptions);\n if (block.command === '\\\\section') {\n return { kind: 'heading', id: block.id, level: 1, inlines };\n }\n if (block.command === '\\\\subsection') {\n return { kind: 'heading', id: block.id, level: 2, inlines };\n }\n if (block.command === '\\\\subsubsection') {\n return { kind: 'heading', id: block.id, level: 3, inlines };\n }\n return {\n kind: 'paragraph',\n id: block.id,\n inlines,\n ...(block.centered ? { centered: true } : {}),\n };\n}\n\nfunction floatNumberLabel(\n document: Document2Node,\n key: string | undefined,\n previewOptions: Document2PreviewOptions,\n): string | undefined {\n if (!key || key.trim().length === 0) {\n return undefined;\n }\n const hit = labelNumberMap(document).get(key.trim());\n if (!hit || (hit.kind !== 'fig' && hit.kind !== 'tab')) {\n return undefined;\n }\n return formatFloatCaptionTitle(hit.kind, hit.number, {\n uiLocale: previewOptions.uiLocale ?? 'ar',\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n });\n}\n\nfunction blockPreview(\n block: Document2Block,\n islands: MathIsland2[],\n output: Document2MathOutput,\n equationSide: EditorSide,\n document: Document2Node,\n previewOptions: Document2PreviewOptions,\n): PreviewBlock2 {\n if (block.kind === 'textBlock') {\n return textBlockPreview(block, islands, output, equationSide, document, previewOptions);\n }\n if (block.kind === 'list') {\n return {\n kind: 'list',\n id: block.id,\n ordered: block.command === '\\\\begin{enumerate}',\n items: block.items.map((item) => ({\n id: item.id,\n inlines: previewInlines(item.field, islands, output, equationSide, document, previewOptions),\n blocks: item.blocks.map((child) => blockPreview(child, islands, output, equationSide, document, previewOptions)),\n })),\n };\n }\n if (block.kind === 'table') {\n const label = block.labelEnabled ? block.label.trim() : '';\n return {\n kind: 'table',\n id: block.id,\n rows: block.rows.map((row) => row.map((cell) => previewInlines(cell, islands, output, equationSide, document, previewOptions))),\n ...(block.captionEnabled && block.caption.trim().length > 0 ? { caption: block.caption.trim() } : {}),\n ...(label.length > 0 ? { label, numberLabel: floatNumberLabel(document, label, previewOptions) } : {}),\n };\n }\n if (block.kind === 'image') {\n const label = block.labelEnabled ? block.label.trim() : '';\n return {\n kind: 'image',\n id: block.id,\n src: block.value,\n ...(block.assetId !== undefined ? { assetId: block.assetId } : {}),\n options: block.options,\n ...(block.captionEnabled && block.caption.trim().length > 0 ? { caption: block.caption.trim() } : {}),\n ...(label.length > 0 ? { label, numberLabel: floatNumberLabel(document, label, previewOptions) } : {}),\n };\n }\n if (block.kind === 'bibliography') {\n return {\n kind: 'bibliography',\n id: block.id,\n items: document.references.map((reference, index) => ({\n id: reference.id,\n numberLabel: formatBibliographyNumber(index + 1, {\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n }),\n key: reference.key,\n authors: reference.authors,\n title: reference.title,\n year: reference.year,\n url: reference.url,\n venue: reference.venue,\n fieldSeparator: reference.fieldSeparator,\n })),\n };\n }\n return { kind: 'omit', id: block.id };\n}\n\nfunction articleChromePreview(\n document: Document2Node,\n uiLocale: ButexUiLocale,\n previewOptions: Document2PreviewOptions,\n): PreviewBlock2[] {\n const meta = document.meta ?? emptyDocument2Meta();\n const blocks: PreviewBlock2[] = [\n { kind: 'basmala', id: 'article-basmala', text: BUTEX_BASMALA, tex: butexBasmalaDisplayTex() },\n ];\n if (document2HasMaketitle(meta)) {\n blocks.push({\n kind: 'titleBlock',\n id: 'article-title',\n ...(meta.title.trim().length > 0 ? { title: meta.title.trim() } : {}),\n ...(meta.authors.trim().length > 0 ? { authors: meta.authors.trim() } : {}),\n date: formatHijriDate(meta.date, {\n locale: uiLocale,\n digitForm: previewOptions.digitForm,\n }),\n });\n }\n if (document2HasAbstract(meta)) {\n blocks.push({ kind: 'abstract', id: 'article-abstract', text: meta.abstract.trim() });\n }\n return blocks;\n}\n\nexport function document2Preview(\n document: Document2Node,\n output: Document2MathOutput = 'svg',\n equationSide: EditorSide = 'arabic',\n previewOptions: Document2PreviewOptions = {},\n): Document2Preview {\n const mathIslands: MathIsland2[] = [];\n const options: Document2PreviewOptions = {\n documentDirection: previewOptions.documentDirection ?? 'rtl',\n digitForm:\n previewOptions.digitForm ??\n (previewOptions.documentDirection === 'ltr' ? 'western' : 'arabicIndic'),\n uiLocale: previewOptions.uiLocale ?? 'ar',\n };\n const body = document.blocks.map((block) => blockPreview(block, mathIslands, output, equationSide, document, options));\n return {\n blocks: [\n ...articleChromePreview(document, options.uiLocale ?? 'ar', options),\n ...body,\n { kind: 'closing', id: 'article-closing', text: BUTEX_CLOSING_HAMDALA, tex: butexDiwaniDisplayTex(BUTEX_CLOSING_HAMDALA) },\n ],\n mathIslands,\n };\n}\n"],"mappings":";AAAA,IAAI,SAAS;AAEN,SAAS,YAAY,QAAwB;AAClD,QAAM,KAAK,GAAG,MAAM,IAAI,OAAO,MAAM,CAAC;AACtC,YAAU;AACV,SAAO;AACT;;;ACJA,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,IAAI;AACnC;AAEO,SAAS,aAAa,OAAe,YAAyB,WAAmB;AACtF,QAAM,SAAS,UAAU,SAAS;AAClC,SAAO,MAAM,KAAK,OAAO,CAAC,SAAS;AACjC,UAAMA,SAAQ,WAAW,IAAI;AAC7B,WAAOA,UAAS,IAAI,OAAOA,MAAK,IAAI;AAAA,EACtC,CAAC,EAAE,KAAK,EAAE;AACZ;;;ACzBO,IAAM,sBAAsB;AAE5B,IAAM,sBAAsB;AAE5B,IAAM,wBAAwB;AAG9B,IAAM,gBAAgB,GAAG,mBAAmB;AAAA,EAAK,mBAAmB;AAAA,EAAK,qBAAqB;AAE9F,IAAM,wBAAwB;AAErC,SAAS,mBAAmB,MAAsB;AAChD,SAAO,KAAK,QAAQ,OAAO,mBAAmB,EAAE,QAAQ,SAAS,MAA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;AAAA,MACN,IAAI;AAAA,MACJ,GAAI,KAAK,MAAM,KAAK,EAAE,SAAS,IAAI,EAAE,OAAO,KAAK,MAAM,KAAK,EAAE,IAAI,CAAC;AAAA,MACnE,GAAI,KAAK,QAAQ,KAAK,EAAE,SAAS,IAAI,EAAE,SAAS,KAAK,QAAQ,KAAK,EAAE,IAAI,CAAC;AAAA,MACzE,MAAM,gBAAgB,KAAK,MAAM;AAAA,QAC/B,QAAQ;AAAA,QACR,WAAW,eAAe;AAAA,MAC5B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACA,MAAI,qBAAqB,IAAI,GAAG;AAC9B,WAAO,KAAK,EAAE,MAAM,YAAY,IAAI,oBAAoB,MAAM,KAAK,SAAS,KAAK,EAAE,CAAC;AAAA,EACtF;AACA,SAAO;AACT;AAEO,SAAS,iBACdA,WACA,SAA8B,OAC9B,eAA2B,UAC3B,iBAA0C,CAAC,GACzB;AAClB,QAAM,cAA6B,CAAC;AACpC,QAAM,UAAmC;AAAA,IACvC,mBAAmB,eAAe,qBAAqB;AAAA,IACvD,WACE,eAAe,cACd,eAAe,sBAAsB,QAAQ,YAAY;AAAA,IAC5D,UAAU,eAAe,YAAY;AAAA,EACvC;AACA,QAAM,OAAOA,UAAS,OAAO,IAAI,CAAC,UAAU,aAAa,OAAO,aAAa,QAAQ,cAAcA,WAAU,OAAO,CAAC;AACrH,SAAO;AAAA,IACL,QAAQ;AAAA,MACN,GAAG,qBAAqBA,WAAU,QAAQ,YAAY,MAAM,OAAO;AAAA,MACnE,GAAG;AAAA,MACH,EAAE,MAAM,WAAW,IAAI,mBAAmB,MAAM,uBAAuB,KAAK,sBAAsB,qBAAqB,EAAE;AAAA,IAC3H;AAAA,IACA;AAAA,EACF;AACF;","names":["value","node","parseChain","document","isObject","nextId","scripts","document","block","reference","document","document"]}
|
|
1
|
+
{"version":3,"sources":["../src/document2/ids.ts","../src/editor/digits.ts","../src/document2/articleMeta.ts","../src/document2/citations.ts","../src/ast/commands/index.ts","../src/ast/arabic_ast.ts","../src/document/mathObject.ts","../src/document2/labels.ts","../src/document2/inlineScanner.ts","../src/document2/importJson.ts","../src/editor/atomicCommands.ts","../src/editor/atomicCommandsOperators.ts","../src/editor/factory.ts","../src/editor/divideOperator.ts","../src/editor/render.ts","../src/editor/display/delimiter.ts","../src/editor/display/frac.ts","../src/editor/display/sqrt.ts","../src/editor/display/env.ts","../src/diwani-font.ts","../src/editor/display/atomicCommand.ts","../src/editor/display/atomicCommandsOperators.ts","../src/editor/styles.ts","../src/document/normalizeCharImport.ts","../src/document/mathEditorAdapter.ts","../src/document2/mathBridge.ts","../src/document2/commands.ts","../src/document2/keys.ts","../src/document2/arabicPreamble.ts","../src/document2/exportLatex.ts","../src/document2/history.ts","../src/document2/blockSelection.ts","../src/document2/previewModel.ts"],"sourcesContent":["let nextId = 1;\n\nexport function document2Id(prefix: string): string {\n const id = `${prefix}_${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 { Document2HijriDate, Document2Meta, 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\n/** Display-math body using BuTeX Diwani (for MathJax preview islands). */\nexport function butexDiwaniDisplayTex(text: string): string {\n return `\\\\butexdiwani{${escapeButexTextArg(text)}}`;\n}\n\n/** Full display equation for XeLaTeX export. */\nexport function butexDiwaniDisplayLatex(text: string): string {\n return `\\\\[\\n${butexDiwaniDisplayTex(text)}\\n\\\\]`;\n}\n\nconst BASMALA_LINES = [BUTEX_BASMALA_LINE1, BUTEX_BASMALA_LINE2, BUTEX_BASMALA_SALAWAT] as const;\n\n/** Three-line Diwani body for MathJax basmala islands. */\nexport function butexBasmalaDisplayTex(): string {\n return BASMALA_LINES.map((line) => butexDiwaniDisplayTex(line)).join(' \\\\\\\\ ');\n}\n\n/** Standalone display equation when there is no \\\\maketitle (title-less docs). */\nexport function butexBasmalaDisplayLatex(): string {\n return `\\\\[\\n${butexBasmalaDisplayTex()}\\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 ` ${butexDiwaniDisplayTex(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: Document2HijriDate = {\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 emptyDocument2Meta(): Document2Meta {\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 normalizeDocument2HijriDate(value: unknown): Document2HijriDate {\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 normalizeDocument2Meta(value: unknown): Document2Meta {\n if (typeof value !== 'object' || value === null) {\n return emptyDocument2Meta();\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: normalizeDocument2HijriDate(raw.date),\n abstract: typeof raw.abstract === 'string' ? raw.abstract : '',\n };\n}\n\nexport type Document2MetaProp = Partial<Omit<Document2Meta, 'date'>> & {\n date?: Partial<Document2HijriDate>;\n};\n\n/** Prop fills gaps; JSON wins only when the key is present on the JSON object. */\nexport function mergeDocument2Meta(fromJson: unknown, fromProp?: Document2MetaProp): Document2Meta {\n const fromPropMeta: Document2Meta = {\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 ? normalizeDocument2HijriDate({ ...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 ? normalizeDocument2HijriDate(json.date) : fromPropMeta.date,\n };\n}\n\n/** For live Document2Node meta: prop fills empty title/authors/abstract; date patch merges. */\nexport function fillDocument2MetaGaps(current: Document2Meta, fromProp?: Document2MetaProp): Document2Meta {\n if (!fromProp) {\n return cloneDocument2Meta(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 ? normalizeDocument2HijriDate({ ...current.date, ...fromProp.date })\n : { ...current.date },\n };\n}\n\nexport function document2HasMaketitle(meta: Document2Meta): boolean {\n return meta.title.trim().length > 0 || meta.authors.trim().length > 0;\n}\n\nexport function document2HasAbstract(meta: Document2Meta): boolean {\n return meta.abstract.trim().length > 0;\n}\n\nexport function document2HasTitleStack(meta: Document2Meta): boolean {\n return document2HasMaketitle(meta) || document2HasAbstract(meta);\n}\n\nexport type FormatHijriDateOptions = {\n locale?: ButexUiLocale;\n digitForm?: DigitFormId;\n};\n\nexport function formatHijriDate(date: Document2HijriDate, 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 cloneDocument2Meta(meta: Document2Meta): Document2Meta {\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 { document2Id } 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: document2Id('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 createEmptyReference2(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};\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\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 }\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 = this.name === '\\\\sqrt' ? '\\\\arabsqrt' : 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 const fullContent = `${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 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 { ChainNode, fromArabicJson, fromEnglishJson } 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\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 type {\n Document2Block,\n Document2Direction,\n Document2Node,\n FormatCiteLabelOptions,\n ImageBlock2,\n InlineField2,\n MathToken2,\n TableBlock2,\n} from './types.js';\n\nexport type Document2LabelKind = 'fig' | 'tab' | 'eq';\n\nexport type Document2LabelEntry = {\n key: string;\n kind: Document2LabelKind;\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: '';\n labelEnabled: false;\n label: '';\n} {\n return {\n centered: true,\n captionEnabled: false,\n caption: '',\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/** Collect enabled labels in document order, numbering per kind. */\nexport function collectDocument2Labels(document: Document2Node): Document2LabelEntry[] {\n const entries: Document2LabelEntry[] = [];\n const counters: Record<Document2LabelKind, number> = { fig: 0, tab: 0, eq: 0 };\n\n function pushEqFromField(tokens: MathToken2[] | InlineField2['tokens']): void {\n for (const token of tokens) {\n if (token.kind !== 'math') {\n continue;\n }\n if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {\n counters.eq += 1;\n entries.push({\n key: token.label.trim(),\n kind: 'eq',\n caption: '',\n ownerId: token.id,\n number: counters.eq,\n });\n }\n }\n }\n\n function walk(blocks: Document2Block[]): void {\n for (const block of blocks) {\n if (block.kind === 'image' && block.labelEnabled && block.label.trim().length > 0) {\n counters.fig += 1;\n entries.push({\n key: block.label.trim(),\n kind: 'fig',\n caption: block.captionEnabled ? block.caption : '',\n ownerId: block.id,\n number: counters.fig,\n });\n }\n if (block.kind === 'table') {\n if (block.labelEnabled && block.label.trim().length > 0) {\n counters.tab += 1;\n entries.push({\n key: block.label.trim(),\n kind: 'tab',\n caption: block.captionEnabled ? block.caption : '',\n ownerId: block.id,\n number: counters.tab,\n });\n }\n for (const row of block.rows) {\n for (const cell of row) {\n pushEqFromField(cell.tokens);\n }\n }\n }\n if (block.kind === 'textBlock') {\n pushEqFromField(block.field.tokens);\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n pushEqFromField(item.field.tokens);\n walk(item.blocks);\n }\n }\n }\n }\n\n walk(document.blocks);\n return entries;\n}\n\nexport function labelNumberMap(document: Document2Node): Map<string, { kind: Document2LabelKind; number: number }> {\n const map = new Map<string, { kind: Document2LabelKind; number: number }>();\n for (const entry of collectDocument2Labels(document)) {\n if (!map.has(entry.key)) {\n map.set(entry.key, { kind: entry.kind, number: entry.number });\n }\n }\n return map;\n}\n\nexport type FormatFloatCaptionTitleOptions = {\n uiLocale?: ButexUiLocale;\n documentDirection?: Document2Direction;\n digitForm?: DigitFormId;\n};\n\n/** Localized numbered float/equation title: الشكل ١ / Figure 1 / المعادلة ١. */\nexport function formatFloatCaptionTitle(\n kind: Document2LabelKind,\n number: number,\n options: FormatFloatCaptionTitleOptions = {},\n): string {\n const locale = options.uiLocale ?? 'ar';\n const kindWord =\n kind === 'fig'\n ? locale === 'ar'\n ? 'الشكل'\n : 'Figure'\n : kind === 'tab'\n ? locale === 'ar'\n ? 'الجدول'\n : 'Table'\n : locale === 'ar'\n ? 'المعادلة'\n : 'Equation';\n const digits = formatBibliographyNumber(number, {\n documentDirection: options.documentDirection ?? (locale === 'ar' ? 'rtl' : 'ltr'),\n digitForm: options.digitForm ?? (locale === 'ar' ? 'arabicIndic' : 'western'),\n });\n return `${kindWord} ${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: Document2Node,\n refCommand: 'ref' | 'eqref',\n options: FormatCiteLabelOptions = {},\n): string {\n const documentDirection: Document2Direction = options.documentDirection ?? 'rtl';\n const digitForm: DigitFormId = options.digitForm ?? (documentDirection === 'rtl' ? 'arabicIndic' : 'western');\n const map = labelNumberMap(document);\n const parts = keys.map((key) => {\n const hit = map.get(key);\n if (!hit) {\n return '?';\n }\n return formatDigits(String(hit.number), digitForm);\n });\n const body = parts.join(documentDirection === 'rtl' ? '،' : ', ');\n if (refCommand === 'eqref') {\n return `(${body})`;\n }\n return body;\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 if (trimmed.startsWith('\\\\begin{equation}') && trimmed.endsWith('\\\\end{equation}')) {\n return trimmed.slice('\\\\begin{equation}'.length, -'\\\\end{equation}'.length).trim();\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 }\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 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 let refCommand: 'ref' | 'eqref' = 'ref';\n let prefix = refPrefix;\n if (value.startsWith(eqrefPrefix, start) && !isEscaped(value, start)) {\n refCommand = 'eqref';\n prefix = eqrefPrefix;\n } else if (value.startsWith(refPrefix, start) && !isEscaped(value, start)) {\n refCommand = 'ref';\n prefix = refPrefix;\n } else {\n return null;\n }\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 detectMathSpans2(value: string): DetectedMathSpan2[] {\n return detectInlineSpans2(value)\n .filter((span): span is DetectedInlineSpan2 & { kind: 'math' } => span.kind === 'math')\n .map(({ kind: _kind, ...span }) => span);\n}\n\n/** Left-to-right math + \\\\cite + \\\\ref/\\\\eqref spans without overlap. */\nexport function detectInlineSpans2(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 '../document/mathObject.js';\nimport { normalizeDocument2Meta, emptyDocument2Meta } from './articleMeta.js';\nimport { referenceFromJson } from './citations.js';\nimport { document2Id } from './ids.js';\nimport { detectInlineSpans2, detectMathSpans2 } from './inlineScanner.js';\nimport { parseFloatMetaFromJson } from './labels.js';\nimport type {\n BibliographyBlock2,\n Document2Block,\n Document2BlockJson,\n Document2Diagnostic,\n Document2ListItemJson,\n Document2Node,\n Document2ParseMode,\n ImageBlock2,\n ImportDocument2Options,\n InlineField2,\n InlineToken2,\n ListBlock2,\n ListItem2,\n MathObject2Json,\n RawBlock2,\n Reference2,\n Reference2Json,\n TableBlock2,\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): Document2BlockJson {\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 Document2BlockJson;\n}\n\nfunction pushDiagnostic(diagnostics: Document2Diagnostic[], options: ImportDocument2Options, 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 createInlineField2(\n value = '',\n mathObjects: MathObject2Json[] = [],\n options: ImportDocument2Options = {},\n path = '$',\n diagnostics: Document2Diagnostic[] = [],\n): InlineField2 {\n const mode: Document2ParseMode = options.mode ?? 'english';\n const spans = detectInlineSpans2(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 tokens.push({ id: document2Id('text'), kind: 'text', text: value.slice(index, span.start) });\n }\n\n if (span.kind === 'cite') {\n tokens.push({\n id: document2Id('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: document2Id('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 if (mathJson && (mathJson.math_mode !== span.opening || mathJson.closing !== span.closing)) {\n pushDiagnostic(diagnostics, options, path, 'math_objects order mismatch');\n }\n\n if (mathJson && mathJson.math_mode === span.opening && mathJson.closing === span.closing) {\n tokens.push({\n id: document2Id('math'),\n kind: 'math',\n display: span.display,\n opening: span.opening,\n closing: span.closing,\n source: span.source,\n sourceSide: mode,\n math: fromMathObjectJson(mathJson, mode),\n editable: true,\n sourceOwner: 'imported-structured',\n });\n } else {\n tokens.push({\n id: document2Id('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 });\n }\n\n index = span.end;\n }\n\n if (index < value.length || tokens.length === 0) {\n tokens.push({ id: document2Id('text'), kind: 'text', text: value.slice(index) });\n }\n\n return { id: document2Id('field'), tokens };\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(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): TextBlock2 {\n const value = requireString(json.value, `${json.command} requires string value`);\n return {\n id: document2Id('block'),\n kind: 'textBlock',\n command: json.command as TextBlock2['command'],\n field: createInlineField2(value, json.math_objects ?? [], options, `${path}.value`, diagnostics),\n ...(json.centered === true ? { centered: true } : {}),\n };\n}\n\nfunction parseListItem(json: Document2ListItemJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): 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: document2Id('item'),\n field: createInlineField2(value, json.math_objects ?? [], options, `${path}.value`, diagnostics),\n blocks: blocksJson.map((block, index) => parseBlock(asBlockJson(block), options, `${path}.blocks[${String(index)}]`, diagnostics)),\n };\n}\n\nfunction parseListBlock(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): 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: document2Id('block'),\n kind: 'list',\n command,\n closing,\n items: json.items.map((item, index) => parseListItem(item, options, `${path}.items[${String(index)}]`, diagnostics)),\n };\n}\n\nfunction parseTableBlock(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): 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 = detectMathSpans2(value).length;\n const cellMathObjects = mathObjects.slice(mathObjectIndex, mathObjectIndex + spanCount);\n mathObjectIndex += spanCount;\n return createInlineField2(value, cellMathObjects, options, `${path}.rows[${String(rowIndex)}][${String(columnIndex)}]`, diagnostics);\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 return {\n id: document2Id('block'),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: typeof json.columns === 'string' ? json.columns : '',\n rows,\n ...parseFloatMetaFromJson(json),\n };\n}\n\nfunction parseImageBlock(json: Document2BlockJson): 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 return {\n id: document2Id('block'),\n kind: 'image',\n command: '\\\\includegraphics',\n value,\n ...(assetId !== undefined ? { assetId } : {}),\n options: isRecordOfStrings(json.options) ? json.options : {},\n ...parseFloatMetaFromJson(json),\n };\n}\n\nfunction parseRawBlock(json: Document2BlockJson): RawBlock2 {\n return {\n id: document2Id('block'),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : '',\n };\n}\n\nfunction parseBibliographyBlock(): BibliographyBlock2 {\n return {\n id: document2Id('block'),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n };\n}\n\nfunction parseBlock(json: Document2BlockJson, options: ImportDocument2Options, path: string, diagnostics: Document2Diagnostic[]): Document2Block {\n if (TEXT_COMMANDS.has(json.command)) {\n return parseTextBlock(json, options, path, diagnostics);\n }\n if (LIST_COMMANDS.has(json.command)) {\n return parseListBlock(json, options, path, diagnostics);\n }\n if (json.command === '\\\\begin{tabular}') {\n return parseTableBlock(json, options, path, diagnostics);\n }\n if (json.command === '\\\\includegraphics') {\n return parseImageBlock(json);\n }\n if (json.command === '\\\\begin{thebibliography}' || json.command === '\\\\bibliography') {\n return parseBibliographyBlock();\n }\n if (json.command === '\\\\raw') {\n return parseRawBlock(json);\n }\n return {\n id: document2Id('block'),\n kind: 'raw',\n command: '\\\\raw',\n value: typeof json.value === 'string' ? json.value : json.command,\n };\n}\n\nexport function fromDocumentJson2(json: unknown, options: ImportDocument2Options = {}): Document2Node {\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: Document2Diagnostic[] = [];\n return {\n nodeType: 'DocumentObject',\n meta: normalizeDocument2Meta(json.meta),\n references: parseReferences(json.references),\n blocks: json.blocks.map((block, index) => parseBlock(asBlockJson(block), options, `$.blocks[${String(index)}]`, diagnostics)),\n diagnostics,\n };\n}\n\nexport function createEmptyDocument2(): Document2Node {\n return {\n nodeType: 'DocumentObject',\n meta: emptyDocument2Meta(),\n references: [],\n blocks: [],\n diagnostics: [],\n };\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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Label: '⇒',\n title: 'يستلزم',\n svg_path: null,\n },\n impliedby: {\n id: 'impliedby',\n category: 'operators3',\n Tex: '\\\\impliedby',\n mirror: 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 Label: '⟹',\n title: 'سهم مزدوج طويل إلى اليمين',\n svg_path: null,\n },\n Longleftarrow: {\n id: 'Longleftarrow',\n category: 'operators3',\n Tex: '\\\\Longleftarrow',\n mirror: 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 Label: '→',\n title: 'يؤول إلى',\n svg_path: null,\n },\n rightleftharpoons: {\n id: 'rightleftharpoons',\n category: 'operators3',\n Tex: '\\\\rightleftharpoons',\n mirror: 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 Label: '←',\n title: 'سهم إلى اليسار',\n svg_path: null,\n },\n rightarrow: {\n id: 'rightarrow',\n category: 'operators3',\n Tex: '\\\\rightarrow',\n mirror: 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 Label: '⇐',\n title: 'سهم مزدوج إلى اليسار',\n svg_path: null,\n },\n rightarrowDouble: {\n id: 'rightarrowDouble',\n category: 'operators3',\n Tex: '\\\\Rightarrow',\n mirror: 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 Label: '↼',\n title: 'سهم خطافي علوي إلى اليسار',\n svg_path: null,\n },\n rightharpoonup: {\n id: 'rightharpoonup',\n category: 'operators3',\n Tex: '\\\\rightharpoonup',\n mirror: 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 Label: '↽',\n title: 'سهم خطافي سفلي إلى اليسار',\n svg_path: null,\n },\n rightharpoondown: {\n id: 'rightharpoondown',\n category: 'operators3',\n Tex: '\\\\rightharpoondown',\n mirror: 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 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 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 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 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 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 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 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 };\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);\n\nfunction matchingMirroredOperator(tex: string, index: number): string | null {\n for (const operatorTex of MIRRORED_OPERATOR_TEX) {\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): string {\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 result += tex.slice(index, end + 1);\n index = end + 1;\n continue;\n }\n }\n\n const operatorTex = matchingMirroredOperator(tex, index);\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, EditorNode, EditorSession, EditorSide, EnvColumnAlignment, GridEnvName, MatrixEnvStyle } from './types.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 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 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 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 = 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 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.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 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 { 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\nexport function isDivideOperatorExpr(expr: string): boolean {\n return expr === DIVIDE_OPERATOR_EN || expr === DIVIDE_OPERATOR_AR;\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 { DigitFormId, EditorChain, EditorNode, EditorSession, EnvColumnAlignment } from './types.js';\nimport { atomicCommandSpec } from './atomicCommands.js';\nimport { atomicOperatorCommandSpec } from './atomicCommandsOperators.js';\nimport { isDivideOperatorExpr, renderDivideOperatorLatex } from './divideOperator.js';\nimport { formatDigits } from './digits.js';\n\ntype RenderOptions = {\n digitForm?: DigitFormId;\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 return `\\\\begin{${envName}}${rows.join(' \\\\\\\\\\n')}\\\\end{${envName}}`;\n}\n\nfunction escapeText(s: string): string {\n return s.replace(/\\\\/g, '\\\\textbackslash{}').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 if (font === 'takween') {\n return `\\\\butextakween{${escapeText(expr)}}`;\n }\n if (font === 'diwani') {\n return `\\\\butexdiwani{${escapeText(expr)}}`;\n }\n if (font === 'diwaniOutline') {\n return `\\\\butexdiwanioutline{${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 === '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 === '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 = atomicOperatorCommandSpec(node.expr)?.Tex ?? node.expr;\n return `${body}${latinScripts(node, options)}`;\n }\n if (node.kind === 'char') {\n return `${renderCharContent(node, options)}${latinScripts(node, options)}`;\n }\n if (node.kind === 'operator' && isDivideOperatorExpr(node.expr)) {\n return `${renderDivideOperatorLatex('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 === '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 = `\\\\arabsqrt${optionalRootIndexArabic(node, options)}{${renderChainArabic(node.radicand, 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 === 'char') {\n const expr = formatDigits(node.expr, selectedDigitForm(options));\n const content = renderCharContent(node, options);\n return arabicScripts(node, (node.characterFont ?? 'default') === 'default'\n ? `\\\\text{${escapeText(expr)}}`\n : content, options);\n }\n if (node.kind === 'operator' && isDivideOperatorExpr(node.expr)) {\n return arabicScripts(node, renderDivideOperatorLatex('arabic'), options);\n }\n return arabicScripts(node, formatDigits(node.expr, selectedDigitForm(options)), options);\n}\n\nexport function renderChainEnglish(chain: EditorChain, options?: RenderOptions): string {\n return chain.nodes.map((node) => renderNodeEnglish(node, options)).join(' ');\n}\n\nexport function renderChainArabic(chain: EditorChain, options?: RenderOptions): string {\n return chain.nodes\n .slice()\n .reverse()\n .map((node) => renderNodeArabic(node, options))\n .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","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\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', '')\n .replace('\\\\right', '')\n .replace('\\\\{', '{')\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 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, 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__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}`;\n\n const style = node.envName ?? node.matrixStyle ?? 'matrix';\n const glyphs = 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 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_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_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_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`.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 { DELIMITER_CSS } from './display/delimiter.js';\nimport { FRAC_CSS } from './display/frac.js';\nimport { SQRT_CSS } from './display/sqrt.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 {\n BUTEX_DIWANI_FONT_STACK,\n BUTEX_DIWANI_OUTLINE_FONT_STACK,\n BUTEX_FONT_FACE_CSS,\n BUTEX_TAKWEEN_FONT_STACK,\n} from '../diwani-font.js';\n\nexport const BUTEX_EDITOR_CSS = `\n${BUTEX_FONT_FACE_CSS}\n\n.surface {\n border: 1px solid var(--butex-border, #e2e8f0);\n border-radius: 12px;\n min-height: 100px;\n padding: 8px 10px;\n background: var(--butex-surface-bg, linear-gradient(180deg, #ffffff 0%, #fafbfc 100%));\n color: var(--butex-surface-fg, #0f172a);\n outline: none;\n cursor: text;\n transition: box-shadow 0.15s ease, border-color 0.15s ease;\n}\n\n.surface: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.node-value--takween {\n font-family: ${BUTEX_TAKWEEN_FONT_STACK};\n}\n\n.node-value--diwani {\n font-family: ${BUTEX_DIWANI_FONT_STACK};\n}\n\n.node-value--diwani-outline {\n font-family: ${BUTEX_DIWANI_OUTLINE_FONT_STACK};\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.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${FRAC_CSS}\n\n${SQRT_CSS}\n\n${MATRIX_ENV_CSS}\n\n${ATOMIC_COMMAND_CSS}\n\n${ATOMIC_OPERATOR_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';\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 { prefix: '\\\\butexdiwanioutline', font: 'diwaniOutline' },\n { prefix: '\\\\diwanioutlineshaded', font: 'diwaniOutline' },\n { prefix: '\\\\butexdiwani', font: 'diwani' },\n { prefix: '\\\\butextakween', font: 'takween' },\n { prefix: '\\\\diwani', font: 'diwani' },\n { prefix: '\\\\takween', font: 'takween' },\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 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 {\n buildInitialSyncMap,\n cloneEditorSession,\n createDelimiterNode,\n createEditorChain,\n createEditorNode,\n createEditorSession,\n createFracNode,\n createGridEnvNode,\n createSqrtNode,\n renderArabicLatexFromSession,\n} from '../editor/index.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 type { MathNode } from './types.js';\n\ntype CommandFontPolicy = CharacterFontId | 'infer';\n\nconst COMMAND_FONT_MAP: Record<string, CommandFontPolicy> = {\n '\\\\text': 'infer',\n '\\\\butextakween': 'takween',\n '\\\\takween': 'takween',\n '\\\\butexdiwani': 'diwani',\n '\\\\diwani': 'diwani',\n '\\\\butexdiwanioutline': 'diwaniOutline',\n '\\\\diwanioutlineshaded': 'diwaniOutline',\n};\n\nconst CHAR_FONT_EXPORT_TEX: Record<Exclude<CharacterFontId, 'default'>, string> = {\n takween: '\\\\butextakween',\n diwani: '\\\\butexdiwani',\n diwaniOutline: '\\\\butexdiwanioutline',\n};\n\nfunction charEditorNodeToAstNode(node: EditorNode): BaseAstNode {\n const font = node.characterFont ?? 'default';\n const charNode = new CharNode(node.expr);\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 for (const spec of Object.values(ATOMIC_OPERATOR_COMMANDS)) {\n if (spec.Tex === tex) {\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: { superscript: ChainNode | null; subscript: ChainNode | null }, editorNode: EditorNode): UnsupportedAdapterResult | null {\n if (astNode.superscript) {\n const sup = chainToEditorChain(astNode.superscript);\n if (!sup.editable) {\n return sup;\n }\n editorNode.superscript = sup.chain;\n }\n if (astNode.subscript) {\n const sub = chainToEditorChain(astNode.subscript);\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';\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 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 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 ((node.name === '\\\\sqrt' || node.name === '\\\\arabsqrt') && node.mandatoryArgs.length >= 1) {\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 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 const scripts = attachScripts(node, atomicOperator);\n if (scripts) {\n return scripts;\n }\n return { editable: true, node: atomicOperator };\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\nfunction chainToEditorChain(chain: ChainNode): ChainAdapterResult {\n const nodes: EditorNode[] = [];\n for (const astNode of 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 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 === '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 === 'atomicCommand') {\n const tex = atomicCommandSpec(node.expr)?.englishTex;\n if (!tex) {\n return { ok: false, reason: `أمر رياضي غير مدعوم حاليا: ${node.expr}` };\n }\n astNode = new CommandNode(tex);\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(tex);\n } else if (node.kind === 'env') {\n return editorEnvToAstNode(node);\n } else {\n return { ok: false, reason: `عقدة رياضية غير مدعومة حاليا: ${node.kind}` };\n }\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 return { ok: true, chain: new ChainNode(nodes) };\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\n/** Delimited Arabic TeX for document text/preview — matches `<ButexEditor />` arabic output. */\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 '../document/mathEditorAdapter.js';\nimport type { MathNode } from '../document/types.js';\nimport {\n buildInitialSyncMap,\n createEditorChain,\n createEditorSession,\n renderArabicLatexFromSession,\n renderEnglishLatexFromSession,\n type EditorSide,\n type EditorSession,\n} from '../editor/index.js';\nimport type { MathToken2 } from './types.js';\n\nexport type Document2MathBridgeResult =\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'): Document2MathBridgeResult {\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): Document2MathBridgeResult {\n return mathTokenToEditorSession(math, 'arabic');\n}\n\nexport function mathSourceFromSession(\n session: EditorSession,\n side: EditorSide,\n opening = '$',\n closing = '$',\n): string {\n const inner = side === 'english'\n ? renderEnglishLatexFromSession(session)\n : 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): string {\n if (!token.math || token.sourceOwner === 'raw') {\n return token.source;\n }\n if (token.sourceSide === side) {\n return token.source;\n }\n const result = mathTokenToEditorSession(token.math, side);\n if (!result.editable) {\n return token.source;\n }\n return mathSourceFromSession(result.session, side, token.opening, token.closing);\n}\n","import { document2Id } from './ids.js';\nimport { cloneDocument2Meta, emptyDocument2Meta, normalizeDocument2HijriDate } from './articleMeta.js';\nimport { createEmptyReference2 } from './citations.js';\nimport { createInlineField2 } from './importJson.js';\nimport { applyFloatMetaPatch, defaultFloatMeta, type FloatMetaPatch } from './labels.js';\nimport { mathNodeFromSession, mathSourceFromSession } from './mathBridge.js';\nimport type {\n BibliographyBlock2,\n CiteToken2,\n Document2Block,\n Document2Node,\n ImageBlock2,\n InlineField2,\n InlineToken2,\n ListBlock2,\n MathToken2,\n Reference2,\n Reference2Json,\n RefToken2,\n TableBlock2,\n TextToken2,\n} from './types.js';\nimport type { Document2MetaProp } from './articleMeta.js';\nimport type { EditorSession, EditorSide } from '../editor/index.js';\n\nfunction cloneToken(token: InlineToken2): InlineToken2 {\n return token.kind === 'text' ? { ...token } : { ...token };\n}\n\nfunction cloneField(field: InlineField2): InlineField2 {\n return { id: field.id, tokens: field.tokens.map(cloneToken) };\n}\n\nfunction cloneBlock(block: Document2Block): Document2Block {\n if (block.kind === 'textBlock') {\n return { ...block, field: cloneField(block.field) };\n }\n if (block.kind === 'list') {\n return {\n ...block,\n items: block.items.map((item) => ({\n ...item,\n field: cloneField(item.field),\n blocks: item.blocks.map(cloneBlock),\n })),\n };\n }\n if (block.kind === 'table') {\n return { ...block, rows: block.rows.map((row) => row.map(cloneField)) };\n }\n if (block.kind === 'image') {\n return { ...block, options: { ...block.options } };\n }\n return { ...block };\n}\n\nfunction cloneDocument(document: Document2Node): Document2Node {\n return {\n nodeType: 'DocumentObject',\n meta: cloneDocument2Meta(document.meta ?? emptyDocument2Meta()),\n references: document.references.map((reference) => ({ ...reference })),\n blocks: document.blocks.map(cloneBlock),\n diagnostics: document.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n}\n\nfunction visitFields(blocks: Document2Block[], visitor: (field: InlineField2) => boolean): boolean {\n for (const block of blocks) {\n if (block.kind === 'textBlock') {\n if (visitor(block.field)) {\n return true;\n }\n } else if (block.kind === 'list') {\n for (const item of block.items) {\n if (visitor(item.field) || visitFields(item.blocks, visitor)) {\n return true;\n }\n }\n } else if (block.kind === 'table') {\n for (const row of block.rows) {\n for (const cell of row) {\n if (visitor(cell)) {\n return true;\n }\n }\n }\n }\n }\n return false;\n}\n\nexport function findFirstInlineField(document: Document2Node): InlineField2 | null {\n let found: InlineField2 | null = null;\n visitFields(document.blocks, (field) => {\n found = field;\n return true;\n });\n return found;\n}\n\nexport function updateTextToken(document: Document2Node, fieldId: string, tokenId: string, text: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n const token = field.tokens.find((entry): entry is TextToken2 => entry.id === tokenId && entry.kind === 'text');\n if (!token) {\n return true;\n }\n token.text = text;\n return true;\n });\n return next;\n}\n\nfunction mathTokenFromSession(session: EditorSession, opening = '$', closing = '$', side: EditorSide = 'arabic'): MathToken2 {\n return {\n id: document2Id('math'),\n kind: 'math',\n display: opening === '$$' || opening === '\\\\[' || opening.startsWith('\\\\begin{'),\n opening,\n closing,\n source: mathSourceFromSession(session, side, opening, closing),\n sourceSide: side,\n math: mathNodeFromSession(session, opening, closing),\n editable: true,\n sourceOwner: 'editor',\n };\n}\n\nfunction splitTextForInsertion(token: TextToken2): InlineToken2[] | null {\n const gap = token.text.indexOf(' ');\n if (gap < 0) {\n return null;\n }\n return [\n { id: token.id, kind: 'text', text: token.text.slice(0, gap + 1) },\n { id: document2Id('text'), kind: 'text', text: token.text.slice(gap + 1) },\n ];\n}\n\nexport function cloneDocument2Node(document: Document2Node): Document2Node {\n return cloneDocument(document);\n}\n\nfunction insertBlockAfter(blocks: Document2Block[], afterBlockId: string | null | undefined, block: Document2Block): void {\n if (!afterBlockId) {\n blocks.push(block);\n return;\n }\n const index = blocks.findIndex((entry) => entry.id === afterBlockId);\n if (index < 0) {\n blocks.push(block);\n return;\n }\n blocks.splice(index + 1, 0, block);\n}\n\nexport function insertDocument2BlockAfter(\n document: Document2Node,\n afterBlockId: string | null | undefined,\n block: Document2Block,\n): Document2Node {\n const next = cloneDocument(document);\n insertBlockAfter(next.blocks, afterBlockId, block);\n return next;\n}\n\nexport function moveDocument2BlockById(document: Document2Node, blockId: string, direction: -1 | 1): Document2Node {\n const next = cloneDocument(document);\n const index = next.blocks.findIndex((block) => block.id === blockId);\n const targetIndex = index + direction;\n if (index < 0 || targetIndex < 0 || targetIndex >= next.blocks.length) {\n return document;\n }\n const [block] = next.blocks.splice(index, 1);\n if (!block) {\n return document;\n }\n next.blocks.splice(targetIndex, 0, block);\n return next;\n}\n\nexport function moveDocument2BlockRange(\n document: Document2Node,\n from: number,\n to: number,\n direction: -1 | 1,\n): Document2Node {\n const count = document.blocks.length;\n if (from < 0 || to < 0 || from >= count || to >= count || from > to) {\n return document;\n }\n const insertAt = from + direction;\n if (insertAt < 0 || to + direction >= count) {\n return document;\n }\n const next = cloneDocument(document);\n const slice = next.blocks.splice(from, to - from + 1);\n next.blocks.splice(insertAt, 0, ...slice);\n return next;\n}\n\nexport function removeDocument2BlockRange(document: Document2Node, from: number, to: number): Document2Node {\n const count = document.blocks.length;\n if (from < 0 || to < 0 || from >= count || to >= count || from > to) {\n return document;\n }\n const next = cloneDocument(document);\n next.blocks = [...next.blocks.slice(0, from), ...next.blocks.slice(to + 1)];\n return next;\n}\n\nfunction normalizeFieldTokens(tokens: InlineToken2[]): InlineToken2[] {\n if (tokens.length === 0) {\n return [{ id: document2Id('text'), kind: 'text', text: '' }];\n }\n return tokens;\n}\n\nfunction stitchTextAroundRemovedToken(tokens: InlineToken2[], index: number): InlineToken2[] {\n const before = tokens[index - 1];\n const after = tokens[index + 1];\n if (before?.kind === 'text' && after?.kind === 'text') {\n return [\n ...tokens.slice(0, index - 1),\n { ...before, text: before.text + after.text },\n ...tokens.slice(index + 2),\n ];\n }\n return [...tokens.slice(0, index), ...tokens.slice(index + 1)];\n}\n\nexport function removeMathTokenById(document: Document2Node, tokenId: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'math');\n if (index < 0) {\n return false;\n }\n field.tokens = normalizeFieldTokens(stitchTextAroundRemovedToken(field.tokens, index));\n return true;\n });\n return next;\n}\n\nfunction splitTextTokenAt(token: TextToken2, offset: number): [TextToken2, TextToken2] {\n const safeOffset = Math.max(0, Math.min(offset, token.text.length));\n return [\n { id: token.id, kind: 'text', text: token.text.slice(0, safeOffset) },\n { id: document2Id('text'), kind: 'text', text: token.text.slice(safeOffset) },\n ];\n}\n\nexport function insertMathTokenAtCaret(\n document: Document2Node,\n fieldId: string,\n textTokenId: string | null,\n caretOffset: number,\n session: EditorSession,\n opening = '$',\n closing = '$',\n side: EditorSide = 'arabic',\n): Document2Node {\n const next = cloneDocument(document);\n const mathToken = mathTokenFromSession(session, opening, closing, side);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n const textIndex = textTokenId\n ? field.tokens.findIndex((token) => token.id === textTokenId && token.kind === 'text')\n : field.tokens.findIndex((token) => token.kind === 'text');\n\n if (textIndex < 0) {\n field.tokens.push(mathToken);\n field.tokens.push({ id: document2Id('text'), kind: 'text', text: '' });\n return true;\n }\n\n const current = field.tokens[textIndex] as TextToken2;\n const [before, after] = splitTextTokenAt(current, caretOffset);\n const parts: InlineToken2[] = [...field.tokens.slice(0, textIndex)];\n if (before.text.length > 0) {\n parts.push(before);\n }\n parts.push(mathToken);\n parts.push(after);\n parts.push(...field.tokens.slice(textIndex + 1));\n field.tokens = normalizeFieldTokens(parts);\n return true;\n });\n return next;\n}\n\nexport function insertMathToken(\n document: Document2Node,\n fieldId: string,\n insertIndex: number,\n session: EditorSession,\n opening = '$',\n closing = '$',\n side: EditorSide = 'arabic',\n): Document2Node {\n const next = cloneDocument(document);\n const mathToken = mathTokenFromSession(session, opening, closing, side);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n if (field.tokens.length === 1 && field.tokens[0]?.kind === 'text') {\n const split = splitTextForInsertion(field.tokens[0]);\n if (split) {\n field.tokens = [split[0]!, mathToken, split[1]!];\n return true;\n }\n }\n\n const safeIndex = Math.max(0, Math.min(insertIndex, field.tokens.length));\n field.tokens.splice(safeIndex, 0, mathToken);\n return true;\n });\n return next;\n}\n\nexport function replaceMathTokenFromSession(\n document: Document2Node,\n tokenId: string,\n session: EditorSession,\n opening?: string,\n closing?: string,\n side: EditorSide = 'arabic',\n): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'math');\n if (index < 0) {\n return false;\n }\n const current = field.tokens[index] as MathToken2;\n const open = opening ?? current.opening;\n const close = closing ?? current.closing;\n const replaced = mathTokenFromSession(session, open, close, side);\n replaced.id = current.id;\n if (current.labelEnabled !== undefined) {\n replaced.labelEnabled = current.labelEnabled;\n }\n if (current.label !== undefined) {\n replaced.label = current.label;\n }\n field.tokens[index] = replaced;\n return true;\n });\n return next;\n}\n\nexport function addDocument2TextBlock(\n document: Document2Node,\n command: '\\\\section' | '\\\\subsection' | '\\\\subsubsection' | '\\\\paragraph' = '\\\\paragraph',\n afterBlockId?: string | null,\n): Document2Node {\n const block = {\n id: document2Id('block'),\n kind: 'textBlock' as const,\n command,\n field: createInlineField2(''),\n ...(command === '\\\\paragraph' ? { centered: false } : {}),\n };\n return insertDocument2BlockAfter(document, afterBlockId, block);\n}\n\nexport function updateDocument2TextBlockCentered(\n document: Document2Node,\n blockId: string,\n centered: boolean,\n): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'textBlock' && block.command === '\\\\paragraph') {\n block.centered = centered;\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function removeDocument2BlockById(document: Document2Node, blockId: string): Document2Node {\n const next = cloneDocument(document);\n next.blocks = next.blocks.filter((block) => block.id !== blockId);\n return next;\n}\n\nfunction newListBlock(ordered: boolean): ListBlock2 {\n const command: ListBlock2['command'] = ordered ? '\\\\begin{enumerate}' : '\\\\begin{itemize}';\n const closing = ordered ? '\\\\end{enumerate}' : '\\\\end{itemize}';\n return {\n id: document2Id('block'),\n kind: 'list',\n command,\n closing,\n items: [{ id: document2Id('item'), field: createInlineField2(''), blocks: [] }],\n };\n}\n\nexport function addDocument2ListBlock(document: Document2Node, ordered: boolean, afterBlockId?: string | null): Document2Node {\n return insertDocument2BlockAfter(document, afterBlockId, newListBlock(ordered));\n}\n\nexport function addDocument2TableBlock(\n document: Document2Node,\n columns = 'lll',\n rowCount = 3,\n colCount = 3,\n afterBlockId?: string | null,\n): Document2Node {\n const rows = Math.max(1, rowCount);\n const cols = Math.max(1, colCount);\n const tableRows: InlineField2[][] = [];\n for (let r = 0; r < rows; r += 1) {\n const row: InlineField2[] = [];\n for (let c = 0; c < cols; c += 1) {\n row.push(createInlineField2(''));\n }\n tableRows.push(row);\n }\n const block: TableBlock2 = {\n id: document2Id('block'),\n kind: 'table',\n command: '\\\\begin{tabular}',\n closing: '\\\\end{tabular}',\n columns: columns || 'l'.repeat(cols),\n rows: tableRows,\n ...defaultFloatMeta(),\n };\n return insertDocument2BlockAfter(document, afterBlockId, block);\n}\n\nexport function addDocument2ImageBlock(document: Document2Node, src = '', afterBlockId?: string | null): Document2Node {\n const block: ImageBlock2 = {\n id: document2Id('block'),\n kind: 'image',\n command: '\\\\includegraphics',\n value: src,\n options: { width: '0.8\\\\columnwidth' },\n ...defaultFloatMeta(),\n };\n return insertDocument2BlockAfter(document, afterBlockId, block);\n}\n\nexport function updateDocument2ImageValue(document: Document2Node, blockId: string, value: string): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'image') {\n block.value = value;\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function updateDocument2ImageMeta(document: Document2Node, blockId: string, patch: FloatMetaPatch): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'image') {\n applyFloatMetaPatch(block, patch);\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function updateDocument2TableMeta(document: Document2Node, blockId: string, patch: FloatMetaPatch): Document2Node {\n const next = cloneDocument(document);\n function visit(blocks: Document2Block[]): boolean {\n for (const block of blocks) {\n if (block.id === blockId && block.kind === 'table') {\n applyFloatMetaPatch(block, patch);\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (visit(item.blocks)) {\n return true;\n }\n }\n }\n }\n return false;\n }\n visit(next.blocks);\n return next;\n}\n\nexport function updateMathTokenLabel(\n document: Document2Node,\n tokenId: string,\n patch: { labelEnabled?: boolean; label?: string },\n): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const token = field.tokens.find((entry): entry is MathToken2 => entry.id === tokenId && entry.kind === 'math');\n if (!token) {\n return false;\n }\n if (typeof patch.labelEnabled === 'boolean') {\n token.labelEnabled = patch.labelEnabled;\n }\n if (typeof patch.label === 'string') {\n token.label = patch.label;\n }\n return true;\n });\n return next;\n}\n\nfunction refTokenFromKeys(keys: string[], refCommand: 'ref' | 'eqref'): RefToken2 {\n return { id: document2Id('ref'), kind: 'ref', keys: [...keys], refCommand };\n}\n\nexport function insertRefTokenAtCaret(\n document: Document2Node,\n fieldId: string,\n textTokenId: string | null,\n caretOffset: number,\n keys: string[],\n refCommand: 'ref' | 'eqref' = 'ref',\n): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n const refToken = refTokenFromKeys(keys, refCommand);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n const textIndex = textTokenId\n ? field.tokens.findIndex((token) => token.id === textTokenId && token.kind === 'text')\n : field.tokens.findIndex((token) => token.kind === 'text');\n\n if (textIndex < 0) {\n field.tokens.push(refToken);\n field.tokens.push({ id: document2Id('text'), kind: 'text', text: '' });\n return true;\n }\n\n const current = field.tokens[textIndex] as TextToken2;\n const [before, after] = splitTextTokenAt(current, caretOffset);\n const parts: InlineToken2[] = [...field.tokens.slice(0, textIndex)];\n if (before.text.length > 0) {\n parts.push(before);\n }\n parts.push(refToken);\n parts.push(after);\n parts.push(...field.tokens.slice(textIndex + 1));\n field.tokens = normalizeFieldTokens(parts);\n return true;\n });\n return next;\n}\n\nexport function updateRefTokenKeys(\n document: Document2Node,\n tokenId: string,\n keys: string[],\n refCommand?: 'ref' | 'eqref',\n): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const token = field.tokens.find((entry): entry is RefToken2 => entry.id === tokenId && entry.kind === 'ref');\n if (!token) {\n return false;\n }\n token.keys = [...keys];\n if (refCommand) {\n token.refCommand = refCommand;\n }\n return true;\n });\n return next;\n}\n\nexport function removeRefTokenById(document: Document2Node, tokenId: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'ref');\n if (index < 0) {\n return false;\n }\n field.tokens = normalizeFieldTokens(stitchTextAroundRemovedToken(field.tokens, index));\n return true;\n });\n return next;\n}\n\nfunction mutateListBlockById(blocks: Document2Block[], listBlockId: string, mutator: (list: ListBlock2) => void): boolean {\n for (const block of blocks) {\n if (block.id === listBlockId && block.kind === 'list') {\n mutator(block);\n return true;\n }\n if (block.kind === 'list') {\n for (const item of block.items) {\n if (mutateListBlockById(item.blocks, listBlockId, mutator)) {\n return true;\n }\n }\n }\n }\n return false;\n}\n\nexport function addDocument2ListItem(document: Document2Node, listBlockId: string): Document2Node {\n const next = cloneDocument(document);\n mutateListBlockById(next.blocks, listBlockId, (list) => {\n list.items.push({ id: document2Id('item'), field: createInlineField2(''), blocks: [] });\n });\n return next;\n}\n\nexport function removeDocument2ListItem(document: Document2Node, listBlockId: string, itemId: string): Document2Node {\n const next = cloneDocument(document);\n mutateListBlockById(next.blocks, listBlockId, (list) => {\n if (list.items.length < 2) {\n return;\n }\n const index = list.items.findIndex((item) => item.id === itemId);\n if (index >= 0) {\n list.items.splice(index, 1);\n }\n });\n return next;\n}\n\nfunction citeTokenFromKeys(keys: string[]): CiteToken2 {\n return { id: document2Id('cite'), kind: 'cite', keys: [...keys] };\n}\n\nexport function insertCiteTokenAtCaret(\n document: Document2Node,\n fieldId: string,\n textTokenId: string | null,\n caretOffset: number,\n keys: string[],\n): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n const citeToken = citeTokenFromKeys(keys);\n visitFields(next.blocks, (field) => {\n if (field.id !== fieldId) {\n return false;\n }\n\n const textIndex = textTokenId\n ? field.tokens.findIndex((token) => token.id === textTokenId && token.kind === 'text')\n : field.tokens.findIndex((token) => token.kind === 'text');\n\n if (textIndex < 0) {\n field.tokens.push(citeToken);\n field.tokens.push({ id: document2Id('text'), kind: 'text', text: '' });\n return true;\n }\n\n const current = field.tokens[textIndex] as TextToken2;\n const [before, after] = splitTextTokenAt(current, caretOffset);\n const parts: InlineToken2[] = [...field.tokens.slice(0, textIndex)];\n if (before.text.length > 0) {\n parts.push(before);\n }\n parts.push(citeToken);\n parts.push(after);\n parts.push(...field.tokens.slice(textIndex + 1));\n field.tokens = normalizeFieldTokens(parts);\n return true;\n });\n return next;\n}\n\nexport function updateCiteTokenKeys(document: Document2Node, tokenId: string, keys: string[]): Document2Node {\n if (keys.length === 0) {\n return document;\n }\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const token = field.tokens.find((entry): entry is CiteToken2 => entry.id === tokenId && entry.kind === 'cite');\n if (!token) {\n return false;\n }\n token.keys = [...keys];\n return true;\n });\n return next;\n}\n\nexport function removeCiteTokenById(document: Document2Node, tokenId: string): Document2Node {\n const next = cloneDocument(document);\n visitFields(next.blocks, (field) => {\n const index = field.tokens.findIndex((token) => token.id === tokenId && token.kind === 'cite');\n if (index < 0) {\n return false;\n }\n field.tokens = normalizeFieldTokens(stitchTextAroundRemovedToken(field.tokens, index));\n return true;\n });\n return next;\n}\n\nexport function ensureDocument2BibliographyBlock(document: Document2Node, afterBlockId?: string | null): Document2Node {\n if (document.blocks.some((block) => block.kind === 'bibliography')) {\n return document;\n }\n const block: BibliographyBlock2 = {\n id: document2Id('block'),\n kind: 'bibliography',\n command: '\\\\begin{thebibliography}',\n closing: '\\\\end{thebibliography}',\n };\n return insertDocument2BlockAfter(document, afterBlockId ?? null, block);\n}\n\nexport function addDocument2Reference(document: Document2Node, partial: Partial<Reference2Json> = {}): Document2Node {\n const next = cloneDocument(document);\n next.references.push(createEmptyReference2(partial));\n return next;\n}\n\nexport function updateDocument2Reference(document: Document2Node, referenceId: string, patch: Partial<Reference2Json>): Document2Node {\n const next = cloneDocument(document);\n const reference = next.references.find((entry) => entry.id === referenceId);\n if (!reference) {\n return document;\n }\n if (typeof patch.key === 'string' && patch.key.trim().length > 0) {\n reference.key = patch.key.trim();\n }\n if (typeof patch.authors === 'string') {\n reference.authors = patch.authors;\n }\n if (typeof patch.title === 'string') {\n reference.title = patch.title;\n }\n if (typeof patch.year === 'string') {\n reference.year = patch.year;\n }\n if (typeof patch.url === 'string') {\n reference.url = patch.url;\n }\n if (typeof patch.venue === 'string') {\n reference.venue = patch.venue;\n }\n if (patch.field_separator === ',' || patch.field_separator === '،') {\n reference.fieldSeparator = patch.field_separator;\n }\n return next;\n}\n\nexport function removeDocument2Reference(document: Document2Node, referenceId: string): Document2Node {\n const next = cloneDocument(document);\n next.references = next.references.filter((reference) => reference.id !== referenceId);\n return next;\n}\n\nexport function moveDocument2Reference(document: Document2Node, referenceId: string, direction: -1 | 1): Document2Node {\n const next = cloneDocument(document);\n const index = next.references.findIndex((reference) => reference.id === referenceId);\n const targetIndex = index + direction;\n if (index < 0 || targetIndex < 0 || targetIndex >= next.references.length) {\n return document;\n }\n const [reference] = next.references.splice(index, 1);\n if (!reference) {\n return document;\n }\n next.references.splice(targetIndex, 0, reference);\n return next;\n}\n\nexport function setDocument2References(document: Document2Node, references: Reference2[]): Document2Node {\n const next = cloneDocument(document);\n next.references = references.map((reference) => ({ ...reference }));\n return next;\n}\n\nexport function updateDocument2Meta(document: Document2Node, patch: Document2MetaProp): Document2Node {\n const next = cloneDocument(document);\n const current = next.meta ?? emptyDocument2Meta();\n next.meta = {\n title: typeof patch.title === 'string' ? patch.title : current.title,\n authors: typeof patch.authors === 'string' ? patch.authors : current.authors,\n abstract: typeof patch.abstract === 'string' ? patch.abstract : current.abstract,\n date: patch.date\n ? normalizeDocument2HijriDate({ ...current.date, ...patch.date })\n : { ...current.date },\n };\n return next;\n}\n","import type { Document2LabelEntry } from './labels.js';\nimport type { Reference2 } from './types.js';\n\nexport type Document2KeyError = 'empty' | 'invalid' | 'duplicate';\n\nconst DOCUMENT2_KEY_PATTERN = /^[\\p{L}\\p{M}0-9:._-]+$/u;\n\n/** NFC-normalize and trim a document key (label or bibliography). */\nexport function normalizeDocument2Key(key: string): string {\n return key.normalize('NFC').trim();\n}\n\n/** True when key matches Unicode letters/marks, ASCII digits, and :._- with no spaces. */\nexport function isValidDocument2Key(key: string): boolean {\n const normalized = normalizeDocument2Key(key);\n return normalized.length > 0 && DOCUMENT2_KEY_PATTERN.test(normalized);\n}\n\nexport type Document2KeyNamespace = {\n references?: Array<Pick<Reference2, 'id' | 'key'>>;\n labels?: Array<Pick<Document2LabelEntry, '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 isDuplicateDocument2Key(key: string, namespace: Document2KeyNamespace): boolean {\n const normalized = normalizeDocument2Key(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 (normalizeDocument2Key(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 (normalizeDocument2Key(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 document2KeyError(key: string, namespace: Document2KeyNamespace = {}): Document2KeyError | null {\n const normalized = normalizeDocument2Key(key);\n if (normalized.length === 0) {\n return 'empty';\n }\n if (!DOCUMENT2_KEY_PATTERN.test(normalized)) {\n return 'invalid';\n }\n if (isDuplicateDocument2Key(normalized, namespace)) {\n return 'duplicate';\n }\n return null;\n}\n","/** Arabic XeLaTeX preamble fragments for full-document export. */\n\nexport type ArabicDigitsMapping = 'arabicdigits' | 'digits';\n\nexport type ArabicXeLatexPreambleOptions = {\n digitsMapping?: ArabicDigitsMapping;\n /** When true, add the article class twocolumn option. Default false. */\n twocolumn?: boolean;\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} % For bidirectional text handling\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\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 return `\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n% Toggle between eastern and western digits by changing the Mapping in the below fonts (inside math font as well) between \"arabicdigits\" and \"digits\"\n\\\\setdefaultlanguage[calendar=gregorian]{arabic} % from polyglossia\n\\\\setmainfont[Script=Arabic , Mapping=${digitsMapping}]{Amiri}\n\\\\newfontfamily\\\\diwani[Script=Arabic,Mapping=${digitsMapping}]{Diwani Letter}\n\\\\newfontfamily\\\\diwanioutlineshaded[Script=Arabic,Mapping=${digitsMapping}]{Diwani Outline Shaded}\n\\\\newfontfamily\\\\takween[Script=Arabic,Mapping=${digitsMapping}]{Takween}\n\\\\newfontfamily\\\\boldarabic[Script=Arabic,Mapping=${digitsMapping}]{Amiri Bold}\n\\\\newfontfamily\\\\italicarabic[Script=Arabic,Mapping=${digitsMapping}]{Amiri Italic}\n\n% Explicitly set math font to XITS Math\n% Remove \"Script=Arabic\" to cancel reflected symbols and other RTL symbols\n\\\\setmathfont[Script=Arabic , Mapping=${digitsMapping}]{XITS Math} % Ensure XITS Math is correctly installed and available\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n`;\n}\n\nexport function arabicXeLatexPreambleCmd(): string {\n return String.raw`\n% Run with XeLaTeX compiler\n\\newcommand{\\butextakween}[1]{\\text{\\takween{#1}}}\n\\newcommand{\\butexdiwani}[1]{\\text{\\diwani{#1}}}\n\\newcommand{\\butexdiwanioutline}[1]{\\text{\\diwanioutlineshaded{#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\\newcommand{\\arabsqrt}[2]{\\reflectbox{\\(\\sqrt[\\reflectbox{\\(#1\\)}]{\\reflectbox{\\(#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{\\arsqrt}[2][]{\\reflectbox{\\(\\sqrt[\\reflectbox{\\(#1\\)}]{\\reflectbox{\\(#2\\)}}\\)}}\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{\\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 '../document/mathObject.js';\nimport {\n getArabicXeLatexPreamble,\n type ArabicDigitsMapping,\n} from './arabicPreamble.js';\nimport {\n BUTEX_CLOSING_HAMDALA,\n butexBasmalaDisplayLatex,\n butexBasmalaTitlingPreamble,\n butexDiwaniDisplayLatex,\n document2HasAbstract,\n document2HasMaketitle,\n emptyDocument2Meta,\n formatHijriDate,\n} from './articleMeta.js';\nimport { bibliographyEntryLatex, citeTokenLatex } from './citations.js';\nimport { refTokenLatex, stripDisplayMathDelimiters } from './labels.js';\nimport type {\n Document2Block,\n Document2Meta,\n Document2Node,\n ImageBlock2,\n InlineField2,\n InlineToken2,\n ListBlock2,\n MathToken2,\n TableBlock2,\n TextBlock2,\n} from './types.js';\n\nexport type Document2LatexOptions = {\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 /** When true, use article class option twocolumn. Default false. */\n twocolumn?: boolean;\n};\n\nfunction mathBodyLatex(token: MathToken2): string {\n if (!token.math || token.sourceOwner === 'raw' || token.sourceOwner === 'editor') {\n return stripDisplayMathDelimiters(token.source);\n }\n const rendered = renderMathNodeLatex(token.math);\n return stripDisplayMathDelimiters(rendered);\n}\n\nfunction tokenLatex(token: InlineToken2): string {\n if (token.kind === 'text') {\n return token.text;\n }\n if (token.kind === 'cite') {\n return citeTokenLatex(token.keys);\n }\n if (token.kind === 'ref') {\n return refTokenLatex(token.keys, token.refCommand);\n }\n if (token.display && token.labelEnabled && token.label && token.label.trim().length > 0) {\n const body = mathBodyLatex(token);\n return `\\\\begin{equation}\\n${body}\\n\\\\label{${token.label.trim()}}\\n\\\\end{equation}`;\n }\n if (!token.math || token.sourceOwner === 'raw' || token.sourceOwner === 'editor') {\n return token.source;\n }\n return renderMathNodeLatex(token.math);\n}\n\nexport function inlineFieldLatex(field: InlineField2): string {\n return field.tokens.map((token) => tokenLatex(token)).join('');\n}\n\nfunction textBlockLatex(block: TextBlock2): string {\n const body = `${block.command}{${inlineFieldLatex(block.field)}}`;\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(block: ListBlock2, references: Document2Node['references']): string {\n const items = block.items\n .map((item) => {\n const nested = item.blocks.map((child) => '\\n' + indent(blockLatex(child, references))).join('');\n return ` \\\\item ${inlineFieldLatex(item.field)}${nested}`;\n })\n .join('\\n');\n return `${block.command}\\n${items}\\n${block.closing}`;\n}\n\nfunction tabularInnerLatex(block: TableBlock2): string {\n const rows = block.rows\n .map((row) => ` ${row.map((cell) => inlineFieldLatex(cell)).join(' & ')}`)\n .join(' \\\\\\\\\\n');\n return `${block.command}{${block.columns}}\\n${rows}\\n${block.closing}`;\n}\n\nfunction floatCaptionLabelLines(block: ImageBlock2 | TableBlock2): string[] {\n const lines: string[] = [];\n if (block.captionEnabled && block.caption.trim().length > 0) {\n lines.push(` \\\\caption{${block.caption.trim()}}`);\n }\n if (block.labelEnabled && block.label.trim().length > 0) {\n lines.push(` \\\\label{${block.label.trim()}}`);\n }\n return lines;\n}\n\nfunction tableBlockLatex(block: TableBlock2): string {\n const lines = ['\\\\begin{table}[htbp]'];\n if (block.centered) {\n lines.push(' \\\\centering');\n }\n lines.push(...floatCaptionLabelLines(block));\n lines.push(indent(tabularInnerLatex(block)));\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): string {\n const lines = ['\\\\begin{figure}[htbp]'];\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));\n lines.push('\\\\end{figure}');\n return lines.join('\\n');\n}\n\nfunction blockLatex(block: Document2Block, references: Document2Node['references']): string {\n if (block.kind === 'textBlock') {\n return textBlockLatex(block);\n }\n if (block.kind === 'list') {\n return listBlockLatex(block, references);\n }\n if (block.kind === 'table') {\n return tableBlockLatex(block);\n }\n if (block.kind === 'image') {\n return imageBlockLatex(block);\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: Document2Meta, twocolumn = false): string {\n if (!document2HasMaketitle(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: 'arabicIndic' })}}`);\n return parts.join('\\n');\n}\n\nfunction articleFrontMatterLatex(meta: Document2Meta): string[] {\n const parts: string[] = [];\n if (document2HasMaketitle(meta)) {\n parts.push('\\\\maketitle');\n } else {\n parts.push(butexBasmalaDisplayLatex());\n }\n if (document2HasAbstract(meta)) {\n parts.push(`\\\\begin{abstract}\\n${meta.abstract.trim()}\\n\\\\end{abstract}`);\n }\n return parts;\n}\n\nexport function document2Latex(\n document: Document2Node,\n options: Document2LatexOptions = {},\n): string {\n const meta = document.meta ?? emptyDocument2Meta();\n const twocolumn = options.twocolumn === true;\n const front = articleFrontMatterLatex(meta);\n const bodyBlocks = document.blocks.map((block) => blockLatex(block, document.references));\n const closing = butexDiwaniDisplayLatex(BUTEX_CLOSING_HAMDALA);\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 preamble =\n getArabicXeLatexPreamble({\n digitsMapping: options.digitsMapping ?? 'arabicdigits',\n twocolumn,\n }) +\n '\\n' +\n articleMaketitlePreamble(meta, twocolumn);\n return `${preamble}\\n\\\\begin{document}\\n\\n${body}\\n\\n\\\\end{document}\\n`;\n}\n","import type { Document2Node } from './types.js';\nimport { cloneDocument2Node } from './commands.js';\n\nexport const DEFAULT_DOCUMENT2_HISTORY_MAX_DEPTH = 100;\n\nexport type Document2HistoryStacks = {\n past: Document2Node[];\n future: Document2Node[];\n maxDepth: number;\n};\n\nexport function createDocument2History(maxDepth: number = DEFAULT_DOCUMENT2_HISTORY_MAX_DEPTH): Document2HistoryStacks {\n return { past: [], future: [], maxDepth };\n}\n\nexport function pushDocument2Snapshot(stacks: Document2HistoryStacks, documentBeforeEdit: Document2Node): void {\n stacks.past.push(cloneDocument2Node(documentBeforeEdit));\n if (stacks.past.length > stacks.maxDepth) {\n stacks.past.splice(0, stacks.past.length - stacks.maxDepth);\n }\n stacks.future = [];\n}\n\nexport function restoreDocument2Undo(stacks: Document2HistoryStacks, documentNow: Document2Node): Document2Node | null {\n if (stacks.past.length === 0) {\n return null;\n }\n stacks.future.push(cloneDocument2Node(documentNow));\n return stacks.past.pop() ?? null;\n}\n\nexport function restoreDocument2Redo(stacks: Document2HistoryStacks, documentNow: Document2Node): Document2Node | null {\n if (stacks.future.length === 0) {\n return null;\n }\n stacks.past.push(cloneDocument2Node(documentNow));\n return stacks.future.pop() ?? null;\n}\n\nexport function document2HistoryCanUndo(stacks: Document2HistoryStacks): boolean {\n return stacks.past.length > 0;\n}\n\nexport function document2HistoryCanRedo(stacks: Document2HistoryStacks): boolean {\n return stacks.future.length > 0;\n}\n","export type BlockSelectionRange = { from: number; to: number };\n\nexport type BlockSelectionState = {\n selection: BlockSelectionRange | null;\n anchor: number | null;\n};\n\nexport function emptyBlockSelection(): BlockSelectionState {\n return { selection: null, anchor: null };\n}\n\nexport function normalizeBlockSelection(\n selection: BlockSelectionRange | null,\n blockCount: number,\n): BlockSelectionRange | null {\n if (!selection) {\n return null;\n }\n const { from, to } = selection;\n if (\n blockCount <= 0 ||\n from < 0 ||\n to < 0 ||\n from >= blockCount ||\n to >= blockCount ||\n from > to\n ) {\n return null;\n }\n return { from, to };\n}\n\nfunction inRange(selection: BlockSelectionRange, index: number): boolean {\n return index >= selection.from && index <= selection.to;\n}\n\n/** Checkbox click without Shift */\nexport function toggleBlockInSelection(\n state: BlockSelectionState,\n index: number,\n blockCount: number,\n): BlockSelectionState {\n if (index < 0 || index >= blockCount) {\n return state;\n }\n\n const selection = normalizeBlockSelection(state.selection, blockCount);\n if (!selection) {\n return { selection: { from: index, to: index }, anchor: index };\n }\n\n if (inRange(selection, index)) {\n if (selection.from === selection.to) {\n return emptyBlockSelection();\n }\n if (index === selection.from) {\n return { selection: { from: selection.from + 1, to: selection.to }, anchor: state.anchor };\n }\n if (index === selection.to) {\n return { selection: { from: selection.from, to: selection.to - 1 }, anchor: state.anchor };\n }\n return emptyBlockSelection();\n }\n\n if (index === selection.from - 1) {\n return { selection: { from: index, to: selection.to }, anchor: state.anchor ?? index };\n }\n if (index === selection.to + 1) {\n return { selection: { from: selection.from, to: index }, anchor: state.anchor ?? index };\n }\n\n return { selection: { from: index, to: index }, anchor: index };\n}\n\n/** Shift+click on checkbox or header label */\nexport function extendBlockSelectionFromAnchor(\n state: BlockSelectionState,\n index: number,\n blockCount: number,\n): BlockSelectionState {\n if (index < 0 || index >= blockCount) {\n return state;\n }\n\n const anchor = state.anchor ?? index;\n const from = Math.min(anchor, index);\n const to = Math.max(anchor, index);\n return {\n selection: { from, to },\n anchor: state.anchor ?? index,\n };\n}\n\nexport function remapSelectionAfterRangeMove(\n selection: BlockSelectionRange,\n direction: -1 | 1,\n): BlockSelectionRange {\n return { from: selection.from + direction, to: selection.to + direction };\n}\n","import { formatBibliographyNumber, formatCiteLabel } from './citations.js';\nimport {\n BUTEX_BASMALA,\n BUTEX_CLOSING_HAMDALA,\n butexBasmalaDisplayTex,\n butexDiwaniDisplayTex,\n document2HasAbstract,\n document2HasMaketitle,\n emptyDocument2Meta,\n formatHijriDate,\n} from './articleMeta.js';\nimport { formatFloatCaptionTitle, formatRefLabel, labelNumberMap } from './labels.js';\nimport { mathTokenSourceForSide } from './mathBridge.js';\nimport type { DigitFormId } from '../editor/types.js';\nimport type { EditorSide } from '../editor/index.js';\nimport type { ButexUiLocale } from '../uiLocale.js';\nimport type {\n Document2Block,\n Document2Direction,\n Document2MathOutput,\n Document2Node,\n Document2Preview,\n InlineField2,\n MathIsland2,\n PreviewBlock2,\n PreviewInline2,\n TextBlock2,\n} from './types.js';\n\nexport type Document2PreviewOptions = {\n documentDirection?: Document2Direction;\n digitForm?: DigitFormId;\n uiLocale?: ButexUiLocale;\n};\n\nfunction mathTex(token: Extract<InlineField2['tokens'][number], { kind: 'math' }>, equationSide: EditorSide): string {\n return mathTokenSourceForSide(token, equationSide);\n}\n\nfunction previewInlines(\n field: InlineField2,\n islands: MathIsland2[],\n output: Document2MathOutput,\n equationSide: EditorSide,\n document: Document2Node,\n previewOptions: Document2PreviewOptions,\n): PreviewInline2[] {\n return field.tokens.map((token) => {\n if (token.kind === 'text') {\n return { kind: 'text', text: token.text };\n }\n if (token.kind === 'cite') {\n return {\n kind: 'cite',\n id: token.id,\n keys: [...token.keys],\n label: formatCiteLabel(token.keys, document.references, {\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n }),\n };\n }\n if (token.kind === 'ref') {\n return {\n kind: 'ref',\n id: token.id,\n keys: [...token.keys],\n refCommand: token.refCommand,\n label: formatRefLabel(token.keys, document, token.refCommand, {\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n }),\n };\n }\n const island = {\n id: token.id,\n tex: mathTex(token, equationSide),\n display: token.display,\n output,\n editable: token.editable,\n };\n islands.push(island);\n return { kind: 'math', ...island };\n });\n}\n\nfunction textBlockPreview(\n block: TextBlock2,\n islands: MathIsland2[],\n output: Document2MathOutput,\n equationSide: EditorSide,\n document: Document2Node,\n previewOptions: Document2PreviewOptions,\n): PreviewBlock2 {\n const inlines = previewInlines(block.field, islands, output, equationSide, document, previewOptions);\n if (block.command === '\\\\section') {\n return { kind: 'heading', id: block.id, level: 1, inlines };\n }\n if (block.command === '\\\\subsection') {\n return { kind: 'heading', id: block.id, level: 2, inlines };\n }\n if (block.command === '\\\\subsubsection') {\n return { kind: 'heading', id: block.id, level: 3, inlines };\n }\n return {\n kind: 'paragraph',\n id: block.id,\n inlines,\n ...(block.centered ? { centered: true } : {}),\n };\n}\n\nfunction floatNumberLabel(\n document: Document2Node,\n key: string | undefined,\n previewOptions: Document2PreviewOptions,\n): string | undefined {\n if (!key || key.trim().length === 0) {\n return undefined;\n }\n const hit = labelNumberMap(document).get(key.trim());\n if (!hit || (hit.kind !== 'fig' && hit.kind !== 'tab')) {\n return undefined;\n }\n return formatFloatCaptionTitle(hit.kind, hit.number, {\n uiLocale: previewOptions.uiLocale ?? 'ar',\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n });\n}\n\nfunction blockPreview(\n block: Document2Block,\n islands: MathIsland2[],\n output: Document2MathOutput,\n equationSide: EditorSide,\n document: Document2Node,\n previewOptions: Document2PreviewOptions,\n): PreviewBlock2 {\n if (block.kind === 'textBlock') {\n return textBlockPreview(block, islands, output, equationSide, document, previewOptions);\n }\n if (block.kind === 'list') {\n return {\n kind: 'list',\n id: block.id,\n ordered: block.command === '\\\\begin{enumerate}',\n items: block.items.map((item) => ({\n id: item.id,\n inlines: previewInlines(item.field, islands, output, equationSide, document, previewOptions),\n blocks: item.blocks.map((child) => blockPreview(child, islands, output, equationSide, document, previewOptions)),\n })),\n };\n }\n if (block.kind === 'table') {\n const label = block.labelEnabled ? block.label.trim() : '';\n return {\n kind: 'table',\n id: block.id,\n rows: block.rows.map((row) => row.map((cell) => previewInlines(cell, islands, output, equationSide, document, previewOptions))),\n ...(block.captionEnabled && block.caption.trim().length > 0 ? { caption: block.caption.trim() } : {}),\n ...(label.length > 0 ? { label, numberLabel: floatNumberLabel(document, label, previewOptions) } : {}),\n };\n }\n if (block.kind === 'image') {\n const label = block.labelEnabled ? block.label.trim() : '';\n return {\n kind: 'image',\n id: block.id,\n src: block.value,\n ...(block.assetId !== undefined ? { assetId: block.assetId } : {}),\n options: block.options,\n ...(block.captionEnabled && block.caption.trim().length > 0 ? { caption: block.caption.trim() } : {}),\n ...(label.length > 0 ? { label, numberLabel: floatNumberLabel(document, label, previewOptions) } : {}),\n };\n }\n if (block.kind === 'bibliography') {\n return {\n kind: 'bibliography',\n id: block.id,\n items: document.references.map((reference, index) => ({\n id: reference.id,\n numberLabel: formatBibliographyNumber(index + 1, {\n documentDirection: previewOptions.documentDirection,\n digitForm: previewOptions.digitForm,\n }),\n key: reference.key,\n authors: reference.authors,\n title: reference.title,\n year: reference.year,\n url: reference.url,\n venue: reference.venue,\n fieldSeparator: reference.fieldSeparator,\n })),\n };\n }\n return { kind: 'omit', id: block.id };\n}\n\nfunction articleChromePreview(\n document: Document2Node,\n uiLocale: ButexUiLocale,\n previewOptions: Document2PreviewOptions,\n): PreviewBlock2[] {\n const meta = document.meta ?? emptyDocument2Meta();\n const blocks: PreviewBlock2[] = [\n { kind: 'basmala', id: 'article-basmala', text: BUTEX_BASMALA, tex: butexBasmalaDisplayTex() },\n ];\n if (document2HasMaketitle(meta)) {\n blocks.push({\n kind: 'titleBlock',\n id: 'article-title',\n ...(meta.title.trim().length > 0 ? { title: meta.title.trim() } : {}),\n ...(meta.authors.trim().length > 0 ? { authors: meta.authors.trim() } : {}),\n date: formatHijriDate(meta.date, {\n locale: uiLocale,\n digitForm: previewOptions.digitForm,\n }),\n });\n }\n if (document2HasAbstract(meta)) {\n blocks.push({ kind: 'abstract', id: 'article-abstract', text: meta.abstract.trim() });\n }\n return blocks;\n}\n\nexport function document2Preview(\n document: Document2Node,\n output: Document2MathOutput = 'svg',\n equationSide: EditorSide = 'arabic',\n previewOptions: Document2PreviewOptions = {},\n): Document2Preview {\n const mathIslands: MathIsland2[] = [];\n const options: Document2PreviewOptions = {\n documentDirection: previewOptions.documentDirection ?? 'rtl',\n digitForm:\n previewOptions.digitForm ??\n (previewOptions.documentDirection === 'ltr' ? 'western' : 'arabicIndic'),\n uiLocale: previewOptions.uiLocale ?? 'ar',\n };\n const body = document.blocks.map((block) => blockPreview(block, mathIslands, output, equationSide, document, options));\n return {\n blocks: [\n ...articleChromePreview(document, options.uiLocale ?? 'ar', options),\n ...body,\n { kind: 'closing', id: 'article-closing', text: BUTEX_CLOSING_HAMDALA, tex: butexDiwaniDisplayTex(BUTEX_CLOSING_HAMDALA) },\n ],\n mathIslands,\n };\n}\n"],"mappings":";AAAA,IAAI,SAAS;AAEN,SAAS,YAAY,QAAwB;AAClD,QAAM,KAAK,GAAG,MAAM,IAAI,OAAO,MAAM,CAAC;AACtC,YAAU;AACV,SAAO;AACT;;;ACJA,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,QA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A,MACzE,MAAM,gBAAgB,KAAK,MAAM;AAAA,QAC/B,QAAQ;AAAA,QACR,WAAW,eAAe;AAAA,MAC5B,CAAC;AAAA,IACH,CAAC;AAAA,EACH;AACA,MAAI,qBAAqB,IAAI,GAAG;AAC9B,WAAO,KAAK,EAAE,MAAM,YAAY,IAAI,oBAAoB,MAAM,KAAK,SAAS,KAAK,EAAE,CAAC;AAAA,EACtF;AACA,SAAO;AACT;AAEO,SAAS,iBACdA,WACA,SAA8B,OAC9B,eAA2B,UAC3B,iBAA0C,CAAC,GACzB;AAClB,QAAM,cAA6B,CAAC;AACpC,QAAM,UAAmC;AAAA,IACvC,mBAAmB,eAAe,qBAAqB;AAAA,IACvD,WACE,eAAe,cACd,eAAe,sBAAsB,QAAQ,YAAY;AAAA,IAC5D,UAAU,eAAe,YAAY;AAAA,EACvC;AACA,QAAM,OAAOA,UAAS,OAAO,IAAI,CAAC,UAAU,aAAa,OAAO,aAAa,QAAQ,cAAcA,WAAU,OAAO,CAAC;AACrH,SAAO;AAAA,IACL,QAAQ;AAAA,MACN,GAAG,qBAAqBA,WAAU,QAAQ,YAAY,MAAM,OAAO;AAAA,MACnE,GAAG;AAAA,MACH,EAAE,MAAM,WAAW,IAAI,mBAAmB,MAAM,uBAAuB,KAAK,sBAAsB,qBAAqB,EAAE;AAAA,IAC3H;AAAA,IACA;AAAA,EACF;AACF;","names":["value","node","parseChain","document","isObject","nextId","scripts","document","block","reference","document","document"]}
|