diff --git a/lmlayer.js b/lmlayer.js index af7a7092f0..e6a5d1687b 100644 --- a/lmlayer.js +++ b/lmlayer.js @@ -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. */