Skip to content

Commit

Permalink
doc: document the code
Browse files Browse the repository at this point in the history
  • Loading branch information
pythonbrad committed Mar 24, 2024
1 parent 3aeb191 commit e97a3ac
Show file tree
Hide file tree
Showing 4 changed files with 175 additions and 8 deletions.
69 changes: 67 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,77 @@
wasm-pack build
```

## 🔋 Features Included
### 🔋 Features Included

* `strsim` for text similarity.
* `rhai` for scripting.

## License
### Installation

```
npm install afrim-js
```

### Usage

```javascript
import { Preprocessor, Translator } from "afrim-js";
import { convertTomlToJson } from "afrim-js";

(async function () {
// We execute preprocessor commands in idle.
var processCommand = () => {
var cmd = preprocessor.popQueue();
// ...
requestAnimationFrame(processCommand);
};
// ...

// We config the afrim ime.
var preprocessor = new Preprocessor(data, 64);
var translator = new Translator(dictionary, false);
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);
})();
```

### License

Licensed under MIT license ([LICENSE](LICENSE) or http://opensource.org/licenses/MIT).

Expand Down
12 changes: 12 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ use toml::{self};
use wasm_bindgen::prelude::*;

/// Convert TOML to JSON.
///
/// # Example
///
/// ```ignore
/// let data = convertTomlToJson(
/// "[info]\n" +
/// "name = \"sample\"\n" +
/// "\n" +
/// "[data]\n" +
/// "hello = \"hi\"\n"
/// );
/// ```
#[wasm_bindgen(js_name = convertTomlToJson)]
pub fn convert_toml_to_json(content: &str) -> Result<JsValue, String> {
let data: toml::Value = toml::from_str(content)
Expand Down
65 changes: 62 additions & 3 deletions src/preprocessor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,14 @@ pub struct Preprocessor {

#[wasm_bindgen]
impl Preprocessor {
/// Initiate the preprocessor.
/// Initializes the preprocessor.
///
/// # Example
///
/// ```ignore
/// let data = { a1: "à", ae: "æ" };
/// let preprocessor = new Preprocessor(data, 64);
/// ```
#[wasm_bindgen(constructor)]
pub fn new(data: &JsValue, buffer_size: usize) -> Result<Preprocessor, String> {
let data: IndexMap<String, String> = serde_wasm_bindgen::from_value(data.clone())
Expand All @@ -30,20 +37,50 @@ impl Preprocessor {
})
}

/// Process the keyboard event.
/// Process an keyboard event.
///
/// # Example
///
/// ```ignore
/// let data = { a1: "à", ae: "æ" };
/// let preprocessor = new Preprocessor(data, 64);
/// preprocessor.process("a", "keydown");
/// preprocessor.process("1", "keydown");
/// ```
pub fn process(&mut self, key: String, state: String) -> Result<bool, String> {
let key_event = utils::parse_event(key, state)?;
let (changed, _) = self.engine.process(key_event);

Ok(changed)
}

/// Commit the text.
/// Commit a text.
///
/// # Example
///
/// ```ignore
/// let preprocessor = new Preprocessor(data, 64);
/// preprocessor.commit("ŋna");
/// ```
pub fn commit(&mut self, text: String) {
self.engine.commit(text);
}

/// Return the next command to be executed.
///
/// # Example
///
/// ```ignore
/// let data = { a1: "à", ae: "æ" };
/// let preprocessor = new Preprocessor(data, 64);
/// preprocessor.process("a", "keydown");
/// preprocessor.process("1", "keydown");
///
/// preprocessor.popQueue() == "Pause";
/// preprocessor.popQueue() == { CommitText: "à" };
/// preprocessor.popQueue() == "Resume";
/// preprocessor.popQueue() == "NOP";
/// ```
#[wasm_bindgen(js_name = popQueue)]
pub fn pop_queue(&mut self) -> String {
self.engine
Expand All @@ -53,12 +90,34 @@ impl Preprocessor {
}

/// Return the input from the memory.
///
/// # Example
///
/// ```ignore
/// let preprocessor = new Preprocessor(data, 64);
/// preprocessor.process("a", "keydown");
/// preprocessor.process("1", "keydown");
///
/// preprocessor.getInput() == "a1";
/// ```
#[wasm_bindgen(js_name = getInput)]
pub fn get_input(&self) -> String {
self.engine.get_input()
}

/// Clear the preprocessor commands from the queue.
///
/// # Example
///
/// ```ignore
/// let data = { a1: "à", ae: "æ" };
/// let preprocessor = new Preprocessor(data, 64);
/// preprocessor.process("a", "keydown");
/// preprocessor.process("1", "keydown");
///
/// preprocessor.clearQueue();
/// preprocessor.popQueue() == "NOP";
/// ```
#[wasm_bindgen(js_name = clearQueue)]
pub fn clear_queue(&mut self) {
self.engine.clear_queue();
Expand Down
37 changes: 34 additions & 3 deletions src/translator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,14 @@ pub struct Translator {

#[wasm_bindgen]
impl Translator {
/// Initiate the translator.
/// Initializes the translator.
///
/// # Example
///
/// ```ignore
/// let data = { hi: [ "hello", "hola", "hey" ] };
/// let translator = new Translator(data, false);
/// ```
#[wasm_bindgen(constructor)]
pub fn new(dictionary: &JsValue, auto_commit: bool) -> Result<Translator, String> {
let dictionary: IndexMap<String, Vec<String>> =
Expand All @@ -28,8 +35,24 @@ impl Translator {
})
}

#[cfg(feature = "rhai")]
/// Register a translator from source code.
///
/// Note that the translator is written using [The Rhai Script Language](https://rhai.rs).
///
/// # Example
///
/// ```ignore
/// let translator = new Translator({}, false);
/// translator.register(
/// count_script,
/// "fn translate(input) {" +
/// " return [input, "", input.len().to_string(), false];" +
/// "}"
/// );
///
/// translator.translate("hello") == [["hello", "", ["5"], false]];
/// ```
#[cfg(feature = "rhai")]
pub fn register(&mut self, name: String, source: String) -> Result<(), String> {
let engine = Engine::new_raw();
let ast = engine.compile(source).map_err(|err| {
Expand All @@ -43,13 +66,21 @@ impl Translator {
Ok(())
}

/// Unregister a translator.
#[cfg(feature = "rhai")]
/// Unregister a translator
pub fn unregister(&mut self, name: &str) {
self.engine.unregister(name);
}

/// Generate predicates based on the input.
///
/// # Example
///
/// ```ignore
/// let data = { hi: [ "hello" ] };
/// let translator = new Translator(data, false);
/// translator.translate("hi") == ["hi", "", ["hello"], true];
/// ```
pub fn translate(&self, input: &str) -> JsValue {
serde_wasm_bindgen::to_value(&self.engine.translate(input)).unwrap()
}
Expand Down

0 comments on commit e97a3ac

Please sign in to comment.