Skip to main content

Using Enriched Markdown in Exact

Exact is an app framework from Expo. You write the app in Exact's own language, and Exact builds it as a native app for each platform. Exact is not React Native and not the Expo SDK. If you have an Expo or React Native app, follow React Native installation instead.

An Exact app uses a different Enriched Markdown package on each platform. You wrap each one in an Exact native module: a small piece of platform code that Exact places in your layout like any other view.

PlatformPackageModule file
iOSenriched-markdown-ios (Swift package)modules/apple/*.swift
Androidcom.swmansion.enriched.markdown:compose (Maven)modules/android/*.kt
Webreact-native-enriched-markdown (npm, web build only)modules/web/index.js

All three modules take the same props and send the same events, so the app code is the same everywhere.

caution

Exact has no releases yet, and its native module API can still change. This page was tested with Exact at commit 03729e336, enriched-markdown-ios 0.4.0, the Android artifacts 0.3.0, and react-native-enriched-markdown 1.3.0-nightly-20261130-5407083f6. The web build works without React Native from version 1.3.0. Until 1.3.0 is released, use that nightly version.

Declare the view​

Give the view a tag name, and list the platforms that implement it in app.json. Add the packages for iOS and Android in the same file:

app.json
{
"host": {
"ios": {
"swiftPackages": [
{
"url": "https://github.com/software-mansion-labs/enriched-markdown-ios",
"exactVersion": "0.4.0",
"products": ["EnrichedMarkdown", "EnrichedMarkdownLaTeX"]
}
]
},
"android": {
"maven": [
"com.swmansion.enriched.markdown:compose:0.3.0",
"com.swmansion.enriched.markdown:math:0.3.0"
]
}
},
"modules": [
{ "tag": "enriched-markdown", "hosts": ["ios", "android", "web"] }
]
}

EnrichedMarkdownLaTeX and math add LaTeX support, and you can leave them out. If you do, also remove the lines that use them from the modules below: import EnrichedMarkdownLaTeX and .markdownLaTeX() on iOS, and the LatexMathPlugin import and plugins = listOf(LatexMathPlugin) on Android. See iOS products and Android artifacts for the full list.

Exact locks and verifies every dependency. After you change these lists, run bun exact.mjs lock in your app's folder. For Android, also write the Gradle lock and verification files (gradle.lockfile and gradle-verification.xml), as Maven libraries in Exact's Android guide describes, and keep them with your app's source.

Then use the tag in your view. Exact refuses a native view that is not inside a check for the platforms that implement it, so wrap it in an if. The app then still builds for a platform that has no module:

shape Page
platform: string

component Notes
resource page = exactPage() as shape Page
state done = 0
derive notes = `- [${done == 1 ? "x" : " "}] Buy milk`
action toggled(message: string)
// "check 0" or "uncheck 0": this list has one task, at index 0
done = message == "check 0" ? 1 : 0
view
column
if page.platform == "ios" || page.platform == "android" || page.platform == "web"
enriched-markdown source=notes message=toggled width="100%"

exactPage() is Exact's built-in resource that reports the current platform. The if sits inside a column because it cannot be a view's root.

In this example:

  • source is the Markdown to render. Here it is built from done, so the checkbox shows the app's state after each tap.
  • message names the action to run when the reader ticks or unticks a task. The modules below send check <index> or uncheck <index>, where <index> is the task's position among the document's tasks, starting at 0.

Exact sends every prop to your module as a string.

iOS​

The module hosts the SwiftUI EnrichedMarkdownText in a UIHostingController. Exact sizes native views with CSS, so the module also reports the document's height for the width it gets. The module needs iOS 16.4 or later. Exact's default minimum is iOS 17.0, so there is nothing to change.

modules/apple/EnrichedMarkdown.swift
#if os(iOS)
import EnrichedMarkdown
import EnrichedMarkdownLaTeX
import SwiftUI
import UIKit

let exactModule: ExactModule.Type = MarkdownModule.self

final class MarkdownModule: ExactModule {
override class var views: [String: ExactNativeFactory] {
["enriched-markdown": ExactNativeFactory { props, events in MarkdownInstance(props, events) }]
}
}

final class MarkdownModel: ObservableObject {
@Published var source = ""
var toggled: ((TaskListItemToggle) -> Void)?
var resized: ((CGFloat) -> Void)?
}

struct MarkdownDocument: View {
@ObservedObject var model: MarkdownModel
var body: some View {
EnrichedMarkdownText(model.source)
.markdownLaTeX()
.onTaskListItemToggle { model.toggled?($0) }
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
.onGeometryChange(for: CGFloat.self) { $0.size.height } action: { model.resized?($0) }
.frame(maxHeight: .infinity, alignment: .top)
}
}

final class MarkdownInstance: ExactNativeInstance {
private let model = MarkdownModel()
private let host: UIHostingController<MarkdownDocument>
private let box = MeasuringView()

init(_ props: [String: String], _ events: ExactNativeEvents) {
host = UIHostingController(rootView: MarkdownDocument(model: model))
super.init(events: events)
host.view.backgroundColor = .clear
host.sizingOptions = [.intrinsicContentSize]
host.safeAreaRegions = []
box.addSubview(host.view)
box.hosted = host.view
box.measured = { [weak self] size in self?.events.intrinsicSize(size) }
model.resized = { [weak box] height in box?.report(height: height) }
model.toggled = { [weak self] task in
self?.events.message("\(task.isChecked ? "check" : "uncheck") \(task.index)")
}
try? setProps(props)
}

override var view: ExactNativeView { box }

override func setProps(_ props: [String: String]) throws {
let source = props["source"] ?? ""
if source != model.source { model.source = source }
}

override func destroy() {
box.measured = nil
model.toggled = nil
model.resized = nil
}
}

/// Lays out the hosted document and reports its size to Exact.
final class MeasuringView: UIView {
var hosted: UIView?
var measured: ((CGSize) -> Void)?
private var height: CGFloat = 0
private var sent = CGSize.zero

override func layoutSubviews() {
super.layoutSubviews()
// Never shorter than the document, so SwiftUI does not squeeze it.
hosted?.frame = CGRect(x: 0, y: 0, width: bounds.width, height: max(bounds.height, height))
send()
}

func report(height: CGFloat) {
self.height = ceil(height)
setNeedsLayout()
send()
}

private func send() {
let size = CGSize(width: bounds.width, height: height)
guard size.width > 0, size.height > 0, size != sent else { return }
sent = size
measured?(size)
}
}
#endif

To style the document, add a MarkdownTheme with .markdownTheme(...). A font your Exact app declares with a font block is registered for your app, so you can use it by its PostScript name, as in Custom fonts.

Android​

The module returns a ComposeView that shows EnrichedMarkdownText. Keep the source in Compose state, so a new source prop updates the view in place. Exact looks for your modules in a class named exact.app.Modules, so keep that package and class name.

modules/android/Modules.kt
package exact.app

import android.content.Context
import android.view.View
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.platform.ComposeView
import com.swmansion.enriched.markdown.compose.EnrichedMarkdownText
import com.swmansion.enriched.markdown.math.LatexMathPlugin
import dev.exact.canvas.NativeModule
import dev.exact.canvas.NativeModules
import dev.exact.canvas.NativeViewSizing
import org.json.JSONObject

class Modules : NativeModules {
override val modules: Map<String, NativeModule> = mapOf("enriched-markdown" to EnrichedMarkdown)
}

object EnrichedMarkdown : NativeModule {
private val sources = HashMap<View, MutableState<String>>()
private val emitters = HashMap<View, (String, String) -> Unit>()

override fun create(context: Context, props: JSONObject): View {
val source = mutableStateOf(props.optString("source"))
lateinit var view: ComposeView
view = ComposeView(context).apply {
id = View.generateViewId()
setContent {
EnrichedMarkdownText(
markdown = source.value,
onTaskListItemToggle = { task ->
emitters[view]?.invoke("message", "${if (task.checked) "check" else "uncheck"} ${task.index}")
},
plugins = listOf(LatexMathPlugin),
)
}
}
sources[view] = source
return view
}

override fun events(view: View, emit: (String, String) -> Unit) {
emitters[view] = emit
}

// The height follows the width, as with `wrap_content`.
override fun sizing(view: View, events: NativeViewSizing) = events.wrapContent()

override fun update(view: View, props: JSONObject) {
sources[view]?.value = props.optString("source")
}

override fun destroy(view: View) {
sources.remove(view)
emitters.remove(view)
(view as ComposeView).disposeComposition()
}
}

To style the document, pass a style built with markdownStyle { ... } (see Style properties). Exact packs your app's assets/ folder into the APK under app/assets/, so you can load a font your app ships with Font("app/assets/fonts/<file>", context.assets), as in Custom fonts.

Web​

On the web, Exact loads modules/web/index.js as an ES module and gives it the view's DOM element. The module renders the web build of EnrichedMarkdownText into that element with React.

Keep the module's source in its own small project, for example modules/web-src/, and install the packages there:

npm install react react-dom react-native-enriched-markdown@1.3.0-nightly-20261130-5407083f6 katex

You don't need React Native. See Web support for what the web build renders. The example below leaves out KaTeX's stylesheet; see Math (KaTeX) if you want it.

modules/web-src/main.jsx
import katex from 'katex';
import { createRoot } from 'react-dom/client';
import {
EnrichedMarkdownText,
registerKaTeX,
} from 'react-native-enriched-markdown';

registerKaTeX(katex);

export const abi = 1;
export const roster = { 'enriched-markdown': { snapshot: false } };

const MESSAGE = 8; // Exact's event number for `message`

// Exact's CSS reset displays every `input` as a block. Keep checkboxes inline.
let styled = false;
function addStyles() {
if (styled) return;
styled = true;
const style = document.createElement('style');
style.textContent = 'enriched-markdown input[type="checkbox"] { display: inline-block; }';
document.head.append(style);
}

function Document({ props, event }) {
return (
<EnrichedMarkdownText
markdown={props.source ?? ''}
enableTaskListItemToggle
onTaskListItemPress={(task) =>
event(MESSAGE, `${task.checked ? 'check' : 'uncheck'} ${task.index}`)
}
containerStyle={{ width: '100%' }}
/>
);
}

export function create(tag, element, propsJson, event) {
addStyles();
element.style.display = 'block';
const view = { root: createRoot(element), event };
setProps(view, propsJson);
return view;
}

export function setProps(view, propsJson) {
view.root.render(<Document props={JSON.parse(propsJson)} event={view.event} />);
}

export function snapshot() {}

export function destroy(view) {
view.root.unmount();
}

Exact loads modules/web/index.js as it is, without bundling it, so bundle main.jsx into that one file. With Bun:

modules/web-src/build.mjs
const result = await Bun.build({
entrypoints: ['main.jsx'],
target: 'browser',
format: 'esm',
minify: true,
define: { 'process.env.NODE_ENV': '"production"' },
});
if (!result.success) {
for (const log of result.logs) console.error(log);
process.exit(1);
}
await Bun.write('../web/index.js', await result.outputs[0].text());

Run bun build.mjs each time you change main.jsx. Any bundler that writes a single ES module works too.

Things to know on the web​

  • Checkboxes. Exact's CSS reset displays every input as a block. The addStyles rule in the example keeps each checkbox on its task's line; keep it if you rewrite the module.
  • Fonts. On the web, Exact registers the fonts from your app's font blocks under its own internal family names. To use one of them in a style, declare it again with @font-face under its real name, pointing at the same file in assets/fonts/.
  • Dark backgrounds. The default style is made for a light page: text is dark grey, and checked tasks are black (taskList.checkedTextColor). On a dark page, set the text colors yourself.

Test it​

On the web (bun exact.mjs test web), a test or the agent driver can tap a task's checkbox by its accessible label, Task: followed by the task's text. With the Notes component above:

test "ticking a task runs the action"
tap "Task: Buy milk"
expect state done == 1

The label includes all of the item's text, including inline code and bold text, so a task written as Buy milk `2 L` has the label Task: Buy milk 2 L. On iOS the checkbox is announced as Task, checked or Task, not checked instead, and Android has no such label, so a test that runs there needs another target.