Extract function: onMessageWhenReady().

This commit is contained in:
Eddie Antonio Santos 2018-10-11 11:42:32 -06:00
parent d98b128dde
commit e7fe39862d
No known key found for this signature in database
GPG key ID: DD411EA4D9509D87

View file

@ -20,37 +20,12 @@ self.registerModel = function registerModel(modelFactory /* (c: Configuration) =
* Handles messages from the keyboard.
*/
self.onmessage = function (event) {
const {message, token} = event.data;
const {message} = event.data;
if (message === 'initialize') {
onMessageUninitialized(event);
} else if (message === 'predict') {
// XXX: induce the other end to reject the promise, because of a
// token/message mismatch. This is for testing purposes.
if (token === null) {
cast('invalid', {token});
return;
}
// TODO: rip contexts out of message.
let rawSuggestions = model.predict();
// Sort in-place according to weight.
rawSuggestions.sort((a, b) => a.weight - b.weight);
// Convert the internal suggestion format to the one required by the keyboard.
let suggestions = rawSuggestions.map((internal) => {
let displayAs = internal.displayAs;
// Try to make up a display string.
if (displayAs === null || displayAs === undefined) {
displayAs = internal.transform.insert;
}
return { displayAs, ...internal.transform };
});
cast('suggestions', { token, suggestions });
onMessageWhenReady(event);
} else {
throw new Error('invalid message');
}
@ -77,6 +52,44 @@ function onMessageUninitialized(event) {
cast('ready', { configuration: model.configuration });
}
/**
* Handles messages when ready to predict.
*/
function onMessageWhenReady(event) {
const {message, token} = event.data;
if (message !== 'predict') {
throw new Error('invalid message');
}
// XXX: induce the other end to reject the promise, because of a
// token/message mismatch. This is for testing purposes.
if (token === null) {
cast('invalid', {token});
return;
}
// TODO: rip contexts out of message.
let rawSuggestions = model.predict();
// Sort in-place according to weight.
rawSuggestions.sort((a, b) => a.weight - b.weight);
// Convert the internal suggestion format to the one required by the keyboard.
let suggestions = rawSuggestions.map((internal) => {
let displayAs = internal.displayAs;
// Try to make up a display string.
if (displayAs === null || displayAs === undefined) {
displayAs = internal.transform.insert;
}
return { displayAs, ...internal.transform };
});
cast('suggestions', { token, suggestions });
};
/**
* Send a message to the keyboard.
*/