elisp-react APImain

elisp-react API

The complete API of elisp-react, for an implementer, human or coding agent, who knows React and Emacs Lisp and has never seen elisp-react. It describes lisp/react.el (protocol 3), lisp/react-testing.el and js/elisp-react.js as they are on main. Where this document and the source disagree, the source is right.

Every elisp block below was run as it stands in a batch Emacs with react.el and react-testing.el loaded. A comment ;; => VALUE after a form is the printed value that form returned; ;; error: SYMBOL means the form signals that error. Blocks that use self without defining it were run with self bound to a mounted component instance that renders (div () (input (:ref "field"))).

Words used throughout:

Contents#

Index#

Every public symbol of react.el and react-testing.el (names without --). Struct accessors are generated by cl-defstruct.

NameKindPurpose
jsxmacroBuild an element from markup without backquote; alias of react-jsx.
react-allfunctionAwaitable of the values of several awaitables, in order.
react-asyncmacroRun a body that can wait with react-await; returns a task.
react-async-errorerrorSignalled at a react-await whose operation failed.
react-awaitmacroInside react-async: wait for an awaitable and return its value.
react-cancelfunctionForget a request and tell the page to stop it.
react-changed-pfunctionWhether two plists differ in given keys (for :should-update).
react-clear-timerfunctionAlias of react-cancel, for timers.
react-componentsymbol propertyWhere react-define-component stores a definition.
react-contextfunctionRead the value a react-provide above hands down.
react-define-componentfunctionDefine a component.
react-dispatch-eventfunctionHost entry point: run a DOM event's listener and flush.
react-effectfunctionIn a render: run a function after the render when its deps changed.
react-event-sourcefunctionServer-sent events (EventSource).
react-fetchfunctionThe browser's fetch, with callbacks.
react-fetch-asyncfunctionAwaitable of a fetch response.
react-flushfunctionFinish pending renders; return the DOM operations.
react-focusfunctionFocus the element with a :ref.
react-force-updatefunctionRender one instance again, past :should-update.
react-form-valuefunctionOne field of a submitted form.
react-form-valuesfunctionEvery value of a field of a submitted form.
react-handlerfunction, struct typeA listener prop with options the page applies at once (preventDefault, keys...).
react-handler-functionstruct accessorThe function of a react-handler.
react-handler-optionsstruct accessorThe options plist of a react-handler.
react-handler-pstruct predicateWhether a value is a react-handler.
react-history-gofunctionMove in the browser history.
react-host-callfunctionAsk the host (or a page command) for something answered later.
react-host-repliesfunctionHost entry point: several answers at once, then one flush.
react-host-replyfunctionHost entry point: one answer to a request, then flush.
react-host-tellfunctionTell the host (or a page command) something; no answer.
react-htmlfunctionWhat is mounted at a selector, as HTML text.
react-html-tagsconstantHTML tags that jsx recognises.
react-inspectfunctionMounted components with props and state.
react-intlfunctionHave the browser's Intl format numbers, dates, lists...
react-intl-asyncfunctionAwaitable of react-intl.
react-invalidatefunctionMark query keys stale and reload them.
react-invokefunctionCall a method of a DOM node (focus, showModal, play...).
react-jsxmacroSame as jsx.
react-listen-pagefunctionListen to events of window or document.
react-localefunctionThe visitor's languages and time zone.
react-locationfunctionThe page's address.
react-location-unwatchfunctionStop a location watcher.
react-location-watchfunctionCall a function when the address changes.
react-make-reffunctionA ref a component hands to a component below.
react-measurefunctionMeasure a DOM node's box and scrolling.
react-media-queryfunctionFollow a CSS media query.
react-mountfunctionRender an element into a page element.
react-navigatefunctionGo to a URL (history push or replace).
react-node-idfunctionThe number by which the page knows a ref's DOM node.
react-observe-visiblefunctionWhether a node is in view (IntersectionObserver).
react-page-callfunctionHost entry point for window.elispReact.send.
react-plist-withfunctionA copy of a plist with keys set.
react-propsfunctionProps of an instance.
react-providefunctionAn element that hands a value to everything below it.
react-providercomponentThe built-in component behind react-provide.
react-queryfunctionData loaded by key, shared and cached.
react-query-datafunctionRead a query key without subscribing.
react-query-setfunctionPut data under a query key.
react-racefunctionAwaitable of the first answer of several.
react-reffunctionThe mounted element with a :ref.
react-refreshfunctionRender every instance (of a type) again.
react-render-errorerrorA :render failed and no boundary caught it.
react-render-to-stringfunctionAn element as HTML text, without a page (server side).
react-resetfunctionForget everything mounted (tests).
react-response-bytesfunctionA base64 response body as a unibyte string.
react-response-headerfunctionOne header of a response.
react-response-jsonfunctionA response body parsed as JSON.
react-rootfunctionThe component instance mounted at a selector.
react-set-intervalfunctionCall a function every N ms.
react-set-metafunctionSet or remove a <meta>.
react-set-propertyfunctionSet a DOM property of a node.
react-set-statefunctionChange state and schedule a render.
react-set-timeoutfunctionCall a function once after N ms.
react-set-titlefunctionSet the document's title.
react-shallow-equalfunctionWhether two plists have the same values (one level).
react-sleepfunctionAwaitable that finishes after N ms.
react-statefunctionState of an instance.
react-storage-getfunctionRead a value from the page's localStorage.
react-storage-removefunctionRemove a key from localStorage.
react-storage-setfunctionStore a Lisp value in localStorage.
react-storage-unwatchfunctionStop a storage watcher.
react-storage-watchfunctionHear when another tab changes a key.
react-svg-tagsconstantSVG tags that jsx recognises.
react-taskstruct typeWhat react-async returns.
react-task-cancelfunctionStop a task.
react-task-iteratorstruct accessorThe generator of a task (internal use).
react-task-pstruct predicateWhether a value is a task.
react-task-requeststruct accessorThe request the task waits for, or nil.
react-task-statestruct accessornil (running), done, failed or cancelled.
react-task-valuestruct accessorThe body's value, or the failure's message.
react-task-waitingstruct accessorThose who await the task (internal use).
react-testing-answerfunctionTest kit: answer the oldest request of a command.
react-testing-answer-fetchfunctionTest kit: answer the oldest fetch.
react-testing-attributefunctionTest kit: an attribute of a node.
react-testing-clickfunctionTest kit: click a node.
react-testing-dispatchfunctionTest kit: dispatch any event, bubbling.
react-testing-findfunctionTest kit: the first matching element.
react-testing-find-allfunctionTest kit: all matching elements.
react-testing-flushfunctionTest kit: apply pending operations to the fake page.
react-testing-htmlfunctionTest kit: the fake page as HTML.
react-testing-inputfunctionTest kit: type into an input.
react-testing-invokedvariableTest kit: methods called on nodes.
react-testing-keyfunctionTest kit: press a key.
react-testing-loadfunctionTest kit: start afresh and load a file.
react-testing-locationfunctionTest kit: change the page's address.
react-testing-propertyfunctionTest kit: a DOM property Lisp set.
react-testing-renderfunctionTest kit: start afresh and render an element.
react-testing-requestsvariableTest kit: requests waiting for an answer.
react-testing-resetfunctionTest kit: forget everything.
react-testing-storagefunctionTest kit: put a value in the page's storage.
react-testing-submitfunctionTest kit: submit a form with its fields.
react-testing-textfunctionTest kit: the text of a node.
react-testing-time-passesfunctionTest kit: fire waiting timers.
react-testing-toldvariableTest kit: notices Lisp sent to the page.
react-unmountfunctionTake down what is mounted at a selector.
react-url-queryfunctionA query string as an alist.
react-websocketfunctionOpen a WebSocket.
react-websocket-sendfunctionSend text on a WebSocket.

The host's JavaScript API (start(), window.elispReact, window.elispReactCommands, document events) is in Page setup.

Mental model#

What runs where#

Page lifecycle#

  1. The module elisp-react.js runs after the document is parsed. If the document has at least one <script type="text/emacs-lisp"> and <html> has no data-elisp-react-manual attribute, it calls start() and sets window.elispReact = { ready }.
  2. The host imports the wasmacs client from the wasmacs site and starts Emacs. In parallel it fetches the text of every Lisp script (a src with cache: "no-store", or the inline text), react.el, and the compiled-code manifest if one is named.
  3. It loads react.el, then checks react--protocol against its own (3). A mismatch stops the start.
  4. It writes every page script whose file name matches ^[\w.+-]+\.el$ to /tmp/elisp-react/lib/ and adds that directory to load-path.
  5. It hands Lisp the page's stored values (localStorage), its address and the visitor's locale.
  6. It loads the page's scripts one by one, in document order. Each is byte-compiled in Emacs (or taken from the cache or the manifest) and loaded. A file that does not compile (an error, not a warning) is evaluated from source instead, so that the error shown is the program's own.
  7. It calls react-flush and applies the operations: the first screen appears. Then it resolves ready and fires elisp-react:ready on document.

react-mount in a script renders at once (step 6). The DOM operations wait until step 7; :did-mount functions and effects run there too.

Compiled code cache. The byte code of each file is kept in localStorage under elisp-react:compiled:URL (sessionStorage with cache: "session"). It is found again under a SHA-256 hash of Emacs's version, the hash of the file loaded before it, and its source: byte code holds the expansions of the macros it used, so a change in react.el or in any file compiles that file and every file after it again. Where crypto.subtle is missing (a page served over plain HTTP from a host other than localhost), nothing is kept and every start compiles. elisp-react:compiled-by:PAGE lists the files each page loaded; code no page loads any more is removed.

