wasm-pack build
Note: Always use wasm-pack build --debug in debug mode.
strsimfor text similarity.rhaifor scripting.
We also offer a lite version of this library for those who need a more lightweight solution.
You can find it here npm/afrim-lite.
Note: This version implies the dropped rhai feature.
npm install afrim
The afrim_bg.wasm file is large (~900 KB), but it compresses very well: gzip brings it down
to ~340 KB, about 62% smaller. Serve it compressed to cut download time and speed up page
loads, especially on slow mobile connections.
Most CDNs (jsDelivr, unpkg, Cloudflare) and static hosts (GitHub Pages, Netlify, Vercel)
already do this for you. If you host the file yourself, make sure compression is enabled for
the application/wasm MIME type. For example:
- nginx:
gzip on;andgzip_types application/wasm; - Apache:
AddOutputFilterByType DEFLATE application/wasm
Brotli usually compresses even better than gzip, if your server supports it.
To check, open your browser's devtools, select the .wasm request in the Network tab, and
look for a Content-Encoding: gzip (or br) response header.
import { Preprocessor, Translator } from "afrim";
import { convertTomlToJson } from "afrim";
(async function () {
// We execute preprocessor commands in idle.
var processCommand = () => {
var cmd = JSON.parse(preprocessor.popQueue());
// ...
requestAnimationFrame(processCommand);
};
// ...
// We config the afrim ime.
var preprocessor = new Preprocessor(data, 64);
var translator = new Translator(dictionary, false, 0.7);
Object.entries(scripts).forEach((e) =>
translator.register(e[0], e[1]),
);
// ...
// We listen keyboard events.
textFieldElement.addEventListener(
"keyup",
(event) => {
// ...
// Commit the predicate.
if (event.code == "Space") {
var predicate = global.memory.predicates[global.memory.predicateId];
if (predicate) preprocessor.commit(predicate[3]);
clearPredicate();
}
var changed = preprocessor.process(event.key, "keydown");
var input = preprocessor.getInput();
// We update the predicates
if (!changed) return;
tooltipInputElement.innerText = "📝 " + input;
var predicates = translator.translate(input);
loadPredicates(predicates);
updatePredicate();
// ...
},
false,
);
// ...
// We start the processor.
requestAnimationFrame(processCommand);
})();
Licensed under MIT license (LICENSE or http://opensource.org/licenses/MIT).
We are open for contributions.