tinymce basic user manual

Posted by hi-liter on Tue, 28 Dec 2021 03:37:02 +0100

catalogue

1. Start
2. Quick use
3. Common configuration

4. Advanced functions

5. Typesetting
6.tinymce-vue

7. Custom use in vue (recommended)

1. Start

Official website documents: https://www.tiny.cloud/docs/
Latest official packaging address of community version and development version: https://www.tiny.cloud/get-tiny/self-hosted/
Localization package: http://tinymce.ax-z.cn/static/tiny/langs/zh_CN.js

2. Quick use

  • Introduce tinymce script
  • Initialize tinymce as part of the page
    • We need to use TinyMCE Init() to initialize; tinymce. The initialization object in init () contains many parameters, but all of them can be omitted. The only necessary parameter is selector (it is allowed to specify the content container to be bound by TinyMCE through css selector. Both div and textarea are allowed)
    • For example:
<div id = "tinydemo"></div>
<script >
    tinymce.init({
        selector: '#tinydemo'
    }); 
</script>
  • Several ways to get tinymce rich text box content:
    • If the current page has only one editor
      • Get content: TinyMCE activeEditor. getContent()
      • Setting content: TinyMCE activeEditor. Setcontent ("editor content to be set")
    • If the current page has multiple editors (the following "[0]" represents the first editor, and so on)
      • Get content: TinyMCE editors[0]. getContent()
      • Setting content: TinyMCE editors[0]. Setcontent ("editor content to be set")
    • Gets plain text content without HTML tags
var activeEditor = tinymce.activeEditor;
var editBody = activeEditor.getBody();
activeEditor.selection.select(editBody);
//Plain text content
var text = activeEditor.selection.getContent({
    'format': 'text'
});
  • textarea can be submitted by form
<h1>TinyMCE Quick Start Guide</h1>
<form method="post">
      <textarea id="mytextarea">Hello, World!</textarea>
</form>
<script>
      tinymce.init({
        selector: '#mytextarea'
      });
</script>

3. Common configuration

selector

Render DOM, required, String value, use CSS selector.

language

Specifies the language, String, and case sensitive values.

language_url

Chinese packet path

height

Set the height of the entire editor, including the menu bar, toolbar and status bar. If numbers are provided, TinyMCE sets the height in pixels. If a string is provided, TinyMCE assumes that the value is a valid CSS and sets the height of the editor to a string value. This allows spare units, such as%, em, and vh. (test% does not work)

readonly

Read only, Boolean. Set the editor to read-only mode and cannot be edited.

plugins

Specify the plug-in to be loaded, String or Array. This plug-in must already exist in the plugins directory; If String value is used, multiple plug-ins are separated by spaces; No plug-ins will be loaded by default, and self writing plug-ins are supported.
Optional plug-in configuration: https://www.tiny.cloud/docs/plugins/opensource/advlist/

toolbar

Customize Toolbar, Boolean or string or Array; If false, the toolbar will be closed; String value is used to customize the toolbar, for example: toolbar: "link | preview", and the "|" group can be inserted into the value; Supports multi-level toolbars, for example: toolbar1: '', toolbar2: ''; Official website: https://www.tiny.cloud/docs/configure/editor-appearance/#toolbar

menu

Customize the menu. Example:

