flm_core/stdlib/backends/html/mathjax.rs
1//! The formula renderer's script definition, `flm.html.mathjax`: what this
2//! backend ships so that a page can typeset the mathematics it carries, and
3//! what a host that does not trust the authors of that mathematics has to do
4//! for itself.
5//!
6//! The **formula renderer** is MathJax, a script that runs in the reader's
7//! browser, reads LaTeX out of the page and typesets it. This backend does not
8//! translate passthrough mathematics (a formula whose source the
9//! [`math-passthrough`](crate::math_passthrough) feature
10//! carries unread): it writes the author's LaTeX into the page and lets
11//! that script do the rest ([the emitter](super::emit)). The definition
12//! [`mathjax_script`] is how a page gets the script: its **configuration**
13//! first, then the **address** its program is loaded from ([`MATHJAX_LOADER`]),
14//! in that order, because the program reads the configuration when it runs. A
15//! host decides how both parts arrive, through the render option
16//! [`definitions`](super::HtmlRenderOptions::definitions).
17//!
18//! # What the shipped configuration says
19//!
20//! It holds what this backend's own output needs, and nothing that restricts
21//! what an author may write inside a formula.
22//!
23//! - It loads the extension that lets a formula carry HTML of the page
24//! inside it (`[tex]/texhtml`), adds that extension's package to the
25//! packages that apply, and switches its reading on (`allowTexHTML`). That
26//! mechanism is how content inside a formula (the argument of a text
27//! command, and the invisible point a reference leads to) reaches the
28//! reader.
29//! - It declares the delimiters this backend writes — `\(…\)`, `\[…\]` and
30//! environments (`processEnvironments`) — and no others, so a stray `$` in a
31//! formula is not read as a delimiter.
32//! - It tells the renderer to set the words of a formula in the page's own
33//! text font rather than in its mathematical font (`mtextInheritFont`). The
34//! words a document writes inside a formula are page text and this backend
35//! writes them into the page itself; the words the renderer sets for itself
36//! — the text of an equation's tag — then look like them.
37//! - It turns the renderer's own equation numbering and cross-reference
38//! handling off (`tags: 'none'`, `processRefs: false`): a document's numbers
39//! and references are this library's to resolve.
40//! - It typesets only inside elements carrying the class of a formula
41//! (`startup.elements`), so a backslash in code and a `\(` in
42//! prose are left alone.
43//!
44//! After the configuration object, the same part carries one short listener for
45//! clicks on the page. MathJax takes the address off every link inside its
46//! output, keeping it in a `data-mjx-href` attribute, and follows only the
47//! links it made itself; a reference written in text inside a formula is a
48//! link this backend wrote, so without the listener a click on it
49//! would do nothing. The listener follows such a link — a plain primary click,
50//! no modifier key held, on one of this backend's links inside a typeset
51//! formula — and leaves every other click on the page alone. Reaching such a
52//! link from the keyboard is not repaired by it: MathJax makes the whole
53//! content of a formula unfocusable when it attaches the description it speaks
54//! to a screen reader.
55//!
56//! The same part keeps the formulas typeset while a script of the page brings
57//! it up to date in place, under the two conventions for a page updated in
58//! place that the rendering guide states
59//! ([`REGION_UPDATED_EVENT`](super::page::REGION_UPDATED_EVENT),
60//! [`ORIGINAL_HTML_ATTRIBUTE`](super::page::ORIGINAL_HTML_ATTRIBUTE)). Just
61//! before the renderer typesets a formula, it records the HTML inside the
62//! formula's element in that attribute, so that an update leaves the typeset
63//! formula alone while its HTML stays the same; and when a region of the page
64//! was updated, it typesets the formulas of that region that carry no record —
65//! the new ones and those whose HTML changed. When a script of the page shows a
66//! copy of part of the page
67//! ([`CONTENT_COPIED_EVENT`](super::page::CONTENT_COPIED_EVENT)), it typesets
68//! the formulas of the copy that are not typeset: those that carry no record,
69//! and those that were not typeset yet when they were copied, which first get
70//! back the HTML of their record. A host that replaces this part with a
71//! configuration of its own and updates its pages in place, or shows copies of
72//! them, keeps these lines.
73//!
74//! # Mathematics is not inspected
75//!
76//! **FLM does not look inside a mathematics region**, by design and for now.
77//! It keeps no list of allowed symbols, it does not check whether a document
78//! defines a command there, and it hands the characters the author typed to
79//! the renderer unchanged. The intended solution is a mathematics parser
80//! of FLM's own, which does not exist yet; until it does, an author who writes
81//! mathematics is trusted with what the renderer makes of it.
82//!
83//! That is a statement about the *content* of a formula. The emitter still
84//! escapes its own `<tex-html>` mechanism in what it writes inside a formula
85//! ([the emitter](super::emit)).
86//!
87//! # Rendering mathematics written by authors the host does not trust
88//!
89//! A host that renders mathematics written by authors it does not trust
90//! replaces the shipped configuration with the hardened configuration below,
91//! through the [`definitions`](super::HtmlRenderOptions::definitions) option.
92//! This section is the whole of what such a host needs.
93//!
94//! This library does not make such mathematics safe by itself, for three
95//! reasons. Mathematics is not inspected, as above. The `<tex-html>` mechanism
96//! is on, because it is how content inside a formula reaches the page, and
97//! MathJax's own documentation warns that it must not be used "in settings
98//! where your readers can enter expressions that are shown to other users",
99//! since the HTML inside a formula is not filtered in any way. And a document
100//! that *defines a macro* inside mathematics can build that tag out of parts
101//! that never appear in the source, which no rewriting of the source can catch.
102//! No locked configuration is shipped either, because a library that does not
103//! inspect mathematics cannot promise that the result is safe. This holds for
104//! the mathematics that
105//! [`math-passthrough`](crate::math_passthrough) writes,
106//! which is what this script typesets.
107//!
108//! Every fact below was checked against **MathJax 4.1.3** — the packages, the
109//! defaults and the filter's behavior are that version's. A host should check
110//! them again against the version it ships.
111//!
112//! ## What reaches the page when nothing is added
113//!
114//! Under the packages MathJax loads by default (`base`, `ams`, `newcommand`,
115//! `textmacros`, `noundefined`, `require`, `autoload`, `configmacros`), a
116//! formula can put this into the page, command by command:
117//!
118//! | what a document writes inside a formula | what arrives in the page | what closes it |
119//! |---|---|---|
120//! | `\href{javascript:…}{x}` | an `<a href>` carrying that address | emptying the `html` autoload entry; the safe component's address filter |
121//! | `\cssId{…}{x}` | an `id`, which can shadow an identifier this backend wrote | the same, or the safe component's `cssIDs` |
122//! | `\class{…}{x}` | a class, which pulls in the host page's own styling | the same, or the safe component's `classes` |
123//! | `\style{background: url(…)}{x}` | a `style` whose declaration makes the browser fetch a file | the same, or the safe component's `styles` |
124//! | `\data{foo}{bar}{x}` | a `data-foo` attribute | the same, or the safe component's `dataPattern` |
125//! | `\require{html}…` | all of the above again, regardless of what was removed | removing the `require` package |
126//! | `\bbox[background: url(…)]{x}` | a `style` that fetches a file | the safe component's `styles` |
127//! | `\mmlToken{mi}[href=…][id=…][class=…][style=…]{x}` | an `<a href>`, an `id`, a class and a fetching `style` | **only** the safe component |
128//!
129//! `\mmlToken` decides the shape of the recipe: it is defined in the `base`
130//! package, which MathJax does not let a configuration remove, so
131//! no list of removed packages closes it. The safe component is what does.
132//!
133//! ## The recipe
134//!
135//! **The safe component.** `ui/safe` is a component MathJax ships that walks
136//! the mathematics it has built and filters the attributes a document can
137//! reach from inside a formula:
138//! addresses, class names, element identifiers and style declarations. Four
139//! settings say how far it goes, and the values below are the ones this
140//! library's own measurements back:
141//!
142//! - `URLs: 'safe'` — keeps `http:`, `https:` and `file:` and refuses
143//! `javascript:` and `data:`.
144//! - `classes: 'none'`, `cssIDs: 'none'` — drops a class or an identifier
145//! written from inside a formula altogether. No FLM construct needs an
146//! author to set either.
147//! - `styles: 'none'` — drops every style declaration written from inside a
148//! formula. MathJax's milder `styles: 'safe'` keeps the declarations on a
149//! list of its own, and **that is not enough**: `cursor` is on that list and
150//! `http:` is a safe address, so `\bbox[cursor: url(http://…)]{x}` survives
151//! it and makes the reader's browser fetch a file the document named.
152//!
153//! With `'none'`, the *style argument* of `\bbox` and of `\enclose` has no
154//! effect, and nothing reports it: `\bbox[border: 2px solid red]{x}` is set
155//! with no border. Their color forms keep working —
156//! `\bbox[yellow]{x}`, `\color{red}`, `\enclose{circle}[mathbackground="yellow"]`
157//! — because a color is set as an attribute of the mathematics rather than as
158//! a style declaration.
159//!
160//! **Three commands still put a style declaration into the page, and none of
161//! them makes the browser fetch anything.**
162//! `\enclose{…}[mathbackground="url(…)"]`, `\colorbox{url(…)}` and
163//! `\color{url(…)}` each put `background-color: url(…)` or `color: url(…)`
164//! into the page. Those two properties take a color and not an image, so the
165//! declaration is invalid and a browser discards it: nothing is fetched. A
166//! second declaration cannot be added beside the color either —
167//! `\colorbox{red; cursor: url(http://…)}{x}` is refused with
168//! `Invalid color value`.
169//!
170//! **The safe component does not filter the HTML a `<tex-html>` carries.** That
171//! HTML is not part of the mathematics the component walks, which is why this
172//! backend's own identifiers, classes and `data-flm-*` attributes survive it
173//! untouched — and equally why it does not stop the macros defined inside
174//! mathematics (below). The two
175//! must be closed separately.
176//!
177//! **The packages.** Remove `html` (it is what gives `\href`, `\class`,
178//! `\style`, `\cssId` and `\data`) **and** empty its autoload entry
179//! (`autoload: {html: []}`): removing it from the package list alone changes
180//! nothing, because autoloading — MathJax's habit of fetching a package the
181//! first time one of its commands is used — puts it straight back. Remove
182//! `require` too, or `\require{html}` loads it back by hand. Without
183//! `require`, a document cannot use the packages MathJax ships but neither
184//! loads by default nor autoloads, which are reachable only through
185//! `\require`:
186//! `physics` is one, measured — under this recipe
187//! `\require{physics}\dv{f}{x}` comes out as the command names in red instead
188//! of a derivative. A host that wants such a package lists it in the package
189//! list of its own configuration instead.
190//!
191//! **Macros defined inside mathematics.** Stopping them takes two settings
192//! together: remove the
193//! `newcommand` package **and** empty its autoload entry
194//! (`autoload: {newcommand: []}`). The first alone changes nothing, for the
195//! same autoloading reason. Together they remove `\newcommand`,
196//! `\renewcommand`, `\newenvironment`, `\renewenvironment`, `\def` and `\let`
197//! from mathematics: an everyday `\newcommand{\Reals}{\mathbb{R}}` in a
198//! formula then comes out as the command name in red. Because authors lose
199//! these commands, the choice belongs to the host and not to this library.
200//!
201//! ## The hardened configuration, whole
202//!
203//! ```js
204//! /* flm.html.mathjax */
205//! window.MathJax = {
206//! loader: {load: ['[tex]/texhtml', 'ui/safe']},
207//! tex: {
208//! packages: {'[+]': ['texhtml'], '[-]': ['html', 'require', 'newcommand']},
209//! autoload: {html: [], newcommand: []},
210//! allowTexHTML: true,
211//! inlineMath: [['\\(', '\\)']],
212//! displayMath: [['\\[', '\\]']],
213//! processEnvironments: true,
214//! processRefs: false,
215//! tags: 'none'
216//! },
217//! chtml: {mtextInheritFont: true},
218//! options: {
219//! safeOptions: {
220//! allow: {URLs: 'safe', classes: 'none', cssIDs: 'none', styles: 'none'}
221//! }
222//! },
223//! startup: {elements: ['.flm-pres-math--passthrough']}
224//! };
225//! document.addEventListener('click', function (event) {
226//! if (event.defaultPrevented || event.button !== 0 ||
227//! event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) { return; }
228//! var from = event.target;
229//! var link = from && from.closest &&
230//! from.closest('mjx-container mjx-html a.flm-pres-link[data-mjx-href]');
231//! if (!link) { return; }
232//! event.preventDefault();
233//! window.location.href = link.getAttribute('data-mjx-href');
234//! });
235//! ```
236//!
237//! The class in `startup.elements` is the class of the presentation element
238//! that holds passthrough mathematics
239//! ([`class_of_element`](super::names::class_of_element) of
240//! `flm.pres.math-passthrough`), and the class in the listener's selector is the
241//! class of the link element (the same function of `flm.pres.link`); a host
242//! that copies this block copies both classes with it.
243//!
244//! The listener comes after the object here; a host writing its own
245//! configuration copies it unchanged if it wants a link inside the text of a
246//! formula to be followed when a reader clicks it.
247//!
248//! ## How a host delivers it
249//!
250//! An override replaces the *whole* content of the definition, so a host
251//! writes both parts: its configuration, and then the address the program is
252//! loaded from.
253//!
254//! ```rust
255//! use std::collections::BTreeMap;
256//!
257//! use flm_core::core::registry::DefContent;
258//! use flm_core::model::names::Name;
259//! use flm_core::stdlib::backends::html::{
260//! DefinitionOverride, HtmlRenderOptions, MATHJAX_LOADER,
261//! };
262//!
263//! // The host's own configuration, hardened as above (abbreviated here).
264//! let hardened = "window.MathJax = {/* … */};";
265//!
266//! let mut definitions = BTreeMap::new();
267//! definitions.insert(
268//! Name::from("flm.html.mathjax"),
269//! DefinitionOverride::Parts(vec![
270//! DefContent::Inline(String::from(hardened)),
271//! DefContent::Url(String::from(MATHJAX_LOADER)),
272//! ]),
273//! );
274//!
275//! let options = HtmlRenderOptions { definitions, ..HtmlRenderOptions::default() };
276//! assert_eq!(options.definitions.len(), 1);
277//! ```
278
279use crate::core::registry::{DefContent, ScriptDef};
280use crate::model::names::Name;
281
282use super::conventions::SCRIPT_MATHJAX;
283
284/// The address the formula renderer's program is loaded from by default:
285/// MathJax version 4, from the content delivery network its own documentation
286/// gives, pinned to the major version so that corrections arrive without an
287/// edit here.
288///
289/// A host that will not load from a network replaces it through the
290/// [`definitions`](super::HtmlRenderOptions::definitions) option; this library
291/// never fetches the address itself.
292pub const MATHJAX_LOADER: &str = "https://cdn.jsdelivr.net/npm/mathjax@4/tex-chtml.js";
293
294/// The configuration of the formula renderer, read from `mathjax-config.js`:
295/// the first part of the script
296/// definition [`mathjax_script`] registers.
297///
298/// See the [module documentation](self) for what it says, for what this
299/// library does and does not promise about mathematics, and for the
300/// configuration a host writes instead when it does not trust the authors of
301/// the mathematics it renders.
302const MATHJAX_CONFIGURATION: &str = include_str!("mathjax-config.js");
303
304/// Returns the script definition of the formula renderer, `flm.html.mathjax`: its
305/// configuration and then the address its program is loaded from, in that
306/// order, because the program reads the configuration when it runs.
307///
308/// The emitter requires this definition at the first passthrough formula it
309/// writes in a tree, so a document with no passthrough mathematics loads
310/// nothing.
311///
312/// What the configuration says, and what a host that renders mathematics
313/// written by authors it does not trust has to write instead, is the [module
314/// documentation](self).
315pub fn mathjax_script() -> ScriptDef {
316 ScriptDef {
317 id: Name::from(SCRIPT_MATHJAX),
318 content: vec![
319 DefContent::Inline(String::from(MATHJAX_CONFIGURATION)),
320 DefContent::Url(String::from(MATHJAX_LOADER)),
321 ],
322 docs: String::from(
323 "the formula renderer: its configuration, then the address its program is loaded \
324 from",
325 ),
326 }
327}
328
329#[cfg(test)]
330mod tests {
331 use super::*;
332 use crate::stdlib::backends::html::page::{
333 CONTENT_COPIED_EVENT, ORIGINAL_HTML_ATTRIBUTE, REGION_UPDATED_EVENT,
334 };
335
336 #[test]
337 fn the_configuration_follows_the_contract_for_a_page_updated_in_place() {
338 assert!(MATHJAX_CONFIGURATION.contains(&format!("'{REGION_UPDATED_EVENT}'")));
339 assert!(MATHJAX_CONFIGURATION.contains(&format!("'{CONTENT_COPIED_EVENT}'")));
340 assert!(MATHJAX_CONFIGURATION.contains(&format!("'{ORIGINAL_HTML_ATTRIBUTE}'")));
341 assert!(!MATHJAX_CONFIGURATION.to_ascii_lowercase().contains("</script"));
342 }
343}