Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

doc: document the code #15

Merged
merged 1 commit into from
Mar 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 69 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,79 @@
wasm-pack build
```

## 🔋 Features Included
**Note**: Always use `wasm-pack build --debug` in debug mode.

### 🔋 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 = JSON.parse(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: &str, state: &str) -> Result<bool, String> {
let key_event = utils::deserialize_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 @@ -54,12 +91,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
Loading