tinymce.init({
    selector: '#tinydemo',
    menu: {
        file: {title: 'file', items: 'newdocument'},
        edit: {title: 'edit', items: 'undo redo | cut copy paste pastetext | selectall'},
        insert: {title: 'insert', items: 'link media | template hr'},
        view: {title: 'see', items: 'visualaid'},
        format: {title: 'format', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
        table: {title: 'form', items: 'inserttable tableprops deletetable | cell row column'},
        tools: {title: 'tool', items: 'spellchecker code'}
    }
});

When there are multi-level menus:

tinymce.init({
    selector: '#tinydemo',
    menubar: 'my1',
    menu: {
        my1: {title: 'My menu', items: 'copy paste' }
    }
});

menubar

Level 1 menu, Boolean or string; If false, the menu bar will be closed; String is used to customize the level 1 menu, for example: menubar: "file edit"; Official website: https://www.tiny.cloud/docs/configure/editor-appearance/#menubar

placeholder

Content pre display text, String value.

resize

The editor resizing tool has a drag mark in the lower right corner of the editor. Press and hold it with the mouse to change the size of the editor. Default resize: true; The optional values are: true (only the height can be changed), false (don't let you move at all), 'both' (both width and height can be changed, pay attention to quotation marks).

4. Advanced functions

Picture upload

tinymce.init({
    selector: '#tinydemo',
    language: 'zh_CN',
    plugins: 'image', //Using the image plugin
    toolbar: 'image', //Toolbar display
    images_upload_url: '/api/controller/action', //Used to specify the address of a backend handler that receives uploaded files
    images_upload_base_path: '/demo', //If the returned address is a relative path, this parameter can specify the basic path to which the relative path is relative
});

Cross domain problem: if TinyMCE and the program accepting uploaded pictures are not under the same domain name, the browser will refuse the operation due to the cross domain problem. When the back-end program returns the result, it needs to give the browser an instruction to allow cross domain.

Picture upload extension parameters

namedescribe
images_upload_credentialsYes, images_ upload_ Whether to pass cross domain credentials such as cookie s when calling the address specified in the URL. The value is Boolean, and the default is false
images_upload_handler (picture upload custom implementation)This option allows you to use custom functions instead of TinyMCE to handle upload operations. The user-defined function needs to provide four parameters: blobInfo, success callback and failure callback, and upload progress (value 1-100)
//The following is a code example of a custom upload implementation
tinymce.init({
    selector: '#tinydemo',
    images_upload_handler: function(blobInfo, success, failure, progress) {
        var xhr, formData;
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', 'action');

        xhr.upload.onprogress = function(e) {
            progress(e.loaded / e.total * 100);
        }

        xhr.onload = function() {
            var json;
            if (xhr.status == 403) {
                failure('HTTP Error: ' + xhr.status, {
                    remove: true
                });
                return;
            }
            if (xhr.status < 200 || xhr.status >= 300) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }
            json = JSON.parse(xhr.responseText);
            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }
            success(json.location);
        };

        xhr.onerror = function() {
            failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
        }

        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());

        xhr.send(formData);
    }
});

File upload

The original text only involves image upload. There is no explanation for file upload. Only file can be used_ picker_ Callback write callback.
For more parameters, please go to the official website: https://www.tiny.cloud/docs/configure/file-image-upload/#automatic_uploads
Simple example:
tinymce.init({
    selector: '#tinydemo',
    language: 'zh_CN',
    plugins: 'link',        
    toolbar: 'link',            
    file_picker_callback: function(callback, value, meta) {
    //Document classification
    var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
    var upurl = '/api/controller/';
    //Specify the file type and back-end address for different plug-ins
    switch (meta.filetype) {
        case 'image':
            filetype = '.jpg, .jpeg, .png, .gif';
            upurl += 'action1';
            break;
        case 'media':
            filetype = '.mp3, .mp4';
            upurl += 'action2';
            break;
            case 'file':
                break;
    };
    //Simulate an input for adding local files
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', filetype);
    input.click();
    input.onchange = function() {
        var file = this.files[0];
        var xhr, formData;
        console.log(file.name);
        //TODO: write the request here
        };
    },            
});                

Custom plug-ins

First, create a new directory under tinymce/plugins, which is the same as the plug-in name you want to get, and create a new plugin under the plug-in directory Min.js, as follows:

The upfile shown in the figure above is the name of my custom plug-in, and the location is tinymce/plugins/upfile

Second, understand the following code and refer to the official website: https://www.tiny.cloud/docs/api/tinymce/tinymce.addonmanager/

/**
 * Upload file plugin
 */

tinymce.PluginManager.add('upfile', function (editor, url) {
    var openDialog = function () {
        return editor.windowManager.open({
            title: 'Upload file',
            body: {
                type: 'panel',
                items: [
                    {
                        type: 'htmlpanel', // component type
                        html: '<div><input id="TinymcefileToUpload" type="file"  name="TinymcefileToUpload" class="input"></div>'
                    }
                ]
            },
            buttons: [
                {
                    type: 'cancel',
                    text: 'Close'
                },
                {
                    type: 'submit',
                    text: 'Upload',
                    primary: true
                }
            ],
            onSubmit: function (api) {
                let input = document.getElementById("TinymcefileToUpload");
                console.log("Come in");
                if (input.files.length > 0) {
                    let file = input.files[0];
                    let formData = new FormData();
                    formData.append("formFile", file);
                    axios.post("https://192.168.0.174:7183/api/Test/UploadFile", formData).then(res => {
                        if (res.data?.path != "") {
                            editor.insertContent(res.data.fileName + ":" + res.data?.path);
                            alert("File uploaded successfully");
                        }
                        else {
                            alert("Upload failed");
                        }
                    }).catch(err => console.log(err));
                }
                api.close();
            }
        });
    };

    // Add a button that opens a window
    editor.ui.registry.addButton('upfile', {
        text: `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-box-arrow-in-up" viewBox="0 0 16 16">
            < path fill- rule="evenodd" d = "M3.5 10a.5.5 0 0 1-.5-.5v-8a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 .5.5v8a.5.5 0 0 1-.5.5h-2a.5.5 0 0 0 0 1h2A1.5 1.5 0 0 0 14 9.5v-8A1.5 1.5 0 0 0 12.5 0h-9A1.5 1.5 0 0 0 2 1.5v8A1.5 1.5 0 0 0 3.5 11h2a.5.5 0 0 0 0-1h-2z" />
            <path fill-rule="evenodd" d="M7.646 4.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V14.5a.5.5 0 0 1-1 0V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3z" />
      </svg> `,
        onAction: function () {
            // Open window
            openDialog();
        }
    });

    // Adds a menu item, which can then be included in any menu via the menu/menubar configuration
    editor.ui.registry.addMenuItem('upfile', {
        text: 'Example plugin',
        onAction: function () {
            // Open window
            openDialog();
        }
    });

    return {
        getMetadata: function () {
            return {
                name: "Example plugin",
                url: "http://exampleplugindocsurl.com"
            };
        }
    };
});