Compiling ahead of time. node tools/compile.mjs -o compiled.json app.el ... (the page's files, in page order; it needs a wasmacs checkout next to the repository, or $WASMACS) writes a manifest of byte code under the same hashes. <meta name="elisp-react:compiled" content="compiled.json"> names it; files whose hash is in it are not compiled in the page.

Render cycle#

Lifecycle order#

(defvar order-log nil)
(react-define-component 'Child
  :initial-state (lambda (props) (push (list 'child-initial (plist-get props :n)) order-log) nil)
  :did-mount (lambda (self) (push (list 'child-did-mount (react-props self :n)) order-log))
  :did-update (lambda (self _props _state) (push (list 'child-did-update (react-props self :n)) order-log))
  :will-unmount (lambda (self) (push (list 'child-will-unmount (react-props self :n)) order-log))
  :render (lambda (self)
            (push (list 'child-render (react-props self :n)) order-log)
            (react-effect self 'effect (react-props self :n)
              (lambda () (push 'child-effect order-log) (lambda () (push 'child-cleanup order-log))))
            (jsx (li (react-props self :n)))))
(react-define-component 'Parent
  :initial-state (lambda (_props) (push 'parent-initial order-log) (list :n 1))
  :did-mount (lambda (_self) (push 'parent-did-mount order-log))
  :did-update (lambda (_self _props _state) (push 'parent-did-update order-log))
  :will-unmount (lambda (_self) (push 'parent-will-unmount order-log))
  :render (lambda (self)
            (push 'parent-render order-log)
            (jsx (ul (Child (:n (react-state self :n)))))))

(react-mount (jsx (Parent)) "#app")
(reverse order-log)
;; => (parent-initial parent-render (child-initial 1) (child-render 1))
(setq order-log nil)
(react-flush)
(reverse order-log)
;; => ((child-did-mount 1) parent-did-mount child-effect)
(setq order-log nil)
(react-set-state (react-root "#app") :n 2)
(reverse order-log)
;; => nil
(react-flush)
(reverse order-log)
;; => (parent-render (child-render 2) parent-did-update (child-did-update 2) child-cleanup child-effect)
(setq order-log nil)
(react-unmount "#app")
(reverse order-log)
;; => (parent-will-unmount (child-will-unmount 2) child-cleanup)

Page setup#

HTML#

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>App</title>
  </head>
  <body>
    <div id="app">Loading Emacs…</div>
    <script type="text/emacs-lisp" src="helpers.el"></script>
    <script type="text/emacs-lisp" src="app.el"></script>
    <script type="module" src="https://modeverv.github.io/elisp-react/js/elisp-react.js"></script>
  </body>
</html>

Settings#

A page that starts by itself reads <meta name="elisp-react:...">. A page that starts by hand passes the options to start().

<meta name>start() optionValueDefault
elisp-react:wasmacswasmacsURL of the wasmacs site. ?wasmacs=URL in the page's address overrides the meta (not the option), for localhost, 127.0.0.1 and [::1] only.https://modeverv.github.io/wasmacs/
elisp-react:timeouttimeoutMilliseconds Lisp may take to answer one call; 0: no limit. Past it the host stops Emacs and reports the error symbol timeout; the page must be reloaded.30000
elisp-react:boot-timeoutbootTimeoutMilliseconds the start may take; 0: no limit. Past it the start fails with boot-timeout.120000
elisp-react:compiledcompiledURL of a manifest from tools/compile.mjs.none
elisp-react:cachecacheWhere compiled code is kept. Meta: local, session, none (any other value: local). Option: true or "local", "session", false.local
elisp-react:storagestorageThe name under which react-storage-set keeps values: keys are elisp-react:NAME:KEY.the page's path without a final index.html (/app/ for /app/ and /app/index.html; /app/other.html for that page)
location"browser": the page's address. "memory": one the host keeps, starting at /, with its own history; it follows hash links itself."browser", or "memory" in an about:srcdoc frame
libraryURL of react.el.../lisp/react.el next to elisp-react.js
sources[{ name, text }] to load instead of the page's scripts.the page's scripts
fetchA function used instead of fetch for react-fetch.fetch
signalAn AbortSignal that aborts the start (error symbol aborted).none
onProgress({ phase, url, bytes, from }) => void: phases "build id", "download", "emacs", then "lisp" per file (from: "manifest", "kept", "compiled", "evaluated").none

A timeout or boot-timeout meta that is not a number of 0 or more counts as absent.

Starting by hand#

<html lang="en" data-elisp-react-manual>
  <body>
    <div id="app">Loading Emacs…</div>
    <script type="text/emacs-lisp" src="app.el"></script>
    <script type="module">
      import { start } from "https://modeverv.github.io/elisp-react/js/elisp-react.js";
      window.elispReact = { ready: start({ timeout: 10000 }) };
      window.elispReact.ready.then((app) => Object.assign(window.elispReact, app), console.error);
    </script>
  </body>
</html>

start(options) returns a promise of the object below. Started by hand, nothing fires elisp-react:ready, nothing is copied onto window.elispReact, and a failed start is not shown on the page: the caller handles all three.

Property
emacsThe eval service: emacs.eval(source), emacs.call(name, ...args), emacs.terminate().
version, bootMs, cached, filesEmacs's version; start time; whether nothing was downloaded; "on demand" or "all".
load(name, text)Compile and load changed source in the running page, then flush. Resolves with { file, log, from }, plus renderError when the source loaded but the render failed. A good render removes the error box. Compiled code of load is never kept.
send(name, ...args)Call the Lisp function name with args (JSON) and render what it changed. Resolves (with no value) when the page is updated; rejects after a Lisp error or when Emacs was stopped.
run(text)Evaluate forms as they are (not compiled), then flush.
location{ current, navigate(url, replace), go(delta) }: the address, for tools around the page.
library, compileLogs{ file, log, from } for react.el; [{ name, file, log, from }] for the page's files. log is what the byte compiler said ("" if nothing).
domThe host's DOM applier (internal).

A page that starts by itself has window.elispReact = { ready } at once; when the start succeeds, the properties above are copied onto window.elispReact.

Document events#

Event on documentdetail
elisp-react:readyThe object above (automatic start only).
elisp-react:errorAn Error; symbol is the Lisp error symbol, timeout, boot-timeout or aborted when known.
elisp-react:progress{ phase, url, bytes, from }.
elisp-react:location{ href, pathname, search, hash } after the address changed.

Errors on the page#

If elisp-react.js itself cannot load, nothing runs and nothing is shown. A page can guard against that with an ordinary script that checks window.elispReact after a delay.

Versions and the protocol#

Elements#

Plain list form#

An element is Lisp data.

FormRenders
"text", 42, 1.5A text node. Numbers are written with (format "%s" N).
(TAG PROPS CHILD...)A DOM element. TAG is a symbol; its name is the DOM tag, as written (div, input, svg, x-widget).
(TAG CHILD...)The same without props.
(NAME PROPS CHILD...)A component, when NAME was defined with react-define-component (the symbol has the property react-component). Otherwise NAME is a DOM tag.
(<> CHILD...), (<> (:key K) CHILD...)A fragment: its children without an element around them.

The second item of an element is its props when it is nil or a list whose first item is a keyword. So (p "x"), (p () "x") and (p nil "x") are the same.

Children, after the props:

(react-mount `(ul () (li () "a") nil ,(mapcar (lambda (n) `(li () ,n)) '(1 2)) t) "#app")
(react-html "#app")
;; => "<ul><li>a</li><li>1</li><li>2</li></ul>"
(react-mount '(p () loading) "#other")
;; error: error

With backquote, every computed part needs a comma, handlers too: (button (:on-click ,(lambda (_event) ...))). Without the comma the prop is a quoted list, which does not close over self. The jsx macro needs no commas.

A Capitalized tag that is no component (a misspelled name, or a component whose file loads later) renders as an unknown element and prints a message, once: react: VideoCrad is not a defined component; .... A custom element is a name with a hyphen: (x-widget (:size "2")), or (X-widget ...) in jsx.

jsx#

(jsx FORM) and (react-jsx FORM) are one macro. It expands markup into the list calls that build the plain list form; nothing is looked up at expansion time.

  1. FORM must be markup: a list whose first item is <>, a member of react-html-tags or react-svg-tags, or a symbol whose name starts with A–Z. Otherwise expansion signals jsx: FORM does not start with an HTML tag, a Capitalized component name or <>.
  2. In markup (TAG X ...), X is the props when it is ()/nil or a list whose first item is a keyword. Props must be written out as KEY VALUE pairs with keyword keys, or expansion signals jsx: X is not a prop name in FORM. A props variable is not possible in jsx; build such an element with list: (list 'button (append '(:class "primary") extra-props) "OK").
  3. Each prop value and each child is read by the same rules: markup becomes an element; anything else is Lisp and is evaluated (a string, a number, a variable, (format ...), (when ...), (mapcar ...)). Its value may be an element, a list of elements, text or nil.
  4. Markup inside such Lisp needs jsx again: (when done (jsx (b "!"))), (mapcar (lambda (item) (jsx (li item))) items).
  5. Only Capitalized names are components. (jsx (div (counter))) calls a function counter. A list that starts with a tag name is always markup: Emacs's function mark, or functions of your own named label, filter, search, time, title, data, text, cannot be called directly inside jsx.
(macroexpand '(jsx (p (:id name) (upcase name))))
;; => (list 'p (list :id name) (upcase name))
(let ((count 3) (items '("x" "y")))
  (jsx (div (:class "box")
         (p (format "Count: %d" count))
         (when (> count 5) (jsx (strong "many")))
         (mapcar (lambda (item) (jsx (li (:key item) item))) items))))
;; => (div (:class "box") (p nil "Count: 3") nil ((li (:key "x") "x") (li (:key "y") "y")))
(macroexpand '(jsx (counter (:start 3))))
;; error: error

With react.el loaded, every tag and react-define-component indent with their first argument (the props) as a distinguished argument.

Fragments#

(<> CHILD...) puts its children where it stands, among its parent's children. A fragment takes no props but :key; anything else signals A fragment takes no props but :key: .... A :render that returns a list of elements returns a fragment of them. On the page a fragment is its children's nodes followed by an empty text node that marks its place.

(react-define-component 'Row        ; a row that opens a second row below it
  :initial-state (lambda (_props) (list :open nil))
  :render
  (lambda (self)
    (jsx (<> (tr (:on-click (lambda (_event) (react-set-state self :open (not (react-state self :open)))))
               (td (react-props self :name)))
             (when (react-state self :open)
               (jsx (tr (:class "detail") (td "more"))))))))
(react-testing-render (jsx (table (tbody (Row (:name "a")) (Row (:name "b"))))))
(react-testing-click (react-testing-find :tag 'tr :text "a"))
(react-testing-html)
;; => "<table><tbody><tr><td>a</td></tr><tr class=\"detail\"><td>more</td></tr><tr><td>b</td></tr></tbody></table>"

Props of DOM elements#

PropEffect
:keyNot rendered. Identifies the child among its siblings (compared with equal).
:refNot rendered. A name (any data, compared with equal; usually a string) under which the component that rendered the element finds its DOM node; or a ref from react-make-ref.
:on-EVENTA listener for the DOM event EVENT: the text after :on-, as it is (:on-click, :on-input, :on-change, :on-submit, :on-keydown, :on-dblclick, :on-pointerdown, :on-close). The value is a function of one argument (the event plist), a react-handler, or nil (no listener).
:valueThe DOM property value. Not a string: written with format; nil: "". Written at every render of the element.
:checkedThe DOM property checked: true unless the value is nil or :false. Written at every render.
:classA string, or a list whose nil items are dropped and the others joined with spaces.
:styleA string, or a plist: (:color "red" :margin-top 4) is "color: red; margin-top: 4px". Numbers get px, except 0, custom properties (:--gap) and unitless properties (opacity, z-index, flex, flex-grow, flex-shrink, order, font-weight, line-height, zoom, column-count, orphans, widows, tab-size, fill-opacity, stroke-opacity, stroke-miterlimit, flood-opacity, stop-opacity, animation-iteration-count, grid-row, grid-column, grid-row-start, grid-row-end, grid-column-start, grid-column-end, aspect-ratio, scale). nil values are left out. Set through CSSOM, so a CSP without 'unsafe-inline' styles allows it.
:inner-htmlHTML text from elsewhere, which the host cleans before it shows it. The element must have no children (A <div> with :inner-html has children too).
:aria-NAMEt is "true", :false is "false", nil removes it.
anything elseAn attribute named after the keyword, as written (:for, :tabindex, :data-id, :viewBox, :stroke-width). A string is used as it is, a number or symbol formatted; t sets it empty (present); nil and :false remove it.
(react-render-to-string
 '(div (:class ("card" nil active) :hidden t :title nil :data-n 3 :aria-pressed :false
        :style (:width 120 :opacity 0.5 :margin 0 :--gap 4))
    (input (:value 42 :disabled nil))))
;; => "<div class=\"card active\" hidden data-n=\"3\" aria-pressed=\"false\" style=\"width: 120px; opacity: 0.5; margin: 0; --gap: 4\"><input value=\"42\"></div>"

Controlled inputs. :value (or :checked) with a listener that sets state is a controlled input. The host does not write a node's value while a newer input or change event of that node is still waiting for Lisp, so fast typing is not lost. A <select> gets its :value after its options exist.

The host's attribute policy. The host drops attribute names starting with on (any case) and srcdoc, and javascript:/vbscript: URLs in href, src, action, formaction, data, xlink:href, background, cite, codebase, longdesc, manifest, profile, usemap (and script URLs in SVG animation values). It removes the attribute and warns in the console.

:inner-html cleaning. The HTML is parsed in an inert <template>. script, style, frames, object, embed, template, noscript, link, meta, base, form controls, svg, math, media, canvas, dialog and slot are dropped with their content. Elements outside a abbr b bdi bdo blockquote br caption cite code col colgroup dd del details dfn div dl dt em figcaption figure h1–h6 hr i img ins kbd li mark ol p picture pre q rp rt ruby s samp small source span strong sub summary sup table tbody td tfoot th thead time tr u ul var wbr are replaced by their children. Attributes other than href src srcset sizes alt title class width height colspan rowspan lang dir start reversed type datetime cite open loading headers scope, and script URLs, are removed; <a href> gets rel="noopener noreferrer". Text in a text child is always text: "&amp;" shows as &amp;.

Events#

A listener gets one argument, a plist the host builds from the DOM event:

KeyValue
:typeThe event type, "click".
:valueevent.target.value when it is a string (input, textarea, select, button), else nil.
:checkedevent.target.checked when it is a boolean (checkbox, radio), else nil.
:key, :codeevent.key, event.code of a keyboard event, else nil.
:alt, :ctrl, :meta, :shiftt or nil.
:repeatt for an auto-repeated key.
:composingt while an input method is still composing (an Enter that confirms a conversion).
:buttonThe mouse button number (0 is the main one), else nil.
:x, :yclientX, clientY (of the first touch for touch events), else nil.
:targetThe number of the node where the event happened (the nearest node Lisp created at or above event.target).
:filesFor an element that has files (a file input): a vector of (:name :size :type) plists. Else nil.
:formFor a submit event of a form: its fields as a vector of [NAME VALUE] (the submitter included; a file field gives its file name). Read it with react-form-value. Else nil.

The values describe event.target, where the event happened, which may be a child of the element that listens. Each element with a listener has its own DOM listener: a click runs the child's listener, then each listening ancestor's, each as its own call and render. The listener that runs is the one in the element's props at the time of the event (the closure of the latest render).

Default actions. Lisp answers after the browser has acted on the event, too late to prevent it. The host always calls preventDefault for a submit event that Lisp listens to, so a form handled in Lisp never navigates. Everything else that must be decided at once (prevent, stop, filter keys) is declared with react-handler. A <button> inside a <form> submits it; give other buttons :type "button".

(react-define-component 'Search
  :initial-state (lambda (_props) (list :query "" :submitted nil))
  :render
  (lambda (self)
    (jsx (form (:on-submit (lambda (event)
                             (react-set-state self :submitted (react-form-value event "q"))))
           (input (:name "q" :value (react-state self :query)
                   :on-input (lambda (event) (react-set-state self :query (plist-get event :value)))))
           (button "search")
           (p (:class "result") (or (react-state self :submitted) ""))))))
(react-testing-render (jsx (Search)))
(react-testing-input (react-testing-find :tag 'input) "emacs")
(react-testing-submit (react-testing-find :tag 'form))
(react-testing-text (react-testing-find :class "result"))
;; => "emacs"

SVG#

Inside an svg element every element is created in the SVG namespace, also when a component inside renders later; inside foreignObject the children are HTML again. Attribute names are used as written (:viewBox, :stroke-width). jsx knows the tags in react-svg-tags; set is not among them (it is a Lisp function), so write it in the plain list form.

(react-render-to-string (jsx (svg (:viewBox "0 0 10 10" :width 20) (circle (:cx 5 :cy 5 :r 4 :fill "teal")))))
;; => "<svg viewBox=\"0 0 10 10\" width=\"20\"><circle cx=\"5\" cy=\"5\" r=\"4\" fill=\"teal\"></circle></svg>"

Components#

react-define-component#

(react-define-component NAME &rest SPEC) → NAME

Defines the component NAME, a symbol. The definition is stored as the symbol's property react-component; an element (NAME PROPS CHILD...) then renders it. Signals (error "Component NAME has no :render function") when :render is not a function. Defining a name again changes the mounted instances (see Redefinition).

KeyValueWhen
:render(lambda (SELF)) → an element, a list of elements (a fragment), a string, a number, or nil (an empty text node). Required.At every render.
:initial-state(lambda (PROPS)) → the first state, a plist.Once, when the instance is created, before its first render.
:did-mount(lambda (SELF)), or a list of such functions, called in order.Once, at the flush after the first render. Children before parents.
:did-update(lambda (SELF PREVIOUS-PROPS PREVIOUS-STATE)), or a list.After each later render that was not skipped. Parents before children.
:will-unmount(lambda (SELF)), or a list.Before the instance is taken off. Parents before children.
:should-update(lambda (SELF PREVIOUS-PROPS PREVIOUS-STATE)) → nil to skip the render. SELF already has the new props and state; the previous ones are what the last actual render saw.Before each later render.
:puret: render only when a prop or the state changed by react-shallow-equal.Ignored when :should-update is given.
:did-catch(lambda (SELF ERROR)): an error boundary. ERROR is the condition, (SYMBOL . DATA).When the :render of a component below signals.

Other keys are kept in the definition and ignored.

Props. A component gets the element's props plist as written, :key included, plus :children: the element's children, flattened and without nil, when there are any. :ref on a component element is an ordinary prop, not a DOM ref (hand down a react-make-ref instead).

(react-define-component 'Card
  :render (lambda (self)
            (jsx (section (h2 (react-props self :title)) (react-props self :children)))))
(react-testing-render (jsx (Card (:title "T" :key 7) (p "a") nil (p "b"))))
(react-testing-html)
;; => "<section><h2>T</h2><p>a</p><p>b</p></section>"
(react-props (react-root "#app"))
;; => (:title "T" :key 7 :children ((p nil "a") (p nil "b")))

Functions that take SELF: react-props, react-state, react-set-state, react-force-update, react-effect, react-context, react-query, react-ref, react-make-ref, react-focus, react-invoke, react-set-property, react-measure, react-observe-visible. An instance stays valid after it is unmounted, but nothing renders it any more.

Skipping renders#

:pure, react-shallow-equal and react-changed-p compare values this way: strings with string=, numbers with =, everything else with eq. Two closures of the same lambda are the same when the values they captured are the same by that comparison (one level deep), so (Item (:on-pick (lambda (_event) (pick item)))) does not defeat :pure while item is the same object. A closure that captures a list built in the render does. State has to be replaced, never modified in place, for this to work.

(defvar item-renders 0)
(react-define-component 'Item
  :pure t
  :render (lambda (self) (setq item-renders (1+ item-renders)) (format "%s" (react-props self :n))))
(react-define-component 'Items
  :initial-state (lambda (_props) (list :clicks 0 :data (list 1 2)))
  :render (lambda (self)
            (let ((data (react-state self :data)))
              (jsx (div (Item (:n 1 :data data :on-pick (lambda (_event) data)))
                        (Item (:n 2 :data (list 1 2))))))))
(react-testing-render (jsx (Items)))
(setq item-renders 0)
(react-set-state (react-root "#app") :clicks 1)
(react-testing-flush)
item-renders
;; => 1

The first Item skipped its render; the second got a new list and rendered.

Error boundaries#

An error in a :render is caught by the nearest component above it (in render order) that has :did-catch. The failed component renders an empty text node, and the boundary usually sets state to show something else. Without a boundary the error becomes react-render-error, whose message names the component and those above it. Boundaries do not catch errors in event handlers, :did-mount, :did-update, effects, timers, or the Not an element error of a bad element that a render returned.

(react-define-component 'Broken :render (lambda (_self) (car 1)))
(react-define-component 'Boundary
  :initial-state (lambda (_props) (list :error nil))
  :did-catch (lambda (self error) (react-set-state self :error error))
  :render (lambda (self)
            (if (react-state self :error)
                (jsx (p (:class "error") (format "Failed: %s" (error-message-string (react-state self :error)))))
              (react-props self :children))))
(react-testing-render (jsx (Boundary (div (Broken)))))
(react-testing-html)
;; => "<p class=\"error\">Failed: Wrong type argument: listp, 1</p>"
(react-testing-render (jsx (div (Broken))))
;; error: react-render-error

When a flush fails, what was still waiting (dirty components, :did-mount and :did-update calls, effects) stays queued and runs at the next flush.

react-render-error#

The error symbol (message "Error while rendering") signalled when a :render fails and no :did-catch above catches it. Its data is one string, "MESSAGE, in Card < Page < App": the original message and the component path. (cadr err) is that string; error-message-string gives Error while rendering: "...". A failure in the first render signals it out of react-mount itself.

Redefinition#

Evaluating react-define-component for a name that is already defined gives every mounted instance of it the new definition and renders it again at the next flush, past :should-update, with the state it has. :initial-state and :did-mount do not run again, and a timer the old :did-mount started still calls the old closure. This is how the host's load(name, text) changes a running page (elisp-studio uses it).

Loading a file again also re-evaluates its other forms: defun replaces the function, defconst and setq set the new value, and defvar keeps the value the variable already has. Keep application data in defvar (it survives) and constants in defconst.

Reference#

Mounting#

react-mount#

(react-mount ELEMENT SELECTOR) → SELECTOR

Renders ELEMENT into the page element that the CSS SELECTOR names; the host replaces that element's children with it. Rendering runs at once; the DOM operations go out at the end of the call. Mounting again at the same SELECTOR updates what is there by reconciliation (component state survives where type and key match). Several selectors can each have a root. A selector that matches nothing in the page is an error of the host.

(react-mount (jsx (p "hello")) "#app")
;; => "#app"
(react-flush)
;; => [["create" 1 "p"] ["text" 2 "hello"] ["insert" 1 2 nil] ["mount" "#app" 1]]

react-unmount#

(react-unmount SELECTOR) → nil

Takes down what react-mount rendered into SELECTOR: runs :will-unmount and effect cleanups, removes the nodes. Nothing there: does nothing.

react-root#

(react-root SELECTOR) → an instance or nil

The component instance that react-mount rendered into SELECTOR; nil when nothing is there or the root is not a component. For code outside the components.

react-render-to-string#

(react-render-to-string ELEMENT) → a string

ELEMENT as HTML text, without a page: a server's first screen, in a native Emacs too. Components render with their initial state; :did-mount, :did-update and effects do not run; nothing stays mounted and no operation is queued. Text and attribute values are escaped (& < >, and " in attributes). Listeners, :key, :ref and :inner-html are left out; :value and :checked become attributes; void elements have no end tag. The page's react-mount later replaces this HTML (there is no hydration).

(react-render-to-string (jsx (p "Tom & <Jerry>" (input (:value "x" :checked t)) (br))))
;; => "<p>Tom &amp; &lt;Jerry&gt;<input value=\"x\" checked><br></p>"

react-html#

(react-html SELECTOR) → a string or nil

What is mounted at SELECTOR, as HTML text, from Lisp's own tree, after running pending renders (it does not take the queued operations). Escaped like react-render-to-string. For tests and debugging.

react-inspect#

(react-inspect &optional SELECTOR) → a list

The mounted components at SELECTOR (or everywhere), parents first: (:component NAME :depth N :props PROPS :state STATE) each.

(react-testing-render (jsx (Card (:title "x"))))
(react-inspect "#app")
;; => ((:component Card :depth 0 :props (:title "x") :state nil))

react-reset#

(react-reset) → nil

Forgets everything mounted and pending: roots, queued operations, dirty instances, requests, the copy of the storage, storage and location watchers, queries, the address and the locale. No :will-unmount runs. Component definitions stay. For tests (react-testing-reset calls it).

Constants#

react-html-tags#

The HTML elements that jsx reads as markup (111 symbols): a abbr address area article aside audio b bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u ul var video wbr. Any other lowercase tag is written in the plain list form, or Capitalized with a hyphen for a custom element.

react-svg-tags#

The SVG elements that jsx reads as markup (38 symbols): svg g defs symbol use path circle ellipse line polyline polygon rect text tspan textPath linearGradient radialGradient stop clipPath mask pattern marker image foreignObject animate animateMotion animateTransform desc filter feBlend feColorMatrix feComposite feFlood feGaussianBlur feMerge feMergeNode feOffset feDropShadow. Not set, a Lisp function.

(list (length react-html-tags) (length react-svg-tags) (memq 'set react-svg-tags))
;; => (111 38 nil)

Host entry points#

The host calls these; applications rarely do. Each returns the vector of DOM operations of react-flush.

react-flush#

(react-flush) → a vector of operations

Finishes pending renders (and the :did-mount, :did-update and effect calls they cause) and returns the operations since the last call, oldest first. Each operation is a vector:

OperationMeaning
["create" ID TAG], ["create" ID TAG "svg"]Create an element (in the SVG namespace).
["text" ID STRING], ["set-text" ID STRING]Create a text node; change its text.
["attr" ID NAME VALUE]Set an attribute; t is empty, nil removes it.
["prop" ID NAME VALUE]Set a DOM property (value, checked, those of react-set-property).
["listen" ID EVENT OPTIONS], ["unlisten" ID EVENT]Add or remove the host's listener; OPTIONS from react-handler, or nil.
["insert" PARENT-ID ID BEFORE-ID], ["before" ID BEFORE-ID]Put a node into a parent (before BEFORE-ID, or at the end when nil); put a node in front of another (fragments).
["replace" OLD-ID ID], ["remove" ID]Replace a node; remove a node.
["mount" SELECTOR ID...]The root's nodes go into the page element.
["html" ID HTML]Cleaned HTML into the node (:inner-html).
["invoke" ID METHOD ARG...]Call a method of the node.
["call" REQUEST COMMAND ARGUMENT]Do something and answer later with react-host-reply.
["tell" COMMAND ARGUMENT]Do something; no answer.
["cancel" REQUEST]Stop a request.

react-dispatch-event#

(react-dispatch-event DOM-ID NAME EVENT) → operations

The node DOM-ID received the DOM event NAME ("click") with the plist EVENT: runs the current :on-NAME listener of that element, if any, and flushes.

react-host-reply#

(react-host-reply REQUEST OK VALUE) → operations

The page's answer to REQUEST: calls the function waiting for it with OK (non-nil for success) and VALUE, then flushes. A request that is not kept (react-host-call without KEEP) is forgotten after its first answer; an unknown or cancelled request is ignored.

react-host-replies#

(react-host-replies REPLIES) → operations

REPLIES is a vector of [REQUEST OK VALUE]: the answers that arrived while Lisp was busy. Runs every waiting function, then renders once. An error in one does not stop the others; the first error is signalled after all ran, and what they changed renders at the next flush.

react-page-call#

(react-page-call NAME ARGS) → operations

What window.elispReact.send(NAME, ...ARGS) calls: (apply (intern NAME) ARGS), where ARGS is a vector of JSON values, then flushes. See Calling page JavaScript.

State#

react-props#

(react-props SELF &optional KEY) → the props plist, or the value of KEY

react-state#

(react-state SELF &optional KEY) → the state plist, or the value of KEY

State is whatever :initial-state returned, changed only by react-set-state.

react-set-state#

(react-set-state SELF &rest CHANGES) → nil

CHANGES is a plist merged into the state, (react-set-state self :count 1 :label "x"), or one function that gets the current state and returns that plist. A new plist is installed at once; the old one is not modified. A mounted instance renders at the end of the call; several calls cause one render. An unmounted instance gets the new state and does not render.

(react-define-component 'Tally
  :initial-state (lambda (_props) (list :count 0 :label "n"))
  :render (lambda (self) (format "%s=%d" (react-state self :label) (react-state self :count))))
(react-testing-render (jsx (Tally)))
(let ((self (react-root "#app")))
  (react-set-state self :count 1)
  (react-set-state self (lambda (state) (list :count (+ 10 (plist-get state :count)))))
  (list (react-state self) (react-testing-html)))
;; => ((:count 11 :label "n") "n=0")
(react-testing-flush)
(react-testing-html)
;; => "n=11"

react-plist-with#

(react-plist-with PLIST &rest CHANGES) → a new plist

PLIST with the keys of CHANGES set; PLIST is not modified. New keys go at the end. The way to change a record kept in state.

(let ((todo '(:id 1 :text "a" :done nil)))
  (list (react-plist-with todo :done t :tag "x") todo))
;; => ((:id 1 :text "a" :done t :tag "x") (:id 1 :text "a" :done nil))

react-force-update#

(react-force-update SELF) → nil

Renders SELF again at the end of this call, whatever :should-update says: for a component that reads something other than its props and state.

react-refresh#

(react-refresh &optional TYPE) → nil

Renders every mounted instance (of the component TYPE, a symbol) again at the end of this call, past :should-update: after global data changed.

react-shallow-equal#

(react-shallow-equal A B) → non-nil when the plists A and B have the same keys with the same values, compared as in Skipping renders.

(list (react-shallow-equal '(:a "x" :b 1) '(:a "x" :b 1)) (react-shallow-equal '(:a (1)) '(:a (1))))
;; => (t nil)

react-changed-p#

(react-changed-p NEW OLD &rest KEYS) → non-nil when the plists differ in one of KEYS

For :should-update, to compare only the props the render uses. Leaving a function prop out is safe when handlers read it at the time of the event, (funcall (react-props self :on-change) ...), because a skipped component still receives its new props.

(react-define-component 'TodoRow
  :should-update (lambda (self previous-props previous-state)
                   (or (not (eq (react-state self) previous-state))
                       (react-changed-p (react-props self) previous-props :todo)))
  :render (lambda (self) (jsx (li (plist-get (react-props self :todo) :text)))))
(react-changed-p '(:a 1 :b (x)) '(:a 1 :b (x)) :a)
;; => nil

Effects#

react-effect#

(react-effect SELF KEY DEPS FUNCTION) → nil

Called in a render of SELF. KEY (a symbol, compared with eq) names the effect among the instance's effects. FUNCTION takes no arguments and runs after the render (after :did-mount and :did-update) when DEPS (any data) is not equal to the deps of its last run; it always runs the first time. If FUNCTION returns a function, that one is the cleanup: it runs before FUNCTION runs again, and when the instance is taken off. DEPS nil runs once. A render that :should-update skipped does not reach its effects; they keep their last run. Stateful logic becomes an ordinary function that several components call:

(defun my-use-interval (self ms function)
  "Call FUNCTION every MS milliseconds while SELF is mounted."
  (react-effect self 'interval ms
    (lambda ()
      (let ((timer (react-set-interval ms function)))
        (lambda () (react-clear-timer timer))))))

(react-define-component 'Ticker
  :initial-state (lambda (_props) (list :ticks 0))
  :render (lambda (self)
            (my-use-interval self 1000 (lambda () (react-set-state self :ticks (1+ (react-state self :ticks)))))
            (format "%d" (react-state self :ticks))))
(react-testing-render (jsx (Ticker)))
(react-testing-time-passes)
(react-testing-time-passes)
(list (react-testing-html) (mapcar #'cadr react-testing-requests))
;; => ("2" ("interval"))
(react-unmount "#app")
(react-testing-flush)
react-testing-requests
;; => nil

Context#

react-provide#

(react-provide KEY VALUE CHILD) → an element

An element that renders CHILD (an element, or a list of elements) and hands VALUE to every component below it under KEY (any data, compared with equal), however deep. It is (react-provider (:context KEY :value VALUE) CHILD).

react-context#

(react-context SELF KEY &optional DEFAULT) → the value

The VALUE of the nearest react-provide of KEY above SELF, or DEFAULT when there is none. SELF becomes a reader: when the provider renders with a different value (strings and numbers by value, other data by identity), every reader renders again, even below a component that skipped its render. "Above" follows render order: the component whose render produced a component is its parent.

(react-define-component 'Label
  :pure t
  :render (lambda (self) (jsx (span (react-context self 'language "none")))))
(react-define-component 'Middle :pure t :render (lambda (_self) (jsx (p (Label)))))
(react-define-component 'LanguageApp
  :initial-state (lambda (_props) (list :language "ja"))
  :render (lambda (self)
            (jsx (div (react-provide 'language (react-state self :language) (jsx (Middle)))
                      (Label)))))
(react-testing-render (jsx (LanguageApp)))
(react-testing-html)
;; => "<div><p><span>ja</span></p><span>none</span></div>"
(react-set-state (react-root "#app") :language "en")
(react-testing-flush)
(react-testing-html)
;; => "<div><p><span>en</span></p><span>none</span></div>"

react-provider#

The built-in component that react-provide returns an element of. Its props are :context and :value. Use react-provide rather than writing it.

Refs and DOM nodes#

A :ref names a DOM element for the component that rendered it. The functions below act on it after the render's DOM operations, because they emit their operation when they are called and the host applies operations in order. Call them in :did-mount, :did-update, an effect, or a handler for an element that exists already. Each does nothing (returns nil) when the component has no element with that ref.

react-ref#

(react-ref SELF NAME) → the mounted element, or nil

The element SELF rendered with :ref NAME (compared with equal). The value is opaque: it is good for react-node-id and for react-fetch's :file and :form.

react-make-ref#

(react-make-ref SELF NAME) → a ref

A ref that SELF hands to a component below, which puts it on an element: (input (:ref (react-props self :input-ref))). That element is then SELF's ref NAME, as if SELF had rendered it.

(react-define-component 'Field
  :render (lambda (self) (jsx (input (:ref (react-props self :input-ref))))))
(react-define-component 'SearchForm
  :did-mount (lambda (self) (react-focus self "search"))
  :render (lambda (self) (jsx (form (Field (:input-ref (react-make-ref self "search")))))))
(react-testing-render (jsx (SearchForm)))
react-testing-invoked
;; => ((2 "focus"))

react-node-id#

(react-node-id REF) → an integer, or nil

The number by which the page knows the DOM node of REF (a value of react-ref): a page command gets the node with node(id).

react-focus#

(react-focus SELF NAME) → nil

Gives the keyboard focus to the element with :ref NAME. Same as (react-invoke SELF NAME "focus").

(react-focus self "field")
(react-flush)
;; => [["invoke" 2 "focus"]]

react-invoke#

(react-invoke SELF NAME METHOD &rest ARGS) → nil

Calls METHOD with ARGS (JSON values) on the DOM node with :ref NAME. METHOD is one of "focus", "blur", "select", "click", "scrollIntoView", "scrollTo", "scrollBy", "setSelectionRange", "showModal", "show", "close", "requestSubmit", "reset", "reportValidity", "setCustomValidity", "play", "pause", "load", "requestFullscreen", "showPicker"; any other is an error of the host. A method the node does not have, or a promise it rejects (play without a gesture), is a console warning.

(react-invoke self "field" "setSelectionRange" 0 3)
(react-invoke self "field" "scrollIntoView" '(:block "center"))
(react-flush)
;; => [["invoke" 2 "setSelectionRange" 0 3] ["invoke" 2 "scrollIntoView" (:block "center")]]

A <dialog> opened with (react-invoke self "dialog" "showModal") is a real modal: the page behind is inert, the focus goes to its :autofocus field, Escape closes it and fires :on-close.

react-set-property#

(react-set-property SELF NAME PROPERTY VALUE) → nil

Sets the DOM property PROPERTY of the node with :ref NAME. PROPERTY is one of "indeterminate", "selectedIndex", "open", "muted", "volume", "currentTime", "playbackRate", "loop", "scrollTop", "scrollLeft" (value and checked are props); the host ignores others with a warning. t and nil are true and false.

react-measure#

(react-measure SELF NAME FUNCTION) → a request, or nil

Measures the node with :ref NAME once the DOM operations are applied and calls FUNCTION with a plist: (:x :y :width :height) of its box, (:scrollTop :scrollLeft :scrollWidth :scrollHeight :clientWidth :clientHeight), and for audio and video (:currentTime :duration :paused).

react-observe-visible#

(react-observe-visible SELF NAME FUNCTION &rest OPTIONS) → a request, or nil

Calls FUNCTION with VISIBLE (t or nil) and RATIO (a number) when the node with :ref NAME comes into view or leaves it (an IntersectionObserver), and once at the start. OPTIONS: :margin "200px" (counted as visible that much earlier), :threshold 0.5. Use it after the element is on the page (:did-mount); react-cancel stops it.

Events and forms#

react-handler#

(react-handler FUNCTION &rest OPTIONS) → a react-handler

A listener prop that the host acts on before Lisp answers. FUNCTION gets the event as a plain function prop would. OPTIONS:

OptionEffect in the page
:keys LISTOnly events whose event.key is in LIST ('("Enter" "/")) reach Lisp, and only those are prevented or stopped.
:self tOnly events of this element, not of its children.
:prevent tpreventDefault: no link followed, no key typed, no scrolling.
:stop tstopPropagation: listeners of the parents do not hear it.
:capture tListen in the capture phase.
:passive tA passive listener.
:throttle MSAt most one event per MS milliseconds; the last event of a burst is sent at the end.

Other options are ignored. A listener whose options change is listened to again; a new function with the same options costs no DOM operation. The struct has the accessors react-handler-function and react-handler-options and the predicate react-handler-p.

(defun my-link (href text)
  "A link that changes the address without loading a page."
  (jsx (a (:href href :on-click (react-handler (lambda (_event) (react-navigate href)) :prevent t))
         text)))
(react-mount (my-link "/about" "About") "#app")
(react-flush)
;; => [["create" 1 "a"] ["attr" 1 "href" "/about"] ["listen" 1 "click" (:prevent t)] ["text" 2 "About"] ["insert" 1 2 nil] ["mount" "#app" 1]]
(react-handler-options (react-handler #'ignore :keys '("Enter") :prevent t))
;; => (:keys ("Enter") :prevent t)

react-form-value#

(react-form-value EVENT NAME) → a string, or nil

The value of the field NAME in the form a submit EVENT sent (the first one of that name). A file field gives the file's name.

react-form-values#

(react-form-values EVENT NAME) → a list of strings

Every value of the field NAME: checkboxes, a multiple select.

(let ((event '(:type "submit" :form [["q" "括弧"] ["tag" "a"] ["tag" "b"]])))
  (list (react-form-value event "q") (react-form-values event "tag") (react-form-value event "none")))
;; => ("括弧" ("a" "b") nil)

Timers#

react-set-timeout#

(react-set-timeout MILLISECONDS FUNCTION) → a request

Calls FUNCTION, with no arguments, once after MILLISECONDS.

react-set-interval#

(react-set-interval MILLISECONDS FUNCTION) → a request

Calls FUNCTION, with no arguments, every MILLISECONDS until it is cancelled. Start it in :did-mount (or an effect) and cancel it in :will-unmount (or the effect's cleanup).

react-clear-timer#

(react-clear-timer REQUEST) → nil. An alias of react-cancel.

react-cancel#

(react-cancel REQUEST) → nil

Forgets REQUEST (its function will not be called) and tells the host to stop it: clear a timer, abort a fetch, close a connection, remove a page listener or observer, or call the cancel function a page command returned. REQUEST nil does nothing.

(let ((timer (react-set-timeout 500 #'ignore)))
  (react-clear-timer timer)
  (react-flush))
;; => [["call" 1 "timeout" 500] ["cancel" 1]]

Network#

react-fetch#

(react-fetch URL &rest OPTIONS) → a request

Requests URL with the browser's fetch. OPTIONS:

Option
:method STRING"GET" by default.
:headers PLIST(:content-type "application/json" :authorization "Bearer ...").
:body STRINGThe body.
:file REFInstead of :body: the first file chosen in the file input REF ((react-ref SELF NAME)), sent as it is, whatever its size. No file chosen: :catch gets "No file is chosen".
:form LISTInstead of :body: NAME VALUE ... sent as multipart/form-data; a VALUE is a string, or a ref to a file input whose files are sent.
:as 'base64The body arrives as :base64 instead of :text (bytes; see react-response-bytes). Without it the body is decoded as UTF-8.
:credentials, :cache, :redirect, :mode, :keepalive, :priority, :referrerPolicyPassed to fetch as they are (a symbol value as its name): :credentials "include" sends cookies to another origin.
:then FUNCTION(RESPONSE): the plist (:status 200 :ok t :url "..." :redirected nil :headers (:content-type "..." ...) :text "..."). An HTTP error status is a response too, with :ok nil. Header names are lower case.
:catch FUNCTION(MESSAGE): there was no response at all (offline, refused, CORS). Without :catch the message is printed with message.

Cookies of the page's own origin go with every request (the browser's defaults). react-cancel aborts it.

(react-fetch "/api/notes" :method "POST" :headers '(:content-type "application/json") :body "{\"text\":\"x\"}"
             :then (lambda (response) (message "%s" (plist-get response :status))))
;; => 1
(react-flush)
;; => [["call" 1 "fetch" (:url "/api/notes" :method "POST" :headers (:content-type "application/json") :body "{\"text\":\"x\"}")]]

react-response-json#

(react-response-json RESPONSE) → Lisp data

The :text of RESPONSE parsed as JSON: objects are plists, arrays vectors, null and false are nil, true is t. Invalid JSON signals json-parse-error.

(react-response-json '(:text "{\"a\":null,\"b\":false,\"c\":true,\"d\":[1,{\"e\":\"x\"}]}"))
;; => (:a nil :b nil :c t :d [1 (:e "x")])

react-response-header#

(react-response-header RESPONSE NAME) → a string, or nil

The header NAME (any case) of RESPONSE. Headers that CORS does not expose to the page are not there.

react-response-bytes#

(react-response-bytes RESPONSE) → a unibyte string

The body of a response fetched with :as 'base64.

react-websocket#

(react-websocket URL &rest OPTIONS) → a connection (a request)

Opens a WebSocket to URL (ws:, wss:, or a path of this site, made ws:/wss:). OPTIONS: :on-open (), :on-message (TEXT) for each message (nil for a binary one), :on-close (CODE REASON), :on-error (), :protocols LIST. Nothing comes after the close. react-cancel closes it: do that in :will-unmount. Every message is one call to Lisp and one render.

react-websocket-send#

(react-websocket-send CONNECTION TEXT) → nil

Sends TEXT once the operations of this call are applied. On a connection that is not open the host prints a warning in the console and sends nothing.

react-event-source#

(react-event-source URL &rest OPTIONS) → a connection

Server-sent events of URL. OPTIONS: :on-message (EVENT) with the plist (:type "message" :data "..." :id ...), :events LIST (more event names to receive; their :type is the name), :on-open (), :on-error () (the connection broke; the browser reconnects by itself), :on-close (nil nil) (the browser gave up), :with-credentials t. react-cancel closes it.

Storage#

The page's localStorage, holding any printable Lisp data. The host hands Lisp a copy at the start, so reading is immediate; writing changes the copy and tells the page. Keys are strings. Values are printed with prin1 and read back with read: lists, strings, numbers, symbols, vectors; not buffers or other objects that do not read back.

react-storage-get#

(react-storage-get KEY &optional DEFAULT) → the value, or DEFAULT

DEFAULT also when the value was stored with a MAX-AGE that has passed.

react-storage-set#

(react-storage-set KEY VALUE &optional MAX-AGE) → VALUE

Stores VALUE under KEY, replacing what is there, also what another tab stored meanwhile. A value whose printed text is unchanged is not written again. With MAX-AGE (seconds) the value is forgotten that long after: react-storage-get no longer returns it, and a later start removes it.

(react-storage-set "todos" '((:id 1 :text "a")))
;; => ((:id 1 :text "a"))
(react-storage-get "todos")
;; => ((:id 1 :text "a"))
(react-flush)
;; => [["tell" "storage-set" (:key "todos" :value "((:id 1 :text \"a\"))")]]
(react-storage-get "missing" 'none)
;; => none

react-storage-remove#

(react-storage-remove KEY) → nil

react-storage-watch#

(react-storage-watch KEY FUNCTION) → a handle

Calls FUNCTION with the new value when another tab of the page changes KEY (nil when it removed it). Lisp's copy already has the new value. Merge before writing when tabs share a list, or set state to render again.

react-storage-unwatch#

(react-storage-unwatch HANDLE) → nil

Stops the watcher HANDLE (in :will-unmount).

Query cache#

Data that components load, kept by key outside the components: components that ask for one key share one request and one result, a component that comes back shows the data at once, and a key loads again when it is stale or invalidated. Keys are never evicted.

react-query#

(react-query SELF KEY LOADER &rest OPTIONS) → (:status STATUS :data DATA :error ERROR :fetching BOOL)

Called in a render. KEY is any data compared with equal, such as ("videos" "home"). LOADER is a function of no arguments that returns a function of (RESOLVE REJECT): (lambda () (react-fetch-async "/videos.json")). A task (react-async) is not accepted there. STATUS is loading (no data yet), success or error; :data is the last successful data and stays while the key loads again (:fetching t); :error is the message of the last failure. The first time SELF asks for KEY, the key loads when it is older than :stale-ms (OPTIONS, default 0: always). Later renders of SELF only read. SELF renders again whenever the key's data or status changes, :pure or not. A failed background load of a key that had data keeps success, with :error set.

(react-define-component 'Videos
  :render (lambda (self)
            (let ((query (react-query self '("videos" "home")
                                      (lambda () (react-fetch-async "/videos.json"))
                                      :stale-ms 60000)))
              (pcase (plist-get query :status)
                ('loading (jsx (p "Loading…")))
                ('error (jsx (p (:class "error") (plist-get query :error))))
                (_ (jsx (ul (mapcar (lambda (title) (jsx (li (:key title) title)))
                                    (react-response-json (plist-get query :data))))))))))
(react-testing-render (jsx (Videos)))
(react-testing-html)
;; => "<p>Loading…</p>"
(react-testing-answer-fetch 200 "[\"a\",\"b\"]")
(react-testing-html)
;; => "<ul><li>a</li><li>b</li></ul>"

react-invalidate#

(react-invalidate PREFIX) → nil

Makes every key that is PREFIX, or a list that starts with the list PREFIX, stale. Answers on their way are dropped; keys that mounted components read load again at once (their old data stays meanwhile). If that reload fails, the status is error, with the old :data still there.

react-query-set#

(react-query-set KEY DATA) → DATA

Puts DATA under KEY as if it had loaded (an optimistic update, or the answer of a request that changed it). Components that read it render again.

react-query-data#

(react-query-data KEY) → the data, or nil

Reads KEY without subscribing to it.

Address and history#

react-location#

(react-location &optional PART) → (:href :pathname :search :hash), or one PART

The page's address, known from the start, so a render can read it. In the host's "memory" mode :href is the path, query and hash only. Reading it does not subscribe: a component re-renders on a change only through a watcher.

react-location-watch#

(react-location-watch FUNCTION) → a handle

Calls FUNCTION with the new address plist when it changes: Back or Forward, a change of the hash (a link to #...), and react-navigate within the origin.

(react-define-component 'Router
  :render (lambda (self)
            (react-effect self 'location nil
              (lambda ()
                (let ((handle (react-location-watch (lambda (_location) (react-force-update self)))))
                  (lambda () (react-location-unwatch handle)))))
            (pcase (react-location :hash)
              ("#/about" (jsx (h1 "About")))
              (_ (jsx (h1 "Home"))))))
(react-mount (jsx (Router)) "#app")
(react-testing-flush)
(react-testing-location "http://localhost/#/about")
(react-testing-html)
;; => "<h1>About</h1>"

react-location-unwatch#

(react-location-unwatch HANDLE) → nil

react-navigate#

(react-navigate URL &optional REPLACE) → nil

Goes to URL: a new history entry, or with REPLACE the current one changed. Within the page's origin the page stays (pushState/replaceState) and the location watchers run, in a call of their own; another origin is loaded.

react-history-go#

(react-history-go DELTA) → nil

Moves DELTA entries in the history; -1 is Back.

react-url-query#

(react-url-query SEARCH) → an alist

The query string SEARCH (with or without ?) as (("NAME" . "VALUE")...). %XX escapes are read as UTF-8, + is a space; a name without = has the value "".

(react-url-query "?q=%E6%8B%AC+x&page=2&flag")
;; => (("q" . "括 x") ("page" . "2") ("flag" . ""))

react-set-title#

(react-set-title TEXT) → nil

Makes TEXT the document's title.

react-set-meta#

(react-set-meta NAME CONTENT) → nil

Sets the <meta> NAME ("description"; og:..., article:... and the like are property metas) to CONTENT; nil removes it.

(react-navigate "#/watch?v=b")
(react-navigate "/elsewhere" t)
(react-history-go -1)
(react-set-title "Parens")
(react-set-meta "og:title" "A video")
(react-flush)
;; => [["tell" "navigate" (:url "#/watch?v=b" :replace nil)] ["tell" "navigate" (:url "/elsewhere" :replace t)] ["tell" "history-go" (:delta -1)] ["tell" "title" (:text "Parens")] ["tell" "meta" (:name "og:title" :content "A video")]]

Page events#

react-listen-page#

(react-listen-page TARGET EVENT FUNCTION &rest OPTIONS) → a request

Calls FUNCTION at each EVENT ("keydown", "resize", "scroll", "visibilitychange") of TARGET, window or document (a symbol or string). FUNCTION gets (:type :key :width :height :x :y :visibility): the event's type and key, innerWidth/innerHeight, scrollX/scrollY, and "visible" or "hidden". OPTIONS: :keys LIST (only these keys), :prevent t (preventDefault for the events that pass :keys), :throttle MS (at most one call per MS, the last event of a burst kept). react-cancel removes it.

(react-define-component 'Shortcuts
  :initial-state (lambda (_props) (list :listener nil :pressed nil))
  :did-mount (lambda (self)
               (react-set-state self :listener
                 (react-listen-page 'document "keydown"
                                    (lambda (event) (react-set-state self :pressed (plist-get event :key)))
                                    :keys '("/" "Escape") :prevent t)))
  :will-unmount (lambda (self) (react-cancel (react-state self :listener)))
  :render (lambda (self) (format "%s" (or (react-state self :pressed) "-"))))
(react-testing-render (jsx (Shortcuts)))
(react-testing-answer "page-listen" '(:type "keydown" :key "/"))
(react-testing-html)
;; => "/"

react-media-query#

(react-media-query QUERY FUNCTION) → a request

Calls FUNCTION with t or nil, whether the CSS media QUERY ("(prefers-color-scheme: dark)", "(max-width: 600px)") matches: as soon as the page answers, and at each change. react-cancel stops it.

Locale and Intl#

The page's Emacs runs in the C locale: format-time-string writes English names, string-collate-lessp compares code points, and the time zone is UTC unless told otherwise. The browser knows the visitor's; Lisp asks it.

react-locale#

(react-locale &optional PART) → (:languages ["ja" "en-US"] :timeZone "Asia/Tokyo" :offset 540), or one PART

Known from the start. :offset is minutes east of UTC.

react-intl#

(react-intl ITEMS FUNCTION &optional LOCALE) → a request

Has the browser's Intl write ITEMS, then calls FUNCTION with the texts, a list in the same order. LOCALE (a string) defaults to the visitor's languages. An item is a plist; :options are those of the Intl constructor:

ItemText
(:type number :value 1234567 :options (:notation "compact"))"123万" in Japanese
(:type date :value MILLISECONDS-OR-ISO-STRING :options (:dateStyle "medium"))a date
(:type relative :value -3 :unit "day")"3 日前"
(:type plural :value 2)the plural category, "other"
(:type list :value ("a" "b"))"a、b"
(:type sort :value ("b" "a"))a list of the strings, sorted for the locale

The texts arrive later: keep them in state. An unknown :type is an error of the host.

react-intl-async#

(react-intl-async ITEMS &optional LOCALE) → an awaitable whose value is the list of texts

Calling page JavaScript#

What the host does not do, the page's own script can. Lisp calls commands the page registers; the page calls Lisp functions.

<script>
  window.elispReactCommands = {
    // (react-host-call "width" (react-node-id (react-ref self "box")) FUNCTION)
    width(id, { reply, node }) { reply(node(id).getBoundingClientRect().width); },
    // (react-host-call "confirm" "Delete it?" FUNCTION)
    confirm(text, { reply }) { reply(window.confirm(text)); },
    // (react-host-tell "log" "text"): a notice gets (ARGUMENT, { node })
    log(text) { console.log(text); },
  };
  // A Lisp function the script calls; the promise resolves when the page is updated.
  document.addEventListener("elisp-react:ready", () => window.elispReact.send("my-app-resized", innerWidth));
</script>

A command is (ARGUMENT, { reply, fail, node }) => CANCEL: reply(VALUE) answers Lisp (again and again if Lisp kept the request), fail(MESSAGE) answers with a failure and ends the request, node(ID) is the DOM node Lisp knows by ID, and a function it returns is called by react-cancel. The host's own commands take precedence: timeout, interval, fetch, page-listen, measure, intl, media, observe-visible, websocket, event-source; notices navigate, history-go, title, meta, websocket-send, storage-set, storage-remove. Only the object's own properties count. A command that is neither is an error of the host.

react-host-call#

(react-host-call COMMAND ARGUMENT &optional FUNCTION KEEP) → a request

Asks the host to do COMMAND (a string) with ARGUMENT (JSON data). When it answers, FUNCTION is called with OK (non-nil for success) and VALUE. With KEEP, FUNCTION stays for further answers until react-cancel. Without FUNCTION the answer is ignored. The building block of the timer, fetch and page functions above.

(defun my-confirm-async (text)
  "An awaitable whose value is t when the visitor confirms TEXT."
  (lambda (resolve reject)
    (react-host-call "confirm" text
                     (lambda (ok value) (if ok (funcall resolve value) (funcall reject value))))))
(defvar my-confirmed 'unknown)
(react-async (setq my-confirmed (react-await (my-confirm-async "Delete it?"))))
(react-testing-flush)
(react-testing-answer "confirm" t)
;; => "Delete it?"
my-confirmed
;; => t

react-host-tell#

(react-host-tell COMMAND ARGUMENT) → nil

Tells the host, or a page command, to do COMMAND with ARGUMENT; there is no answer. An error the notice throws is a console warning.

From the page to Lisp: window.elispReact.send(NAME, ...ARGS) calls the Lisp function NAME (a string, interned) with ARGS converted from JSON (arrays are vectors, objects plists) through react-page-call, then renders. The function's value is not returned.

(defvar my-width nil)
(defun my-app-resized (width) (setq my-width width))
(react-page-call "my-app-resized" [640])
;; => []
my-width
;; => 640

Async#

Lisp cannot wait: a call from the host runs to its end. react-async writes waiting code top to bottom anyway. It is built on Emacs's generator.el: the body becomes a state machine that stops at each react-await, returns to the page, and goes on when the page answers.

An awaitable is a function of two arguments, RESOLVE and REJECT. It starts something and calls exactly one of them, once, now or later: (funcall RESOLVE VALUE) or (funcall REJECT MESSAGE). Its return value matters only for cancelling: when it is a request (an integer from react-host-call and the functions built on it), react-task-cancel cancels it. A task is accepted wherever an awaitable is, except by react-query.

react-async#

(react-async BODY...) → a task

Runs BODY at once, until its first react-await whose awaitable does not answer at once; the rest runs when the page answers. The task's value is BODY's last value.

react-await#

(react-await AWAITABLE) → the value AWAITABLE resolved with

Only inside react-async (elsewhere: iter-yield used outside a generator). AWAITABLE is a function of (RESOLVE REJECT) or a task. When it rejects, react-await signals react-async-error with the message as its data: (react-async-error MESSAGE), so (cadr err) is the message.

react-sleep#

(react-sleep MILLISECONDS) → an awaitable whose value is nil

react-fetch-async#

(react-fetch-async URL &rest OPTIONS) → an awaitable whose value is the response

OPTIONS are those of react-fetch except :then and :catch. An HTTP error status is a response (check :ok); no response at all rejects, so the await signals react-async-error with the browser's message.

react-all#

(react-all AWAITABLES) → an awaitable

Its value is the list of the values of AWAITABLES (a list of awaitables or tasks), in order, once all have answered; nil at once for an empty list. It fails as soon as one fails.

react-race#

(react-race AWAITABLES) → an awaitable

Answers as the first of AWAITABLES answers, value or failure.

react-task-cancel#

(react-task-cancel TASK) → nil

Stops a running task: the request it waits for is cancelled, the body never goes on, its state becomes cancelled, and those who await it get react-async-error with the message "cancelled". A finished task is left alone. Limits: Lisp between two awaits always runs to the next await (a call is never interrupted); the requests inside react-all and react-race are not cancelled (their answers are ignored).

react-task#

The struct react-async returns. Accessors: react-task-state (nil while running, then done, failed or cancelled), react-task-value (the body's value, or the failure's message), react-task-request (the request it waits for, or nil), react-task-iterator and react-task-waiting (internal). Predicate: react-task-p.

react-async-error#

The error symbol (message "Asynchronous operation failed") signalled at a react-await whose operation failed. Its data is (MESSAGE).

Async examples#

(defvar async-log nil)
(react-async
  (push 'start async-log)
  (dotimes (i 2)
    (react-await (react-sleep 100))
    (push (list 'tick i) async-log))
  (condition-case err
      (react-await (react-fetch-async "/down"))
    (react-async-error (push (cadr err) async-log))))
(reverse async-log)
;; => (start)
(react-testing-flush)
(react-testing-time-passes)
(react-testing-time-passes)
(react-testing-answer "fetch" "Failed to fetch" :fail)
;; => (:url "/down" :method "GET" :headers nil :body nil)
(reverse async-log)
;; => (start (tick 0) (tick 1) "Failed to fetch")

Tasks compose: one body awaits another, and react-all waits for several.

(defvar all-values nil)
(let ((a (react-async (react-await (react-sleep 10)) 'a))
      (b (react-async (react-await (react-sleep 20)) 'b)))
  (react-async (setq all-values (react-await (react-all (list a b (lambda (resolve _reject) (funcall resolve 3))))))))
(react-testing-flush)
(react-testing-time-passes)
all-values
;; => (a b 3)

A component stops its task when it is taken off, or when the thing it loads changes, with an effect:

(react-define-component 'Note
  :initial-state (lambda (_props) (list :text nil))
  :render
  (lambda (self)
    (react-effect self 'load (react-props self :id)
      (lambda ()
        (let ((task (react-async
                      (let ((response (react-await (react-fetch-async
                                                    (format "/notes/%s" (react-props self :id))))))
                        (react-set-state self :text (plist-get response :text))))))
          (lambda () (react-task-cancel task)))))
    (or (react-state self :text) "…")))
(react-testing-render (jsx (Note (:id 1))))
(react-unmount "#app")
(react-testing-flush)
react-testing-requests
;; => nil

Testing#

lisp/react-testing.el is a page made of Lisp data, for ERT. It applies the operations react-flush returns, as the host would, and keeps the tree, the attributes, the properties, the listeners (with their react-handler options), and what Lisp asked of the page. A test renders, finds elements, clicks and types, answers requests, and looks. It runs in any Emacs; the page's own Emacs 30.2 runs it under Node with wasmacs's tools/scripts/ert.mjs.

emacs --batch -Q -L path/to/elisp-react/lisp -L . -l app-test.el -f ert-run-tests-batch-and-exit

-L . puts the application's directory on load-path: react-testing-load and load find a relative file name there, not in the current directory. Node ids are the numbers Lisp chose (:target in events). Differences from a browser: there is no default action, no preventDefault, no FormData rules (see react-testing-submit), no layout, and react-navigate changes nothing (it is only recorded in react-testing-told).

react-testing-render#

(react-testing-render ELEMENT &optional SELECTOR) → the root instance, or nil

Starts afresh (react-testing-reset), mounts ELEMENT at SELECTOR (default "#app") and applies the operations. Returns the root component instance when ELEMENT is a component.

react-testing-load#

(react-testing-load FILE) → nil

Starts afresh and loads FILE, an application that mounts itself, then applies the operations. FILE is found as load finds it.

react-testing-reset#

(react-testing-reset) → nil

Forgets everything on both sides (react-reset and the fake page). The address becomes http://localhost/ (:pathname "/"), the locale (:languages ["en"] :timeZone "UTC" :offset 0).

react-testing-flush#

(react-testing-flush) → nil

Applies what Lisp has pending (react-flush) to the fake page. Needed after react-mount, load or a direct react-set-state; the other react-testing- functions that act apply their own operations.

react-testing-storage#

(react-testing-storage KEY VALUE) → nil

Makes the page's storage hold VALUE under KEY, as if an earlier visit had stored it. react-testing-render and react-testing-load reset the storage, so the order is react-testing-reset, react-testing-storage, then react-mount or load, then react-testing-flush.

react-testing-location#

(react-testing-location HREF) → nil

Makes HREF the address and tells Lisp (the location watchers run), then applies the operations. :search and :hash are taken from HREF; :pathname is always "/".

react-testing-find-all#

(react-testing-find-all &key TAG CLASS TEXT ATTRIBUTE SELECTOR) → a list of node ids

The elements that match every given criterion, in document order: TAG (a symbol or string), CLASS (one of its classes), TEXT (its whole text, children included), ATTRIBUTE ((NAME VALUE), both strings). SELECTOR limits the search to one root.

react-testing-find#

(react-testing-find &key TAG CLASS TEXT ATTRIBUTE SELECTOR) → a node id

The first element that matches; signals react-testing: no element matches ... when there is none.

react-testing-text#

(react-testing-text ID) → a string

The text of the node ID and everything in it. For an element with :inner-html, the HTML as given.

react-testing-attribute#

(react-testing-attribute ID NAME) → a string, or nil

The attribute NAME (a string) of the node ID: "" for one set with t, nil when absent.

react-testing-property#

(react-testing-property ID NAME) → the value

The DOM property NAME ("value", "checked", or one of react-set-property) that Lisp set on the node ID, or that react-testing-input typed. "checked" is t or nil.

react-testing-html#

(react-testing-html &optional SELECTOR) → a string, or nil

The fake page at SELECTOR (default "#app") as HTML, for a quick look: text is not escaped, every element has an end tag, attributes come in the order they were last set.

react-testing-dispatch#

(react-testing-dispatch ID NAME &optional EVENT) → nil

The event NAME happens on the node ID with the plist EVENT (:type NAME :target ID are added). It goes up through the node and its parents, running each listener of that name, as in a browser, honouring the react-handler options :self, :keys and :stop. Use it for events without a helper: (react-testing-dispatch id "change" '(:checked t)).

react-testing-click#

(react-testing-click ID) → nil

A click event with no other data.

react-testing-input#

(react-testing-input ID VALUE) → nil

Types VALUE into the input ID: sets its value property, then an input event and a change event with :value VALUE.

react-testing-key#

(react-testing-key ID KEY) → nil

A keydown event with :key KEY ("Enter", "a").

react-testing-submit#

(react-testing-submit ID) → nil

A submit event on the form ID, with :form built from every element in it that has a name attribute: its value property, else its value attribute, else "". Unlike a browser it includes unchecked checkboxes and every named button.

react-testing-answer#

(react-testing-answer COMMAND VALUE &optional OK) → the request's argument

Answers the oldest waiting request of COMMAND ("fetch", "timeout", "page-listen", a page command) with VALUE, successfully unless OK is :fail, and applies the operations. Signals react-testing: nothing waits for COMMAND when there is none. The request leaves react-testing-requests at this answer, also a kept one (a page listener, a media query, a connection): the test kit answers it once. Intervals are fired again and again by react-testing-time-passes.

react-testing-answer-fetch#

(react-testing-answer-fetch STATUS TEXT) → the fetch's argument, (:url ... :method ...)

Answers the oldest waiting fetch with the response (:status STATUS :ok (< STATUS 400) :text TEXT :headers nil).

react-testing-time-passes#

(react-testing-time-passes) → nil

Fires every timeout that is waiting now, once (and forgets it), and every interval once. Timers started by what fires wait for the next call.

react-testing-requests#

A variable: what Lisp asked of the page and waits for, oldest first, each (REQUEST COMMAND ARGUMENT). Cancelled requests are taken out.

react-testing-told#

A variable: what Lisp told the page, oldest first, each (COMMAND ARGUMENT): ("storage-set" (:key ... :value ...)), ("navigate" (:url ... :replace ...)), ("title" (:text ...)).

react-testing-invoked#

A variable: methods called on nodes, oldest first, each (ID METHOD ARGS...).

Rules and pitfalls#

  1. Start every file with ;;; NAME.el --- ... -*- lexical-binding: t; -*-. The page adds the cookie when the first line lacks it, but a native Emacs (tests, a server) loads such a file with dynamic binding, and closures over self fail with void-variable.
  2. A native Emacs needs react.el loaded before it compiles an application file: put (require 'react) at the top, or -l react on the command line. Otherwise jsx and react-async compile as function calls. As a lint, byte-compile with warnings as errors: emacs --batch -Q -L path/to/lisp -l react --eval '(setq byte-compile-error-on-warn t)' -f batch-byte-compile app.el.
  3. react-mount renders at once. Every component it uses must be defined by then: put react-mount last, in the last file. A component defined in a later file renders as an unknown element (with a message) and stays one.
  4. List library files before the files that require them, and end them with (provide 'NAME). A file required before its turn is loaded twice (from source by require, compiled in its turn), so its top-level forms run twice.
  5. In jsx, components are Capitalized names. A lowercase component name works only in the plain list form; in jsx it is a function call.
  6. A component named like an HTML or SVG tag (label, button, title) replaces that tag in every element of the page.
  7. Inside jsx, a list that starts with a tag name is markup. A function named like a tag (mark, or your own label, filter, search, time, data) cannot be called there directly; compute the value before, or use funcall.
  8. All files share one Emacs. Prefix global function and variable names with the application's name; a defun of an existing name replaces it for everything, react.el included.
  9. Give every child of a list that changes a :key, unique among its siblings. Without keys children are matched by position, and the state of row components stays with the position, not the row.
  10. Never modify state in place (setcar, plist-put on a plist in state, nconc, delete, sort on the state's list). Build new values: react-plist-with, mapcar, seq-remove, append. :pure, :should-update, react-changed-p and context compare lists by identity.
  11. In a handler, read state when the event happens, (react-state self :todos), not a value the render captured: two quick events would otherwise both start from the old value. After a react-await, read state again.
  12. The event name is the DOM event type after :on-: :on-keydown, :on-dblclick, :on-pointerdown. :on-key-down listens for an event key-down that never comes.
  13. Lisp cannot prevent a default action after the fact. Declare it: (react-handler f :prevent t). A form's submit is always prevented; a <button> in a form submits it unless it has :type "button".
  14. Symbols, keywords and vectors are not children (Not an element). Write (symbol-name x) or (format "%s" x); turn a vector from react-response-json into a list with (append v nil) or mapcar.
  15. :value makes an input controlled: set state from :on-input, or the next render writes the old value back.
  16. react-location, react-locale and react-storage-get are not state. A component that reads them does not render again when they change: watch them (react-location-watch, react-storage-watch) and set state or react-force-update.
  17. What starts in :did-mount or an effect stops in :will-unmount or the effect's cleanup: react-set-interval, react-listen-page, react-media-query, react-observe-visible, react-websocket, react-event-source, react-location-watch, react-storage-watch. Otherwise they go on calling a component that is gone.
  18. Do not call react-set-state unconditionally in :render or :did-update: the flush gives up after 100 rounds with "Components keep changing state while rendering".
  19. react-effect keys are symbols, unique within the component; deps are compared with equal; deps nil runs once.
  20. react-await only where generator.el can rewrite it: not inside lambda, mapcar, seq-map, cl-loop, with-temp-buffer, save-excursion or unwind-protect. Loop with dolist, dotimes or while.
  21. A call from the host cannot be interrupted. Past the timeout (30 s) Emacs is stopped for good. Break long work inside react-async with (react-await (react-sleep 0)).
  22. Everything sent to the page is JSON: arguments of react-host-call, react-host-tell and react-invoke, :headers. Use plists with keyword keys, vectors, strings, numbers, t, :false and nil. A symbol or a plain list ('("a" "b")) has no JSON form and makes the whole answer of that call fail; use vconcat for arrays and symbol-name for symbols.
  23. Use only the react-invoke methods and react-set-property properties listed, and only commands the host or the page defines. An unknown method or command makes the host drop the rest of that answer's operations.
  24. react-query's loader returns a function of (RESOLVE REJECT), such as (react-fetch-async URL); a react-async task there is an error in the render.
  25. :ref on a component element is just a prop. To reach an element a child renders, pass (react-make-ref self NAME) down under a prop of your own and put it on the element.
  26. A string with raw bytes (json-serialize output, url-unhex-string) is decoded as UTF-8; what is still not text becomes U+FFFD, with a message. Fetch bytes with :as 'base64.
  27. Reloading a file (the host's load) keeps defvar values and re-runs defconst, setq and defun. Redefined components keep their state; a changed :initial-state shows only on a new instance or after a page reload.
  28. In tests, react-testing-render and react-testing-load reset the storage and the address: set them with react-testing-storage after react-testing-reset, then mount or load, then react-testing-flush.
  29. Do not require react-testing in the page: it is not on the page's load-path. Keep tests in files the page does not list.
  30. Keep secrets out of localStorage: every page of an origin can read it, and the compiled code kept there too.

Worked examples#

Each example is a file and a test. Run a test with the command in Testing.

Counter#

<!doctype html>
<html lang="en">
  <head><meta charset="utf-8"><title>Counter</title></head>
  <body>
    <div id="app">Loading Emacs…</div>
    <script type="text/emacs-lisp" src="counter.el"></script>
    <script type="module" src="https://modeverv.github.io/elisp-react/js/elisp-react.js"></script>
  </body>
</html>
;;; counter.el --- a counter  -*- lexical-binding: t; -*-

(require 'react)

(react-define-component 'Counter
  :initial-state (lambda (props) (list :count (or (plist-get props :start) 0)))
  :render
  (lambda (self)
    (let ((count (react-state self :count)))
      (jsx (div (:class "counter")
             (p (:class "count") (format "Count: %d" count))
             (button (:class "increment"
                      :on-click (lambda (_event)
                                  (react-set-state self :count (1+ (react-state self :count)))))
               "+1")
             (button (:class "reset" :disabled (= count 0)
                      :on-click (lambda (_event) (react-set-state self :count 0)))
               "reset"))))))

(react-mount (jsx (Counter (:start 3))) "#app")
;;; counter-test.el --- tests of counter.el  -*- lexical-binding: t; -*-

(require 'ert)
(require 'react-testing)

(ert-deftest counter-counts-and-resets ()
  (react-testing-load "counter.el")
  (should (equal (react-testing-text (react-testing-find :class "count")) "Count: 3"))
  (react-testing-click (react-testing-find :class "increment"))
  (should (equal (react-testing-text (react-testing-find :class "count")) "Count: 4"))
  (should-not (react-testing-attribute (react-testing-find :class "reset") "disabled"))
  (react-testing-click (react-testing-find :class "reset"))
  (should (equal (react-testing-text (react-testing-find :class "count")) "Count: 0"))
  (should (equal (react-testing-attribute (react-testing-find :class "reset") "disabled") "")))

Todo list#

A keyed list, a controlled input, a form submit, rows that skip their render, and the list kept in localStorage.

;;; todos.el --- a todo list  -*- lexical-binding: t; -*-

(require 'react)
(require 'seq)
(require 'subr-x)

(defun todos-next-id (todos)
  (1+ (apply #'max 0 (mapcar (lambda (todo) (plist-get todo :id)) todos))))

(react-define-component 'TodoItem
  ;; Renders only when its todo changed; the handlers read the function
  ;; props when the event happens.
  :pure t
  :render
  (lambda (self)
    (let ((todo (react-props self :todo)))
      (jsx (li (:class (if (plist-get todo :done) "todo done" "todo"))
             (input (:type "checkbox" :class "toggle" :checked (plist-get todo :done)
                     :on-change (lambda (_event)
                                  (funcall (react-props self :on-toggle) (plist-get todo :id)))))
             (span (:class "text") (plist-get todo :text))
             (button (:type "button" :class "delete"
                      :on-click (lambda (_event)
                                  (funcall (react-props self :on-delete) (plist-get todo :id))))
               "×"))))))

(react-define-component 'TodoApp
  :initial-state (lambda (_props) (list :todos (react-storage-get "todos" nil) :draft ""))
  :did-update (lambda (self _previous-props previous-state)
                (unless (eq (react-state self :todos) (plist-get previous-state :todos))
                  (react-storage-set "todos" (react-state self :todos))))
  :render
  (lambda (self)
    (let* ((todos (react-state self :todos))
           (toggle-todo
            (lambda (id)
              (react-set-state
               self :todos
               (mapcar (lambda (todo)
                         (if (= (plist-get todo :id) id)
                             (react-plist-with todo :done (not (plist-get todo :done)))
                           todo))
                       (react-state self :todos)))))
           (delete-todo
            (lambda (id)
              (react-set-state
               self :todos
               (seq-remove (lambda (todo) (= (plist-get todo :id) id)) (react-state self :todos)))))
           (add-todo
            (lambda (event)
              (let ((text (string-trim (or (react-form-value event "text") "")))
                    (todos (react-state self :todos)))
                (unless (string-empty-p text)
                  (react-set-state
                   self
                   :todos (append todos (list (list :id (todos-next-id todos) :text text :done nil)))
                   :draft ""))))))
      (jsx (main
             (form (:class "new" :on-submit add-todo)
               (input (:name "text" :class "new-text" :placeholder "What needs to be done?"
                       :value (react-state self :draft)
                       :on-input (lambda (event) (react-set-state self :draft (plist-get event :value)))))
               (button (:class "add" :disabled (string-empty-p (string-trim (react-state self :draft))))
                 "add"))
             (ul (:class "todos")
               (mapcar (lambda (todo)
                         (jsx (TodoItem (:key (plist-get todo :id) :todo todo
                                         :on-toggle toggle-todo :on-delete delete-todo))))
                       todos))
             (p (:class "left")
               (format "%d left" (seq-count (lambda (todo) (not (plist-get todo :done))) todos))))))))

(react-mount (jsx (TodoApp)) "#app")

Loading data#

react-async with a loading state, an error state and a retry. quotes.json is an array of {"id": ..., "text": ...}.

;;; quotes.el --- loading data with react-async  -*- lexical-binding: t; -*-

(require 'react)

(defun quotes-load (self)
  "Load the quotes into SELF's state: loading, then loaded or failed."
  (react-async
    (react-set-state self :status 'loading :error nil)
    (condition-case failure
        (let ((response (react-await (react-fetch-async "quotes.json"))))
          (if (plist-get response :ok)
              (react-set-state self :status 'loaded
                               :quotes (append (react-response-json response) nil))
            (react-set-state self :status 'failed
                             :error (format "HTTP %d" (plist-get response :status)))))
      ;; No response at all: offline, refused.
      (react-async-error (react-set-state self :status 'failed :error (cadr failure))))))

(react-define-component 'Quotes
  :initial-state (lambda (_props) (list :status 'loading :quotes nil :error nil))
  :did-mount (lambda (self) (quotes-load self))
  :render
  (lambda (self)
    (pcase (react-state self :status)
      ('loading (jsx (p (:class "status") "Loading…")))
      ('failed (jsx (div (p (:class "error") (react-state self :error))
                         (button (:class "retry" :on-click (lambda (_event) (quotes-load self)))
                           "retry"))))
      (_ (jsx (ul (:class "quotes")
                (mapcar (lambda (item) (jsx (li (:key (plist-get item :id)) (plist-get item :text))))
                        (react-state self :quotes))))))))

(react-mount (jsx (Quotes)) "#app")
;;; quotes-test.el --- tests of quotes.el  -*- lexical-binding: t; -*-

(require 'ert)
(require 'react-testing)

(ert-deftest quotes-load-fail-retry ()
  (react-testing-load "quotes.el")
  (should (equal (react-testing-text (react-testing-find :class "status")) "Loading…"))
  ;; No response at all.
  (should (equal (plist-get (react-testing-answer "fetch" "Failed to fetch" :fail) :url) "quotes.json"))
  (should (equal (react-testing-text (react-testing-find :class "error")) "Failed to fetch"))
  ;; Retry: an HTTP error, then data.
  (react-testing-click (react-testing-find :class "retry"))
  (react-testing-answer-fetch 500 "")
  (should (equal (react-testing-text (react-testing-find :class "error")) "HTTP 500"))
  (react-testing-click (react-testing-find :class "retry"))
  (react-testing-answer-fetch 200 "[{\"id\":1,\"text\":\"Simple things should be simple.\"}]")
  (should (equal (mapcar #'react-testing-text (react-testing-find-all :tag 'li))
                 '("Simple things should be simple."))))

Theme from a context#

A theme provided at the top, read two levels below, through a :pure component that skips its render.

;;; theme.el --- context  -*- lexical-binding: t; -*-

(require 'react)

(react-define-component 'ThemedButton
  :render
  (lambda (self)
    (jsx (button (:class (list "button" (react-context self 'theme "light")))
           (react-props self :label)))))

(react-define-component 'Toolbar
  :pure t
  :render (lambda (_self) (jsx (nav (ThemedButton (:label "Save")) (ThemedButton (:label "Load"))))))

(react-define-component 'ThemeApp
  :initial-state (lambda (_props) (list :theme "light"))
  :render
  (lambda (self)
    (jsx (div
           (button (:class "switch"
                    :on-click (lambda (_event)
                                (react-set-state self :theme (if (equal (react-state self :theme) "light")
                                                                 "dark"
                                                               "light"))))
             "switch theme")
           (react-provide 'theme (react-state self :theme) (jsx (Toolbar)))))))

(react-mount (jsx (ThemeApp)) "#app")
;;; theme-test.el --- tests of theme.el  -*- lexical-binding: t; -*-

(require 'ert)
(require 'react-testing)

(ert-deftest theme-reaches-buttons-below-a-pure-component ()
  (react-testing-load "theme.el")
  (should (equal (length (react-testing-find-all :class "light")) 2))
  (react-testing-click (react-testing-find :class "switch"))
  (should (equal (length (react-testing-find-all :class "dark")) 2))
  (should (equal (react-testing-attribute (react-testing-find :text "Save") "class") "button dark")))

A test with react-testing.el#

The todo list above, tested: stored data at the start, typing and submitting, keys keeping DOM nodes, a checkbox, and what the page was told to store.

;;; todos-test.el --- tests of todos.el  -*- lexical-binding: t; -*-

(require 'ert)
(require 'react-testing)

(defun todos-test-texts ()
  (mapcar #'react-testing-text (react-testing-find-all :class "text")))

(ert-deftest todos-add-delete-toggle ()
  ;; Not react-testing-load: it would reset the storage set here.
  (react-testing-reset)
  (react-testing-storage "todos" '((:id 1 :text "Write tests" :done nil)))
  (load "todos.el" nil t)
  (react-testing-flush)
  (should (equal (todos-test-texts) '("Write tests")))
  (should (react-testing-attribute (react-testing-find :class "add") "disabled"))
  ;; Type, then submit the form.
  (react-testing-input (react-testing-find :class "new-text") "Run them")
  (should-not (react-testing-attribute (react-testing-find :class "add") "disabled"))
  (react-testing-submit (react-testing-find :tag 'form :class "new"))
  (should (equal (todos-test-texts) '("Write tests" "Run them")))
  (should (equal (react-testing-property (react-testing-find :class "new-text") "value") ""))
  ;; Keys: the second row keeps its DOM node when the first goes.
  (let ((second-row (cadr (react-testing-find-all :tag 'li))))
    (react-testing-click (car (react-testing-find-all :class "delete")))
    (should (equal (react-testing-find-all :tag 'li) (list second-row))))
  ;; A checkbox: a change event.
  (react-testing-dispatch (react-testing-find :class "toggle") "change" '(:checked t))
  (should (equal (react-testing-text (react-testing-find :class "left")) "0 left"))
  (should (equal (react-testing-attribute (react-testing-find :tag 'li) "class") "todo done"))
  ;; The page was told to store the list.
  (let ((stored (car (last react-testing-told))))
    (should (equal (car stored) "storage-set"))
    (should (equal (read (plist-get (cadr stored) :value))
                   '((:id 2 :text "Run them" :done t))))))