@druide-informatique/antidote-api-js
v1.3.4
Published
[Lire en français](README.fr.md)
Readme
antidote-api-js
antidote-api-js is a JavaScript/TypeScript library that enables you to integrate the Antidote corrector into your web or hybrid applications (Cordova, Electron, etc.). It provides functions to launch the corrector, manage communication with Antidote Web, and interact with the texts to be corrected.
Installation
npm install @druide-informatique/antidote-api-jsor
yarn add @druide-informatique/antidote-api-jsBuild
Package
npm install
npm run buildCommunication API for interacting directly with the Antidote Connector or Antidote Web
Objet principal : Antidote
import { AntidoteConnector } from '@druide-informatique/antidote-api-js';
import { Antidote } from '@druide-informatique/antidote-api-js';Functions for launching the corrector
Antidote.launchAntidoteWebCorrector(noeud, creeFenetre?, appliedCorrectionFunction?)Antidote.launchAntidoteCorrector(noeud, creeFenetre?, appliedCorrectionFunction?)
Parameters
noeud:HTMLElement | HTMLElement[]– The DOM element(s) to be corrected.createWindow?:() => AntidoteWebWindow | null– Optional function to create the corrector window.appliedCorrectionFunction?:() => void– Optional function called after applying the corrections.
Connector detection
AntidoteConnector.isDetected(): boolean – Checks whether the Antidote Connector is available.
⸻
Creation of Antidote windows
createCordovaWindow():AntidoteWebWindow– For Cordova applications.createPostMessageAntidoteWebWindow():AntidoteWebWindow | null– For communication via postMessage.
AntidoteWebWindow Interface
export interface AntidoteWebWindow {
sendMessageToAntidoteWeb(jsonMessage: AntidoteMessage): void;
initializeCommunicationAntidoteWeb(): void;
showDocument(): void;
returnToDocument(): void;
}Handling messages from Antidote Web
aWebMessageHandler(event: MessageEvent<AntidoteMessage>): voidTypes
type NodeOrListOfNodes = HTMLElement | HTMLElement[];
interface AntidoteMessage {
}
type AppliedCorrectionFunction = () => void;
type CreateWindowAntidoteWebFunction = () => AntidoteWebWindow | null;Usage example
import { Antidote, creeFenetreWindowPostMessage } from '@druide-informatique/antidote-api-js';
const textarea = document.querySelector('#myTextarea');
Antidote.launchAntidoteCorrector(
textarea,
createPostMessageAntidoteWebWindow,
() => console.log('applied correction!')
);WebSocket API — Direct connection with Connectix
This API enables communication with Antidote tools: Corrector, Dictionaries, and Guides.
Once the protocol is established, the application allows bidirectional communication between the application's text and Antidote. Corrections suggested by Antidote are sent via messages to perform only the minimal replacements on the original text. It is possible to open the corrector to edit one or more documents—whether large or small—and to open dictionaries or guides for a short phrase or a single word. For dictionaries, this API allows managing the replace function.
Example
Subclass of WordProcessorAgent
The WordProcessorAgent represents your application to Antidote. It is the one that will provide your application's information to Antidote. At a minimum, you must define the functions configuration, correctIntoWordProcessor, allowEdit, and zonesToCorrect. In the following example, we want to correct the content of the fields in fieldsToCorrect.
import { applyCorrection, retrieveText, selectInterval } from '@druide-informatique/antidote-api-js';
export class WordProcessorAgentTextArea extends WordProcessorAgent {
private fieldsToCorrect: HTMLElement[];
constructor(fieldsToCorrect: HTMLElement[]) {
super();
this.fieldsToCorrect = fieldsToCorrect;
}
correctIntoWordProcessor(params: ParamsReplace): boolean {
const fieldToCorrect = this.fieldsToCorrect[Number(params.zoneId)];
const rangeToCorrect = { start: params.positionStartReplace,
end: params.positionReplaceEnd,
string: params.newString };
return applyCorrection(fieldToCorrect, rangeToCorrect);
}
configuration(): WordProcessorConfiguration {
return {};
}
allowEdit(params: ParamsAllowEdit): boolean {
const fieldToCorrect = this.fieldsToCorrect[Number(params.zoneId)];
const text = retrieveText(fieldToCorrect);
return text.substring(params.positionStart, params.positionEnd) == params.context;
}
selectInterval(params: ParamsSelect): void {
const fieldToCorrect = this.fieldsToCorrect[Number(params.zoneId)];
selectInterval(fieldToCorrect, params.positionStart, params.positionEnd);
}
zonesToCorrect(_params: ParamsGetZonesToCorrect): TextZone[] {
return this.fieldsToCorrect.map(function(value, index) {
return {
text: retrieveText(value),
zoneId: index.toString(),
zoneIsFocused: index == 0
};
});
}
}Using AgentConnectix
To communicate with Antidote, you must use the AgentConnectix class. To instantiate it, you need to provide the subclass of WordProcessorAgent as a parameter. Once the class is instantiated, you can open one of the three tools: Corrector, Dictionaries, or Guides.
const zones_to_correct = [
document.getElementById('text_area') as HTMLElement,
document.getElementById('div_editable') as HTMLElement
];
const wordProcessorAgent = new WordProcessorAgentTextArea(zones_to_correct);
const agent = new ConnectixAgent(wordProcessorAgent, function() { return 3000; });
await agent.connectWithAntidote(); // Initializing communication with the ConnectixAgent process.
agent.launchCorrector(); // Launches the corrector.Complete exameple
For a complete example, see the the demonstration projects.
Principle
The AgentConnectix is a daemon process that manages communication between your word processors and Antidote. It is what allows you to correct your texts directly within applications. The AgentConnectix runs a local WebSocket server (localhost) that remains open, enabling you to communicate with it to launch Antidote (Corrector, Dictionaries, and Guides).
Connecting to the AgentConnectix WebSocket Server
To find the WebSocket server’s port, run the command-line application AgentConnectixConsole with the --api parameter. The location varies by platform:
- macOS:
/Applications/Antidote/Connectix 11.app/Contents/SharedSupport/AgentConnectixConsole/Applications/Antidote/Connectix 12.app/Contents/SharedSupport/AgentConnectixConsole
- Windows: The folder path containing
AgentConnectixConsoleis specified in the following registry key:HKEY_LOCAL_MACHINE\SOFTWARE\Druide informatique inc.\Connectix, under the valueDossierConnectix.
The application returns the port number as JSON:
% AgentConnectixConsole --api
{"port": 59004}With this value, connect to the WebSocket server using the URL ws://localhost:PORT, replacing PORT with the obtained number.
Communication Protocol
All received and sent packets are JSON documents. To handle JSON documents of any size, a packeting system is implemented. Each packet itself is a JSON document with the format:
{
"idFrame": x,
"totalFrame": y,
"data": z
}idFramecorresponds to the packet number sent (between 0 andtotalFrame – 1);totalFrameis the total number of packets in the message being sent;datais a string that, once all packets are received, can be concatenated to form a JSON document.
With this protocol, you cannot mix packets from different messages. Packets belonging to the same message must be sent consecutively.
Once packets 0 through N‑1 have been received, concatenate the data strings. The resulting string is then a JSON document that can be processed as a message.
Messages
Initiate a call to Antidote
To launch a call to Antidote, send one of theses messages :
LaunchToolthe parameterstool_apiandapi_versionwith the following JSON document :
{
"api_version": 2,
"message": "LaunchTool",
"tool_api": "Corrector" | "Dictionaries" | "Guides"
}AntiOopswith theses parameters :
{
"api_version": 2,
"message": "AntiOops",
"subject": subject, // string
"body": body, // string
"recipients": [ recipients’ names ], // optional, list of recipient email address strings
"id": identifiant // to allow responses to be associated with the request
}Incoming messages to reply to
Antidote responds with a JSON document of the following format:
{
"idMessage": identifier,
"message": messageType,
"data": boolean | string | dictionary
}where
idMessageis a random string that must be returned in the reply to the message.messageis one of the types defined below.datacontains the message parameters. These parameters are optional depending on the message type and may be a boolean, a string, or a dictionary.
Below is the list of possible messages along with the required response. The parameters are contained in the value of the data key of the message.
init: Initialization message for the correction.Parameters: No parameters.
Response: Word‑processor configuration. All keys are optional.
{ // String from the `idMessage` key received in the `init` message. "idMessage": "", // Document title. Will be displayed in Antidote’s Corrector title bar. "documentTitle": "", // Carriage‑return type (e.g., "\n", "\r", "\r\n"). "carriageReturn" : "", // Indicates how to handle the correction state cache (only possible value: `forceEmplacementFichier`). "cacheIdType": "", // Whether carriage returns may be inserted from the Corrector. "allowCarriageReturn": true | false, // Whether the word processor allows non‑breaking spaces. "allowNBSpace": true | false, // Whether the word processor allows fine spaces. "allowThinSpace": true | false, // Indicates whether the context allows sending an email from Antidote (Anti-Oops!). "allowSending": true | false, // Whether text can be replaced without a selection. "replaceWithoutSelection": true | false, // Base64 string representing the state of the last correction. This is generated by Antidote; it should not be constructed manually. "correctionMemory": "", // Type of document to be corrected. "activeMarkup": "text" | "latex" | "markdown" | "subrip" | "html", // JSON dictionary of settings to use during correction. If omitted, the user’s settings will be used. "antidoteSettings": {} }
documentPath: Message requesting the path of the document to be corrected.Parameters: No parameters.
Response: Returns the document path in the
datakey.{ // String from the `idMessage` key received in the `documentPath` message. "idMessage": "", // Path of the document being corrected. Used for the correction state managed by Antidote. "data": "" }
docIsAvailable: Message asking whether the document being corrected is still accessible.Parameters: No parameters.
Response: Boolean indicating whether the document can still be corrected. The document may become unavailable if the user closes it.
{ // String from the `idMessage` key received in the `docIsAvailable` message. "idMessage": "", // Boolean indicating the state of the document being corrected. "data": true | false }
getTextZones: Message requesting the text zones to be corrected.Parameters
{ // If true, return a single text zone containing the current selection. // Usually true for dictionary and guide calls, false for the corrector. "forActiveSelection": true | false }Response : The list of text zones to be corrected.
{ // String from the `idMessage` key received in the `getTextZones` message. "idMessage": "", // List of text zones. "data": [ { // String corresponding to the text to correct. "text": "", // Optional integer indicating the start position of the selection within the word processor. // Omit if there is no selection. "positionSelectionStart": x, // Optional integer indicating the end position of the selection within the word processor. // Omit if there is no selection. "positionSelectionEnd": x, // Indicates whether this zone has focus (i.e., receives keyboard events). "zoneIsFocused": true | false, // Identifier for the text zone. Must be unique and allow easy retrieval of the zone using this string. "zoneId": "", // List of styles applied to the text (optional) "styleInfo": [ { "positionStart": x, "positionEnd": y, "style": "bold" | "italic" | "superscript" | "subscript" | "strike" } ] }, … ] }
allowEdit: Message asking whether the text at the requested positions is indeed the one Antidote expects.Parameters
{ "zoneId": "", // Identifier of the zone to check. "context": "", // Expected string at positions `positionStart` and `positionEnd` within zone `zoneId`. "positionStart": x, // Start position of the string to verify. "positionEnd": x // End position of the string to verify. }Response : A boolean indicating whether the string is exactly as expected.
{ // String from the `idMessage` key received in the `allowEdit` message. "idMessage": "", // Boolean indicating whether the string matches the expectation. "data": true | false }
replace: Message requesting to perform a replacement in the document.Parameters
{ // Identifier of the zone to correct. "zoneId": "", // String to replace between positions `positionRemplacementDebut` // and `positionRemplacementFin` within zone `idZone`. "newString": "", // Start position of the string to replace. "positionStartReplace": x, // End position of the string to replace. "positionReplaceEnd": x }Response : A boolean indicating whether the replacement was successfully performed.
{ // String from the `idMessage` key received in the `replace` message. "idMessage": "", // Boolean indicating whether the replacement succeeded. "data": true | false }
select: Message requesting to perform a selection in the document during correction.Parameters
{ // Identifier of the zone to correct. "zoneId": "", // Position where the selection should start. "positionStart": x, // Position where the selection should end. "positionEnd": x }Response : No response to send.
returnToDocument: Message requesting to bring the word processor to the foreground.Parameters : None.
Response : No response to send.
newCorrectionMemory: Message indicating that a new correction state is available.Parameters : A base64‑encoded string containing the data of the correction state to be saved.
Response : No response to send.
antiOopsResponse: Message that provides the result of the Anti-Oops! call. Depending on the result, the corrector may need to be opened (messageLaunchToolwithCorrector).Parameters :
{ // Identifier of the call requesting an Anti-Oops! request. "id": identifiant, // Optional: error code of the call. "errorCode": x, // Optional: list of detections found by Anti-Oops! // One of these detections may require opening the corrector "detections": [ ("errors" | "typography" | "attachments" | "inactiveLanguage" | "abrasiveTone") ] }Response : No response to send.
send: Message qui demande à envoyer le courriel dont la correction est en cours.Parameters : None.
Response : No response to send.