Third, the author understands

It is not difficult to see that this is a self writing file upload plug-in. It should be noted that the plug-in is based on tinymce5 x,5. An error will be reported below X;

Back to the code, where upfile is the plug-in name;

openDialog() is used to open the pop-up window;

editor.windowManager.open is used to customize pop-up theme content and button callback;

Title is the pop-up title;

body is the middle content of the pop-up window;

The above plug-in uses a container containing many sub items, in which an html container is used, which supports html output;

buttons pop up button set; onSubmit is the event triggered by the submit button;

editor.ui.registry is used to add user-defined items. For details, refer to: https://www.tiny.cloud/docs/api/tinymce.editor.ui/tinymce.editor.ui.registry/#methods

5. Typesetting

Introduce typeo CSS, adding "class =" typeo "to div can automatically typeset. For details, see: https://typo.sofi.sh/

6. TinyMCE Vue (not recommended)

a. Quick use

This section is based on the vue2 demonstration
First, create the project using vuecli

vue create vue-demo

Select vue2

Installation components

npm install --save "@tinymce/tinymce-vue@^3"

Complete use:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
    <editor api-key="no-api-key" :init="initME" />
  </div>
</template>

<script src="http://tinymce.ax-z.cn/static/tiny/langs/zh_CN.js"></script>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import Editor from "@tinymce/tinymce-vue";

export default {
  name: "App",
  components: {
    HelloWorld,
    Editor,
  },
  data() {
    return {
      initME: {
        height: 500,
        language: "zh_CN",
        plugins: [
          "advlist autolink lists link image charmap print preview anchor",
          "searchreplace visualblocks code fullscreen",
          "insertdatetime media table paste code help wordcount",
        ],
        toolbar:
          "undo redo | formatselect | bold italic backcolor | \
           alignleft aligncenter alignright alignjustify | \
           bullist numlist outdent indent | removeformat | help",
      },
    };
  },
  mounted() {
    tinymce.init({});
},
};
</script>

b. Component configuration item

api-key

Tiny Cloud API key. When deploying with Tiny Cloud, you need to provide TinyMCE editor.
Default value: no API key, type: String

cloud-channel

Unknown

disabled

The disabled attribute dynamically switches the editor between disabled (read-only) mode (true) and standard editable mode (false).

id

The ID. of the editor is used to use this TinyMCE The get ('id ') method retrieves the editor instance. The default is automatically generated UUID

init

Object to TinyMCE Init is used to initialize the editor, the same as to configure.

initial-value

When the editor is initialized, the initial content of the editor is consistent with the usage of the native placeholder.

inline

Whether to enable inline mode. The default is false

model-events

Change the event to trigger the v-model event. The default is' change keyup '

output-format

Used to specify the format of content emitted through the input event. This affects the format of content used with data binding.
Default: html Optional: html,text

plugins

Plug in, same as plugins.

tag-name

Valid only when inline=true, used to define HTML elements for editors in inline mode.

toolbar

Toolbar, same as toolbar.

tinymce-script-src

Use TinyMCE script srcprop to specify the external version of TinyMCE for delayed loading. String value, for example:

<editor
  tinymce-script-src="/path/to/tinymce.min.js"
/>

v-model

Directive can be used to create a two-way data binding.

selectionChange

For event binding, see: https://www.tiny.cloud/docs/integrations/vue/#eventbinding

7. Custom use in vue (recommended)

First, introduce, for example:

<script src="../tinymce/tinymce.min.js"></script>

Second, create div or textarea, for example:

<div id="tinymcedemo"></div>

Third, the tinymce initialization method writes the methods attribute of the vue instance, for example:

methods:{
    init(){
        window.tinymce.init({
            selector:"#tinymcedemo"
        })
    }
}

Fourth, mount, for example:

mounted(){
    this.init();
}

After the mount is completed, you can use it

Topics: Javascript Vue.js