This commit is contained in:
2025-10-22 15:39:40 +08:00
commit b0b510fac1
2720 changed files with 415933 additions and 0 deletions

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: advlist Demo Page</title>
</head>
<body>
<h2>Plugin: advlist Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/advlist/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'lists advlist code',
toolbar: 'bullist numlist | outdent indent | code',
height: 600
});
export {};

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Tools from 'tinymce/core/api/util/Tools';
import Commands from './api/Commands';
import Buttons from './ui/Buttons';
PluginManager.add('advlist', function (editor) {
const hasPlugin = function (editor, plugin) {
const plugins = editor.settings.plugins ? editor.settings.plugins : '';
return Tools.inArray(plugins.split(/[ ,]/), plugin) !== -1;
};
if (hasPlugin(editor, 'lists')) {
Buttons.register(editor);
Commands.register(editor);
}
});
export default function () { }

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Actions from '../core/Actions';
const register = function (editor) {
editor.addCommand('ApplyUnorderedListStyle', function (ui, value) {
Actions.applyListFormat(editor, 'UL', value['list-style-type']);
});
editor.addCommand('ApplyOrderedListStyle', function (ui, value) {
Actions.applyListFormat(editor, 'OL', value['list-style-type']);
});
};
export default {
register
};

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getNumberStyles = function (editor) {
const styles = editor.getParam('advlist_number_styles', 'default,lower-alpha,lower-greek,lower-roman,upper-alpha,upper-roman');
return styles ? styles.split(/[ ,]/) : [];
};
const getBulletStyles = function (editor) {
const styles = editor.getParam('advlist_bullet_styles', 'default,circle,disc,square');
return styles ? styles.split(/[ ,]/) : [];
};
export default {
getNumberStyles,
getBulletStyles
};

View File

@@ -0,0 +1,15 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const applyListFormat = function (editor, listName, styleValue) {
const cmd = listName === 'UL' ? 'InsertUnorderedList' : 'InsertOrderedList';
editor.execCommand(cmd, false, styleValue === false ? null : { 'list-style-type': styleValue });
};
export default {
applyListFormat
};

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const isChildOfBody = function (editor, elm) {
return editor.$.contains(editor.getBody(), elm);
};
const isTableCellNode = function (node) {
return node && /^(TH|TD)$/.test(node.nodeName);
};
const isListNode = function (editor) {
return function (node) {
return node && (/^(OL|UL|DL)$/).test(node.nodeName) && isChildOfBody(editor, node);
};
};
const getSelectedStyleType = function (editor) {
const listElm = editor.dom.getParent(editor.selection.getNode(), 'ol,ul');
return editor.dom.getStyle(listElm, 'listStyleType') || '';
};
export default {
isTableCellNode,
isListNode,
getSelectedStyleType
};

View File

@@ -0,0 +1,91 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
import Settings from '../api/Settings';
import Actions from '../core/Actions';
import ListUtils from '../core/ListUtils';
import ListStyles from './ListStyles';
const findIndex = function (list, predicate) {
for (let index = 0; index < list.length; index++) {
const element = list[index];
if (predicate(element)) {
return index;
}
}
return -1;
};
const listState = function (editor, listName) {
return function (e) {
const ctrl = e.control;
editor.on('NodeChange', function (e) {
const tableCellIndex = findIndex(e.parents, ListUtils.isTableCellNode);
const parents = tableCellIndex !== -1 ? e.parents.slice(0, tableCellIndex) : e.parents;
const lists = Tools.grep(parents, ListUtils.isListNode(editor));
ctrl.active(lists.length > 0 && lists[0].nodeName === listName);
});
};
};
const updateSelection = function (editor) {
return function (e) {
const listStyleType = ListUtils.getSelectedStyleType(editor);
e.control.items().each(function (ctrl) {
ctrl.active(ctrl.settings.data === listStyleType);
});
};
};
const addSplitButton = function (editor, id, tooltip, cmd, nodeName, styles) {
editor.addButton(id, {
active: false,
type: 'splitbutton',
tooltip,
menu: ListStyles.toMenuItems(styles),
onPostRender: listState(editor, nodeName),
onshow: updateSelection(editor),
onselect (e) {
Actions.applyListFormat(editor, nodeName, e.control.settings.data);
},
onclick () {
editor.execCommand(cmd);
}
});
};
const addButton = function (editor, id, tooltip, cmd, nodeName, styles) {
editor.addButton(id, {
active: false,
type: 'button',
tooltip,
onPostRender: listState(editor, nodeName),
onclick () {
editor.execCommand(cmd);
}
});
};
const addControl = function (editor, id, tooltip, cmd, nodeName, styles) {
if (styles.length > 0) {
addSplitButton(editor, id, tooltip, cmd, nodeName, styles);
} else {
addButton(editor, id, tooltip, cmd, nodeName, styles);
}
};
const register = function (editor) {
addControl(editor, 'numlist', 'Numbered list', 'InsertOrderedList', 'OL', Settings.getNumberStyles(editor));
addControl(editor, 'bullist', 'Bullet list', 'InsertUnorderedList', 'UL', Settings.getBulletStyles(editor));
};
export default {
register
};

View File

@@ -0,0 +1,27 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
const styleValueToText = function (styleValue) {
return styleValue.replace(/\-/g, ' ').replace(/\b\w/g, function (chr) {
return chr.toUpperCase();
});
};
const toMenuItems = function (styles) {
return Tools.map(styles, function (styleValue) {
const text = styleValueToText(styleValue);
const data = styleValue === 'default' ? '' : styleValue;
return { text, data };
});
};
export default {
toMenuItems
};

View File

