# Duden Korrektur Javascript Plugin

This is a TinyMCE Plugin for using DKS with Websites. It works with simple Textarea and Input Fields (for example in Web Forms) or with most WYSIWYG Editors. If you encounter Problems with a specific HTML Editor / Content Managment System, please [contact us](https://www.epc.de/) so we can add support for it.

### Requirements

- A DKS Server with either public API or an API User

### Installation Instructions

1. Unzip/Copy the "dkce" directory and put it somewhere on your webserver.

2. Add the DKCE Javascript Source on the page(s) you want to use the spellchecker.
```html
<script type="text/javascript" src="dkce/dkce.js"></script>
```

If you're using another path, please make sure to add the path also to the settings when initializing the plugin or the assets
cannot be found (Localization Files, Images).

### Write the initialization code

You then need to initialize the plugin to the elements of your page. You can attach it to *DIV*-Tags that have *contenteditable* set to *true*, to *Textarea*-Elements and to *Input*-Elements of type *text*.

The plugin itself scans all childs of the element you provide, so if you attach it to the body element of your page it will look for all
elements that are supported. You can also ommit the element completly and the Spellchecker tries to attach it to all elements where it makes sense (but this is not recommened).

Here is an example. This will initialize the Plugin to the Element with the ID *editor*.

```html
    <script>
        DKCE.init(document.querySelector('#editor'), {
            apiEndpoint: 'http://127.0.0.1:8080/api',
            apiCredentials: {
                username: "duden",
                password: "duden"
            }
        });
    </script>
```

### Settings

There are a lot of different settings you can provide on initialisation. Here is a full list of all settings available.
- ai
    - Enables AI functionality (requires AI Support in DKS, Currently this only works with the TinyMCE 5+)
    - Defaults to: false
- apiEndpoint
    - The api endpoint of the DKS Serer
    - Defaults to: http://127.0.0.1:8080/api
- apiCredentials
    - The api credentials required for the DKS Server. May be ommited if the DKS Api is not secured. You can either use username/password or an apiKey
        - username
        - password
        - apiKey
    - Defaults to: null
- configFile
    - Tries to load the given json file at startup and overwrites and update all other configuration settings.
    - Set it to null or empty string if you want to skip the HTTP Request to detect the file.
    - Defaults to: {path}/duden-config.json
- propertySets
    - Which property sets should the DKS use
    - Defaults to: ["base"]
- singleWordModeAttributes
    - Every HTML element that contains at least one of the attributes defined here will be checked by the spell checker in Single Word Mode (useful, e.g., for headings or lists)
    - Defaults to: ['duden-use-single-word-mode']
- singleWordModeClasses
    - Every HTML element that contains at least one of the classes defined here will be checked by the spell checker in Single Word Mode (useful, e.g., for headings or lists)
    - Defaults to: ['duden-use-single-word-mode']
- dictionaries
    - Which dictionaries sets should the DKS use
    - Defaults to: []
- detectManualHyphenation
    - If a user manually adds hyphenation, DKCE will auto detect it and replaces the '-' char with a soft hyphen
    - Defaults to: true
- language
    - Which language should the DKCE Plugin use
    - Defaults to the browser language of the user
- fallbackLanguage
    - Which fallback Language should the DKCE Plugin use, if the main language cannot be found. This is especially important when you ommit the language setting, and the language is detected automatically by the users browser settings.
    - Defaults to: "en"
- activated
    - Should the plugin be activated. If set to false, you can later activate it through the messaging api
    - Defaults to: true
- hideStatusPanel
    - Can be used to disable the Duden-Status-Panel at the top of the screen (which indicates network communication)
    - Defaults to: false
- hyphenation
    - Defaults to: true
- hyphenationStandard
    - Defaults to: null (Server Settings is used by default.)
- glossary
    - Defaults to: null (Server Settings is used by default.)
- hyphenationInStem
    - Defaults to: true
- hyphenationUnaest
    - Defaults to: null (Server Settings is used by default.)
- ignoreAttributes
    - When set it will ignore spellchecks for all child elements who has the given attribute in the HTML set (can be string or array of strings)
    - Defaults to: []
- layerAttributes
    - When set it will separate spellchecks for all child elements who has the given attribute in the HTML set (can be string or array of strings). This can be useful for footnotes in HTML code, for example.
    - Defaults to: []
- useSingleWordModeOnLayers
    - Use single word mode for layers defined in layer Attributes (except when it detects end of sentence characters. Default is true.)
    - Defaults to: true
- ignoreClasses
    - When set it will ignore spellchecks for all child elements who has the given classes in the HTML set (can be string or array of strings)
    - Defaults to: []
- ignoreErrorCodes
    - Array of objects that define specific error codes to ignore based on CSS selectors. Each object contains 'code' (error code number) and 'selector' (CSS selector string). The logic is applied recursively for all child elements of selector nodes.
    - Example: [{ code: 111, selector: '.no-lowercase-check' }, { code: 166, selector: '.no-sentence-end-check' }]
    - Defaults to: []
- ignoreCharacters
    - Every single character of this string will be ignored during the correction check. This can be useful, for example, if the editor inserts characters for marking that are to be ignored by the spell checker.
    - Defaults to: ""
- checkLanguages
    - When set it will ignore spellchecks for paragraphs that have a language attribute attached that are not defined here. If ommited all languages will be checked.
    - Defaults to: []
- correctionProposals
    - Defaults to: true
- singleWordMode
    - Defaults to: false
- styleForeign
    - Defaults to: null (Server Settings is used by default.)
- styleOld
    - Defaults to: null (Server Settings is used by default.)
- styleRegional
    - Defaults to: null (Server Settings is used by default.)
- styleColloquial
    - Defaults to: null (Server Settings is used by default.)
- styleFiller
    - Defaults to: null (Server Settings is used by default.)
- markupMode
    - Defaults to: "text"
- messageLanguage
    - Defaults to: null (Server Settings is used by default.)
- textLanguage
    - Defaults to: null (Server Settings is used by default.)
- messageLevel
    - Defaults to: null (Server Settings is used by default.)
- cssFiles
    - Array of CSS Files to use for DKCE. Please keep in mind that most of the css classes only make sense in markup mode
    - Defaults to: ['assets/css/dkce.css'] in current path
- colors
    - Definition which colors should be used (Please keep in mind, that in markUp Mode it may be overwritten from included cssFiles)
    - Defaults to: { spellingError: '#faa6ae', gramarError: '#abe89e', rejectedWord: '#abe89e', styleError: '#ffd7a8', glossaryInfo: '#ffff00' }
- spellcheckingLevel
    - Defaults to: null (Server Settings is used by default.)
- orthographyStandard
    - Defaults to: null (Server Settings is used by default.)

- openContextMenuOn
    - Defaults to 'mouseOver'
    - Possible Values are 'mouseOver', 'leftClick' and 'rightClick'

- debug
    - Can be used to activate debug output to browser console.
    - Defaults to: false
- isChromeExtension
    - Only for internal usage, is used by the chrome extension
    - Defaults to: false
- overlayMode
    - Can be used to disable overlay mode and instead use markup mode
    - Defaults to: true
- removeMarkupForSelection
    - If set to true (and instance is in MarkUp Mode) all markup code is removed from selections (and readded when selection is removed)
    - Defaults to: false
- path
    - Path to the dkce javascript source files. Is important so the plugin finds the assets like images and localization files.
    - Defaults to: "dkce"
- proposalDictionary
    - Can set the dictonary where proposals will be submitted to.
    - Defaults to: "Proposals"
- setUpWatcher
    - If set to true, duden will observer the HTML elements and inject the Spellchecker automatically on dynamically created or changed HTML nodes
    - Defaults to: false
- maxCanvasWidth
    - If a canvas exceeds this size (in pixels) in overlay mode, it is split into several individual ones
    - Defaults to: 512
- maxCanvasHeight
    - If a canvas exceeds this size (in pixels) in overlay mode, it is split into several individual ones
    - Defaults to: 512
- debugCanvas
    - Makes the overlay canvas elements visible (for debugging purposes)
    - Defaults to: false
- zIndex
    - The zIndex where the highlights should be rendered. In general this should be higher than the editor element but lower than pop ups / toolbars etc, that are laying in front of the editor.
    - Defaults to: 20

### Initialisation Handlers

You can also add onSuccess and onFailure callbacks to the init function:

```html
    <script>
        const onSuccess = (dkce) =>  {
            // dkce is a javascript object that contains an api to
            // the dkce / spellcheckers instance(s)

            // turn off Spellchecking
            dkce.activate(false);

            // returns true if spellchecking is active
            var isSpellcheckingActive = dkce.isActive();

            // Update DKCE Settings
            dkce.updateSettings({ spellcheckingLevel: 3 });

            // Reinitialize Duden Plugin: This will update the spellchecker elements,
            // which means it will be removed from elements that are no longer editable
            // and added to elements that have become editable
            dkce.reinitialize();

            // returns a js object with all current settings of the
            // dkce instance
            const settings = dkce.getCurrentSettings();

            // returns a array with all property sets of the DKS
            const settings = dkce.getPropsets(onSuccess(result) {
                console.log("Property Sets of DKS: ", result);
            });

            // returns an array with possible AI Actions
            const actions = dkce.getAIActions();

            // Small Example: This sends an AI Request to the DKS with
            // current selection and opens the AI Assistant Dialog
            const selection = window.getSelection();
            if (selection.rangeCount > 0) {
                const range = selection.getRangeAt(0);
                dkce.executeAIActionOnRange('actionId', range);
            }

            // Hides the spellchecker context window (if it's visible)
            dkce.hideContextMenu();

            // Display a DKCE Toast Message
            dkce.toast("Hello world!")

            // Propose a word to the DKS
            dkce.proposeWord("My word");
        };

        const onFailure = (error) => {
            console.log(error);
        };

        DKCE.init(document.querySelector('#editor'), settings, onSuccess, onFailure);
    </script>
```

### Communication with the Plugin

You can send messages to the Plugin, for example to activate it or to update the user settings. This is done through the Browsers Message System.

#### Activate the plugin

```js
window.postMessage({
    'subject': 'activate',
    'activate': true
}, window.location.href);
```
#### Deactivate the plugin

```js
window.postMessage({
    'subject': 'activate',
    'activate': true
}, window.location.href);
```

#### Update the settings

```js
window.postMessage({
    'subject': 'update_settings',
    'settings': {
        /* Whatever settings you want to update */
    }
}, window.location.href);
```

#### Listen to content updates

Whenever the content of the element has updated the DKCE is attached to, a *content_changed* event is sent back via the messaging api. You can listen to it like this:

```js
window.addEventListener("message", (event) => {
    if (event.data === 'content_changed') {
        /* Do something */
    }
};
```

### Special Attributes and Classes

If a DOM Element (or a parent Element) in which the spellchecker is injected contains either the class or the attribute *duden-use-single-word-mode*, the single word mode is enforced for the spellchecking. This might be useful for Elements that expect a single word or a headline as example.

```html
    <textarea contenteditable="true" duden-use-single-word-mode>
    </textarea>

    <textarea contenteditable="true" class="duden-use-single-word-mode">
    </textarea>
```

## License

(C) Copyright 2022 by EPC Consulting und Software GmbH.