@@ -0,0 +1,198 @@
import AdvListPlugin from 'tinymce/plugins/advlist/Plugin';
import ListsPlugin from 'tinymce/plugins/lists/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import { Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.lists.AdvlistPluginTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
AdvListPlugin();
ListsPlugin();
ModernTheme();
const listStyleTest = function (title, definition) {
suite.test(title, function (editor) {
editor.getBody().innerHTML = definition.inputContent;
LegacyUnit.setSelection(editor, definition.inputSelection[0], definition.inputSelection[1]);
editor.execCommand(definition.command, false, { 'list-style-type': definition.listType });
const rng = editor.selection.getRng(true);
const expectedElm = editor.dom.select(definition.expectedSelection[0])[0];
LegacyUnit.equal(editor.getContent(), definition.expectedContent, 'Editor content should be equal');
LegacyUnit.equalDom(rng.startContainer.parentNode, expectedElm, 'Selection elements should be equal');
LegacyUnit.equal(rng.startOffset, definition.expectedSelection[1], 'Selection offset should be equal');
});
};
listStyleTest('Apply unordered list style to an unordered list', {
inputContent: '<ul><li>a</li></ul>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: 'disc',
expectedContent: '<ul style="list-style-type: disc;"><li>a</li></ul>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style to an ordered list', {
inputContent: '<ol><li>a</li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: 'lower-roman',
expectedContent: '<ol style="list-style-type: lower-roman;"><li>a</li></ol>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style to an unordered list', {
inputContent: '<ol><li>a</li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: 'disc',
expectedContent: '<ul style="list-style-type: disc;"><li>a</li></ul>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style to an unordered list with a child unordered list', {
inputContent: '<ul><li>a<ul><li>b</li></ul></li></ul>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: 'disc',
expectedContent: '<ul style="list-style-type: disc;"><li>a<ul><li>b</li></ul></li></ul>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style to an ordered list with a child ordered list', {
inputContent: '<ol><li>a<ol><li>b</li></ol></li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: 'lower-roman',
expectedContent: '<ol style="list-style-type: lower-roman;"><li>a<ol><li>b</li></ol></li></ol>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style to an unordered list with a child ordered list', {
inputContent: '<ul><li>a<ol><li>b</li></ol></li></ul>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: 'disc',
expectedContent: '<ul style="list-style-type: disc;"><li>a<ol><li>b</li></ol></li></ul>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style to an unordered list with a child unordered list', {
inputContent: '<ol><li>a<ul><li>b</li></ul></li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: 'lower-roman',
expectedContent: '<ol style="list-style-type: lower-roman;"><li>a<ul><li>b</li></ul></li></ol>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style to an unordered list with a child unordered list', {
inputContent: '<ul><li>a<ul><li>b</li></ul></li></ul>',
inputSelection: ['li:nth-child(1) > ul > li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: 'disc',
expectedContent: '<ul><li>a<ul style="list-style-type: disc;"><li>b</li></ul></li></ul>',
expectedSelection: ['li:nth-child(1) > ul > li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style to an ordered list with a child ordered list', {
inputContent: '<ol><li>a<ol><li>b</li></ol></li></ol>',
inputSelection: ['li:nth-child(1) > ol > li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: 'lower-roman',
expectedContent: '<ol><li>a<ol style="list-style-type: lower-roman;"><li>b</li></ol></li></ol>',
expectedSelection: ['li:nth-child(1) > ol > li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style to an unordered list with a child ordered list', {
inputContent: '<ul><li>a<ol><li>b</li></ol></li></ul>',
inputSelection: ['li:nth-child(1) > ol > li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: 'lower-roman',
expectedContent: '<ul><li>a<ol style="list-style-type: lower-roman;"><li>b</li></ol></li></ul>',
expectedSelection: ['li:nth-child(1) > ol > li:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style to ordered list with a child unordered list', {
inputContent: '<ol><li>a<ul><li>b</li></ul></li></ol>',
inputSelection: ['li:nth-child(1) > ul > li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: 'disc',
expectedContent: '<ol><li>a<ul style="list-style-type: disc;"><li>b</li></ul></li></ol>',
expectedSelection: ['li:nth-child(1) > ul > li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style to an unordered list with a child ordered list', {
inputContent: '<ul><li>a<ol><li>b</li></ol></li></ul>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: false,
expectedContent: '<ol><li>a<ol><li>b</li></ol></li></ol>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style to an ordered list with a child unordered list', {
inputContent: '<ol><li>a<ul><li>b</li></ul></li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: false,
expectedContent: '<ul><li>a<ul><li>b</li></ul></li></ul>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style "false" to an ordered list with a child unordered list', {
inputContent: '<ol><li>a<ul><li>b</li></ul></li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: false,
expectedContent: '<p>a</p><ul><li style="list-style-type: none;"><ul><li>b</li></ul></li></ul>',
expectedSelection: ['p:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style "false" to an unordered list with a child ordered list', {
inputContent: '<ul><li>a<ol><li>b</li></ol></li></ul>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: false,
expectedContent: '<p>a</p><ol><li style="list-style-type: none;"><ol><li>b</li></ol></li></ol>',
expectedSelection: ['p:nth-child(1)', 0]
});
listStyleTest('Apply unordered list style "false" to an ordered list with a child ordered list', {
inputContent: '<ol><li>a<ol><li>b</li></ol></li></ol>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyUnorderedListStyle',
listType: false,
expectedContent: '<ul><li>a<ol><li>b</li></ol></li></ul>',
expectedSelection: ['li:nth-child(1)', 0]
});
listStyleTest('Apply ordered list style "false" to an unordered list with a child unordered list', {
inputContent: '<ul><li>a<ul><li>b</li></ul></li></ul>',
inputSelection: ['li:nth-child(1)', 0],
command: 'ApplyOrderedListStyle',
listType: false,
expectedContent: '<ol><li>a<ul><li>b</li></ul></li></ol>',
expectedSelection: ['li:nth-child(1)', 0]
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
}, {
plugins: 'advlist lists',
add_unload_trigger: false,
indent: false,
entities: 'raw',
valid_elements: 'li[style],ol[style],ul[style],dl,dt,dd,em,strong,span,#p,div,br',
valid_styles: {
'*': 'list-style-type'
},
disable_nodechange: true,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,88 @@
import { GeneralSteps, Logger, Pipeline } from '@ephox/agar';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import AdvlistPlugin from 'tinymce/plugins/advlist/Plugin';
import ListsPlugin from 'tinymce/plugins/lists/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.lists.ChangeListStyleTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
ListsPlugin();
AdvlistPlugin();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
const tinyUi = TinyUi(editor);
Pipeline.async({}, [
Logger.t('ul to alpha, cursor only in parent', GeneralSteps.sequence([
tinyApis.sSetContent('<ul><li>a</li><ul><li>b</li></ul></ul>'),
tinyApis.sSetCursor([0, 0, 0], 0),
tinyUi.sClickOnToolbar('click numlist button', 'div[aria-label="Numbered list"] button.mce-open'),
tinyUi.sClickOnUi('click lower alpha item', 'div[role="menuitem"] span:contains("Lower Alpha")'),
tinyApis.sAssertContent('<ol style="list-style-type: lower-alpha;"><li>a</li><ul><li>b</li></ul></ol>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 0, 0], 0)
])),
Logger.t('ul to alpha, selection from parent to sublist', GeneralSteps.sequence([
tinyApis.sSetContent('<ul><li>a</li><ul><li>b</li></ul></ul>'),
tinyApis.sSetSelection([0, 0, 0], 0, [0, 1, 0, 0], 1),
tinyUi.sClickOnToolbar('click numlist button', 'div[aria-label="Numbered list"] button.mce-open'),
tinyUi.sClickOnUi('click lower alpha item', 'div[role="menuitem"] span:contains("Lower Alpha")'),
tinyApis.sAssertContent('<ol style="list-style-type: lower-alpha;"><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ol>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 1, 0, 0], 1)
])),
Logger.t('ol to ul, cursor only in parent', GeneralSteps.sequence([
tinyApis.sSetContent('<ol><li>a</li><ol><li>b</li></ol></ol>'),
tinyApis.sSetCursor([0, 0, 0], 0),
tinyUi.sClickOnToolbar('click bullist button', 'div[aria-label="Bullet list"] > button'),
tinyApis.sAssertContent('<ul><li>a</li><ol><li>b</li></ol></ul>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 0, 0], 0)
])),
Logger.t('ol to ul, selection from parent to sublist', GeneralSteps.sequence([
tinyApis.sSetContent('<ol><li>a</li><ol><li>b</li></ol></ol>'),
tinyApis.sSetSelection([0, 0, 0], 0, [0, 1, 0, 0], 1),
tinyUi.sClickOnToolbar('click bullist button', 'div[aria-label="Bullet list"] > button'),
tinyApis.sAssertContent('<ul><li>a</li><ul><li>b</li></ul></ul>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 1, 0, 0], 1)
])),
Logger.t('alpha to ol, cursor only in parent', GeneralSteps.sequence([
tinyApis.sSetContent('<ol style="list-style-type: lower-alpha;"><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ol>'),
tinyApis.sSetCursor([0, 0, 0], 0),
tinyUi.sClickOnToolbar('click numlist button', 'div[aria-label="Numbered list"] button.mce-open'),
tinyUi.sClickOnUi('click lower alpha item', 'div[role="menuitem"] span:contains("Default")'),
tinyApis.sAssertContent('<ol><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ol>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 0, 0], 0)
])),
Logger.t('alpha to ol, selection from parent to sublist', GeneralSteps.sequence([
tinyApis.sSetContent('<ol style="list-style-type: lower-alpha;"><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ol>'),
tinyApis.sSetSelection([0, 0, 0], 0, [0, 1, 0, 0], 1),
tinyUi.sClickOnToolbar('click numlist button', 'div[aria-label="Numbered list"] button.mce-open'),
tinyUi.sClickOnUi('click lower alpha item', 'div[role="menuitem"] span:contains("Default")'),
tinyApis.sAssertContent('<ol><li>a</li><ol><li>b</li></ol></ol>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 1, 0, 0], 1)
])),
Logger.t('alpha to ul, cursor only in parent', GeneralSteps.sequence([
tinyApis.sSetContent('<ol style="list-style-type: lower-alpha;"><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ol>'),
tinyApis.sSetCursor([0, 0, 0], 0),
tinyUi.sClickOnToolbar('click numlist button', 'div[aria-label="Bullet list"] > button'),
tinyApis.sAssertContent('<ul><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ul>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 0, 0], 0)
])),
Logger.t('alpha to ul, selection from parent to sublist', GeneralSteps.sequence([
tinyApis.sSetContent('<ol style="list-style-type: lower-alpha;"><li>a</li><ol style="list-style-type: lower-alpha;"><li>b</li></ol></ol>'),
tinyApis.sSetSelection([0, 0, 0], 0, [0, 1, 0, 0], 1),
tinyUi.sClickOnToolbar('click numlist button', 'div[aria-label="Bullet list"] > button'),
tinyApis.sAssertContent('<ul><li>a</li><ul><li>b</li></ul></ul>'),
tinyApis.sAssertSelection([0, 0, 0], 0, [0, 1, 0, 0], 1)
]))
], onSuccess, onFailure);
}, {
indent: false,
plugins: 'lists advlist',
toolbar: 'numlist bullist',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,31 @@
import AdvListPlugin from 'tinymce/plugins/advlist/Plugin';
import ListsPlugin from 'tinymce/plugins/lists/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import { Pipeline } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.lists.SplitButtonTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
AdvListPlugin();
ListsPlugin();
ModernTheme();
suite.test('Replace splitbutton control with button when advlist_number_styles/advlist_bullet_styles are empty', function (editor) {
LegacyUnit.equal(editor.buttons.numlist.type, 'button');
LegacyUnit.equal(editor.buttons.bullist.type, 'button');
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
}, {
plugins: 'advlist lists',
advlist_bullet_styles: '',
advlist_number_styles: '',
toolbar: 'numlist bullist',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: anchor Demo Page</title>
</head>
<body>
<h2>Plugin: anchor Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/anchor/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'anchor code',
toolbar: 'anchor code',
height: 600
});
export {};

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Commands from './api/Commands';
import FilterContent from './core/FilterContent';
import Buttons from './ui/Buttons';
PluginManager.add('anchor', function (editor) {
FilterContent.setup(editor);
Commands.register(editor);
Buttons.register(editor);
});
export default function () { }

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from '../ui/Dialog';
const register = function (editor) {
editor.addCommand('mceAnchor', function () {
Dialog.open(editor);
});
};
export default {
register
};

View File

@@ -0,0 +1,40 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const isValidId = function (id) {
// Follows HTML4 rules: https://www.w3.org/TR/html401/types.html#type-id
return /^[A-Za-z][A-Za-z0-9\-:._]*$/.test(id);
};
const getId = function (editor) {
const selectedNode = editor.selection.getNode();
const isAnchor = selectedNode.tagName === 'A' && editor.dom.getAttrib(selectedNode, 'href') === '';
return isAnchor ? (selectedNode.id || selectedNode.name) : '';
};
const insert = function (editor, id) {
const selectedNode = editor.selection.getNode();
const isAnchor = selectedNode.tagName === 'A' && editor.dom.getAttrib(selectedNode, 'href') === '';
if (isAnchor) {
selectedNode.removeAttribute('name');
selectedNode.id = id;
editor.undoManager.add();
} else {
editor.focus();
editor.selection.collapse(true);
editor.execCommand('mceInsertContent', false, editor.dom.createHTML('a', {
id
}));
}
};
export default {
isValidId,
getId,
insert
};

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const isAnchorNode = function (node) {
return !node.attr('href') && (node.attr('id') || node.attr('name')) && !node.firstChild;
};
const setContentEditable = function (state) {
return function (nodes) {
for (let i = 0; i < nodes.length; i++) {
if (isAnchorNode(nodes[i])) {
nodes[i].attr('contenteditable', state);
}
}
};
};
const setup = function (editor) {
editor.on('PreInit', function () {
editor.parser.addNodeFilter('a', setContentEditable('false'));
editor.serializer.addNodeFilter('a', setContentEditable(null));
});
};
export default {
setup
};

View File

@@ -0,0 +1,26 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const register = function (editor) {
editor.addButton('anchor', {
icon: 'anchor',
tooltip: 'Anchor',
cmd: 'mceAnchor',
stateSelector: 'a:not([href])'
});
editor.addMenuItem('anchor', {
icon: 'anchor',
text: 'Anchor',
context: 'insert',
cmd: 'mceAnchor'
});
};
export default {
register
};

View File

@@ -0,0 +1,40 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Anchor from '../core/Anchor';
const insertAnchor = function (editor, newId) {
if (!Anchor.isValidId(newId)) {
editor.windowManager.alert(
'Id should start with a letter, followed only by letters, numbers, dashes, dots, colons or underscores.'
);
return true;
} else {
Anchor.insert(editor, newId);
return false;
}
};
const open = function (editor) {
const currentId = Anchor.getId(editor);
editor.windowManager.open({
title: 'Anchor',
body: { type: 'textbox', name: 'id', size: 40, label: 'Id', value: currentId },
onsubmit (e) {
const newId = e.data.id;
if (insertAnchor(editor, newId)) {
e.preventDefault();
}
}
});
};
export default {
open
};

View File

@@ -0,0 +1,48 @@
import { Pipeline, Step, Logger, GeneralSteps } from '@ephox/agar';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import AchorPlugin from 'tinymce/plugins/anchor/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.anchor.AnchorEditTest', (success, failure) => {
AchorPlugin();
ModernTheme();
const sType = function (text) {
return Step.sync(function () {
const elm: any = document.querySelector('div[aria-label="Anchor"].mce-floatpanel input');
elm.value = text;
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
Logger.t('add anchor, change anchor, undo anchor then the anchor should be there as first entered', GeneralSteps.sequence([
tinyApis.sFocus,
tinyApis.sSetContent('abc'),
tinyApis.sExecCommand('mceAnchor'),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"].mce-floatpanel input'),
sType('abc'),
tinyUi.sClickOnUi('click on OK btn', 'div.mce-primary > button'),
tinyApis.sAssertContentPresence({ 'a.mce-item-anchor#abc': 1 }),
tinyApis.sSelect('a.mce-item-anchor', []),
tinyApis.sExecCommand('mceAnchor'),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"].mce-floatpanel input'),
sType('def'),
tinyUi.sClickOnUi('click on OK btn', 'div.mce-primary > button'),
tinyApis.sAssertContentPresence({ 'a.mce-item-anchor#def': 1 }),
tinyApis.sExecCommand('undo'),
tinyApis.sSetCursor([], 0),
tinyApis.sAssertContentPresence({ 'a.mce-item-anchor#abc': 1 })
]))
], onSuccess, onFailure);
}, {
plugins: 'anchor',
toolbar: 'anchor',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,49 @@
import { Chain, Keys, Mouse, Pipeline, UiControls, UiFinder } from '@ephox/agar';
import { TinyActions, TinyApis, TinyLoader } from '@ephox/mcagar';
import { Element } from '@ephox/sugar';
import AnchorPlugin from 'tinymce/plugins/anchor/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('Browser Test: .AnchorInlineTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
AnchorPlugin();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
const tinyActions = TinyActions(editor);
Pipeline.async({}, [
tinyApis.sFocus,
tinyApis.sSetContent('<p>abc 123</p>'),
tinyApis.sSetSelection([0, 0], 4, [0, 0], 7),
tinyActions.sContentKeystroke(Keys.space(), {}),
tinyApis.sExecCommand('mceanchor'),
Chain.asStep(Element.fromDom(document.body), [
Chain.fromParent(UiFinder.cWaitForVisible('wait for dialog', 'div[aria-label="Anchor"][role="dialog"]'),
[
Chain.fromChains([
UiFinder.cFindIn('input'),
UiControls.cSetValue('abc')
]),
Chain.fromChains([
UiFinder.cFindIn('button:contains("Ok")'),
Mouse.cClick
])
]
)
]),
tinyApis.sAssertContent('<p>abc <a id="abc"></a>123</p>')
], onSuccess, onFailure);
}, {
inline: true,
plugins: 'anchor',
toolbar: 'anchor',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,44 @@
import { Pipeline, Step, Waiter } from '@ephox/agar';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import AchorPlugin from 'tinymce/plugins/anchor/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.anchor.AnchorSanityTest.js', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
AchorPlugin();
ModernTheme();
const sType = function (text) {
return Step.sync(function () {
const elm: any = document.querySelector('div[aria-label="Anchor"].mce-floatpanel input');
elm.value = text;
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
tinyApis.sSetContent('abc'),
tinyApis.sFocus,
tinyUi.sClickOnToolbar('click anchor button', 'div[aria-label="Anchor"] button'),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"].mce-floatpanel input'),
sType('abc'),
tinyUi.sClickOnUi('click on OK btn', 'div.mce-primary > button'),
Waiter.sTryUntil('wait for anchor',
tinyApis.sAssertContentPresence(
{ 'a.mce-item-anchor': 1 }
), 100, 4000
)
], onSuccess, onFailure);
}, {
plugins: 'anchor',
toolbar: 'anchor',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: autolink Demo Page</title>
</head>
<body>
<h2>Plugin: autolink Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/autolink/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'autolink code',
toolbar: 'autolink code',
height: 600
});
export {};

View File

@@ -0,0 +1,16 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Keys from './core/Keys';
import { Editor } from 'tinymce/core/api/Editor';
PluginManager.add('autolink', function (editor: Editor) {
Keys.setup(editor);
});
export default function () { }

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getAutoLinkPattern = function (editor) {
return editor.getParam('autolink_pattern', /^(https?:\/\/|ssh:\/\/|ftp:\/\/|file:\/|www\.|(?:mailto:)?[A-Z0-9._%+\-]+@)(.+)$/i);
};
const getDefaultLinkTarget = function (editor) {
return editor.getParam('default_link_target', '');
};
export default {
getAutoLinkPattern,
getDefaultLinkTarget
};

View File

@@ -0,0 +1,213 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Env from 'tinymce/core/api/Env';
import Settings from '../api/Settings';
import { Editor } from 'tinymce/core/api/Editor';
const rangeEqualsDelimiterOrSpace = function (rangeString, delimiter) {
return rangeString === delimiter || rangeString === ' ' || rangeString.charCodeAt(0) === 160;
};
const handleEclipse = function (editor) {
parseCurrentLine(editor, -1, '(');
};
const handleSpacebar = function (editor) {
parseCurrentLine(editor, 0, '');
};
const handleEnter = function (editor) {
parseCurrentLine(editor, -1, '');
};
const scopeIndex = function (container, index) {
if (index < 0) {
index = 0;
}
if (container.nodeType === 3) {
const len = container.data.length;
if (index > len) {
index = len;
}
}
return index;
};
const setStart = function (rng, container, offset) {
if (container.nodeType !== 1 || container.hasChildNodes()) {
rng.setStart(container, scopeIndex(container, offset));
} else {
rng.setStartBefore(container);
}
};
const setEnd = function (rng, container, offset) {
if (container.nodeType !== 1 || container.hasChildNodes()) {
rng.setEnd(container, scopeIndex(container, offset));
} else {
rng.setEndAfter(container);
}
};
const parseCurrentLine = function (editor, endOffset, delimiter) {
let rng, end, start, endContainer, bookmark, text, matches, prev, len, rngText;
const autoLinkPattern = Settings.getAutoLinkPattern(editor);
const defaultLinkTarget = Settings.getDefaultLinkTarget(editor);
// Never create a link when we are inside a link
if (editor.selection.getNode().tagName === 'A') {
return;
}
// We need at least five characters to form a URL,
// hence, at minimum, five characters from the beginning of the line.
rng = editor.selection.getRng(true).cloneRange();
if (rng.startOffset < 5) {
// During testing, the caret is placed between two text nodes.
// The previous text node contains the URL.
prev = rng.endContainer.previousSibling;
if (!prev) {
if (!rng.endContainer.firstChild || !rng.endContainer.firstChild.nextSibling) {
return;
}
prev = rng.endContainer.firstChild.nextSibling;
}
len = prev.length;
setStart(rng, prev, len);
setEnd(rng, prev, len);
if (rng.endOffset < 5) {
return;
}
end = rng.endOffset;
endContainer = prev;
} else {
endContainer = rng.endContainer;
// Get a text node
if (endContainer.nodeType !== 3 && endContainer.firstChild) {
while (endContainer.nodeType !== 3 && endContainer.firstChild) {
endContainer = endContainer.firstChild;
}
// Move range to text node
if (endContainer.nodeType === 3) {
setStart(rng, endContainer, 0);
setEnd(rng, endContainer, endContainer.nodeValue.length);
}
}
if (rng.endOffset === 1) {
end = 2;
} else {
end = rng.endOffset - 1 - endOffset;
}
}
start = end;
do {
// Move the selection one character backwards.
setStart(rng, endContainer, end >= 2 ? end - 2 : 0);
setEnd(rng, endContainer, end >= 1 ? end - 1 : 0);
end -= 1;
rngText = rng.toString();
// Loop until one of the following is found: a blank space, &nbsp;, delimiter, (end-2) >= 0
} while (rngText !== ' ' && rngText !== '' && rngText.charCodeAt(0) !== 160 && (end - 2) >= 0 && rngText !== delimiter);
if (rangeEqualsDelimiterOrSpace(rng.toString(), delimiter)) {
setStart(rng, endContainer, end);
setEnd(rng, endContainer, start);
end += 1;
} else if (rng.startOffset === 0) {
setStart(rng, endContainer, 0);
setEnd(rng, endContainer, start);
} else {
setStart(rng, endContainer, end);
setEnd(rng, endContainer, start);
}
// Exclude last . from word like "www.site.com."
text = rng.toString();
if (text.charAt(text.length - 1) === '.') {
setEnd(rng, endContainer, start - 1);
}
text = rng.toString().trim();
matches = text.match(autoLinkPattern);
if (matches) {
if (matches[1] === 'www.') {
matches[1] = 'http://www.';
} else if (/@$/.test(matches[1]) && !/^mailto:/.test(matches[1])) {
matches[1] = 'mailto:' + matches[1];
}
bookmark = editor.selection.getBookmark();
editor.selection.setRng(rng);
editor.execCommand('createlink', false, matches[1] + matches[2]);
if (defaultLinkTarget) {
editor.dom.setAttrib(editor.selection.getNode(), 'target', defaultLinkTarget);
}
editor.selection.moveToBookmark(bookmark);
editor.nodeChanged();
}
};
const setup = function (editor: Editor) {
let autoUrlDetectState;
editor.on('keydown', function (e) {
if (e.keyCode === 13) {
return handleEnter(editor);
}
});
// Internet Explorer has built-in automatic linking for most cases
if (Env.ie) {
editor.on('focus', function () {
if (!autoUrlDetectState) {
autoUrlDetectState = true;
try {
editor.execCommand('AutoUrlDetect', false, true);
} catch (ex) {
// Ignore
}
}
});
return;
}
editor.on('keypress', function (e) {
if (e.keyCode === 41) {
return handleEclipse(editor);
}
});
editor.on('keyup', function (e) {
if (e.keyCode === 32) {
return handleSpacebar(editor);
}
});
};
export default {
setup
};

View File

@@ -0,0 +1,130 @@
import { Pipeline } from '@ephox/agar';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Env from 'tinymce/core/api/Env';
import Plugin from 'tinymce/plugins/autolink/Plugin';
import KeyUtils from '../module/test/KeyUtils';
import Theme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.autolink.AutoLinkPluginTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
Theme();
Plugin();
const typeUrl = function (editor, url) {
editor.setContent('<p>' + url + '</p>');
LegacyUnit.setSelection(editor, 'p', url.length);
KeyUtils.type(editor, ' ');
return editor.getContent();
};
const typeAnEclipsedURL = function (editor, url) {
url = '(' + url;
editor.setContent('<p>' + url + '</p>');
LegacyUnit.setSelection(editor, 'p', url.length);
KeyUtils.type(editor, ')');
return editor.getContent();
};
const typeNewlineURL = function (editor, url) {
editor.setContent('<p>' + url + '</p>');
LegacyUnit.setSelection(editor, 'p', url.length);
KeyUtils.type(editor, '\n');
return editor.getContent();
};
suite.test('Urls ended with space', function (editor) {
editor.focus();
LegacyUnit.equal(typeUrl(editor, 'http://www.domain.com'), '<p><a href="http://www.domain.com">http://www.domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'https://www.domain.com'), '<p><a href="https://www.domain.com">https://www.domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'ssh://www.domain.com'), '<p><a href="ssh://www.domain.com">ssh://www.domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'ftp://www.domain.com'), '<p><a href="ftp://www.domain.com">ftp://www.domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'www.domain.com'), '<p><a href="http://www.domain.com">www.domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'www.domain.com.'), '<p><a href="http://www.domain.com">www.domain.com</a>.&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'user@domain.com'), '<p><a href="mailto:user@domain.com">user@domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'mailto:user@domain.com'), '<p><a href="mailto:user@domain.com">mailto:user@domain.com</a>&nbsp;</p>');
LegacyUnit.equal(typeUrl(editor, 'first-last@domain.com'), '<p><a href="mailto:first-last@domain.com">first-last@domain.com</a>&nbsp;</p>');
});
suite.test('Urls ended with )', function (editor) {
LegacyUnit.equal(
typeAnEclipsedURL(editor, 'http://www.domain.com'),
'<p>(<a href="http://www.domain.com">http://www.domain.com</a>)</p>'
);
LegacyUnit.equal(
typeAnEclipsedURL(editor, 'https://www.domain.com'),
'<p>(<a href="https://www.domain.com">https://www.domain.com</a>)</p>'
);
LegacyUnit.equal(
typeAnEclipsedURL(editor, 'ssh://www.domain.com'),
'<p>(<a href="ssh://www.domain.com">ssh://www.domain.com</a>)</p>'
);
LegacyUnit.equal(
typeAnEclipsedURL(editor, 'ftp://www.domain.com'),
'<p>(<a href="ftp://www.domain.com">ftp://www.domain.com</a>)</p>'
);
LegacyUnit.equal(typeAnEclipsedURL(editor, 'www.domain.com'), '<p>(<a href="http://www.domain.com">www.domain.com</a>)</p>');
LegacyUnit.equal(typeAnEclipsedURL(editor, 'www.domain.com.'), '<p>(<a href="http://www.domain.com">www.domain.com</a>.)</p>');
});
suite.test('Urls ended with new line', function (editor) {
LegacyUnit.equal(
typeNewlineURL(editor, 'http://www.domain.com'),
'<p><a href="http://www.domain.com">http://www.domain.com</a></p><p>&nbsp;</p>'
);
LegacyUnit.equal(
typeNewlineURL(editor, 'https://www.domain.com'),
'<p><a href="https://www.domain.com">https://www.domain.com</a></p><p>&nbsp;</p>'
);
LegacyUnit.equal(
typeNewlineURL(editor, 'ssh://www.domain.com'),
'<p><a href="ssh://www.domain.com">ssh://www.domain.com</a></p><p>&nbsp;</p>'
);
LegacyUnit.equal(
typeNewlineURL(editor, 'ftp://www.domain.com'),
'<p><a href="ftp://www.domain.com">ftp://www.domain.com</a></p><p>&nbsp;</p>'
);
LegacyUnit.equal(
typeNewlineURL(editor, 'www.domain.com'),
'<p><a href="http://www.domain.com">www.domain.com</a></p><p>&nbsp;</p>'
);
LegacyUnit.equal(
typeNewlineURL(editor, 'www.domain.com.'),
'<p><a href="http://www.domain.com">www.domain.com</a>.</p><p>&nbsp;</p>'
);
});
suite.test('Url inside blank formatting wrapper', function (editor) {
editor.focus();
editor.setContent('<p><br></p>');
editor.selection.setCursorLocation(editor.getBody().firstChild, 0);
editor.execCommand('Bold');
// inserting url via typeUrl() results in different behaviour, so lets simply type it in, char by char
KeyUtils.typeString(editor, 'http://www.domain.com ');
LegacyUnit.equal(
editor.getContent(),
'<p><strong><a href="http://www.domain.com">http://www.domain.com</a>&nbsp;</strong></p>'
);
});
suite.test('default_link_target=\'_self\'', function (editor) {
editor.settings.default_link_target = '_self';
LegacyUnit.equal(
typeUrl(editor, 'http://www.domain.com'),
'<p><a href="http://www.domain.com" target="_self">http://www.domain.com</a>&nbsp;</p>'
);
delete editor.settings.default_link_target;
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const steps = Env.ie ? [] : suite.toSteps(editor);
Pipeline.async({}, steps, onSuccess, onFailure);
}, {
plugins: 'autolink',
indent: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,43 @@
import { GeneralSteps, Logger, Pipeline, Step } from '@ephox/agar';
import { TinyApis, TinyLoader } from '@ephox/mcagar';
import Env from 'tinymce/core/api/Env';
import AutolinkPlugin from 'tinymce/plugins/autolink/Plugin';
import KeyUtils from '../module/test/KeyUtils';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.autolink.ConsecutiveLinkTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
AutolinkPlugin();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
const steps = Env.ie ? [] : [
tinyApis.sFocus,
Logger.t('Chrome adds a nbsp between link and text', GeneralSteps.sequence([
tinyApis.sSetContent('<p><a href="http://www.domain.com">www.domain.com</a>&nbsp;www.domain.com</p>'),
tinyApis.sSetCursor([0, 1], 15),
Step.sync(function () {
KeyUtils.type(editor, ' ');
}),
tinyApis.sAssertContent('<p><a href="http://www.domain.com">www.domain.com</a>&nbsp;<a href="http://www.domain.com">www.domain.com</a>&nbsp;</p>')
])),
Logger.t('FireFox does not seem to add a nbsp between link and text', GeneralSteps.sequence([
tinyApis.sSetContent('<p><a href="http://www.domain.com">www.domain.com</a> www.domain.com</p>'),
tinyApis.sSetCursor([0, 1], 15),
Step.sync(function () {
KeyUtils.type(editor, ' ');
}),
tinyApis.sAssertContent('<p><a href="http://www.domain.com">www.domain.com</a> <a href="http://www.domain.com">www.domain.com</a>&nbsp;</p>')
]))
];
Pipeline.async({}, steps, onSuccess, onFailure);
}, {
plugins: 'autolink',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,35 @@
import { Assertions, Keys, Pipeline, Step } from '@ephox/agar';
import { TinyActions, TinyApis, TinyLoader } from '@ephox/mcagar';
import AutoLinkPlugin from 'tinymce/plugins/autolink/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.autolink.EnterKeyTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
AutoLinkPlugin();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
const tinyActions = TinyActions(editor);
Pipeline.async({}, [
tinyApis.sFocus,
tinyApis.sSetContent('<p>abcdefghijk</p>'),
tinyApis.sSetCursor([0, 0], 11),
tinyActions.sContentKeystroke(Keys.enter(), {}),
Step.sync(function () {
try {
editor.fire('keydown', { keyCode: 13 });
} catch (error) {
Assertions.assertEq('should not throw error', true, false);
}
})
], onSuccess, onFailure);
}, {
plugins: 'autolink',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,134 @@
import { Fun, Arr } from '@ephox/katamari';
import NodeType from 'tinymce/core/dom/NodeType';
import { Range } from '@ephox/dom-globals';
const charCodeToKeyCode = function (charCode) {
const lookup = {
'0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57, 'a': 65, 'b': 66, 'c': 67,
'd': 68, 'e': 69, 'f': 70, 'g': 71, 'h': 72, 'i': 73, 'j': 74, 'k': 75, 'l': 76, 'm': 77, 'n': 78, 'o': 79, 'p': 80, 'q': 81,
'r': 82, 's': 83, 't': 84, 'u': 85, 'v': 86, 'w': 87, 'x': 88, 'y': 89, ' ': 32, ',': 188, '-': 189, '.': 190, '/': 191,
'\\': 220, '[': 219, ']': 221, '\'': 222, ';': 186, '=': 187, ')': 41
};
return lookup[String.fromCharCode(charCode)];
};
const needsNbsp = (rng: Range, chr: string) => {
const container = rng.startContainer;
const offset = rng.startOffset;
if (chr === ' ' && NodeType.isText(container)) {
if (container.data[offset - 1] === ' ' || offset === container.data.length) {
return true;
}
}
return false;
};
const type = function (editor, chr) {
let keyCode, charCode, evt, startElm, rng, offset;
const fakeEvent = function (target, type, evt) {
editor.dom.fire(target, type, evt);
};
// Numeric keyCode
if (typeof chr === 'number') {
charCode = chr;
keyCode = charCodeToKeyCode(charCode);
} else if (typeof chr === 'string') {
// String value
if (chr === '\b') {
keyCode = 8;
charCode = chr.charCodeAt(0);
} else if (chr === '\n') {
keyCode = 13;
charCode = chr.charCodeAt(0);
} else {
charCode = chr.charCodeAt(0);
keyCode = charCodeToKeyCode(charCode);
}
} else {
evt = chr;
if (evt.charCode) {
chr = String.fromCharCode(evt.charCode);
}
if (evt.keyCode) {
keyCode = evt.keyCode;
}
}
evt = evt || { keyCode, charCode };
startElm = editor.selection.getStart();
fakeEvent(startElm, 'keydown', evt);
fakeEvent(startElm, 'keypress', evt);
if (!evt.isDefaultPrevented()) {
if (keyCode === 8) {
if (editor.getDoc().selection) {
rng = editor.getDoc().selection.createRange();
if (rng.text.length === 0) {
rng.moveStart('character', -1);
rng.select();
}
rng.execCommand('Delete', false, null);
} else {
rng = editor.selection.getRng();
if (rng.collapsed) {
if (rng.startContainer.nodeType === 1) {
const nodes = rng.startContainer.childNodes, lastNode = nodes[nodes.length - 1];
// If caret is at <p>abc|</p> and after the abc text node then move it to the end of the text node
// Expand the range to include the last char <p>ab[c]</p> since IE 11 doesn't delete otherwise
if (rng.startOffset >= nodes.length - 1 && lastNode && lastNode.nodeType === 3 && lastNode.data.length > 0) {
rng.setStart(lastNode, lastNode.data.length - 1);
rng.setEnd(lastNode, lastNode.data.length);
editor.selection.setRng(rng);
}
} else if (rng.startContainer.nodeType === 3) {
// If caret is at <p>abc|</p> and after the abc text node then move it to the end of the text node
// Expand the range to include the last char <p>ab[c]</p> since IE 11 doesn't delete otherwise
offset = rng.startOffset;
if (offset > 0) {
rng.setStart(rng.startContainer, offset - 1);
rng.setEnd(rng.startContainer, offset);
editor.selection.setRng(rng);
}
}
}
editor.getDoc().execCommand('Delete', false, null);
}
} else if (typeof chr === 'string') {
rng = editor.selection.getRng(true);
if (rng.startContainer.nodeType === 3 && rng.collapsed) {
rng.startContainer.insertData(rng.startOffset, needsNbsp(rng, chr) ? '\u00a0' : chr);
rng.setStart(rng.startContainer, rng.startOffset + 1);
rng.collapse(true);
editor.selection.setRng(rng);
} else {
rng.deleteContents();
rng.insertNode(editor.getDoc().createTextNode(chr));
}
}
}
fakeEvent(startElm, 'keyup', evt);
};
const typeString = function (editor, str) {
Arr.each(str.split(''), Fun.curry(type, editor));
};
export default {
type,
typeString
};

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: autoresize Demo Page</title>
</head>
<body>
<h2>Plugin: autoresize Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
</body>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/autoresize/demo.js"></script>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'autoresize code',
toolbar: 'autoresize code',
height: 600
});
export {};

View File

@@ -0,0 +1,28 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { Cell } from '@ephox/katamari';
import PluginManager from 'tinymce/core/api/PluginManager';
import Commands from './api/Commands';
import Resize from './core/Resize';
/**
* This class contains all core logic for the autoresize plugin.
*
* @class tinymce.autoresize.Plugin
* @private
*/
PluginManager.add('autoresize', function (editor) {
if (!editor.inline) {
const oldSize = Cell(0);
Commands.register(editor, oldSize);
Resize.setup(editor, oldSize);
}
});
export default function () {}

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Resize from '../core/Resize';
const register = function (editor, oldSize) {
editor.addCommand('mceAutoResize', function () {
Resize.resize(editor, oldSize);
});
};
export default {
register
};

View File

@@ -0,0 +1,34 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getAutoResizeMinHeight = function (editor) {
return parseInt(editor.getParam('autoresize_min_height', editor.getElement().offsetHeight), 10);
};
const getAutoResizeMaxHeight = function (editor) {
return parseInt(editor.getParam('autoresize_max_height', 0), 10);
};
const getAutoResizeOverflowPadding = function (editor) {
return editor.getParam('autoresize_overflow_padding', 1);
};
const getAutoResizeBottomMargin = function (editor) {
return editor.getParam('autoresize_bottom_margin', 50);
};
const shouldAutoResizeOnInit = function (editor) {
return editor.getParam('autoresize_on_init', true);
};
export default {
getAutoResizeMinHeight,
getAutoResizeMaxHeight,
getAutoResizeOverflowPadding,
getAutoResizeBottomMargin,
shouldAutoResizeOnInit
};

View File

@@ -0,0 +1,156 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Env from 'tinymce/core/api/Env';
import Delay from 'tinymce/core/api/util/Delay';
import Settings from '../api/Settings';
/**
* This class contains all core logic for the autoresize plugin.
*
* @class tinymce.autoresize.Plugin
* @private
*/
const isFullscreen = function (editor) {
return editor.plugins.fullscreen && editor.plugins.fullscreen.isFullscreen();
};
/**
* Calls the resize x times in 100ms intervals. We can't wait for load events since
* the CSS files might load async.
*/
const wait = function (editor, oldSize, times, interval, callback?) {
Delay.setEditorTimeout(editor, function () {
resize(editor, oldSize);
if (times--) {
wait(editor, oldSize, times, interval, callback);
} else if (callback) {
callback();
}
}, interval);
};
const toggleScrolling = function (editor, state) {
const body = editor.getBody();
if (body) {
body.style.overflowY = state ? '' : 'hidden';
if (!state) {
body.scrollTop = 0;
}
}
};
/**
* This method gets executed each time the editor needs to resize.
*/
const resize = function (editor, oldSize) {
let deltaSize, doc, body, resizeHeight, myHeight;
let marginTop, marginBottom, paddingTop, paddingBottom, borderTop, borderBottom;
const dom = editor.dom;
doc = editor.getDoc();
if (!doc) {
return;
}
if (isFullscreen(editor)) {
toggleScrolling(editor, true);
return;
}
body = doc.body;
resizeHeight = Settings.getAutoResizeMinHeight(editor);
// Calculate outer height of the body element using CSS styles
marginTop = dom.getStyle(body, 'margin-top', true);
marginBottom = dom.getStyle(body, 'margin-bottom', true);
paddingTop = dom.getStyle(body, 'padding-top', true);
paddingBottom = dom.getStyle(body, 'padding-bottom', true);
borderTop = dom.getStyle(body, 'border-top-width', true);
borderBottom = dom.getStyle(body, 'border-bottom-width', true);
myHeight = body.offsetHeight + parseInt(marginTop, 10) + parseInt(marginBottom, 10) +
parseInt(paddingTop, 10) + parseInt(paddingBottom, 10) +
parseInt(borderTop, 10) + parseInt(borderBottom, 10);
// Make sure we have a valid height
if (isNaN(myHeight) || myHeight <= 0) {
// Get height differently depending on the browser used
// eslint-disable-next-line no-nested-ternary
myHeight = Env.ie ? body.scrollHeight : (Env.webkit && body.clientHeight === 0 ? 0 : body.offsetHeight);
}
// Don't make it smaller than the minimum height
if (myHeight > Settings.getAutoResizeMinHeight(editor)) {
resizeHeight = myHeight;
}
// If a maximum height has been defined don't exceed this height
const maxHeight = Settings.getAutoResizeMaxHeight(editor);
if (maxHeight && myHeight > maxHeight) {
resizeHeight = maxHeight;
toggleScrolling(editor, true);
} else {
toggleScrolling(editor, false);
}
// Resize content element
if (resizeHeight !== oldSize.get()) {
deltaSize = resizeHeight - oldSize.get();
dom.setStyle(editor.iframeElement, 'height', resizeHeight + 'px');
oldSize.set(resizeHeight);
// WebKit doesn't decrease the size of the body element until the iframe gets resized
// So we need to continue to resize the iframe down until the size gets fixed
if (Env.webkit && deltaSize < 0) {
resize(editor, oldSize);
}
}
};
const setup = function (editor, oldSize) {
editor.on('init', function () {
let overflowPadding, bottomMargin;
const dom = editor.dom;
overflowPadding = Settings.getAutoResizeOverflowPadding(editor);
bottomMargin = Settings.getAutoResizeBottomMargin(editor);
if (overflowPadding !== false) {
dom.setStyles(editor.getBody(), {
paddingLeft: overflowPadding,
paddingRight: overflowPadding
});
}
if (bottomMargin !== false) {
dom.setStyles(editor.getBody(), {
paddingBottom: bottomMargin
});
}
});
editor.on('nodechange setcontent keyup FullscreenStateChanged', function (e) {
resize(editor, oldSize);
});
if (Settings.shouldAutoResizeOnInit(editor)) {
editor.on('init', function () {
// Hit it 20 times in 100 ms intervals
wait(editor, oldSize, 20, 100, function () {
// Hit it 5 times in 1 sec intervals
wait(editor, oldSize, 5, 1000);
});
});
}
};
export default {
setup,
resize
};

View File

@@ -0,0 +1,81 @@
import { Assertions, GeneralSteps, Logger, Pipeline, RawAssertions, Step, Waiter } from '@ephox/agar';
import { Arr } from '@ephox/katamari';
import { TinyApis, TinyLoader } from '@ephox/mcagar';
import AutoresizePlugin from 'tinymce/plugins/autoresize/Plugin';
import FullscreenPlugin from 'tinymce/plugins/fullscreen/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { navigator } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.autoresize.AutoresizePluginTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
AutoresizePlugin();
FullscreenPlugin();
ModernTheme();
const sAssertEditorHeightAbove = function (editor, minHeight) {
return Step.sync(function () {
const editorHeight = editor.getContainer().clientHeight;
RawAssertions.assertEq('should be above: ' + editorHeight + '>=' + minHeight, true, editorHeight >= minHeight);
});
};
const sAssertEditorHeightBelow = function (editor, minHeight) {
return Step.sync(function () {
const editorHeight = editor.getContainer().clientHeight;
RawAssertions.assertEq('should be below: ' + editorHeight + '<=' + minHeight, true, editorHeight <= minHeight);
});
};
const sAssertScroll = function (editor, state) {
return Step.sync(function () {
const body = editor.getBody();
Assertions.assertEq('', !state, body.style.overflowY === 'hidden');
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
Pipeline.async({}, Arr.flatten([
[
Logger.t('Fullscreen toggle scroll state', GeneralSteps.sequence([
tinyApis.sExecCommand('mceFullScreen'),
sAssertScroll(editor, true),
tinyApis.sExecCommand('mceFullScreen'),
sAssertScroll(editor, false)
])),
Logger.t('Editor size increase based on content size', GeneralSteps.sequence([
tinyApis.sSetContent('<div style="height: 5000px;">a</div>'),
Waiter.sTryUntil('wait for editor height', sAssertEditorHeightAbove(editor, 5000), 10, 3000)
])),
Logger.t('Editor size decrease based on content size', GeneralSteps.sequence([
tinyApis.sSetContent('<div style="height: 1000px;">a</div>'),
Waiter.sTryUntil('wait for editor height', sAssertEditorHeightBelow(editor, 2000), 10, 3000)
]))
],
// These tests doesn't work on phantom since measuring things seems broken there
navigator.userAgent.indexOf('PhantomJS') === -1 ? [
Logger.t('Editor size decrease content to 1000 based and restrict by max height', GeneralSteps.sequence([
tinyApis.sSetSetting('autoresize_max_height', 200),
tinyApis.sSetContent('<div style="height: 1000px;">a</div>'),
Waiter.sTryUntil('wait for editor height', sAssertEditorHeightBelow(editor, 500), 10, 3000),
tinyApis.sSetSetting('autoresize_max_height', 0)
])),
Logger.t('Editor size decrease content to 10 and set min height to 500', GeneralSteps.sequence([
tinyApis.sSetSetting('autoresize_min_height', 500),
tinyApis.sSetContent('<div style="height: 10px;">a</div>'),
Waiter.sTryUntil('wait for editor height', sAssertEditorHeightAbove(editor, 300), 10, 3000),
tinyApis.sSetSetting('autoresize_min_height', 0)
]))
] : []
]), onSuccess, onFailure);
}, {
plugins: 'autoresize fullscreen',
toolbar: 'autoresize',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: autosave Demo Page</title>
</head>
<body>
<h2>Plugin: autosave Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/autosave/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'autosave code',
toolbar: 'restoredraft code',
height: 600
});
export {};

View File

@@ -0,0 +1,39 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { Cell } from '@ephox/katamari';
import PluginManager from 'tinymce/core/api/PluginManager';
import * as Api from './api/Api';
import * as BeforeUnload from './core/BeforeUnload';
import * as Buttons from './ui/Buttons';
import * as Storage from './core/Storage';
import { Editor } from 'tinymce/core/api/Editor';
import * as Settings from './api/Settings';
/**
* This class contains all core logic for the autosave plugin.
*
* @class tinymce.autosave.Plugin
* @private
*/
PluginManager.add('autosave', function (editor: Editor) {
const started = Cell(false);
BeforeUnload.setup(editor);
Buttons.register(editor, started);
editor.on('init', function () {
if (Settings.shouldRestoreWhenEmpty(editor) && editor.dom.isEmpty(editor.getBody())) {
Storage.restoreDraft(editor);
}
});
return Api.get(editor);
});
export default function () { }

View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import * as Storage from '../core/Storage';
import { Fun } from '@ephox/katamari';
const get = function (editor) {
return {
hasDraft: Fun.curry(Storage.hasDraft, editor),
storeDraft: Fun.curry(Storage.storeDraft, editor),
restoreDraft: Fun.curry(Storage.restoreDraft, editor),
removeDraft: Fun.curry(Storage.removeDraft, editor),
isEmpty: Fun.curry(Storage.isEmpty, editor)
};
};
export {
get
};

View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const fireRestoreDraft = (editor) => {
return editor.fire('RestoreDraft');
};
const fireStoreDraft = (editor) => {
return editor.fire('StoreDraft');
};
const fireRemoveDraft = (editor) => {
return editor.fire('RemoveDraft');
};
export {
fireRestoreDraft,
fireStoreDraft,
fireRemoveDraft
};

View File

@@ -0,0 +1,44 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import * as Time from '../core/Time';
import { document } from '@ephox/dom-globals';
const shouldAskBeforeUnload = (editor) => {
return editor.getParam('autosave_ask_before_unload', true);
};
const getAutoSavePrefix = (editor) => {
let prefix = editor.getParam('autosave_prefix', 'tinymce-autosave-{path}{query}{hash}-{id}-');
prefix = prefix.replace(/\{path\}/g, document.location.pathname);
prefix = prefix.replace(/\{query\}/g, document.location.search);
prefix = prefix.replace(/\{hash\}/g, document.location.hash);
prefix = prefix.replace(/\{id\}/g, editor.id);
return prefix;
};
const shouldRestoreWhenEmpty = (editor) => {
return editor.getParam('autosave_restore_when_empty', false);
};
const getAutoSaveInterval = (editor) => {
return Time.parse(editor.settings.autosave_interval, '30s');
};
const getAutoSaveRetention = (editor) => {
return Time.parse(editor.settings.autosave_retention, '20m');
};
export {
shouldAskBeforeUnload,
getAutoSavePrefix,
shouldRestoreWhenEmpty,
getAutoSaveInterval,
getAutoSaveRetention
};

View File

@@ -0,0 +1,37 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import EditorManager from 'tinymce/core/api/EditorManager';
import Tools from 'tinymce/core/api/util/Tools';
import * as Settings from '../api/Settings';
import { window } from '@ephox/dom-globals';
EditorManager._beforeUnloadHandler = () => {
let msg;
Tools.each(EditorManager.get(), (editor) => {
// Store a draft for each editor instance
if (editor.plugins.autosave) {
editor.plugins.autosave.storeDraft();
}
// Setup a return message if the editor is dirty
if (!msg && editor.isDirty() && Settings.shouldAskBeforeUnload(editor)) {
msg = editor.translate('You have unsaved changes are you sure you want to navigate away?');
}
});
return msg;
};
const setup = (editor) => {
window.onbeforeunload = EditorManager._beforeUnloadHandler;
};
export {
setup
};

View File

@@ -0,0 +1,97 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import LocalStorage from 'tinymce/core/api/util/LocalStorage';
import Tools from 'tinymce/core/api/util/Tools';
import * as Events from '../api/Events';
import * as Settings from '../api/Settings';
import { Editor } from 'tinymce/core/api/Editor';
import { Cell } from '@ephox/katamari';
const isEmpty = (editor: Editor, html?: string) => {
const forcedRootBlockName = editor.settings.forced_root_block;
html = Tools.trim(typeof html === 'undefined' ? editor.getBody().innerHTML : html);
return html === '' || new RegExp(
'^<' + forcedRootBlockName + '[^>]*>((\u00a0|&nbsp;|[ \t]|<br[^>]*>)+?|)<\/' + forcedRootBlockName + '>|<br>$', 'i'
).test(html);
};
const hasDraft = (editor: Editor) => {
const time = parseInt(LocalStorage.getItem(Settings.getAutoSavePrefix(editor) + 'time'), 10) || 0;
if (new Date().getTime() - time > Settings.getAutoSaveRetention(editor)) {
removeDraft(editor, false);
return false;
}
return true;
};
const removeDraft = (editor: Editor, fire?: boolean) => {
const prefix = Settings.getAutoSavePrefix(editor);
LocalStorage.removeItem(prefix + 'draft');
LocalStorage.removeItem(prefix + 'time');
if (fire !== false) {
Events.fireRemoveDraft(editor);
}
};
const storeDraft = (editor: Editor) => {
const prefix = Settings.getAutoSavePrefix(editor);
if (!isEmpty(editor) && editor.isDirty()) {
LocalStorage.setItem(prefix + 'draft', editor.getContent({ format: 'raw', no_events: true }) as string);
LocalStorage.setItem(prefix + 'time', new Date().getTime().toString());
Events.fireStoreDraft(editor);
}
};
const restoreDraft = (editor: Editor) => {
const prefix = Settings.getAutoSavePrefix(editor);
if (hasDraft(editor)) {
editor.setContent(LocalStorage.getItem(prefix + 'draft'), { format: 'raw' });
Events.fireRestoreDraft(editor);
}
};
const startStoreDraft = (editor: Editor, started: Cell<boolean>) => {
const interval = Settings.getAutoSaveInterval(editor);
if (!started.get()) {
setInterval(() => {
if (!editor.removed) {
storeDraft(editor);
}
}, interval);
started.set(true);
}
};
const restoreLastDraft = (editor: Editor) => {
editor.undoManager.transact(() => {
restoreDraft(editor);
removeDraft(editor);
});
editor.focus();
};
export {
isEmpty,
hasDraft,
removeDraft,
storeDraft,
restoreDraft,
startStoreDraft,
restoreLastDraft
};

View File

@@ -0,0 +1,22 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const parse = (timeString: string, defaultTime: string) => {
const multiples = {
s: 1000,
m: 60000
};
const toParse = (timeString || defaultTime);
const parsedTime = /^(\d+)([ms]?)$/.exec('' + toParse);
return (parsedTime[2] ? multiples[parsedTime[2]] : 1) * parseInt(toParse, 10);
};
export {
parse
};

View File

@@ -0,0 +1,50 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import * as Storage from '../core/Storage';
import { Editor } from 'tinymce/core/api/Editor';
import { Cell } from '@ephox/katamari';
const postRender = (editor: Editor, started: Cell<boolean>) => {
return (e) => {
const ctrl = e.control;
ctrl.disabled(!Storage.hasDraft(editor));
editor.on('StoreDraft RestoreDraft RemoveDraft', () => {
ctrl.disabled(!Storage.hasDraft(editor));
});
// TODO: Investigate why this is only done on postrender that would
// make the feature broken if only the menu item was rendered since
// it is rendered when the menu appears
Storage.startStoreDraft(editor, started);
};
};
const register = (editor: Editor, started: Cell<boolean>) => {
editor.addButton('restoredraft', {
title: 'Restore last draft',
onclick () {
Storage.restoreLastDraft(editor);
},
onPostRender: postRender(editor, started)
});
editor.addMenuItem('restoredraft', {
text: 'Restore last draft',
onclick () {
Storage.restoreLastDraft(editor);
},
onPostRender: postRender(editor, started),
context: 'file'
});
};
export {
register
};

View File

@@ -0,0 +1,92 @@
import { Pipeline } from '@ephox/agar';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/autosave/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { document, window, history } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.autosave.AutoSavePluginTest', (success, failure) => {
const suite = LegacyUnit.createSuite();
Plugin();
Theme();
suite.test('isEmpty true', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.isEmpty(''), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty(' '), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('\t\t\t'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p id="x"></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p> </p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p>\t</p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br /></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" /></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br><br></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br /><br /></p>'), true);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" /><br data-mce-bogus="true" /></p>'), true);
});
suite.test('isEmpty false', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.isEmpty('X'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty(' X'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('\t\t\tX'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p>X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p> X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p>\tX</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br>X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br><br>X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br /><br />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<p><br data-mce-bogus="true" /><br data-mce-bogus="true" />X</p>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<h1></h1>'), false);
LegacyUnit.equal(editor.plugins.autosave.isEmpty('<img src="x" />'), false);
});
suite.test('hasDraft/storeDraft/restoreDraft', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), false);
editor.setContent('X');
editor.undoManager.add();
editor.plugins.autosave.storeDraft();
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), true);
editor.setContent('Y');
editor.undoManager.add();
editor.plugins.autosave.restoreDraft();
LegacyUnit.equal(editor.getContent(), '<p>X</p>');
editor.plugins.autosave.removeDraft();
});
suite.test('recognises location hash change', function (editor) {
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), false);
editor.setContent('X');
editor.undoManager.add();
editor.plugins.autosave.storeDraft();
window.location.hash = 'test' + Math.random().toString(36).substring(7);
LegacyUnit.equal(editor.plugins.autosave.hasDraft(), false);
history.replaceState('', document.title, window.location.pathname + window.location.search);
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
}, {
plugins: 'autosave',
indent: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,59 @@
import Theme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { Editor } from 'tinymce/core/api/Editor';
import { Editor as McEditor, ApiChains } from '@ephox/mcagar';
import { Pipeline, Logger, Chain, RawAssertions } from '@ephox/agar';
import Plugin from 'tinymce/plugins/autosave/Plugin';
UnitTest.asynctest('browser.tinymce.plugins.autosave.ShouldRestoreWhenEmptyTest', (success, failure) => {
Theme();
Plugin();
const cAssertHasDraft = (expected: boolean) => Chain.op((editor: Editor) => {
RawAssertions.assertEq(`should${!expected ? 'n\'t' : ''} have draft`, expected, editor.plugins.autosave.hasDraft());
});
const cStoreDraft = Chain.op((editor: Editor) => {
editor.plugins.autosave.storeDraft();
});
const cRemoveDraft = Chain.op((editor: Editor) => {
editor.plugins.autosave.removeDraft();
});
const cAddUndoLevel = Chain.op((editor: Editor) => {
editor.undoManager.add();
});
const testingPrefix = Math.random().toString(36).substring(7);
Pipeline.async({}, [
Logger.t('should restore draft when empty with setting', Chain.asStep({}, [
McEditor.cFromSettings({ skin_url: '/project/js/tinymce/skins/lightgray', plugins: 'autosave', autosave_prefix: testingPrefix }),
cAssertHasDraft(false),
ApiChains.cSetContent('<p>X</p>'),
cAddUndoLevel,
cStoreDraft,
cAssertHasDraft(true),
McEditor.cRemove,
McEditor.cFromSettings({ autosave_restore_when_empty: true, skin_url: '/project/js/tinymce/skins/lightgray', plugins: 'autosave', autosave_prefix: testingPrefix }),
cAssertHasDraft(true),
ApiChains.cAssertContent('<p>X</p>'),
cRemoveDraft,
McEditor.cRemove
])),
Logger.t('shouldn\'t restore draft when empty without setting', Chain.asStep({}, [
McEditor.cFromSettings({ skin_url: '/project/js/tinymce/skins/lightgray', plugins: 'autosave', autosave_prefix: testingPrefix }),
cAssertHasDraft(false),
ApiChains.cSetContent('<p>X</p>'),
cAddUndoLevel,
cStoreDraft,
cAssertHasDraft(true),
McEditor.cRemove,
McEditor.cFromSettings({ skin_url: '/project/js/tinymce/skins/lightgray', plugins: 'autosave', autosave_prefix: testingPrefix }),
cAssertHasDraft(true),
ApiChains.cAssertContent(''),
cRemoveDraft,
McEditor.cRemove
]))
], () => success(), failure);
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: bbcode Demo Page</title>
</head>
<body>
<h2>Plugin: bbcode Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/bbcode/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,28 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
import { document } from '@ephox/dom-globals';
declare let tinymce: any;
let elm: any;
elm = document.querySelector('.tinymce');
elm.value = '[b]bbcode plugin[/b]';
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'bbcode code',
toolbar: 'bbcode code',
height: 600
});
export {};

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Convert from './core/Convert';
PluginManager.add('bbcode', function () {
return {
init (editor) {
editor.on('beforeSetContent', function (e) {
e.content = Convert.bbcode2html(e.content);
});
editor.on('postProcess', function (e) {
if (e.set) {
e.content = Convert.bbcode2html(e.content);
}
if (e.get) {
e.content = Convert.html2bbcode(e.content);
}
});
}
};
});
export default function () { }

View File

@@ -0,0 +1,15 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getDialect = function (editor) {
// Note: This option isn't even used since we only support one dialect
return editor.getParam('bbcode_dialect', 'punbb').toLowerCase();
};
export default {
getDialect
};

View File

@@ -0,0 +1,87 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
const html2bbcode = function (s) {
s = Tools.trim(s);
const rep = function (re, str) {
s = s.replace(re, str);
};
// example: <strong> to [b]
rep(/<a.*?href=\"(.*?)\".*?>(.*?)<\/a>/gi, '[url=$1]$2[/url]');
rep(/<font.*?color=\"(.*?)\".*?class=\"codeStyle\".*?>(.*?)<\/font>/gi, '[code][color=$1]$2[/color][/code]');
rep(/<font.*?color=\"(.*?)\".*?class=\"quoteStyle\".*?>(.*?)<\/font>/gi, '[quote][color=$1]$2[/color][/quote]');
rep(/<font.*?class=\"codeStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, '[code][color=$1]$2[/color][/code]');
rep(/<font.*?class=\"quoteStyle\".*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, '[quote][color=$1]$2[/color][/quote]');
rep(/<span style=\"color: ?(.*?);\">(.*?)<\/span>/gi, '[color=$1]$2[/color]');
rep(/<font.*?color=\"(.*?)\".*?>(.*?)<\/font>/gi, '[color=$1]$2[/color]');
rep(/<span style=\"font-size:(.*?);\">(.*?)<\/span>/gi, '[size=$1]$2[/size]');
rep(/<font>(.*?)<\/font>/gi, '$1');
rep(/<img.*?src=\"(.*?)\".*?\/>/gi, '[img]$1[/img]');
rep(/<span class=\"codeStyle\">(.*?)<\/span>/gi, '[code]$1[/code]');
rep(/<span class=\"quoteStyle\">(.*?)<\/span>/gi, '[quote]$1[/quote]');
rep(/<strong class=\"codeStyle\">(.*?)<\/strong>/gi, '[code][b]$1[/b][/code]');
rep(/<strong class=\"quoteStyle\">(.*?)<\/strong>/gi, '[quote][b]$1[/b][/quote]');
rep(/<em class=\"codeStyle\">(.*?)<\/em>/gi, '[code][i]$1[/i][/code]');
rep(/<em class=\"quoteStyle\">(.*?)<\/em>/gi, '[quote][i]$1[/i][/quote]');
rep(/<u class=\"codeStyle\">(.*?)<\/u>/gi, '[code][u]$1[/u][/code]');
rep(/<u class=\"quoteStyle\">(.*?)<\/u>/gi, '[quote][u]$1[/u][/quote]');
rep(/<\/(strong|b)>/gi, '[/b]');
rep(/<(strong|b)>/gi, '[b]');
rep(/<\/(em|i)>/gi, '[/i]');
rep(/<(em|i)>/gi, '[i]');
rep(/<\/u>/gi, '[/u]');
rep(/<span style=\"text-decoration: ?underline;\">(.*?)<\/span>/gi, '[u]$1[/u]');
rep(/<u>/gi, '[u]');
rep(/<blockquote[^>]*>/gi, '[quote]');
rep(/<\/blockquote>/gi, '[/quote]');
rep(/<br \/>/gi, '\n');
rep(/<br\/>/gi, '\n');
rep(/<br>/gi, '\n');
rep(/<p>/gi, '');
rep(/<\/p>/gi, '\n');
rep(/&nbsp;|\u00a0/gi, ' ');
rep(/&quot;/gi, '"');
rep(/&lt;/gi, '<');
rep(/&gt;/gi, '>');
rep(/&amp;/gi, '&');
return s;
};
const bbcode2html = function (s) {
s = Tools.trim(s);
const rep = function (re, str) {
s = s.replace(re, str);
};
// example: [b] to <strong>
rep(/\n/gi, '<br />');
rep(/\[b\]/gi, '<strong>');
rep(/\[\/b\]/gi, '</strong>');
rep(/\[i\]/gi, '<em>');
rep(/\[\/i\]/gi, '</em>');
rep(/\[u\]/gi, '<u>');
rep(/\[\/u\]/gi, '</u>');
rep(/\[url=([^\]]+)\](.*?)\[\/url\]/gi, '<a href="$1">$2</a>');
rep(/\[url\](.*?)\[\/url\]/gi, '<a href="$1">$1</a>');
rep(/\[img\](.*?)\[\/img\]/gi, '<img src="$1" />');
rep(/\[color=(.*?)\](.*?)\[\/color\]/gi, '<font color="$1">$2</font>');
rep(/\[code\](.*?)\[\/code\]/gi, '<span class="codeStyle">$1</span>&nbsp;');
rep(/\[quote.*?\](.*?)\[\/quote\]/gi, '<span class="quoteStyle">$1</span>&nbsp;');
return s;
};
export default {
html2bbcode,
bbcode2html
};

View File

@@ -0,0 +1,41 @@
import { ApproxStructure, Pipeline } from '@ephox/agar';
import { TinyApis, TinyLoader } from '@ephox/mcagar';
import BbcodePlugin from 'tinymce/plugins/bbcode/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.bbcode.BbcodeSanityTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
BbcodePlugin();
ModernTheme();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
tinyApis.sSetContent('[b]a[/b]'),
tinyApis.sAssertContentStructure(ApproxStructure.build(function (s, str) {
return s.element('body', {
children: [
s.element('p', {
children: [
s.element('strong', {
children: [
s.text(str.is('a'))
]
})
]
})
]
});
}))
], onSuccess, onFailure);
}, {
plugins: 'bbcode',
toolbar: 'bbcode',
skin_url: '/project/js/tinymce/skins/lightgray',
bbcode_dialect: 'punbb'
}, success, failure);
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: charmap Demo Page</title>
</head>
<body>
<h2>Plugin: charmap Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/charmap/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'charmap code',
toolbar: 'charmap code',
height: 600
});
export {};

View File

@@ -0,0 +1,20 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Api from './api/Api';
import Commands from './api/Commands';
import Buttons from './ui/Buttons';
PluginManager.add('charmap', function (editor) {
Commands.register(editor);
Buttons.register(editor);
return Api.get(editor);
});
export default function () { }

View File

@@ -0,0 +1,28 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Actions from '../core/Actions';
import CharMap from '../core/CharMap';
const get = function (editor) {
const getCharMap = function () {
return CharMap.getCharMap(editor);
};
const insertChar = function (chr) {
Actions.insertChar(editor, chr);
};
return {
getCharMap,
insertChar
};
};
export default {
get
};

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from '../ui/Dialog';
const register = function (editor) {
editor.addCommand('mceShowCharmap', function () {
Dialog.open(editor);
});
};
export default {
register
};

View File

@@ -0,0 +1,14 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const fireInsertCustomChar = function (editor, chr) {
return editor.fire('insertCustomChar', { chr });
};
export default {
fireInsertCustomChar
};

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getCharMap = function (editor) {
return editor.settings.charmap;
};
const getCharMapAppend = function (editor) {
return editor.settings.charmap_append;
};
export default {
getCharMap,
getCharMapAppend
};

View File

@@ -0,0 +1,17 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Events from '../api/Events';
const insertChar = function (editor, chr) {
const evtChr = Events.fireInsertCustomChar(editor, chr).chr;
editor.execCommand('mceInsertContent', false, evtChr);
};
export default {
insertChar
};

View File

@@ -0,0 +1,326 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Tools from 'tinymce/core/api/util/Tools';
import Settings from '../api/Settings';
const isArray = Tools.isArray;
const getDefaultCharMap = function () {
return [
['160', 'no-break space'],
['173', 'soft hyphen'],
['34', 'quotation mark'],
// finance
['162', 'cent sign'],
['8364', 'euro sign'],
['163', 'pound sign'],
['165', 'yen sign'],
// signs
['169', 'copyright sign'],
['174', 'registered sign'],
['8482', 'trade mark sign'],
['8240', 'per mille sign'],
['181', 'micro sign'],
['183', 'middle dot'],
['8226', 'bullet'],
['8230', 'three dot leader'],
['8242', 'minutes / feet'],
['8243', 'seconds / inches'],
['167', 'section sign'],
['182', 'paragraph sign'],
['223', 'sharp s / ess-zed'],
// quotations
['8249', 'single left-pointing angle quotation mark'],
['8250', 'single right-pointing angle quotation mark'],
['171', 'left pointing guillemet'],
['187', 'right pointing guillemet'],
['8216', 'left single quotation mark'],
['8217', 'right single quotation mark'],
['8220', 'left double quotation mark'],
['8221', 'right double quotation mark'],
['8218', 'single low-9 quotation mark'],
['8222', 'double low-9 quotation mark'],
['60', 'less-than sign'],
['62', 'greater-than sign'],
['8804', 'less-than or equal to'],
['8805', 'greater-than or equal to'],
['8211', 'en dash'],
['8212', 'em dash'],
['175', 'macron'],
['8254', 'overline'],
['164', 'currency sign'],
['166', 'broken bar'],
['168', 'diaeresis'],
['161', 'inverted exclamation mark'],
['191', 'turned question mark'],
['710', 'circumflex accent'],
['732', 'small tilde'],
['176', 'degree sign'],
['8722', 'minus sign'],
['177', 'plus-minus sign'],
['247', 'division sign'],
['8260', 'fraction slash'],
['215', 'multiplication sign'],
['185', 'superscript one'],
['178', 'superscript two'],
['179', 'superscript three'],
['188', 'fraction one quarter'],
['189', 'fraction one half'],
['190', 'fraction three quarters'],
// math / logical
['402', 'function / florin'],
['8747', 'integral'],
['8721', 'n-ary sumation'],
['8734', 'infinity'],
['8730', 'square root'],
['8764', 'similar to'],
['8773', 'approximately equal to'],
['8776', 'almost equal to'],
['8800', 'not equal to'],
['8801', 'identical to'],
['8712', 'element of'],
['8713', 'not an element of'],
['8715', 'contains as member'],
['8719', 'n-ary product'],
['8743', 'logical and'],
['8744', 'logical or'],
['172', 'not sign'],
['8745', 'intersection'],
['8746', 'union'],
['8706', 'partial differential'],
['8704', 'for all'],
['8707', 'there exists'],
['8709', 'diameter'],
['8711', 'backward difference'],
['8727', 'asterisk operator'],
['8733', 'proportional to'],
['8736', 'angle'],
// undefined
['180', 'acute accent'],
['184', 'cedilla'],
['170', 'feminine ordinal indicator'],
['186', 'masculine ordinal indicator'],
['8224', 'dagger'],
['8225', 'double dagger'],
// alphabetical special chars
['192', 'A - grave'],
['193', 'A - acute'],
['194', 'A - circumflex'],
['195', 'A - tilde'],
['196', 'A - diaeresis'],
['197', 'A - ring above'],
['256', 'A - macron'],
['198', 'ligature AE'],
['199', 'C - cedilla'],
['200', 'E - grave'],
['201', 'E - acute'],
['202', 'E - circumflex'],
['203', 'E - diaeresis'],
['274', 'E - macron'],
['204', 'I - grave'],
['205', 'I - acute'],
['206', 'I - circumflex'],
['207', 'I - diaeresis'],
['298', 'I - macron'],
['208', 'ETH'],
['209', 'N - tilde'],
['210', 'O - grave'],
['211', 'O - acute'],
['212', 'O - circumflex'],
['213', 'O - tilde'],
['214', 'O - diaeresis'],
['216', 'O - slash'],
['332', 'O - macron'],
['338', 'ligature OE'],
['352', 'S - caron'],
['217', 'U - grave'],
['218', 'U - acute'],
['219', 'U - circumflex'],
['220', 'U - diaeresis'],
['362', 'U - macron'],
['221', 'Y - acute'],
['376', 'Y - diaeresis'],
['562', 'Y - macron'],
['222', 'THORN'],
['224', 'a - grave'],
['225', 'a - acute'],
['226', 'a - circumflex'],
['227', 'a - tilde'],
['228', 'a - diaeresis'],
['229', 'a - ring above'],
['257', 'a - macron'],
['230', 'ligature ae'],
['231', 'c - cedilla'],
['232', 'e - grave'],
['233', 'e - acute'],
['234', 'e - circumflex'],
['235', 'e - diaeresis'],
['275', 'e - macron'],
['236', 'i - grave'],
['237', 'i - acute'],
['238', 'i - circumflex'],
['239', 'i - diaeresis'],
['299', 'i - macron'],
['240', 'eth'],
['241', 'n - tilde'],
['242', 'o - grave'],
['243', 'o - acute'],
['244', 'o - circumflex'],
['245', 'o - tilde'],
['246', 'o - diaeresis'],
['248', 'o slash'],
['333', 'o macron'],
['339', 'ligature oe'],
['353', 's - caron'],
['249', 'u - grave'],
['250', 'u - acute'],
['251', 'u - circumflex'],
['252', 'u - diaeresis'],
['363', 'u - macron'],
['253', 'y - acute'],
['254', 'thorn'],
['255', 'y - diaeresis'],
['563', 'y - macron'],
['913', 'Alpha'],
['914', 'Beta'],
['915', 'Gamma'],
['916', 'Delta'],
['917', 'Epsilon'],
['918', 'Zeta'],
['919', 'Eta'],
['920', 'Theta'],
['921', 'Iota'],
['922', 'Kappa'],
['923', 'Lambda'],
['924', 'Mu'],
['925', 'Nu'],
['926', 'Xi'],
['927', 'Omicron'],
['928', 'Pi'],
['929', 'Rho'],
['931', 'Sigma'],
['932', 'Tau'],
['933', 'Upsilon'],
['934', 'Phi'],
['935', 'Chi'],
['936', 'Psi'],
['937', 'Omega'],
['945', 'alpha'],
['946', 'beta'],
['947', 'gamma'],
['948', 'delta'],
['949', 'epsilon'],
['950', 'zeta'],
['951', 'eta'],
['952', 'theta'],
['953', 'iota'],
['954', 'kappa'],
['955', 'lambda'],
['956', 'mu'],
['957', 'nu'],
['958', 'xi'],
['959', 'omicron'],
['960', 'pi'],
['961', 'rho'],
['962', 'final sigma'],
['963', 'sigma'],
['964', 'tau'],
['965', 'upsilon'],
['966', 'phi'],
['967', 'chi'],
['968', 'psi'],
['969', 'omega'],
// symbols
['8501', 'alef symbol'],
['982', 'pi symbol'],
['8476', 'real part symbol'],
['978', 'upsilon - hook symbol'],
['8472', 'Weierstrass p'],
['8465', 'imaginary part'],
// arrows
['8592', 'leftwards arrow'],
['8593', 'upwards arrow'],
['8594', 'rightwards arrow'],
['8595', 'downwards arrow'],
['8596', 'left right arrow'],
['8629', 'carriage return'],
['8656', 'leftwards double arrow'],
['8657', 'upwards double arrow'],
['8658', 'rightwards double arrow'],
['8659', 'downwards double arrow'],
['8660', 'left right double arrow'],
['8756', 'therefore'],
['8834', 'subset of'],
['8835', 'superset of'],
['8836', 'not a subset of'],
['8838', 'subset of or equal to'],
['8839', 'superset of or equal to'],
['8853', 'circled plus'],
['8855', 'circled times'],
['8869', 'perpendicular'],
['8901', 'dot operator'],
['8968', 'left ceiling'],
['8969', 'right ceiling'],
['8970', 'left floor'],
['8971', 'right floor'],
['9001', 'left-pointing angle bracket'],
['9002', 'right-pointing angle bracket'],
['9674', 'lozenge'],
['9824', 'black spade suit'],
['9827', 'black club suit'],
['9829', 'black heart suit'],
['9830', 'black diamond suit'],
['8194', 'en space'],
['8195', 'em space'],
['8201', 'thin space'],
['8204', 'zero width non-joiner'],
['8205', 'zero width joiner'],
['8206', 'left-to-right mark'],
['8207', 'right-to-left mark']
];
};
const charmapFilter = function (charmap) {
return Tools.grep(charmap, function (item) {
return isArray(item) && item.length === 2;
});
};
const getCharsFromSetting = function (settingValue) {
if (isArray(settingValue)) {
return [].concat(charmapFilter(settingValue));
}
if (typeof settingValue === 'function') {
return settingValue();
}
return [];
};
const extendCharMap = function (editor, charmap) {
const userCharMap = Settings.getCharMap(editor);
if (userCharMap) {
charmap = getCharsFromSetting(userCharMap);
}
const userCharMapAppend = Settings.getCharMapAppend(editor);
if (userCharMapAppend) {
return [].concat(charmap).concat(getCharsFromSetting(userCharMapAppend));
}
return charmap;
};
const getCharMap = function (editor) {
return extendCharMap(editor, getDefaultCharMap());
};
export default {
getCharMap
};

View File

@@ -0,0 +1,25 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const register = function (editor) {
editor.addButton('charmap', {
icon: 'charmap',
tooltip: 'Special character',
cmd: 'mceShowCharmap'
});
editor.addMenuItem('charmap', {
icon: 'charmap',
text: 'Special character',
cmd: 'mceShowCharmap',
context: 'insert'
});
};
export default {
register
};

View File

@@ -0,0 +1,111 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Actions from '../core/Actions';
import CharMap from '../core/CharMap';
import GridHtml from './GridHtml';
const getParentTd = function (elm) {
while (elm) {
if (elm.nodeName === 'TD') {
return elm;
}
elm = elm.parentNode;
}
};
const open = function (editor) {
let win;
const charMapPanel = {
type: 'container',
html: GridHtml.getHtml(CharMap.getCharMap(editor)),
onclick (e) {
const target = e.target;
if (/^(TD|DIV)$/.test(target.nodeName)) {
const charDiv = getParentTd(target).firstChild;
if (charDiv && charDiv.hasAttribute('data-chr')) {
const charCodeString = charDiv.getAttribute('data-chr');
const charCode = parseInt(charCodeString, 10);
if (!isNaN(charCode)) {
Actions.insertChar(editor, String.fromCharCode(charCode));
}
if (!e.ctrlKey) {
win.close();
}
}
}
},
onmouseover (e) {
const td = getParentTd(e.target);
if (td && td.firstChild) {
win.find('#preview').text(td.firstChild.firstChild.data);
win.find('#previewTitle').text(td.title);
} else {
win.find('#preview').text(' ');
win.find('#previewTitle').text(' ');
}
}
};
win = editor.windowManager.open({
title: 'Special character',
spacing: 10,
padding: 10,
items: [
charMapPanel,
{
type: 'container',
layout: 'flex',
direction: 'column',
align: 'center',
spacing: 5,
minWidth: 160,
minHeight: 160,
items: [
{
type: 'label',
name: 'preview',
text: ' ',
style: 'font-size: 40px; text-align: center',
border: 1,
minWidth: 140,
minHeight: 80
},
{
type: 'spacer',
minHeight: 20
},
{
type: 'label',
name: 'previewTitle',
text: ' ',
style: 'white-space: pre-wrap;',
border: 1,
minWidth: 140
}
]
}
],
buttons: [
{
text: 'Close', onclick () {
win.close();
}
}
]
});
};
export default {
open
};

View File

@@ -0,0 +1,47 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const getHtml = function (charmap) {
let gridHtml, x, y;
const width = Math.min(charmap.length, 25);
const height = Math.ceil(charmap.length / width);
gridHtml = '<table role="presentation" cellspacing="0" class="mce-charmap"><tbody>';
for (y = 0; y < height; y++) {
gridHtml += '<tr>';
for (x = 0; x < width; x++) {
const index = y * width + x;
if (index < charmap.length) {
const chr = charmap[index];
const charCode = parseInt(chr[0], 10);
const chrText = chr ? String.fromCharCode(charCode) : '&nbsp;';
gridHtml += (
'<td title="' + chr[1] + '">' +
'<div tabindex="-1" title="' + chr[1] + '" role="button" data-chr="' + charCode + '">' +
chrText +
'</div>' +
'</td>'
);
} else {
gridHtml += '<td />';
}
}
gridHtml += '</tr>';
}
gridHtml += '</tbody></table>';
return gridHtml;
};
export default {
getHtml
};

View File

@@ -0,0 +1,95 @@
import { Pipeline } from '@ephox/agar';
import { LegacyUnit, TinyLoader } from '@ephox/mcagar';
import Plugin from 'tinymce/plugins/charmap/Plugin';
import Theme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.charmap.CharMapPluginTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
const suite = LegacyUnit.createSuite();
Plugin();
Theme();
suite.test('Replace characters by array', function (editor) {
editor.settings.charmap = [
[65, 'Latin A'],
[66, 'Latin B']
];
LegacyUnit.deepEqual(editor.plugins.charmap.getCharMap(), [
[65, 'Latin A'],
[66, 'Latin B']
]);
});
suite.test('Replace characters by function', function (editor) {
editor.settings.charmap = function () {
return [
[65, 'Latin A fun'],
[66, 'Latin B fun']
];
};
LegacyUnit.deepEqual(editor.plugins.charmap.getCharMap(), [
[65, 'Latin A fun'],
[66, 'Latin B fun']
]);
});
suite.test('Append characters by array', function (editor) {
editor.settings.charmap = [
[67, 'Latin C']
];
editor.settings.charmap_append = [
[65, 'Latin A'],
[66, 'Latin B']
];
LegacyUnit.deepEqual(editor.plugins.charmap.getCharMap(), [
[67, 'Latin C'],
[65, 'Latin A'],
[66, 'Latin B']
]);
});
suite.test('Append characters by function', function (editor) {
editor.settings.charmap = [
[67, 'Latin C']
];
editor.settings.charmap_append = function () {
return [
[65, 'Latin A fun'],
[66, 'Latin B fun']
];
};
LegacyUnit.deepEqual(editor.plugins.charmap.getCharMap(), [
[67, 'Latin C'],
[65, 'Latin A fun'],
[66, 'Latin B fun']
]);
});
suite.test('Insert character', function (editor) {
let lastEvt;
editor.on('insertCustomChar', function (e) {
lastEvt = e;
});
editor.plugins.charmap.insertChar('A');
LegacyUnit.equal(lastEvt.chr, 'A');
});
TinyLoader.setup(function (editor, onSuccess, onFailure) {
Pipeline.async({}, suite.toSteps(editor), onSuccess, onFailure);
}, {
plugins: 'charmap',
indent: false,
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,34 @@
import { Chain, Mouse, Pipeline, UiFinder } from '@ephox/agar';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import CharmapPlugin from 'tinymce/plugins/charmap/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
UnitTest.asynctest('browser.tinymce.plugins.charmap.InsertQuotationMarkTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
ModernTheme();
CharmapPlugin();
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyApis = TinyApis(editor);
const tinyUi = TinyUi(editor);
Pipeline.async({}, [
tinyApis.sFocus,
tinyUi.sClickOnToolbar('click charmap', 'div[aria-label="Special character"] button'),
Chain.asStep({}, [
tinyUi.cWaitForPopup('wait for popup', 'div[role="dialog"]'),
UiFinder.cFindIn('div[title="quotation mark"]'),
Mouse.cClick
]),
tinyApis.sAssertContent('<p>"</p>')
], onSuccess, onFailure);
}, {
plugins: 'charmap',
toolbar: 'charmap',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: code Demo Page</title>
</head>
<body>
<h2>Plugin: code Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/code/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,22 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare const tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'code',
toolbar: 'code',
height: 600
});
export {};

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Commands from './api/Commands';
import Buttons from './ui/Buttons';
PluginManager.add('code', function (editor) {
Commands.register(editor);
Buttons.register(editor);
return {};
});
export default function () { }

View File

@@ -0,0 +1,18 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from '../ui/Dialog';
const register = function (editor) {
editor.addCommand('mceCodeEditor', function () {
Dialog.open(editor);
});
};
export default {
register
};

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
const getMinWidth = function (editor) {
return editor.getParam('code_dialog_width', 600);
};
const getMinHeight = function (editor) {
return editor.getParam('code_dialog_height', Math.min(DOMUtils.DOM.getViewPort().h - 200, 500));
};
export default {
getMinWidth,
getMinHeight
};

View File

@@ -0,0 +1,29 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const setContent = function (editor, html) {
// We get a lovely "Wrong document" error in IE 11 if we
// don't move the focus to the editor before creating an undo
// transation since it tries to make a bookmark for the current selection
editor.focus();
editor.undoManager.transact(function () {
editor.setContent(html);
});
editor.selection.setCursorLocation();
editor.nodeChanged();
};
const getContent = function (editor) {
return editor.getContent({ source_view: true });
};
export default {
setContent,
getContent
};

View File

@@ -0,0 +1,30 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from './Dialog';
const register = function (editor) {
editor.addButton('code', {
icon: 'code',
tooltip: 'Source code',
onclick () {
Dialog.open(editor);
}
});
editor.addMenuItem('code', {
icon: 'code',
text: 'Source code',
onclick () {
Dialog.open(editor);
}
});
};
export default {
register
};

View File

@@ -0,0 +1,38 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Settings from '../api/Settings';
import Content from '../core/Content';
const open = function (editor) {
const minWidth = Settings.getMinWidth(editor);
const minHeight = Settings.getMinHeight(editor);
const win = editor.windowManager.open({
title: 'Source code',
body: {
type: 'textbox',
name: 'code',
multiline: true,
minWidth,
minHeight,
spellcheck: false,
style: 'direction: ltr; text-align: left'
},
onSubmit (e) {
Content.setContent(editor, e.data.code);
}
});
// Gecko has a major performance issue with textarea
// contents so we need to set it when all reflows are done
win.find('#code').value(Content.getContent(editor));
};
export default {
open
};

View File

@@ -0,0 +1,37 @@
import { Pipeline, RawAssertions, Step } from '@ephox/agar';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import CodePlugin from 'tinymce/plugins/code/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { UnitTest } from '@ephox/bedrock';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.code.CodeSanityTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
CodePlugin();
ModernTheme();
const sAssertTextareaContent = function (expected) {
return Step.sync(function () {
const textarea: any = document.querySelector('div[role="dialog"] textarea');
RawAssertions.assertEq('should have correct value', expected, textarea.value);
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
tinyApis.sSetContent('<b>a</b>'),
tinyUi.sClickOnToolbar('click code button', 'div[aria-label="Source code"] button'),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"]'),
sAssertTextareaContent('<p><strong>a</strong></p>')
], onSuccess, onFailure);
}, {
plugins: 'code',
toolbar: 'code',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: codesample Demo Page</title>
</head>
<body>
<h2>Plugin: codesample Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
<div class="tinymce">Inline editor</div>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/codesample/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,34 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
declare let tinymce: any;
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'codesample code',
toolbar: 'codesample code',
codesample_content_css: '../../../../../js/tinymce/plugins/codesample/css/prism.css',
height: 600
});
tinymce.init({
selector: 'div.tinymce',
inline: true,
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'codesample code',
toolbar: 'codesample code',
codesample_content_css: '../../../../../js/tinymce/plugins/codesample/css/prism.css',
height: 600
});
export {};

View File

@@ -0,0 +1,138 @@
/* http://prismjs.com/download.html?themes=prism&languages=markup+css+clike+javascript */
/**
* prism.js default theme for JavaScript, CSS and HTML
* Based on dabblet (http://dabblet.com)
* @author Lea Verou
*/
code[class*="language-"],
pre[class*="language-"] {
color: black;
text-shadow: 0 1px white;
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
direction: ltr;
text-align: left;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
line-height: 1.5;
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
-webkit-hyphens: none;
-moz-hyphens: none;
-ms-hyphens: none;
hyphens: none;
}
pre[class*="language-"]::-moz-selection, pre[class*="language-"] ::-moz-selection,
code[class*="language-"]::-moz-selection, code[class*="language-"] ::-moz-selection {
text-shadow: none;
background: #b3d4fc;
}
pre[class*="language-"]::selection, pre[class*="language-"] ::selection,
code[class*="language-"]::selection, code[class*="language-"] ::selection {
text-shadow: none;
background: #b3d4fc;
}
@media print {
code[class*="language-"],
pre[class*="language-"] {
text-shadow: none;
}
}
/* Code blocks */
pre[class*="language-"] {
padding: 1em;
margin: .5em 0;
overflow: auto;
}
:not(pre) > code[class*="language-"],
pre[class*="language-"] {
background: #f5f2f0;
}
/* Inline code */
:not(pre) > code[class*="language-"] {
padding: .1em;
border-radius: .3em;
}
.token.comment,
.token.prolog,
.token.doctype,
.token.cdata {
color: slategray;
}
.token.punctuation {
color: #999;
}
.namespace {
opacity: .7;
}
.token.property,
.token.tag,
.token.boolean,
.token.number,
.token.constant,
.token.symbol,
.token.deleted {
color: #905;
}
.token.selector,
.token.attr-name,
.token.string,
.token.char,
.token.builtin,
.token.inserted {
color: #690;
}
.token.operator,
.token.entity,
.token.url,
.language-css .token.string,
.style .token.string {
color: #a67f59;
background: hsla(0, 0%, 100%, .5);
}
.token.atrule,
.token.attr-value,
.token.keyword {
color: #07a;
}
.token.function {
color: #DD4A68;
}
.token.regex,
.token.important,
.token.variable {
color: #e90;
}
.token.important,
.token.bold {
font-weight: bold;
}
.token.italic {
font-style: italic;
}
.token.entity {
cursor: help;
}

View File

@@ -0,0 +1,37 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { Cell } from '@ephox/katamari';
import PluginManager from 'tinymce/core/api/PluginManager';
import Commands from './api/Commands';
import FilterContent from './core/FilterContent';
import LoadCss from './core/LoadCss';
import Buttons from './ui/Buttons';
import Dialog from './ui/Dialog';
import Utils from './util/Utils';
const addedInlineCss = Cell(false);
PluginManager.add('codesample', function (editor, pluginUrl) {
const addedCss = Cell(false);
FilterContent.setup(editor);
Buttons.register(editor);
Commands.register(editor);
editor.on('init', function () {
LoadCss.loadCss(editor, pluginUrl, addedInlineCss, addedCss);
});
editor.on('dblclick', function (ev) {
if (Utils.isCodeSample(ev.target)) {
Dialog.open(editor);
}
});
});
export default function () { }

View File

@@ -0,0 +1,24 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Dialog from '../ui/Dialog';
import Utils from '../util/Utils';
const register = function (editor) {
editor.addCommand('codesample', function () {
const node = editor.selection.getNode();
if (editor.selection.isCollapsed() || Utils.isCodeSample(node)) {
Dialog.open(editor);
} else {
editor.formatter.toggle('code');
}
});
};
export default {
register
};

View File

@@ -0,0 +1,31 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
const getContentCss = function (editor) {
return editor.settings.codesample_content_css;
};
const getLanguages = function (editor) {
return editor.settings.codesample_languages;
};
const getDialogMinWidth = function (editor) {
return Math.min(DOMUtils.DOM.getViewPort().w, editor.getParam('codesample_dialog_width', 800));
};
const getDialogMinHeight = function (editor) {
return Math.min(DOMUtils.DOM.getViewPort().w, editor.getParam('codesample_dialog_height', 650));
};
export default {
getContentCss,
getLanguages,
getDialogMinWidth,
getDialogMinHeight
};

View File

@@ -0,0 +1,54 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import DOMUtils from 'tinymce/core/api/dom/DOMUtils';
import Prism from './Prism';
import Utils from '../util/Utils';
const getSelectedCodeSample = function (editor) {
const node = editor.selection.getNode();
if (Utils.isCodeSample(node)) {
return node;
}
return null;
};
const insertCodeSample = function (editor, language, code) {
editor.undoManager.transact(function () {
const node = getSelectedCodeSample(editor);
code = DOMUtils.DOM.encode(code);
if (node) {
editor.dom.setAttrib(node, 'class', 'language-' + language);
node.innerHTML = code;
Prism.highlightElement(node);
editor.selection.select(node);
} else {
editor.insertContent('<pre id="__new" class="language-' + language + '">' + code + '</pre>');
editor.selection.select(editor.$('#__new').removeAttr('id')[0]);
}
});
};
const getCurrentCode = function (editor) {
const node = getSelectedCodeSample(editor);
if (node) {
return node.textContent;
}
return '';
};
export default {
getSelectedCodeSample,
insertCodeSample,
getCurrentCode
};

View File

@@ -0,0 +1,54 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Prism from './Prism';
import Utils from '../util/Utils';
const setup = function (editor) {
const $ = editor.$;
editor.on('PreProcess', function (e) {
$('pre[contenteditable=false]', e.node).
filter(Utils.trimArg(Utils.isCodeSample)).
each(function (idx, elm) {
const $elm = $(elm), code = elm.textContent;
$elm.attr('class', $.trim($elm.attr('class')));
$elm.removeAttr('contentEditable');
$elm.empty().append($('<code></code>').each(function () {
// Needs to be textContent since innerText produces BR:s
this.textContent = code;
}));
});
});
editor.on('SetContent', function () {
const unprocessedCodeSamples = $('pre').filter(Utils.trimArg(Utils.isCodeSample)).filter(function (idx, elm) {
return elm.contentEditable !== 'false';
});
if (unprocessedCodeSamples.length) {
editor.undoManager.transact(function () {
unprocessedCodeSamples.each(function (idx, elm) {
$(elm).find('br').each(function (idx, elm) {
elm.parentNode.replaceChild(editor.getDoc().createTextNode('\n'), elm);
});
elm.contentEditable = false;
elm.innerHTML = editor.dom.encode(elm.textContent);
Prism.highlightElement(elm);
elm.className = $.trim(elm.className);
});
});
}
});
};
export default {
setup
};

View File

@@ -0,0 +1,44 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Settings from '../api/Settings';
import CodeSample from './CodeSample';
const getLanguages = function (editor) {
const defaultLanguages = [
{ text: 'HTML/XML', value: 'markup' },
{ text: 'JavaScript', value: 'javascript' },
{ text: 'CSS', value: 'css' },
{ text: 'PHP', value: 'php' },
{ text: 'Ruby', value: 'ruby' },
{ text: 'Python', value: 'python' },
{ text: 'Java', value: 'java' },
{ text: 'C', value: 'c' },
{ text: 'C#', value: 'csharp' },
{ text: 'C++', value: 'cpp' }
];
const customLanguages = Settings.getLanguages(editor);
return customLanguages ? customLanguages : defaultLanguages;
};
const getCurrentLanguage = function (editor) {
let matches;
const node = CodeSample.getSelectedCodeSample(editor);
if (node) {
matches = node.className.match(/language-(\w+)/);
return matches ? matches[1] : '';
}
return '';
};
export default {
getLanguages,
getCurrentLanguage
};

View File

@@ -0,0 +1,41 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Settings from '../api/Settings';
// Todo: use a proper css loader here
const loadCss = function (editor, pluginUrl, addedInlineCss, addedCss) {
let linkElm;
const contentCss = Settings.getContentCss(editor);
if (editor.inline && addedInlineCss.get()) {
return;
}
if (!editor.inline && addedCss.get()) {
return;
}
if (editor.inline) {
addedInlineCss.set(true);
} else {
addedCss.set(true);
}
if (contentCss !== false) {
linkElm = editor.dom.create('link', {
rel: 'stylesheet',
href: contentCss ? contentCss : pluginUrl + '/css/prism.css'
});
editor.getDoc().getElementsByTagName('head')[0].appendChild(linkElm);
}
};
export default {
loadCss
};

View File

@@ -0,0 +1,940 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import { self, document, Worker } from '@ephox/dom-globals';
/*eslint-disable*/
/*eslint-enable */
declare const WorkerGlobalScope: any;
const window: any = {};
const global: any = window;
const module: any = { exports: {} };
// ------------------ Start wrap
/* http://prismjs.com/download.html?themes=prism-dark&languages=markup+css+clike+javascript+c+csharp+cpp+java+php+python+ruby */
const _self: any = (typeof window !== 'undefined')
? window // if in browser
: (
(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope)
? self // if in worker
: {} // if in node js
);
/**
* Prism: Lightweight, robust, elegant syntax highlighting
* MIT license http://www.opensource.org/licenses/mit-license.php/
* @author Lea Verou http://lea.verou.me
*/
const Prism = (function () {
// Private helper vars
const lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i;
const _: any = _self.Prism = {
util: {
encode (tokens) {
if (tokens instanceof Token) {
return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias);
} else if (_.util.type(tokens) === 'Array') {
return tokens.map(_.util.encode);
} else {
return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' ');
}
},
type (o) {
return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1];
},
// Deep clone a language definition (e.g. to extend it)
clone (o) {
const type = _.util.type(o);
switch (type) {
case 'Object':
const clone = {};
for (const key in o) {
if (o.hasOwnProperty(key)) {
clone[key] = _.util.clone(o[key]);
}
}
return clone;
case 'Array':
// Check for existence for IE8
return o.map && o.map(function (v) { return _.util.clone(v); });
}
return o;
}
},
languages: {
extend (id, redef) {
const lang = _.util.clone(_.languages[id]);
for (const key in redef) {
lang[key] = redef[key];
}
return lang;
},
/**
* Insert a token before another token in a language literal
* As this needs to recreate the object (we cannot actually insert before keys in object literals),
* we cannot just provide an object, we need anobject and a key.
* @param inside The key (or language id) of the parent
* @param before The key to insert before. If not provided, the function appends instead.
* @param insert Object with the key/value pairs to insert
* @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted.
*/
insertBefore (inside, before, insert, root) {
root = root || _.languages;
const grammar = root[inside];
if (arguments.length === 2) {
insert = arguments[1];
for (const newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
grammar[newToken] = insert[newToken];
}
}
return grammar;
}
const ret = {};
for (const token in grammar) {
if (grammar.hasOwnProperty(token)) {
if (token === before) {
for (const newToken in insert) {
if (insert.hasOwnProperty(newToken)) {
ret[newToken] = insert[newToken];
}
}
}
ret[token] = grammar[token];
}
}
// Update references in other language definitions
_.languages.DFS(_.languages, function (key, value) {
if (value === root[inside] && key !== inside) {
this[key] = ret;
}
});
return root[inside] = ret;
},
// Traverse a language definition with Depth First Search
DFS: <any> function (o, callback, type) {
for (const i in o) {
if (o.hasOwnProperty(i)) {
callback.call(o, i, o[i], type || i);
if (_.util.type(o[i]) === 'Object') {
_.languages.DFS(o[i], callback);
} else if (_.util.type(o[i]) === 'Array') {
_.languages.DFS(o[i], callback, i);
}
}
}
}
},
plugins: {},
highlightAll (async, callback) {
const elements = document.querySelectorAll('code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code');
for (let i = 0, element; element = elements[i++];) {
_.highlightElement(element, async === true, callback);
}
},
highlightElement (element, async, callback) {
// Find language
let language, grammar, parent = element;
while (parent && !lang.test(parent.className)) {
parent = parent.parentNode;
}
if (parent) {
language = (parent.className.match(lang) || [, ''])[1];
grammar = _.languages[language];
}
// Set language on the element, if not present
element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
// Set language on the parent, for styling
parent = element.parentNode;
if (/pre/i.test(parent.nodeName)) {
parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language;
}
const code = element.textContent;
const env: any = {
element,
language,
grammar,
code
};
if (!code || !grammar) {
_.hooks.run('complete', env);
return;
}
_.hooks.run('before-highlight', env);
if (async && _self.Worker) {
const worker = new Worker(_.filename);
worker.onmessage = function (evt) {
env.highlightedCode = evt.data;
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
if (callback) {
callback.call(env.element);
}
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
};
worker.postMessage(JSON.stringify({
language: env.language,
code: env.code,
immediateClose: true
}));
} else {
env.highlightedCode = _.highlight(env.code, env.grammar, env.language);
_.hooks.run('before-insert', env);
env.element.innerHTML = env.highlightedCode;
if (callback) {
callback.call(element);
}
_.hooks.run('after-highlight', env);
_.hooks.run('complete', env);
}
},
highlight (text, grammar, language) {
const tokens = _.tokenize(text, grammar);
return Token.stringify(_.util.encode(tokens), language);
},
tokenize (text, grammar, language) {
const Token = _.Token;
const strarr = [text];
const rest = grammar.rest;
if (rest) {
for (const token in rest) {
grammar[token] = rest[token];
}
delete grammar.rest;
}
tokenloop: for (const token in grammar) {
if (!grammar.hasOwnProperty(token) || !grammar[token]) {
continue;
}
let patterns = grammar[token];
patterns = (_.util.type(patterns) === 'Array') ? patterns : [patterns];
for (let j = 0; j < patterns.length; ++j) {
let pattern = patterns[j];
const inside = pattern.inside;
const lookbehind = !!pattern.lookbehind;
let lookbehindLength = 0;
const alias = pattern.alias;
pattern = pattern.pattern || pattern;
for (let i = 0; i < strarr.length; i++) { // Dont cache length as it changes during the loop
const str = strarr[i];
if (strarr.length > text.length) {
// Something went terribly wrong, ABORT, ABORT!
break tokenloop;
}
if (str instanceof Token) {
continue;
}
pattern.lastIndex = 0;
let match = pattern.exec(str);
if (match) {
if (lookbehind) {
lookbehindLength = match[1].length;
}
const from = match.index - 1 + lookbehindLength;
match = match[0].slice(lookbehindLength);
const len = match.length,
to = from + len,
before = str.slice(0, from + 1),
after = str.slice(to + 1);
const args = [i, 1];
if (before) {
args.push(before);
}
const wrapped = new Token(token, inside ? _.tokenize(match, inside) : match, alias);
args.push(wrapped);
if (after) {
args.push(after);
}
Array.prototype.splice.apply(strarr, args);
}
}
}
}
return strarr;
},
hooks: {
all: {},
add (name, callback) {
const hooks = _.hooks.all;
hooks[name] = hooks[name] || [];
hooks[name].push(callback);
},
run (name, env) {
const callbacks = _.hooks.all[name];
if (!callbacks || !callbacks.length) {
return;
}
for (let i = 0, callback; callback = callbacks[i++];) {
callback(env);
}
}
}
};
const Token: any = _.Token = function (type, content, alias) {
this.type = type;
this.content = content;
this.alias = alias;
};
Token.stringify = function (o, language, parent) {
if (typeof o === 'string') {
return o;
}
if (_.util.type(o) === 'Array') {
return o.map(function (element) {
return Token.stringify(element, language, o);
}).join('');
}
const env: any = {
type: o.type,
content: Token.stringify(o.content, language, parent),
tag: 'span',
classes: ['token', o.type],
attributes: {},
language,
parent
};
if (env.type === 'comment') {
env.attributes.spellcheck = 'true';
}
if (o.alias) {
const aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias];
Array.prototype.push.apply(env.classes, aliases);
}
_.hooks.run('wrap', env);
let attributes = '';
for (const name in env.attributes) {
attributes += (attributes ? ' ' : '') + name + '="' + (env.attributes[name] || '') + '"';
}
return '<' + env.tag + ' class="' + env.classes.join(' ') + '" ' + attributes + '>' + env.content + '</' + env.tag + '>';
};
if (!_self.document) {
if (!_self.addEventListener) {
// in Node.js
return _self.Prism;
}
// In worker
_self.addEventListener('message', function (evt) {
const message = JSON.parse(evt.data),
lang = message.language,
code = message.code,
immediateClose = message.immediateClose;
_self.postMessage(_.highlight(code, _.languages[lang], lang));
if (immediateClose) {
_self.close();
}
}, false);
return _self.Prism;
}
/*
// Get current script and highlight
var script = document.getElementsByTagName('script');
script = script[script.length - 1];
if (script) {
_.filename = script.src;
if (document.addEventListener && !script.hasAttribute('data-manual')) {
document.addEventListener('DOMContentLoaded', _.highlightAll);
}
}
return _self.Prism;
*/
})();
if (typeof module !== 'undefined' && module.exports) {
module.exports = Prism;
}
// hack for components to work correctly in node.js
if (typeof global !== 'undefined') {
global.Prism = Prism;
}
Prism.languages.markup = {
comment: /<!--[\w\W]*?-->/,
prolog: /<\?[\w\W]+?\?>/,
doctype: /<!DOCTYPE[\w\W]+?>/,
cdata: /<!\[CDATA\[[\w\W]*?]]>/i,
tag: {
pattern: /<\/?[^\s>\/=.]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,
inside: {
'tag': {
pattern: /^<\/?[^\s>\/]+/i,
inside: {
punctuation: /^<\/?/,
namespace: /^[^\s>\/:]+:/
}
},
'attr-value': {
pattern: /=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,
inside: {
punctuation: /[=>"']/
}
},
'punctuation': /\/?>/,
'attr-name': {
pattern: /[^\s>\/]+/,
inside: {
namespace: /^[^\s>\/:]+:/
}
}
}
},
entity: /&#?[\da-z]{1,8};/i
};
// Plugin to make entity title show the real entity, idea by Roman Komarov
Prism.hooks.add('wrap', function (env) {
if (env.type === 'entity') {
env.attributes.title = env.content.replace(/&amp;/, '&');
}
});
Prism.languages.xml = Prism.languages.markup;
Prism.languages.html = Prism.languages.markup;
Prism.languages.mathml = Prism.languages.markup;
Prism.languages.svg = Prism.languages.markup;
Prism.languages.css = {
comment: /\/\*[\w\W]*?\*\//,
atrule: {
pattern: /@[\w-]+?.*?(;|(?=\s*\{))/i,
inside: {
rule: /@[\w-]+/
// See rest below
}
},
url: /url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,
selector: /[^\{\}\s][^\{\};]*?(?=\s*\{)/,
string: /("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,
property: /(\b|\B)[\w-]+(?=\s*:)/i,
important: /\B!important\b/i,
function: /[-a-z0-9]+(?=\()/i,
punctuation: /[(){};:]/
};
Prism.languages.css.atrule.inside.rest = Prism.util.clone(Prism.languages.css);
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
style: {
pattern: /<style[\w\W]*?>[\w\W]*?<\/style>/i,
inside: {
tag: {
pattern: /<style[\w\W]*?>|<\/style>/i,
inside: Prism.languages.markup.tag.inside
},
rest: Prism.languages.css
},
alias: 'language-css'
}
});
Prism.languages.insertBefore('inside', 'attr-value', {
'style-attr': {
pattern: /\s*style=("|').*?\1/i,
inside: {
'attr-name': {
pattern: /^\s*style/i,
inside: Prism.languages.markup.tag.inside
},
'punctuation': /^\s*=\s*['"]|['"]\s*$/,
'attr-value': {
pattern: /.+/i,
inside: Prism.languages.css
}
},
alias: 'language-css'
}
}, Prism.languages.markup.tag);
}
Prism.languages.clike = {
'comment': [
{
pattern: /(^|[^\\])\/\*[\w\W]*?\*\//,
lookbehind: true
},
{
pattern: /(^|[^\\:])\/\/.*/,
lookbehind: true
}
],
'string': /(["'])(\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/,
'class-name': {
pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[a-z0-9_\.\\]+/i,
lookbehind: true,
inside: {
punctuation: /(\.|\\)/
}
},
'keyword': /\b(if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/,
'boolean': /\b(true|false)\b/,
'function': /[a-z0-9_]+(?=\()/i,
'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i,
'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/,
'punctuation': /[{}[\];(),.:]/
};
Prism.languages.javascript = Prism.languages.extend('clike', {
keyword: /\b(as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|false|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|true|try|typeof|var|void|while|with|yield)\b/,
number: /\b-?(0x[\dA-Fa-f]+|0b[01]+|0o[0-7]+|\d*\.?\d+([Ee][+-]?\d+)?|NaN|Infinity)\b/,
// Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444)
function: /[_$a-zA-Z\xA0-\uFFFF][_$a-zA-Z0-9\xA0-\uFFFF]*(?=\()/i
});
Prism.languages.insertBefore('javascript', 'keyword', {
regex: {
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\\\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/,
lookbehind: true
}
});
Prism.languages.insertBefore('javascript', 'class-name', {
'template-string': {
pattern: /`(?:\\`|\\?[^`])*`/,
inside: {
interpolation: {
pattern: /\$\{[^}]+\}/,
inside: {
'interpolation-punctuation': {
pattern: /^\$\{|\}$/,
alias: 'punctuation'
},
'rest': Prism.languages.javascript
}
},
string: /[\s\S]+/
}
}
});
if (Prism.languages.markup) {
Prism.languages.insertBefore('markup', 'tag', {
script: {
pattern: /<script[\w\W]*?>[\w\W]*?<\/script>/i,
inside: {
tag: {
pattern: /<script[\w\W]*?>|<\/script>/i,
inside: Prism.languages.markup.tag.inside
},
rest: Prism.languages.javascript
},
alias: 'language-javascript'
}
});
}
Prism.languages.js = Prism.languages.javascript;
Prism.languages.c = Prism.languages.extend('clike', {
keyword: /\b(asm|typeof|inline|auto|break|case|char|const|continue|default|do|double|else|enum|extern|float|for|goto|if|int|long|register|return|short|signed|sizeof|static|struct|switch|typedef|union|unsigned|void|volatile|while)\b/,
operator: /\-[>-]?|\+\+?|!=?|<<?=?|>>?=?|==?|&&?|\|?\||[~^%?*\/]/,
number: /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)[ful]*\b/i
});
Prism.languages.insertBefore('c', 'string', {
macro: {
// allow for multiline macro definitions
// spaces after the # character compile fine with gcc
pattern: /(^\s*)#\s*[a-z]+([^\r\n\\]|\\.|\\(?:\r\n?|\n))*/im,
lookbehind: true,
alias: 'property',
inside: {
// highlight the path of the include statement as a string
string: {
pattern: /(#\s*include\s*)(<.+?>|("|')(\\?.)+?\3)/,
lookbehind: true
}
}
}
});
delete Prism.languages.c['class-name'];
delete Prism.languages.c.boolean;
Prism.languages.csharp = Prism.languages.extend('clike', {
keyword: /\b(abstract|as|async|await|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|foreach|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|void|volatile|while|add|alias|ascending|async|await|descending|dynamic|from|get|global|group|into|join|let|orderby|partial|remove|select|set|value|var|where|yield)\b/,
string: [
/@("|')(\1\1|\\\1|\\?(?!\1)[\s\S])*\1/,
/("|')(\\?.)*?\1/
],
number: /\b-?(0x[\da-f]+|\d*\.?\d+)\b/i
});
Prism.languages.insertBefore('csharp', 'keyword', {
preprocessor: {
pattern: /(^\s*)#.*/m,
lookbehind: true
}
});
Prism.languages.cpp = Prism.languages.extend('c', {
keyword: /\b(alignas|alignof|asm|auto|bool|break|case|catch|char|char16_t|char32_t|class|compl|const|constexpr|const_cast|continue|decltype|default|delete|do|double|dynamic_cast|else|enum|explicit|export|extern|float|for|friend|goto|if|inline|int|long|mutable|namespace|new|noexcept|nullptr|operator|private|protected|public|register|reinterpret_cast|return|short|signed|sizeof|static|static_assert|static_cast|struct|switch|template|this|thread_local|throw|try|typedef|typeid|typename|union|unsigned|using|virtual|void|volatile|wchar_t|while)\b/,
boolean: /\b(true|false)\b/,
operator: /[-+]{1,2}|!=?|<{1,2}=?|>{1,2}=?|\->|:{1,2}|={1,2}|\^|~|%|&{1,2}|\|?\||\?|\*|\/|\b(and|and_eq|bitand|bitor|not|not_eq|or|or_eq|xor|xor_eq)\b/
});
Prism.languages.insertBefore('cpp', 'keyword', {
'class-name': {
pattern: /(class\s+)[a-z0-9_]+/i,
lookbehind: true
}
});
Prism.languages.java = Prism.languages.extend('clike', {
keyword: /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/,
number: /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+(?:e[+-]?\d+)?[df]?\b/i,
operator: {
pattern: /(^|[^.])(?:\+[+=]?|-[-=]?|!=?|<<?=?|>>?>?=?|==?|&[&=]?|\|[|=]?|\*=?|\/=?|%=?|\^=?|[?:~])/m,
lookbehind: true
}
});
/**
* Original by Aaron Harun: http://aahacreative.com/2012/07/31/php-syntax-highlighting-prism/
* Modified by Miles Johnson: http://milesj.me
*
* Supports the following:
* - Extends clike syntax
* - Support for PHP 5.3+ (namespaces, traits, generators, etc)
* - Smarter constant and function matching
*
* Adds the following new token classes:
* constant, delimiter, variable, function, package
*/
Prism.languages.php = Prism.languages.extend('clike', {
keyword: /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|private|protected|parent|throw|null|echo|print|trait|namespace|final|yield|goto|instanceof|finally|try|catch)\b/i,
constant: /\b[A-Z0-9_]{2,}\b/,
comment: {
pattern: /(^|[^\\])(?:\/\*[\w\W]*?\*\/|\/\/.*)/,
lookbehind: true
}
});
// Shell-like comments are matched after strings, because they are less
// common than strings containing hashes...
Prism.languages.insertBefore('php', 'class-name', {
'shell-comment': {
pattern: /(^|[^\\])#.*/,
lookbehind: true,
alias: 'comment'
}
});
Prism.languages.insertBefore('php', 'keyword', {
delimiter: /\?>|<\?(?:php)?/i,
variable: /\$\w+\b/i,
package: {
pattern: /(\\|namespace\s+|use\s+)[\w\\]+/,
lookbehind: true,
inside: {
punctuation: /\\/
}
}
});
// Must be defined after the function pattern
Prism.languages.insertBefore('php', 'operator', {
property: {
pattern: /(->)[\w]+/,
lookbehind: true
}
});
// Add HTML support of the markup language exists
if (Prism.languages.markup) {
// Tokenize all inline PHP blocks that are wrapped in <?php ?>
// This allows for easy PHP + markup highlighting
Prism.hooks.add('before-highlight', function (env) {
if (env.language !== 'php') {
return;
}
env.tokenStack = [];
env.backupCode = env.code;
env.code = env.code.replace(/(?:<\?php|<\?)[\w\W]*?(?:\?>)/ig, function (match) {
env.tokenStack.push(match);
return '{{{PHP' + env.tokenStack.length + '}}}';
});
});
// Restore env.code for other plugins (e.g. line-numbers)
Prism.hooks.add('before-insert', function (env) {
if (env.language === 'php') {
env.code = env.backupCode;
delete env.backupCode;
}
});
// Re-insert the tokens after highlighting
Prism.hooks.add('after-highlight', function (env) {
if (env.language !== 'php') {
return;
}
for (let i = 0, t; t = env.tokenStack[i]; i++) {
// The replace prevents $$, $&, $`, $', $n, $nn from being interpreted as special patterns
env.highlightedCode = env.highlightedCode.replace('{{{PHP' + (i + 1) + '}}}', Prism.highlight(t, env.grammar, 'php').replace(/\$/g, '$$$$'));
}
env.element.innerHTML = env.highlightedCode;
});
// Wrap tokens in classes that are missing them
Prism.hooks.add('wrap', function (env) {
if (env.language === 'php' && env.type === 'markup') {
env.content = env.content.replace(/(\{\{\{PHP[0-9]+\}\}\})/g, '<span class="token php">$1</span>');
}
});
// Add the rules before all others
Prism.languages.insertBefore('php', 'comment', {
markup: {
pattern: /<[^?]\/?(.*?)>/,
inside: Prism.languages.markup
},
php: /\{\{\{PHP[0-9]+\}\}\}/
});
}
Prism.languages.python = {
'comment': {
pattern: /(^|[^\\])#.*/,
lookbehind: true
},
'string': /"""[\s\S]+?"""|'''[\s\S]+?'''|("|')(?:\\?.)*?\1/,
'function': {
pattern: /((?:^|\s)def[ \t]+)[a-zA-Z_][a-zA-Z0-9_]*(?=\()/g,
lookbehind: true
},
'class-name': {
pattern: /(\bclass\s+)[a-z0-9_]+/i,
lookbehind: true
},
'keyword': /\b(?:as|assert|async|await|break|class|continue|def|del|elif|else|except|exec|finally|for|from|global|if|import|in|is|lambda|pass|print|raise|return|try|while|with|yield)\b/,
'boolean': /\b(?:True|False)\b/,
'number': /\b-?(?:0[bo])?(?:(?:\d|0x[\da-f])[\da-f]*\.?\d*|\.\d+)(?:e[+-]?\d+)?j?\b/i,
'operator': /[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]|\b(?:or|and|not)\b/,
'punctuation': /[{}[\];(),.:]/
};
/**
* Original by Samuel Flores
*
* Adds the following new token classes:
* constant, builtin, variable, symbol, regex
*/
(function (Prism) {
Prism.languages.ruby = Prism.languages.extend('clike', {
comment: /#(?!\{[^\r\n]*?\}).*/,
keyword: /\b(alias|and|BEGIN|begin|break|case|class|def|define_method|defined|do|each|else|elsif|END|end|ensure|false|for|if|in|module|new|next|nil|not|or|raise|redo|require|rescue|retry|return|self|super|then|throw|true|undef|unless|until|when|while|yield)\b/
});
const interpolation = {
pattern: /#\{[^}]+\}/,
inside: {
delimiter: {
pattern: /^#\{|\}$/,
alias: 'tag'
},
rest: Prism.util.clone(Prism.languages.ruby)
}
};
Prism.languages.insertBefore('ruby', 'keyword', {
regex: [
{
pattern: /%r([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1[gim]{0,3}/,
inside: {
interpolation
}
},
{
pattern: /%r\((?:[^()\\]|\\[\s\S])*\)[gim]{0,3}/,
inside: {
interpolation
}
},
{
// Here we need to specifically allow interpolation
pattern: /%r\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}[gim]{0,3}/,
inside: {
interpolation
}
},
{
pattern: /%r\[(?:[^\[\]\\]|\\[\s\S])*\][gim]{0,3}/,
inside: {
interpolation
}
},
{
pattern: /%r<(?:[^<>\\]|\\[\s\S])*>[gim]{0,3}/,
inside: {
interpolation
}
},
{
pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/,
lookbehind: true
}
],
variable: /[@$]+[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/,
symbol: /:[a-zA-Z_][a-zA-Z_0-9]*(?:[?!]|\b)/
});
Prism.languages.insertBefore('ruby', 'number', {
builtin: /\b(Array|Bignum|Binding|Class|Continuation|Dir|Exception|FalseClass|File|Stat|File|Fixnum|Fload|Hash|Integer|IO|MatchData|Method|Module|NilClass|Numeric|Object|Proc|Range|Regexp|String|Struct|TMS|Symbol|ThreadGroup|Thread|Time|TrueClass)\b/,
constant: /\b[A-Z][a-zA-Z_0-9]*(?:[?!]|\b)/
});
Prism.languages.ruby.string = [
{
pattern: /%[qQiIwWxs]?([^a-zA-Z0-9\s\{\(\[<])(?:[^\\]|\\[\s\S])*?\1/,
inside: {
interpolation
}
},
{
pattern: /%[qQiIwWxs]?\((?:[^()\\]|\\[\s\S])*\)/,
inside: {
interpolation
}
},
{
// Here we need to specifically allow interpolation
pattern: /%[qQiIwWxs]?\{(?:[^#{}\\]|#(?:\{[^}]+\})?|\\[\s\S])*\}/,
inside: {
interpolation
}
},
{
pattern: /%[qQiIwWxs]?\[(?:[^\[\]\\]|\\[\s\S])*\]/,
inside: {
interpolation
}
},
{
pattern: /%[qQiIwWxs]?<(?:[^<>\\]|\\[\s\S])*>/,
inside: {
interpolation
}
},
{
pattern: /("|')(#\{[^}]+\}|\\(?:\r?\n|\r)|\\?.)*?\1/,
inside: {
interpolation
}
}
];
}(Prism));
export default Prism;

View File

@@ -0,0 +1,23 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
const register = function (editor) {
editor.addButton('codesample', {
cmd: 'codesample',
title: 'Insert/Edit code sample'
});
editor.addMenuItem('codesample', {
cmd: 'codesample',
text: 'Code sample',
icon: 'codesample'
});
};
export default {
register
};

View File

@@ -0,0 +1,55 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Settings from '../api/Settings';
import CodeSample from '../core/CodeSample';
import Languages from '../core/Languages';
export default {
open (editor) {
const minWidth = Settings.getDialogMinWidth(editor);
const minHeight = Settings.getDialogMinHeight(editor);
const currentLanguage = Languages.getCurrentLanguage(editor);
const currentLanguages = Languages.getLanguages(editor);
const currentCode = CodeSample.getCurrentCode(editor);
editor.windowManager.open({
title: 'Insert/Edit code sample',
minWidth,
minHeight,
layout: 'flex',
direction: 'column',
align: 'stretch',
body: [
{
type: 'listbox',
name: 'language',
label: 'Language',
maxWidth: 200,
value: currentLanguage,
values: currentLanguages
},
{
type: 'textbox',
name: 'code',
multiline: true,
spellcheck: false,
ariaLabel: 'Code view',
flex: 1,
style: 'direction: ltr; text-align: left',
classes: 'monospace',
value: currentCode,
autofocus: true
}
],
onSubmit (e) {
CodeSample.insertCodeSample(editor, e.data.language, e.data.code);
}
});
}
};

View File

@@ -0,0 +1,21 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
function isCodeSample(elm) {
return elm && elm.nodeName === 'PRE' && elm.className.indexOf('language-') !== -1;
}
function trimArg(predicateFn) {
return function (arg1, arg2) {
return predicateFn(arg2);
};
}
export default {
isCodeSample,
trimArg
};

View File

@@ -0,0 +1,51 @@
import { ApproxStructure, Pipeline, Step, Waiter } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyApis, TinyLoader, TinyUi } from '@ephox/mcagar';
import CodePlugin from 'tinymce/plugins/codesample/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.codesample.CodeSampleSanityTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
CodePlugin();
ModernTheme();
const sInsertTextareaContent = function (value) {
return Step.sync(function () {
const textarea: any = document.querySelector('div[role="dialog"] textarea');
textarea.value = value;
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
const tinyApis = TinyApis(editor);
Pipeline.async({}, [
tinyUi.sClickOnToolbar('click code button', 'div[aria-label="Insert/Edit code sample"] button'),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"]'),
sInsertTextareaContent('<p>a</p>'),
tinyUi.sClickOnUi('click OK btn', 'div.mce-primary button'),
Waiter.sTryUntil('assert content',
tinyApis.sAssertContentStructure(ApproxStructure.build(function (s, str) {
return s.element('body', {
children: [
s.element('pre', {
attrs: {
contenteditable: str.is('false')
}
}),
s.anything()
]
});
})), 100, 3000)
], onSuccess, onFailure);
}, {
plugins: 'codesample',
toolbar: 'codesample',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,44 @@
import { GeneralSteps, Logger, Pipeline, Step } from '@ephox/agar';
import { UnitTest } from '@ephox/bedrock';
import { TinyLoader, TinyUi } from '@ephox/mcagar';
import CodePlugin from 'tinymce/plugins/codesample/Plugin';
import ModernTheme from 'tinymce/themes/modern/Theme';
import { document } from '@ephox/dom-globals';
UnitTest.asynctest('browser.tinymce.plugins.codesample.DblClickCodesampleTest', function () {
const success = arguments[arguments.length - 2];
const failure = arguments[arguments.length - 1];
CodePlugin();
ModernTheme();
const sInsertTextareaContent = function (value) {
return Step.sync(function () {
const textarea: any = document.querySelector('div[role="dialog"] textarea');
textarea.value = value;
});
};
TinyLoader.setup(function (editor, onSuccess, onFailure) {
const tinyUi = TinyUi(editor);
Pipeline.async({}, [
Logger.t('doubleclick on codesample opens dialog', GeneralSteps.sequence([
tinyUi.sClickOnToolbar('click code button', 'div[aria-label="Insert/Edit code sample"] button'),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"]'),
sInsertTextareaContent('<p>a</p>'),
tinyUi.sClickOnUi('click OK btn', 'div.mce-primary button'),
Step.sync(function () {
const pre = editor.getBody().querySelector('pre');
editor.fire('dblclick', { target: pre });
}),
tinyUi.sWaitForPopup('wait for window', 'div[role="dialog"]')
]))
], onSuccess, onFailure);
}, {
plugins: 'codesample',
toolbar: 'codesample',
skin_url: '/project/js/tinymce/skins/lightgray'
}, success, failure);
});

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Plugin: colorpicker Demo Page</title>
</head>
<body>
<h2>Plugin: colorpicker Demo Page</h2>
<div id="ephox-ui">
<textarea name="" id="" cols="30" rows="10" class="tinymce"></textarea>
</div>
<script src="../../../../../js/tinymce/tinymce.js"></script>
<script src="../../../../../scratch/demos/plugins/colorpicker/demo.js"></script>
</body>
</html>

View File

@@ -0,0 +1,27 @@
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
import { document } from '@ephox/dom-globals';
declare let tinymce: any;
const element: any = document.querySelector('.tinymce');
element.value = '<table><tbody><tr><td>One</td></tr></tbody></table>';
tinymce.init({
selector: 'textarea.tinymce',
theme: 'modern',
skin_url: '../../../../../js/tinymce/skins/lightgray',
plugins: 'table colorpicker code',
toolbar: 'table code',
height: 600
});
export {};

View File

@@ -0,0 +1,19 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import PluginManager from 'tinymce/core/api/PluginManager';
import Dialog from './ui/Dialog';
PluginManager.add('colorpicker', function (editor) {
if (!editor.settings.color_picker_callback) {
editor.settings.color_picker_callback = function (callback, value) {
Dialog.open(editor, callback, value);
};
}
});
export default function () { }

View File

@@ -0,0 +1,107 @@
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*/
import Color from 'tinymce/core/api/util/Color';
const showPreview = function (win, hexColor) {
win.find('#preview')[0].getEl().style.background = hexColor;
};
const setColor = function (win, value) {
const color = Color(value), rgb = color.toRgb();
win.fromJSON({
r: rgb.r,
g: rgb.g,
b: rgb.b,
hex: color.toHex().substr(1)
});
showPreview(win, color.toHex());
};
const open = function (editor, callback, value) {
const win = editor.windowManager.open({
title: 'Color',
items: {
type: 'container',
layout: 'flex',
direction: 'row',
align: 'stretch',
padding: 5,
spacing: 10,
items: [
{
type: 'colorpicker',
value,
onchange () {
const rgb = this.rgb();
if (win) {
win.find('#r').value(rgb.r);
win.find('#g').value(rgb.g);
win.find('#b').value(rgb.b);
win.find('#hex').value(this.value().substr(1));
showPreview(win, this.value());
}
}
},
{
type: 'form',
padding: 0,
labelGap: 5,
defaults: {
type: 'textbox',
size: 7,
value: '0',
flex: 1,
spellcheck: false,
onchange () {
const colorPickerCtrl = win.find('colorpicker')[0];
let name, value;
name = this.name();
value = this.value();
if (name === 'hex') {
value = '#' + value;
setColor(win, value);
colorPickerCtrl.value(value);
return;
}
value = {
r: win.find('#r').value(),
g: win.find('#g').value(),
b: win.find('#b').value()
};
colorPickerCtrl.value(value);
setColor(win, value);
}
},
items: [
{ name: 'r', label: 'R', autofocus: 1 },
{ name: 'g', label: 'G' },
{ name: 'b', label: 'B' },
{ name: 'hex', label: '#', value: '000000' },
{ name: 'preview', type: 'container', border: 1 }
]
}
]
},
onSubmit () {
callback('#' + win.toJSON().hex);
}
});
setColor(win, value);
};
export default {
open
};

Some files were not shown because too many files have changed in this diff Show More